test.cc 527 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226
  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(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(ClientTest, MoveConstructible) {
  269. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  270. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  271. }
  272. TEST(ClientTest, MoveAssignable) {
  273. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  274. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  275. }
  276. #ifdef _WIN32
  277. TEST(StartupTest, WSAStartup) {
  278. WSADATA wsaData;
  279. int ret = WSAStartup(0x0002, &wsaData);
  280. ASSERT_EQ(0, ret);
  281. }
  282. #endif
  283. TEST(DecodePathTest, PercentCharacter) {
  284. EXPECT_EQ(
  285. decode_path_component(
  286. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  287. U8("descrip=Gastos áéíóúñÑ 6"));
  288. }
  289. TEST(DecodePathTest, PercentCharacterNUL) {
  290. string expected;
  291. expected.push_back('x');
  292. expected.push_back('\0');
  293. expected.push_back('x');
  294. EXPECT_EQ(decode_path_component("x%00x"), expected);
  295. }
  296. TEST(DecodePathTest, UnicodeEncoding) {
  297. // %u0041 = 'A' (1-byte UTF-8)
  298. EXPECT_EQ("A", decode_path_component("%u0041"));
  299. // %u00E9 = 'é' (2-byte UTF-8)
  300. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  301. // %u3042 = 'あ' (3-byte UTF-8)
  302. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  303. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  304. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  305. // %uD800 = surrogate (invalid, silently dropped)
  306. EXPECT_EQ("", decode_path_component("%uD800"));
  307. }
  308. TEST(SanitizeFilenameTest, VariousPatterns) {
  309. // Path traversal
  310. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  311. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  312. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  313. // Normal and edge cases
  314. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  315. EXPECT_EQ("filename.txt",
  316. httplib::sanitize_filename("/path/to/filename.txt"));
  317. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  318. EXPECT_EQ("", httplib::sanitize_filename(".."));
  319. EXPECT_EQ("", httplib::sanitize_filename(""));
  320. // Null bytes stripped
  321. EXPECT_EQ("safe.txt",
  322. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  323. // Whitespace-only rejected
  324. EXPECT_EQ("", httplib::sanitize_filename(" "));
  325. }
  326. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  327. string unescapedCharacters = "-_.!~*'()";
  328. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  329. }
  330. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  331. string reservedCharacters = ";,/?:@&=+$";
  332. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  333. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  334. }
  335. TEST(ClientQueryOrder, PreserveOrder) {
  336. // This test reproduces Issue #2259: client may reorder query parameters
  337. // when sending a GET request. The expected behavior is that the client
  338. // preserves the original query string order when the caller supplied it
  339. // as part of the path.
  340. Server svr;
  341. svr.Get("/", [&](const Request &req, Response &res) {
  342. // Echo back the raw target so the test can assert ordering
  343. res.set_content(req.target, "text/plain");
  344. });
  345. std::thread t{[&] { svr.listen(HOST, PORT); }};
  346. auto se = detail::scope_exit([&] {
  347. svr.stop();
  348. t.join();
  349. ASSERT_FALSE(svr.is_running());
  350. });
  351. svr.wait_until_ready();
  352. Client cli(HOST, PORT);
  353. ASSERT_TRUE(cli.is_valid());
  354. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  355. auto res = cli.Get(original);
  356. ASSERT_TRUE(res);
  357. // Expect the echoed target to exactly match the original path (order
  358. // preserved)
  359. EXPECT_EQ(res->body, original);
  360. }
  361. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  362. string chineseCharacters = U8("中国語");
  363. string russianCharacters = U8("дом");
  364. string brazilianCharacters = U8("óculos");
  365. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  366. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  367. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  368. "%D0%B4%D0%BE%D0%BC");
  369. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  370. }
  371. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  372. string unescapedCharacters = "-_.!~*'()";
  373. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  374. }
  375. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  376. string reservedCharacters = ";,/?:@&=+$";
  377. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  378. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  379. }
  380. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  381. string chineseCharacters = U8("中国語");
  382. string russianCharacters = U8("дом");
  383. string brazilianCharacters = U8("óculos");
  384. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  385. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  386. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  387. "%D0%B4%D0%BE%D0%BC");
  388. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  389. }
  390. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  391. // Issue #2082 use case: encoding path component with ampersand
  392. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  393. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  394. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  395. }
  396. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  397. string unescapedCharacters = "-_.!~*'()";
  398. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  399. }
  400. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  401. string reservedCharacters = ";,/?:@&=+$#";
  402. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  403. }
  404. TEST(EncodeUriTest, TestUTF8Characters) {
  405. string chineseCharacters = U8("中国語");
  406. string russianCharacters = U8("дом");
  407. string brazilianCharacters = U8("óculos");
  408. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  409. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  410. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  411. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  412. }
  413. TEST(EncodeUriTest, TestCompleteUri) {
  414. string uri =
  415. "https://example.com/path/to/resource?query=value&param=test#fragment";
  416. EXPECT_EQ(
  417. httplib::encode_uri(uri),
  418. "https://example.com/path/to/resource?query=value&param=test#fragment");
  419. }
  420. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  421. string uri =
  422. "https://example.com/path with spaces/file name.html?q=hello world";
  423. EXPECT_EQ(httplib::encode_uri(uri),
  424. "https://example.com/path%20with%20spaces/"
  425. "file%20name.html?q=hello%20world");
  426. }
  427. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  428. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  429. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  430. }
  431. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  432. string unescapedCharacters = "-_.!~*'()";
  433. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  434. }
  435. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  436. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  437. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  438. string encodedBrazilian = "%C3%B3culos";
  439. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  440. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  441. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  442. }
  443. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  444. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  445. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  446. "Piri Tommy Villiers - on & on");
  447. }
  448. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  449. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  450. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  451. }
  452. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  453. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  454. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  455. }
  456. TEST(DecodeUriTest, TestUTF8Characters) {
  457. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  458. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  459. string encodedBrazilian = "%C3%B3culos";
  460. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  461. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  462. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  463. }
  464. TEST(DecodeUriTest, TestCompleteUri) {
  465. string encodedUri = "https://example.com/path%20with%20spaces/"
  466. "file%20name.html?q=hello%20world";
  467. EXPECT_EQ(
  468. httplib::decode_uri(encodedUri),
  469. "https://example.com/path with spaces/file name.html?q=hello world");
  470. }
  471. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  472. string original =
  473. "https://example.com/path with spaces/file name.html?q=hello world";
  474. string encoded = httplib::encode_uri(original);
  475. string decoded = httplib::decode_uri(encoded);
  476. EXPECT_EQ(decoded, original);
  477. }
  478. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  479. string original = "Piri Tommy Villiers - on & on";
  480. string encoded = httplib::encode_uri_component(original);
  481. string decoded = httplib::decode_uri_component(encoded);
  482. EXPECT_EQ(decoded, original);
  483. }
  484. TEST(TrimTests, TrimStringTests) {
  485. EXPECT_EQ("abc", detail::trim_copy("abc"));
  486. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  487. EXPECT_TRUE(detail::trim_copy("").empty());
  488. }
  489. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  490. // Simple case without quality values
  491. std::vector<std::string> result1;
  492. EXPECT_TRUE(detail::parse_accept_header(
  493. "text/html,application/json,text/plain", result1));
  494. EXPECT_EQ(result1.size(), 3U);
  495. EXPECT_EQ(result1[0], "text/html");
  496. EXPECT_EQ(result1[1], "application/json");
  497. EXPECT_EQ(result1[2], "text/plain");
  498. // With quality values
  499. std::vector<std::string> result2;
  500. EXPECT_TRUE(detail::parse_accept_header(
  501. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  502. EXPECT_EQ(result2.size(), 3U);
  503. EXPECT_EQ(result2[0], "application/json"); // highest q value
  504. EXPECT_EQ(result2[1], "text/html");
  505. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  506. }
  507. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  508. // Mixed with and without quality values
  509. std::vector<std::string> result;
  510. EXPECT_TRUE(detail::parse_accept_header(
  511. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  512. EXPECT_EQ(result.size(), 3U);
  513. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  514. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  515. EXPECT_EQ(result[2], "application/json"); // q=0.5
  516. }
  517. TEST(ParseAcceptHeaderTest, EdgeCases) {
  518. // Empty header
  519. std::vector<std::string> empty_result;
  520. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  521. EXPECT_TRUE(empty_result.empty());
  522. // Single type
  523. std::vector<std::string> single_result;
  524. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  525. EXPECT_EQ(single_result.size(), 1U);
  526. EXPECT_EQ(single_result[0], "application/json");
  527. // Wildcard types
  528. std::vector<std::string> wildcard_result;
  529. EXPECT_TRUE(detail::parse_accept_header(
  530. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  531. EXPECT_EQ(wildcard_result.size(), 3U);
  532. EXPECT_EQ(wildcard_result[0], "application/json");
  533. EXPECT_EQ(wildcard_result[1], "text/*");
  534. EXPECT_EQ(wildcard_result[2], "*/*");
  535. }
  536. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  537. // Common browser Accept header
  538. std::vector<std::string> browser_result;
  539. EXPECT_TRUE(
  540. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  541. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  542. browser_result));
  543. EXPECT_EQ(browser_result.size(), 6U);
  544. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  545. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  546. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  547. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  548. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  549. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  550. // API client header
  551. std::vector<std::string> api_result;
  552. EXPECT_TRUE(detail::parse_accept_header(
  553. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  554. api_result));
  555. EXPECT_EQ(api_result.size(), 3U);
  556. EXPECT_EQ(api_result[0], "application/json");
  557. EXPECT_EQ(api_result[1], "application/xml");
  558. EXPECT_EQ(api_result[2], "text/plain");
  559. }
  560. TEST(ParseAcceptHeaderTest, SpecialCases) {
  561. // Quality value with 3 decimal places
  562. std::vector<std::string> decimal_result;
  563. EXPECT_TRUE(detail::parse_accept_header(
  564. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  565. EXPECT_EQ(decimal_result.size(), 2U);
  566. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  567. EXPECT_EQ(decimal_result[1], "text/html");
  568. // Zero quality (should still be included but with lowest priority)
  569. std::vector<std::string> zero_q_result;
  570. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  571. zero_q_result));
  572. EXPECT_EQ(zero_q_result.size(), 2U);
  573. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  574. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  575. // No spaces around commas
  576. std::vector<std::string> no_space_result;
  577. EXPECT_TRUE(detail::parse_accept_header(
  578. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  579. no_space_result));
  580. EXPECT_EQ(no_space_result.size(), 3U);
  581. EXPECT_EQ(no_space_result[0], "text/html");
  582. EXPECT_EQ(no_space_result[1], "application/json");
  583. EXPECT_EQ(no_space_result[2], "text/plain");
  584. }
  585. TEST(ParseAcceptHeaderTest, InvalidCases) {
  586. std::vector<std::string> result;
  587. // Invalid quality value (> 1.0)
  588. EXPECT_FALSE(
  589. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  590. // Invalid quality value (< 0.0)
  591. EXPECT_FALSE(
  592. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  593. // Invalid quality value (not a number)
  594. EXPECT_FALSE(detail::parse_accept_header(
  595. "text/html;q=invalid,application/json", result));
  596. // Empty quality value
  597. EXPECT_FALSE(
  598. detail::parse_accept_header("text/html;q=,application/json", result));
  599. // Invalid media type format (no slash and not wildcard)
  600. EXPECT_FALSE(
  601. detail::parse_accept_header("invalidtype,application/json", result));
  602. // Empty media type
  603. result.clear();
  604. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  605. // Only commas
  606. result.clear();
  607. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  608. // Valid cases should still work
  609. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  610. EXPECT_EQ(result.size(), 1U);
  611. EXPECT_EQ(result[0], "*/*");
  612. EXPECT_TRUE(detail::parse_accept_header("*", result));
  613. EXPECT_EQ(result.size(), 1U);
  614. EXPECT_EQ(result[0], "*");
  615. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  616. EXPECT_EQ(result.size(), 1U);
  617. EXPECT_EQ(result[0], "text/*");
  618. }
  619. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  620. Server svr;
  621. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  622. EXPECT_EQ(req.accept_content_types.size(), 3U);
  623. EXPECT_EQ(req.accept_content_types[0], "application/json");
  624. EXPECT_EQ(req.accept_content_types[1], "text/html");
  625. EXPECT_EQ(req.accept_content_types[2], "*/*");
  626. res.set_content("ok", "text/plain");
  627. });
  628. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  629. EXPECT_TRUE(false);
  630. res.set_content("bad request", "text/plain");
  631. });
  632. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  633. auto se = detail::scope_exit([&] {
  634. svr.stop();
  635. listen_thread.join();
  636. ASSERT_FALSE(svr.is_running());
  637. });
  638. svr.wait_until_ready();
  639. Client cli("localhost", PORT);
  640. {
  641. auto res =
  642. cli.Get("/accept_ok",
  643. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  644. ASSERT_TRUE(res);
  645. EXPECT_EQ(StatusCode::OK_200, res->status);
  646. }
  647. {
  648. auto res = cli.Get("/accept_bad_request",
  649. {{"Accept", "text/html;q=abc,application/json"}});
  650. ASSERT_TRUE(res);
  651. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  652. }
  653. }
  654. TEST(DivideTest, DivideStringTests) {
  655. auto divide = [](const std::string &str, char d) {
  656. std::string lhs;
  657. std::string rhs;
  658. detail::divide(str, d,
  659. [&](const char *lhs_data, std::size_t lhs_size,
  660. const char *rhs_data, std::size_t rhs_size) {
  661. lhs.assign(lhs_data, lhs_size);
  662. rhs.assign(rhs_data, rhs_size);
  663. });
  664. return std::make_pair(std::move(lhs), std::move(rhs));
  665. };
  666. {
  667. const auto res = divide("", '=');
  668. EXPECT_EQ(res.first, "");
  669. EXPECT_EQ(res.second, "");
  670. }
  671. {
  672. const auto res = divide("=", '=');
  673. EXPECT_EQ(res.first, "");
  674. EXPECT_EQ(res.second, "");
  675. }
  676. {
  677. const auto res = divide(" ", '=');
  678. EXPECT_EQ(res.first, " ");
  679. EXPECT_EQ(res.second, "");
  680. }
  681. {
  682. const auto res = divide("a", '=');
  683. EXPECT_EQ(res.first, "a");
  684. EXPECT_EQ(res.second, "");
  685. }
  686. {
  687. const auto res = divide("a=", '=');
  688. EXPECT_EQ(res.first, "a");
  689. EXPECT_EQ(res.second, "");
  690. }
  691. {
  692. const auto res = divide("=b", '=');
  693. EXPECT_EQ(res.first, "");
  694. EXPECT_EQ(res.second, "b");
  695. }
  696. {
  697. const auto res = divide("a=b", '=');
  698. EXPECT_EQ(res.first, "a");
  699. EXPECT_EQ(res.second, "b");
  700. }
  701. {
  702. const auto res = divide("a=b=", '=');
  703. EXPECT_EQ(res.first, "a");
  704. EXPECT_EQ(res.second, "b=");
  705. }
  706. {
  707. const auto res = divide("a=b=c", '=');
  708. EXPECT_EQ(res.first, "a");
  709. EXPECT_EQ(res.second, "b=c");
  710. }
  711. }
  712. TEST(SplitTest, ParseQueryString) {
  713. string s = "key1=val1&key2=val2&key3=val3";
  714. Params dic;
  715. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  716. [&](const char *b, const char *e) {
  717. string key, val;
  718. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  719. if (key.empty()) {
  720. key.assign(b2, e2);
  721. } else {
  722. val.assign(b2, e2);
  723. }
  724. });
  725. dic.emplace(key, val);
  726. });
  727. EXPECT_EQ("val1", dic.find("key1")->second);
  728. EXPECT_EQ("val2", dic.find("key2")->second);
  729. EXPECT_EQ("val3", dic.find("key3")->second);
  730. }
  731. TEST(SplitTest, ParseInvalidQueryTests) {
  732. {
  733. string s = " ";
  734. Params dict;
  735. detail::parse_query_text(s, dict);
  736. EXPECT_TRUE(dict.empty());
  737. }
  738. {
  739. string s = " = =";
  740. Params dict;
  741. detail::parse_query_text(s, dict);
  742. EXPECT_TRUE(dict.empty());
  743. }
  744. }
  745. TEST(ParseQueryTest, ParseQueryString) {
  746. {
  747. std::string s = "key1=val1&key2=val2&key3=val3";
  748. Params dic;
  749. detail::parse_query_text(s, dic);
  750. EXPECT_EQ("val1", dic.find("key1")->second);
  751. EXPECT_EQ("val2", dic.find("key2")->second);
  752. EXPECT_EQ("val3", dic.find("key3")->second);
  753. }
  754. {
  755. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  756. Params dic;
  757. detail::parse_query_text(s, dic);
  758. EXPECT_EQ("", dic.find("key1")->second);
  759. EXPECT_EQ("val1", dic.find("key2")->second);
  760. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  761. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  762. }
  763. }
  764. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  765. Params dic;
  766. EXPECT_EQ(detail::params_to_query_str(dic), "");
  767. dic.emplace("key1", "val1");
  768. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  769. dic.emplace("key2", "val2");
  770. dic.emplace("key3", "val3");
  771. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  772. }
  773. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  774. string content_type = "multipart/form-data; boundary=something";
  775. string boundary;
  776. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  777. EXPECT_TRUE(ret);
  778. EXPECT_EQ(boundary, "something");
  779. }
  780. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  781. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  782. string boundary;
  783. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  784. EXPECT_TRUE(ret);
  785. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  786. }
  787. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  788. string content_type =
  789. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  790. string boundary;
  791. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  792. EXPECT_TRUE(ret);
  793. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  794. }
  795. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  796. string content_type =
  797. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  798. string boundary;
  799. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  800. EXPECT_TRUE(ret);
  801. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  802. }
  803. TEST(GetHeaderValueTest, DefaultValue) {
  804. Headers headers = {{"Dummy", "Dummy"}};
  805. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  806. EXPECT_STREQ("text/plain", val);
  807. }
  808. TEST(GetHeaderValueTest, DefaultValueInt) {
  809. Headers headers = {{"Dummy", "Dummy"}};
  810. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  811. EXPECT_EQ(100ull, val);
  812. }
  813. TEST(GetHeaderValueTest, RegularValue) {
  814. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  815. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  816. EXPECT_STREQ("text/html", val);
  817. }
  818. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  819. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  820. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  821. EXPECT_STREQ("text/html", val);
  822. }
  823. TEST(GetHeaderValueTest, SetContent) {
  824. Response res;
  825. res.set_content("html", "text/html");
  826. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  827. res.set_content("text", "text/plain");
  828. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  829. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  830. }
  831. TEST(GetHeaderValueTest, RegularValueInt) {
  832. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  833. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  834. EXPECT_EQ(100ull, val);
  835. }
  836. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  837. Headers headers = {{"Content-Length", "x"}};
  838. auto is_invalid_value = false;
  839. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  840. is_invalid_value);
  841. EXPECT_EQ(0ull, val);
  842. EXPECT_TRUE(is_invalid_value);
  843. }
  844. TEST(GetHeaderValueTest, Range) {
  845. {
  846. Headers headers = {make_range_header({{1, -1}})};
  847. auto val = detail::get_header_value(headers, "Range", 0, 0);
  848. EXPECT_STREQ("bytes=1-", val);
  849. }
  850. {
  851. Headers headers = {make_range_header({{-1, 1}})};
  852. auto val = detail::get_header_value(headers, "Range", 0, 0);
  853. EXPECT_STREQ("bytes=-1", val);
  854. }
  855. {
  856. Headers headers = {make_range_header({{1, 10}})};
  857. auto val = detail::get_header_value(headers, "Range", 0, 0);
  858. EXPECT_STREQ("bytes=1-10", val);
  859. }
  860. {
  861. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  862. auto val = detail::get_header_value(headers, "Range", 0, 0);
  863. EXPECT_STREQ("bytes=1-10, 100-", val);
  864. }
  865. {
  866. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  867. auto val = detail::get_header_value(headers, "Range", 0, 0);
  868. EXPECT_STREQ("bytes=1-10, 100-200", val);
  869. }
  870. {
  871. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  872. auto val = detail::get_header_value(headers, "Range", 0, 0);
  873. EXPECT_STREQ("bytes=0-0, -1", val);
  874. }
  875. }
  876. TEST(ParseHeaderValueTest, Range) {
  877. {
  878. Ranges ranges;
  879. auto ret = detail::parse_range_header("bytes=1-", ranges);
  880. EXPECT_TRUE(ret);
  881. EXPECT_EQ(1u, ranges.size());
  882. EXPECT_EQ(1u, ranges[0].first);
  883. EXPECT_EQ(-1, ranges[0].second);
  884. }
  885. {
  886. Ranges ranges;
  887. auto ret = detail::parse_range_header("bytes=-1", ranges);
  888. EXPECT_TRUE(ret);
  889. EXPECT_EQ(1u, ranges.size());
  890. EXPECT_EQ(-1, ranges[0].first);
  891. EXPECT_EQ(1u, ranges[0].second);
  892. }
  893. {
  894. Ranges ranges;
  895. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  896. EXPECT_TRUE(ret);
  897. EXPECT_EQ(1u, ranges.size());
  898. EXPECT_EQ(1u, ranges[0].first);
  899. EXPECT_EQ(10u, ranges[0].second);
  900. }
  901. {
  902. Ranges ranges;
  903. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  904. EXPECT_FALSE(ret);
  905. }
  906. {
  907. Ranges ranges;
  908. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  909. EXPECT_TRUE(ret);
  910. EXPECT_EQ(2u, ranges.size());
  911. EXPECT_EQ(1u, ranges[0].first);
  912. EXPECT_EQ(10u, ranges[0].second);
  913. EXPECT_EQ(100u, ranges[1].first);
  914. EXPECT_EQ(-1, ranges[1].second);
  915. }
  916. {
  917. Ranges ranges;
  918. auto ret =
  919. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  920. EXPECT_TRUE(ret);
  921. EXPECT_EQ(3u, 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(200u, ranges[1].second);
  926. EXPECT_EQ(300u, ranges[2].first);
  927. EXPECT_EQ(400u, ranges[2].second);
  928. }
  929. {
  930. Ranges ranges;
  931. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  932. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  933. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  934. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  935. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  936. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  937. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  938. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  939. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  940. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  941. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  942. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  943. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  944. EXPECT_TRUE(ranges.empty());
  945. }
  946. }
  947. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  948. Request req;
  949. req.set_header("Accept-Encoding", "gzip");
  950. Response res;
  951. res.set_header("Content-Type", "text/plain");
  952. auto ret = detail::encoding_type(req, res);
  953. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  954. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  955. #else
  956. EXPECT_TRUE(ret == detail::EncodingType::None);
  957. #endif
  958. }
  959. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  960. Request req;
  961. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  962. Response res;
  963. res.set_header("Content-Type", "text/plain");
  964. auto ret = detail::encoding_type(req, res);
  965. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  966. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  967. #elif CPPHTTPLIB_ZLIB_SUPPORT
  968. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  969. #elif CPPHTTPLIB_ZSTD_SUPPORT
  970. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  971. #else
  972. EXPECT_TRUE(ret == detail::EncodingType::None);
  973. #endif
  974. }
  975. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  976. Request req;
  977. req.set_header("Accept-Encoding",
  978. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  979. Response res;
  980. res.set_header("Content-Type", "text/plain");
  981. auto ret = detail::encoding_type(req, res);
  982. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  983. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  984. #elif CPPHTTPLIB_ZLIB_SUPPORT
  985. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  986. #elif CPPHTTPLIB_ZSTD_SUPPORT
  987. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  988. #else
  989. EXPECT_TRUE(ret == detail::EncodingType::None);
  990. #endif
  991. }
  992. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  993. // All supported encodings rejected with q=0 should return None
  994. Request req;
  995. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  996. Response res;
  997. res.set_header("Content-Type", "text/plain");
  998. auto ret = detail::encoding_type(req, res);
  999. EXPECT_TRUE(ret == detail::EncodingType::None);
  1000. }
  1001. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1002. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1003. Request req;
  1004. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1005. Response res;
  1006. res.set_header("Content-Type", "text/plain");
  1007. auto ret = detail::encoding_type(req, res);
  1008. EXPECT_TRUE(ret == detail::EncodingType::None);
  1009. }
  1010. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1011. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1012. Request req;
  1013. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1014. Response res;
  1015. res.set_header("Content-Type", "text/plain");
  1016. auto ret = detail::encoding_type(req, res);
  1017. EXPECT_TRUE(ret == detail::EncodingType::None);
  1018. }
  1019. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1020. // RFC 7231: Accept-Encoding values are case-insensitive
  1021. Request req;
  1022. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1023. Response res;
  1024. res.set_header("Content-Type", "text/plain");
  1025. auto ret = detail::encoding_type(req, res);
  1026. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1027. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1028. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1029. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1030. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1031. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1032. #else
  1033. EXPECT_TRUE(ret == detail::EncodingType::None);
  1034. #endif
  1035. }
  1036. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1037. // q value should determine priority, not hardcoded order
  1038. Request req;
  1039. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1040. Response res;
  1041. res.set_header("Content-Type", "text/plain");
  1042. auto ret = detail::encoding_type(req, res);
  1043. // gzip has highest q=1.0, so it should be selected even though
  1044. // br and zstd are also supported
  1045. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1046. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1047. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1048. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1049. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1050. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1051. #else
  1052. EXPECT_TRUE(ret == detail::EncodingType::None);
  1053. #endif
  1054. }
  1055. TEST(BufferStreamTest, read) {
  1056. detail::BufferStream strm1;
  1057. Stream &strm = strm1;
  1058. EXPECT_EQ(5, strm.write("hello"));
  1059. char buf[512];
  1060. EXPECT_EQ(2, strm.read(buf, 2));
  1061. EXPECT_EQ('h', buf[0]);
  1062. EXPECT_EQ('e', buf[1]);
  1063. EXPECT_EQ(2, strm.read(buf, 2));
  1064. EXPECT_EQ('l', buf[0]);
  1065. EXPECT_EQ('l', buf[1]);
  1066. EXPECT_EQ(1, strm.read(buf, 1));
  1067. EXPECT_EQ('o', buf[0]);
  1068. EXPECT_EQ(0, strm.read(buf, 1));
  1069. }
  1070. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1071. auto host = "www.httpwatch.com";
  1072. auto ip = hosted_at(host);
  1073. EXPECT_EQ("23.96.13.243", ip);
  1074. std::vector<std::string> addrs;
  1075. hosted_at(host, addrs);
  1076. EXPECT_EQ(1u, addrs.size());
  1077. }
  1078. #if 0 // It depends on each test environment...
  1079. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1080. auto host = "www.youtube.com";
  1081. std::vector<std::string> addrs;
  1082. hosted_at(host, addrs);
  1083. EXPECT_EQ(20u, addrs.size());
  1084. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1085. EXPECT_TRUE(it != addrs.end());
  1086. }
  1087. #endif
  1088. class ChunkedEncodingTest : public ::testing::Test {
  1089. protected:
  1090. ChunkedEncodingTest()
  1091. : cli_(HOST, PORT)
  1092. #ifdef CPPHTTPLIB_SSL_ENABLED
  1093. ,
  1094. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1095. #endif
  1096. {
  1097. cli_.set_connection_timeout(2);
  1098. #ifdef CPPHTTPLIB_SSL_ENABLED
  1099. cli_.enable_server_certificate_verification(false);
  1100. #endif
  1101. }
  1102. virtual void SetUp() {
  1103. read_file("./image.jpg", image_data_);
  1104. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1105. res.set_content("Hello World!", "text/plain");
  1106. });
  1107. svr_.Get(
  1108. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1109. res.set_chunked_content_provider(
  1110. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1111. size_t remaining = image_data_.size() - offset;
  1112. if (remaining == 0) {
  1113. sink.done();
  1114. } else {
  1115. constexpr size_t CHUNK_SIZE = 1024;
  1116. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1117. sink.write(&image_data_[offset], send_size);
  1118. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1119. }
  1120. return true;
  1121. });
  1122. });
  1123. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1124. svr_.wait_until_ready();
  1125. }
  1126. virtual void TearDown() {
  1127. svr_.stop();
  1128. if (!request_threads_.empty()) {
  1129. std::this_thread::sleep_for(std::chrono::seconds(1));
  1130. for (auto &t : request_threads_) {
  1131. t.join();
  1132. }
  1133. }
  1134. t_.join();
  1135. }
  1136. #ifdef CPPHTTPLIB_SSL_ENABLED
  1137. SSLClient cli_;
  1138. SSLServer svr_;
  1139. #else
  1140. Client cli_;
  1141. Server svr_;
  1142. #endif
  1143. thread t_;
  1144. std::vector<thread> request_threads_;
  1145. std::string image_data_;
  1146. };
  1147. TEST_F(ChunkedEncodingTest, NormalGet) {
  1148. auto res = cli_.Get("/chunked");
  1149. ASSERT_TRUE(res);
  1150. std::string out;
  1151. read_file("./image.jpg", out);
  1152. EXPECT_EQ(StatusCode::OK_200, res->status);
  1153. EXPECT_EQ(out, res->body);
  1154. }
  1155. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1156. std::string body;
  1157. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1158. body.append(data, data_length);
  1159. return true;
  1160. });
  1161. ASSERT_TRUE(res);
  1162. std::string out;
  1163. read_file("./image.jpg", out);
  1164. EXPECT_EQ(StatusCode::OK_200, res->status);
  1165. EXPECT_EQ(out, body);
  1166. }
  1167. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1168. std::string body;
  1169. auto res = cli_.Get(
  1170. "/chunked",
  1171. [&](const Response &response) {
  1172. EXPECT_EQ(StatusCode::OK_200, response.status);
  1173. return true;
  1174. },
  1175. [&](const char *data, size_t data_length) {
  1176. body.append(data, data_length);
  1177. return true;
  1178. });
  1179. ASSERT_TRUE(res);
  1180. std::string out;
  1181. read_file("./image.jpg", out);
  1182. EXPECT_EQ(StatusCode::OK_200, res->status);
  1183. EXPECT_EQ(out, body);
  1184. }
  1185. TEST(RangeTest, FromHTTPBin_Online) {
  1186. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1187. auto host = "httpcan.org";
  1188. auto path = std::string{"/range/32"};
  1189. #else
  1190. auto host = "nghttp2.org";
  1191. auto path = std::string{"/httpbin/range/32"};
  1192. #endif
  1193. #ifdef CPPHTTPLIB_SSL_ENABLED
  1194. auto port = 443;
  1195. SSLClient cli(host, port);
  1196. #else
  1197. auto port = 80;
  1198. Client cli(host, port);
  1199. #endif
  1200. cli.set_connection_timeout(5);
  1201. {
  1202. auto res = cli.Get(path);
  1203. ASSERT_TRUE(res);
  1204. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1205. EXPECT_EQ(StatusCode::OK_200, res->status);
  1206. }
  1207. {
  1208. Headers headers = {make_range_header({{1, -1}})};
  1209. auto res = cli.Get(path, headers);
  1210. ASSERT_TRUE(res);
  1211. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1212. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1213. }
  1214. {
  1215. Headers headers = {make_range_header({{1, 10}})};
  1216. auto res = cli.Get(path, headers);
  1217. ASSERT_TRUE(res);
  1218. EXPECT_EQ("bcdefghijk", res->body);
  1219. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1220. }
  1221. {
  1222. Headers headers = {make_range_header({{0, 31}})};
  1223. auto res = cli.Get(path, headers);
  1224. ASSERT_TRUE(res);
  1225. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1226. EXPECT_EQ(StatusCode::OK_200, res->status);
  1227. }
  1228. {
  1229. Headers headers = {make_range_header({{0, -1}})};
  1230. auto res = cli.Get(path, headers);
  1231. ASSERT_TRUE(res);
  1232. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1233. EXPECT_EQ(StatusCode::OK_200, res->status);
  1234. }
  1235. {
  1236. Headers headers = {make_range_header({{0, 32}})};
  1237. auto res = cli.Get(path, headers);
  1238. ASSERT_TRUE(res);
  1239. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1240. }
  1241. }
  1242. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1243. auto host = "unresolvableaddress.local";
  1244. auto path = std::string{"/"};
  1245. #ifdef CPPHTTPLIB_SSL_ENABLED
  1246. auto port = 443;
  1247. SSLClient cli(host, port);
  1248. #else
  1249. auto port = 80;
  1250. Client cli(host, port);
  1251. #endif
  1252. cli.set_connection_timeout(1);
  1253. {
  1254. auto res = cli.Get(path);
  1255. ASSERT_FALSE(res);
  1256. }
  1257. std::this_thread::sleep_for(std::chrono::seconds(8));
  1258. }
  1259. TEST(ConnectionErrorTest, InvalidHost) {
  1260. auto host = "-abcde.com";
  1261. #ifdef CPPHTTPLIB_SSL_ENABLED
  1262. auto port = 443;
  1263. SSLClient cli(host, port);
  1264. #else
  1265. auto port = 80;
  1266. Client cli(host, port);
  1267. #endif
  1268. cli.set_connection_timeout(std::chrono::seconds(2));
  1269. auto res = cli.Get("/");
  1270. ASSERT_TRUE(!res);
  1271. EXPECT_EQ(Error::Connection, res.error());
  1272. }
  1273. TEST(ConnectionErrorTest, InvalidHost2) {
  1274. auto host = "httpcan.org/";
  1275. #ifdef CPPHTTPLIB_SSL_ENABLED
  1276. SSLClient cli(host);
  1277. #else
  1278. Client cli(host);
  1279. #endif
  1280. cli.set_connection_timeout(std::chrono::seconds(2));
  1281. auto res = cli.Get("/");
  1282. ASSERT_TRUE(!res);
  1283. EXPECT_EQ(Error::Connection, res.error());
  1284. }
  1285. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1286. auto host = "httpcan.org/";
  1287. #ifdef CPPHTTPLIB_SSL_ENABLED
  1288. SSLClient cli(host);
  1289. #else
  1290. Client cli(host);
  1291. #endif
  1292. cli.set_connection_timeout(std::chrono::seconds(2));
  1293. auto res = cli.Get("/");
  1294. ASSERT_TRUE(!res);
  1295. stringstream s;
  1296. s << "error code: " << res.error();
  1297. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1298. }
  1299. TEST(ConnectionErrorTest, InvalidPort) {
  1300. auto host = "localhost";
  1301. auto port = 44380;
  1302. #ifdef CPPHTTPLIB_SSL_ENABLED
  1303. SSLClient cli(host, port);
  1304. #else
  1305. Client cli(host, port);
  1306. #endif
  1307. cli.set_connection_timeout(std::chrono::seconds(2));
  1308. auto res = cli.Get("/");
  1309. ASSERT_TRUE(!res);
  1310. EXPECT_TRUE(Error::Connection == res.error() ||
  1311. Error::ConnectionTimeout == res.error());
  1312. }
  1313. TEST(ConnectionErrorTest, Timeout_Online) {
  1314. auto host = "google.com";
  1315. #ifdef CPPHTTPLIB_SSL_ENABLED
  1316. auto port = 44380;
  1317. SSLClient cli(host, port);
  1318. #else
  1319. auto port = 8080;
  1320. Client cli(host, port);
  1321. #endif
  1322. cli.set_connection_timeout(std::chrono::seconds(2));
  1323. // only probe one address type so that the error reason
  1324. // correlates to the timed-out IPv4, not the unsupported
  1325. // IPv6 connection attempt
  1326. cli.set_address_family(AF_INET);
  1327. auto res = cli.Get("/");
  1328. ASSERT_TRUE(!res);
  1329. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1330. }
  1331. TEST(CancelTest, NoCancel_Online) {
  1332. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1333. auto host = "httpcan.org";
  1334. auto path = std::string{"/range/32"};
  1335. #else
  1336. auto host = "nghttp2.org";
  1337. auto path = std::string{"/httpbin/range/32"};
  1338. #endif
  1339. #ifdef CPPHTTPLIB_SSL_ENABLED
  1340. auto port = 443;
  1341. SSLClient cli(host, port);
  1342. #else
  1343. auto port = 80;
  1344. Client cli(host, port);
  1345. #endif
  1346. cli.set_connection_timeout(std::chrono::seconds(5));
  1347. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1348. ASSERT_TRUE(res);
  1349. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1350. EXPECT_EQ(StatusCode::OK_200, res->status);
  1351. }
  1352. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1353. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1354. auto host = "httpcan.org";
  1355. auto path = std::string{"/range/32"};
  1356. #else
  1357. auto host = "nghttp2.org";
  1358. auto path = std::string{"/httpbin/range/32"};
  1359. #endif
  1360. #ifdef CPPHTTPLIB_SSL_ENABLED
  1361. auto port = 443;
  1362. SSLClient cli(host, port);
  1363. #else
  1364. auto port = 80;
  1365. Client cli(host, port);
  1366. #endif
  1367. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1368. cli.set_connection_timeout(std::chrono::seconds(5));
  1369. ASSERT_TRUE(!res);
  1370. EXPECT_EQ(Error::Canceled, res.error());
  1371. }
  1372. TEST(CancelTest, WithCancelLargePayload_Online) {
  1373. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1374. auto host = "httpcan.org";
  1375. auto path = std::string{"/range/65536"};
  1376. #else
  1377. auto host = "nghttp2.org";
  1378. auto path = std::string{"/httpbin/range/65536"};
  1379. #endif
  1380. #ifdef CPPHTTPLIB_SSL_ENABLED
  1381. auto port = 443;
  1382. SSLClient cli(host, port);
  1383. #else
  1384. auto port = 80;
  1385. Client cli(host, port);
  1386. #endif
  1387. cli.set_connection_timeout(std::chrono::seconds(5));
  1388. uint32_t count = 0;
  1389. auto res =
  1390. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1391. ASSERT_TRUE(!res);
  1392. EXPECT_EQ(Error::Canceled, res.error());
  1393. }
  1394. TEST(CancelTest, NoCancelPost) {
  1395. Server svr;
  1396. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1397. res.set_content("Hello World!", "text/plain");
  1398. });
  1399. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1400. auto se = detail::scope_exit([&] {
  1401. svr.stop();
  1402. thread.join();
  1403. ASSERT_FALSE(svr.is_running());
  1404. });
  1405. svr.wait_until_ready();
  1406. Client cli(HOST, PORT);
  1407. cli.set_connection_timeout(std::chrono::seconds(5));
  1408. auto res =
  1409. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1410. "application/json", [](uint64_t, uint64_t) { return true; });
  1411. ASSERT_TRUE(res);
  1412. EXPECT_EQ("Hello World!", res->body);
  1413. EXPECT_EQ(StatusCode::OK_200, res->status);
  1414. }
  1415. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1416. Server svr;
  1417. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1418. res.set_content("Hello World!", "text/plain");
  1419. });
  1420. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1421. auto se = detail::scope_exit([&] {
  1422. svr.stop();
  1423. thread.join();
  1424. ASSERT_FALSE(svr.is_running());
  1425. });
  1426. svr.wait_until_ready();
  1427. Client cli(HOST, PORT);
  1428. cli.set_connection_timeout(std::chrono::seconds(5));
  1429. auto res =
  1430. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1431. "application/json", [](uint64_t, uint64_t) { return false; });
  1432. ASSERT_TRUE(!res);
  1433. EXPECT_EQ(Error::Canceled, res.error());
  1434. }
  1435. TEST(CancelTest, WithCancelLargePayloadPost) {
  1436. Server svr;
  1437. svr.set_payload_max_length(200 * 1024 * 1024);
  1438. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1439. res.set_content(LARGE_DATA, "text/plain");
  1440. });
  1441. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1442. auto se = detail::scope_exit([&] {
  1443. svr.stop();
  1444. thread.join();
  1445. ASSERT_FALSE(svr.is_running());
  1446. });
  1447. svr.wait_until_ready();
  1448. Client cli(HOST, PORT);
  1449. cli.set_payload_max_length(200 * 1024 * 1024);
  1450. cli.set_connection_timeout(std::chrono::seconds(5));
  1451. auto res =
  1452. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1453. "application/json", [](uint64_t, uint64_t) { return false; });
  1454. ASSERT_TRUE(!res);
  1455. EXPECT_EQ(Error::Canceled, res.error());
  1456. }
  1457. TEST(CancelTest, NoCancelPut) {
  1458. Server svr;
  1459. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1460. res.set_content("Hello World!", "text/plain");
  1461. });
  1462. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1463. auto se = detail::scope_exit([&] {
  1464. svr.stop();
  1465. thread.join();
  1466. ASSERT_FALSE(svr.is_running());
  1467. });
  1468. svr.wait_until_ready();
  1469. Client cli(HOST, PORT);
  1470. cli.set_connection_timeout(std::chrono::seconds(5));
  1471. auto res =
  1472. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1473. "application/json", [](uint64_t, uint64_t) { return true; });
  1474. ASSERT_TRUE(res);
  1475. EXPECT_EQ("Hello World!", res->body);
  1476. EXPECT_EQ(StatusCode::OK_200, res->status);
  1477. }
  1478. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1479. Server svr;
  1480. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1481. res.set_content("Hello World!", "text/plain");
  1482. });
  1483. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1484. auto se = detail::scope_exit([&] {
  1485. svr.stop();
  1486. thread.join();
  1487. ASSERT_FALSE(svr.is_running());
  1488. });
  1489. svr.wait_until_ready();
  1490. Client cli(HOST, PORT);
  1491. cli.set_connection_timeout(std::chrono::seconds(5));
  1492. auto res =
  1493. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1494. "application/json", [](uint64_t, uint64_t) { return false; });
  1495. ASSERT_TRUE(!res);
  1496. EXPECT_EQ(Error::Canceled, res.error());
  1497. }
  1498. TEST(CancelTest, WithCancelLargePayloadPut) {
  1499. Server svr;
  1500. svr.set_payload_max_length(200 * 1024 * 1024);
  1501. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1502. res.set_content(LARGE_DATA, "text/plain");
  1503. });
  1504. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1505. auto se = detail::scope_exit([&] {
  1506. svr.stop();
  1507. thread.join();
  1508. ASSERT_FALSE(svr.is_running());
  1509. });
  1510. svr.wait_until_ready();
  1511. Client cli(HOST, PORT);
  1512. cli.set_payload_max_length(200 * 1024 * 1024);
  1513. cli.set_connection_timeout(std::chrono::seconds(5));
  1514. auto res =
  1515. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1516. "application/json", [](uint64_t, uint64_t) { return false; });
  1517. ASSERT_TRUE(!res);
  1518. EXPECT_EQ(Error::Canceled, res.error());
  1519. }
  1520. TEST(CancelTest, NoCancelPatch) {
  1521. Server svr;
  1522. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1523. res.set_content("Hello World!", "text/plain");
  1524. });
  1525. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1526. auto se = detail::scope_exit([&] {
  1527. svr.stop();
  1528. thread.join();
  1529. ASSERT_FALSE(svr.is_running());
  1530. });
  1531. svr.wait_until_ready();
  1532. Client cli(HOST, PORT);
  1533. cli.set_connection_timeout(std::chrono::seconds(5));
  1534. auto res =
  1535. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1536. "application/json", [](uint64_t, uint64_t) { return true; });
  1537. ASSERT_TRUE(res);
  1538. EXPECT_EQ("Hello World!", res->body);
  1539. EXPECT_EQ(StatusCode::OK_200, res->status);
  1540. }
  1541. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1542. Server svr;
  1543. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1544. res.set_content("Hello World!", "text/plain");
  1545. });
  1546. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1547. auto se = detail::scope_exit([&] {
  1548. svr.stop();
  1549. thread.join();
  1550. ASSERT_FALSE(svr.is_running());
  1551. });
  1552. svr.wait_until_ready();
  1553. Client cli(HOST, PORT);
  1554. cli.set_connection_timeout(std::chrono::seconds(5));
  1555. auto res =
  1556. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1557. "application/json", [](uint64_t, uint64_t) { return false; });
  1558. ASSERT_TRUE(!res);
  1559. EXPECT_EQ(Error::Canceled, res.error());
  1560. }
  1561. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1562. Server svr;
  1563. svr.set_payload_max_length(200 * 1024 * 1024);
  1564. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1565. res.set_content(LARGE_DATA, "text/plain");
  1566. });
  1567. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1568. auto se = detail::scope_exit([&] {
  1569. svr.stop();
  1570. thread.join();
  1571. ASSERT_FALSE(svr.is_running());
  1572. });
  1573. svr.wait_until_ready();
  1574. Client cli(HOST, PORT);
  1575. cli.set_payload_max_length(200 * 1024 * 1024);
  1576. cli.set_connection_timeout(std::chrono::seconds(5));
  1577. auto res =
  1578. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1579. "application/json", [](uint64_t, uint64_t) { return false; });
  1580. ASSERT_TRUE(!res);
  1581. EXPECT_EQ(Error::Canceled, res.error());
  1582. }
  1583. TEST(CancelTest, NoCancelDelete) {
  1584. Server svr;
  1585. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1586. res.set_content("Hello World!", "text/plain");
  1587. });
  1588. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1589. auto se = detail::scope_exit([&] {
  1590. svr.stop();
  1591. thread.join();
  1592. ASSERT_FALSE(svr.is_running());
  1593. });
  1594. svr.wait_until_ready();
  1595. Client cli(HOST, PORT);
  1596. cli.set_connection_timeout(std::chrono::seconds(5));
  1597. auto res =
  1598. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1599. "application/json", [](uint64_t, uint64_t) { return true; });
  1600. ASSERT_TRUE(res);
  1601. EXPECT_EQ("Hello World!", res->body);
  1602. EXPECT_EQ(StatusCode::OK_200, res->status);
  1603. }
  1604. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1605. Server svr;
  1606. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1607. res.set_content("Hello World!", "text/plain");
  1608. });
  1609. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1610. auto se = detail::scope_exit([&] {
  1611. svr.stop();
  1612. thread.join();
  1613. ASSERT_FALSE(svr.is_running());
  1614. });
  1615. svr.wait_until_ready();
  1616. Client cli(HOST, PORT);
  1617. cli.set_connection_timeout(std::chrono::seconds(5));
  1618. auto res =
  1619. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1620. "application/json", [](uint64_t, uint64_t) { return false; });
  1621. ASSERT_TRUE(!res);
  1622. EXPECT_EQ(Error::Canceled, res.error());
  1623. }
  1624. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1625. Server svr;
  1626. svr.set_payload_max_length(200 * 1024 * 1024);
  1627. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1628. res.set_content(LARGE_DATA, "text/plain");
  1629. });
  1630. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1631. auto se = detail::scope_exit([&] {
  1632. svr.stop();
  1633. thread.join();
  1634. ASSERT_FALSE(svr.is_running());
  1635. });
  1636. svr.wait_until_ready();
  1637. Client cli(HOST, PORT);
  1638. cli.set_payload_max_length(200 * 1024 * 1024);
  1639. cli.set_connection_timeout(std::chrono::seconds(5));
  1640. auto res =
  1641. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1642. "application/json", [](uint64_t, uint64_t) { return false; });
  1643. ASSERT_TRUE(!res);
  1644. EXPECT_EQ(Error::Canceled, res.error());
  1645. }
  1646. static std::string remove_whitespace(const std::string &input) {
  1647. std::string output;
  1648. output.reserve(input.size());
  1649. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1650. [](unsigned char c) { return !std::isspace(c); });
  1651. return output;
  1652. }
  1653. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1654. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1655. auto host = "httpcan.org";
  1656. auto path = std::string{"/basic-auth/hello/world"};
  1657. #else
  1658. auto host = "nghttp2.org";
  1659. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1660. #endif
  1661. #ifdef CPPHTTPLIB_SSL_ENABLED
  1662. auto port = 443;
  1663. SSLClient cli(host, port);
  1664. #else
  1665. auto port = 80;
  1666. Client cli(host, port);
  1667. #endif
  1668. {
  1669. auto res = cli.Get(path);
  1670. ASSERT_TRUE(res);
  1671. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1672. }
  1673. {
  1674. auto res =
  1675. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1676. ASSERT_TRUE(res);
  1677. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1678. remove_whitespace(res->body));
  1679. EXPECT_EQ(StatusCode::OK_200, res->status);
  1680. }
  1681. {
  1682. cli.set_basic_auth("hello", "world");
  1683. auto res = cli.Get(path);
  1684. ASSERT_TRUE(res);
  1685. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1686. remove_whitespace(res->body));
  1687. EXPECT_EQ(StatusCode::OK_200, res->status);
  1688. }
  1689. {
  1690. cli.set_basic_auth("hello", "bad");
  1691. auto res = cli.Get(path);
  1692. ASSERT_TRUE(res);
  1693. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1694. }
  1695. {
  1696. cli.set_basic_auth("bad", "world");
  1697. auto res = cli.Get(path);
  1698. ASSERT_TRUE(res);
  1699. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1700. }
  1701. }
  1702. #ifdef CPPHTTPLIB_SSL_ENABLED
  1703. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1704. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1705. auto host = "httpcan.org";
  1706. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1707. auto paths = std::vector<std::string>{
  1708. "/digest-auth/auth/hello/world/MD5",
  1709. "/digest-auth/auth/hello/world/SHA-256",
  1710. "/digest-auth/auth/hello/world/SHA-512",
  1711. };
  1712. #else
  1713. auto host = "nghttp2.org";
  1714. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1715. auto paths = std::vector<std::string>{
  1716. "/httpbin/digest-auth/auth/hello/world/MD5",
  1717. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1718. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1719. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1720. };
  1721. #endif
  1722. auto port = 443;
  1723. SSLClient cli(host, port);
  1724. {
  1725. auto res = cli.Get(unauth_path);
  1726. ASSERT_TRUE(res);
  1727. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1728. }
  1729. {
  1730. cli.set_digest_auth("hello", "world");
  1731. for (const auto &path : paths) {
  1732. auto res = cli.Get(path.c_str());
  1733. ASSERT_TRUE(res);
  1734. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1735. std::string algo(path.substr(path.rfind('/') + 1));
  1736. EXPECT_EQ(
  1737. remove_whitespace("{\"algorithm\":\"" + algo +
  1738. "\",\"authenticated\":true,\"user\":\"hello\"}\n"),
  1739. remove_whitespace(res->body));
  1740. #else
  1741. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1742. remove_whitespace(res->body));
  1743. #endif
  1744. EXPECT_EQ(StatusCode::OK_200, res->status);
  1745. }
  1746. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1747. cli.set_digest_auth("hello", "bad");
  1748. for (const auto &path : paths) {
  1749. auto res = cli.Get(path.c_str());
  1750. ASSERT_TRUE(res);
  1751. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1752. }
  1753. #endif
  1754. }
  1755. }
  1756. #endif
  1757. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1758. auto host = "google.com";
  1759. auto another_host = "example.com";
  1760. auto wrong_ip = "0.0.0.0";
  1761. #ifdef CPPHTTPLIB_SSL_ENABLED
  1762. SSLClient cli(host);
  1763. #else
  1764. Client cli(host);
  1765. #endif
  1766. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1767. auto res = cli.Get("/");
  1768. ASSERT_TRUE(res);
  1769. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1770. }
  1771. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1772. auto host = "google.com";
  1773. auto wrong_ip = "0.0.0.0";
  1774. #ifdef CPPHTTPLIB_SSL_ENABLED
  1775. SSLClient cli(host);
  1776. #else
  1777. Client cli(host);
  1778. #endif
  1779. cli.set_hostname_addr_map({{host, wrong_ip}});
  1780. auto res = cli.Get("/");
  1781. ASSERT_TRUE(!res);
  1782. EXPECT_EQ(Error::Connection, res.error());
  1783. }
  1784. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1785. auto host = "nghttp2.org";
  1786. #ifdef CPPHTTPLIB_SSL_ENABLED
  1787. SSLClient cli(host);
  1788. #else
  1789. Client cli(host);
  1790. #endif
  1791. cli.set_follow_location(true);
  1792. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1793. ASSERT_TRUE(res);
  1794. EXPECT_EQ(StatusCode::OK_200, res->status);
  1795. }
  1796. TEST(RedirectTest, Redirect_Online) {
  1797. auto host = "nghttp2.org";
  1798. #ifdef CPPHTTPLIB_SSL_ENABLED
  1799. SSLClient cli(host);
  1800. #else
  1801. Client cli(host);
  1802. #endif
  1803. cli.set_follow_location(true);
  1804. auto res = cli.Get("/httpbin/redirect/3");
  1805. ASSERT_TRUE(res);
  1806. EXPECT_EQ(StatusCode::OK_200, res->status);
  1807. }
  1808. TEST(RelativeRedirectTest, Redirect_Online) {
  1809. auto host = "nghttp2.org";
  1810. #ifdef CPPHTTPLIB_SSL_ENABLED
  1811. SSLClient cli(host);
  1812. #else
  1813. Client cli(host);
  1814. #endif
  1815. cli.set_follow_location(true);
  1816. auto res = cli.Get("/httpbin/relative-redirect/3");
  1817. ASSERT_TRUE(res);
  1818. EXPECT_EQ(StatusCode::OK_200, res->status);
  1819. }
  1820. TEST(TooManyRedirectTest, Redirect_Online) {
  1821. auto host = "nghttp2.org";
  1822. #ifdef CPPHTTPLIB_SSL_ENABLED
  1823. SSLClient cli(host);
  1824. #else
  1825. Client cli(host);
  1826. #endif
  1827. cli.set_follow_location(true);
  1828. auto res = cli.Get("/httpbin/redirect/21");
  1829. ASSERT_TRUE(!res);
  1830. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1831. }
  1832. #ifdef CPPHTTPLIB_SSL_ENABLED
  1833. TEST(YahooRedirectTest, Redirect_Online) {
  1834. Client cli("yahoo.com");
  1835. auto res = cli.Get("/");
  1836. ASSERT_TRUE(res);
  1837. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1838. cli.set_follow_location(true);
  1839. res = cli.Get("/");
  1840. ASSERT_TRUE(res);
  1841. EXPECT_EQ(StatusCode::OK_200, res->status);
  1842. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1843. }
  1844. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1845. #define REDIR_HOST "httpbingo.org"
  1846. #define REDIR_PATH "/redirect-to"
  1847. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1848. SSLClient cli(REDIR_HOST);
  1849. cli.set_follow_location(true);
  1850. auto res =
  1851. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1852. ASSERT_TRUE(res);
  1853. EXPECT_EQ(StatusCode::OK_200, res->status);
  1854. }
  1855. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1856. SSLClient cli(REDIR_HOST);
  1857. cli.set_follow_location(true);
  1858. Params params;
  1859. params.emplace("url", "http://example.com");
  1860. params.emplace("status_code", "302");
  1861. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1862. ASSERT_TRUE(res);
  1863. EXPECT_EQ(StatusCode::OK_200, res->status);
  1864. }
  1865. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1866. SSLClient cli(REDIR_HOST);
  1867. cli.set_follow_location(true);
  1868. Params params;
  1869. params.emplace("url", "http://example.com");
  1870. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1871. ASSERT_TRUE(res);
  1872. EXPECT_EQ(StatusCode::OK_200, res->status);
  1873. }
  1874. TEST(UrlWithSpace, Redirect_Online) {
  1875. SSLClient cli("edge.forgecdn.net");
  1876. cli.set_follow_location(true);
  1877. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1878. ASSERT_TRUE(res);
  1879. EXPECT_EQ(StatusCode::OK_200, res->status);
  1880. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1881. }
  1882. #endif
  1883. #if !defined(_WIN32) && !defined(_WIN64)
  1884. TEST(ReceiveSignals, Signal) {
  1885. auto setupSignalHandlers = []() {
  1886. struct sigaction act;
  1887. sigemptyset(&act.sa_mask);
  1888. act.sa_flags = SA_SIGINFO;
  1889. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1890. switch (sig) {
  1891. case SIGINT:
  1892. default: break;
  1893. }
  1894. };
  1895. ::sigaction(SIGINT, &act, nullptr);
  1896. };
  1897. Server svr;
  1898. int port = 0;
  1899. auto thread = std::thread([&]() {
  1900. setupSignalHandlers();
  1901. port = svr.bind_to_any_port(HOST);
  1902. svr.listen_after_bind();
  1903. });
  1904. auto se = detail::scope_exit([&] {
  1905. svr.stop();
  1906. thread.join();
  1907. ASSERT_FALSE(svr.is_running());
  1908. });
  1909. svr.wait_until_ready();
  1910. ASSERT_TRUE(svr.is_running());
  1911. pthread_kill(thread.native_handle(), SIGINT);
  1912. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1913. ASSERT_TRUE(svr.is_running());
  1914. }
  1915. #endif
  1916. TEST(RedirectToDifferentPort, Redirect) {
  1917. Server svr1;
  1918. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1919. res.set_content("Hello World!", "text/plain");
  1920. });
  1921. int svr1_port = 0;
  1922. auto thread1 = std::thread([&]() {
  1923. svr1_port = svr1.bind_to_any_port(HOST);
  1924. svr1.listen_after_bind();
  1925. });
  1926. Server svr2;
  1927. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1928. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1929. });
  1930. int svr2_port = 0;
  1931. auto thread2 = std::thread([&]() {
  1932. svr2_port = svr2.bind_to_any_port(HOST);
  1933. svr2.listen_after_bind();
  1934. });
  1935. auto se = detail::scope_exit([&] {
  1936. svr2.stop();
  1937. thread2.join();
  1938. svr1.stop();
  1939. thread1.join();
  1940. ASSERT_FALSE(svr2.is_running());
  1941. ASSERT_FALSE(svr1.is_running());
  1942. });
  1943. svr1.wait_until_ready();
  1944. svr2.wait_until_ready();
  1945. Client cli("localhost", svr2_port);
  1946. cli.set_follow_location(true);
  1947. auto res = cli.Get("/2");
  1948. ASSERT_TRUE(res);
  1949. EXPECT_EQ(StatusCode::OK_200, res->status);
  1950. EXPECT_EQ("Hello World!", res->body);
  1951. }
  1952. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  1953. Server svr;
  1954. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  1955. // Port number that overflows int — should not crash
  1956. res.set_redirect("http://localhost:99999999999999999999/target");
  1957. });
  1958. auto port = svr.bind_to_any_port(HOST);
  1959. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  1960. auto se = detail::scope_exit([&] {
  1961. svr.stop();
  1962. thread.join();
  1963. ASSERT_FALSE(svr.is_running());
  1964. });
  1965. svr.wait_until_ready();
  1966. Client cli(HOST, port);
  1967. cli.set_follow_location(true);
  1968. auto res = cli.Get("/redir");
  1969. // Should fail gracefully, not crash (no valid response due to bad port)
  1970. EXPECT_FALSE(res);
  1971. }
  1972. TEST(RedirectFromPageWithContent, Redirect) {
  1973. Server svr;
  1974. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1975. res.set_content("___", "text/plain");
  1976. res.set_redirect("/2");
  1977. });
  1978. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1979. res.set_content("Hello World!", "text/plain");
  1980. });
  1981. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1982. auto se = detail::scope_exit([&] {
  1983. svr.stop();
  1984. th.join();
  1985. ASSERT_FALSE(svr.is_running());
  1986. });
  1987. svr.wait_until_ready();
  1988. {
  1989. Client cli("localhost", PORT);
  1990. cli.set_follow_location(true);
  1991. std::string body;
  1992. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1993. body.append(data, data_length);
  1994. return true;
  1995. });
  1996. ASSERT_TRUE(res);
  1997. EXPECT_EQ(StatusCode::OK_200, res->status);
  1998. EXPECT_EQ("Hello World!", body);
  1999. }
  2000. {
  2001. Client cli("localhost", PORT);
  2002. std::string body;
  2003. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2004. body.append(data, data_length);
  2005. return true;
  2006. });
  2007. ASSERT_TRUE(res);
  2008. EXPECT_EQ(StatusCode::Found_302, res->status);
  2009. EXPECT_EQ("___", body);
  2010. }
  2011. }
  2012. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2013. Server svr;
  2014. auto port_str = std::to_string(PORT);
  2015. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2016. auto expected_host = "[::1]:" + port_str;
  2017. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2018. res.set_content("___", "text/plain");
  2019. // res.set_redirect("/2");
  2020. res.set_redirect(redirect_url);
  2021. });
  2022. svr.Get("/2", [&](const Request &req, Response &res) {
  2023. auto host_header = req.headers.find("Host");
  2024. ASSERT_TRUE(host_header != req.headers.end());
  2025. EXPECT_EQ(expected_host, host_header->second);
  2026. res.set_content("Hello World!", "text/plain");
  2027. });
  2028. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2029. auto se = detail::scope_exit([&] {
  2030. svr.stop();
  2031. th.join();
  2032. ASSERT_FALSE(svr.is_running());
  2033. });
  2034. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2035. // actually starts anything, so the condition !svr.is_running() will
  2036. // always remain true, and the loop never stops.
  2037. // This basically counts how many milliseconds have passed since the
  2038. // call to svr.listen(), and if after 5 seconds nothing started yet
  2039. // aborts the test.
  2040. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2041. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2042. ASSERT_LT(milliseconds, 5000U);
  2043. }
  2044. {
  2045. Client cli("::1", PORT);
  2046. cli.set_follow_location(true);
  2047. std::string body;
  2048. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2049. body.append(data, data_length);
  2050. return true;
  2051. });
  2052. ASSERT_TRUE(res);
  2053. EXPECT_EQ(StatusCode::OK_200, res->status);
  2054. EXPECT_EQ("Hello World!", body);
  2055. }
  2056. {
  2057. Client cli("::1", PORT);
  2058. std::string body;
  2059. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2060. body.append(data, data_length);
  2061. return true;
  2062. });
  2063. ASSERT_TRUE(res);
  2064. EXPECT_EQ(StatusCode::Found_302, res->status);
  2065. EXPECT_EQ("___", body);
  2066. }
  2067. }
  2068. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2069. Server svr;
  2070. svr.Get("/foo", [](const Request &req, Response &res) {
  2071. auto a = req.params.find("a");
  2072. if (a != req.params.end()) {
  2073. res.set_content((*a).second, "text/plain");
  2074. res.status = StatusCode::OK_200;
  2075. } else {
  2076. res.status = StatusCode::BadRequest_400;
  2077. }
  2078. });
  2079. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2080. auto se = detail::scope_exit([&] {
  2081. svr.stop();
  2082. thread.join();
  2083. ASSERT_FALSE(svr.is_running());
  2084. });
  2085. svr.wait_until_ready();
  2086. {
  2087. Client cli(HOST, PORT);
  2088. cli.set_path_encode(false);
  2089. auto res = cli.Get("/foo?a=explicitly+encoded");
  2090. ASSERT_TRUE(res);
  2091. EXPECT_EQ(StatusCode::OK_200, res->status);
  2092. // This expects it back with a space, as the `+` won't have been
  2093. // url-encoded, and server-side the params get decoded turning `+`
  2094. // into spaces.
  2095. EXPECT_EQ("explicitly encoded", res->body);
  2096. }
  2097. }
  2098. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2099. Server svr;
  2100. svr.Get("/", [](const Request &req, Response &) {
  2101. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2102. });
  2103. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2104. auto se = detail::scope_exit([&] {
  2105. svr.stop();
  2106. thread.join();
  2107. ASSERT_FALSE(svr.is_running());
  2108. });
  2109. svr.wait_until_ready();
  2110. {
  2111. Client cli(HOST, PORT);
  2112. cli.set_path_encode(false);
  2113. auto res = cli.Get("/?something=%0A");
  2114. ASSERT_TRUE(res);
  2115. EXPECT_EQ(StatusCode::OK_200, res->status);
  2116. }
  2117. }
  2118. TEST(BindServerTest, BindDualStack) {
  2119. Server svr;
  2120. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2121. res.set_content("Hello World!", "text/plain");
  2122. });
  2123. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2124. auto se = detail::scope_exit([&] {
  2125. svr.stop();
  2126. thread.join();
  2127. ASSERT_FALSE(svr.is_running());
  2128. });
  2129. svr.wait_until_ready();
  2130. {
  2131. Client cli("127.0.0.1", PORT);
  2132. auto res = cli.Get("/1");
  2133. ASSERT_TRUE(res);
  2134. EXPECT_EQ(StatusCode::OK_200, res->status);
  2135. EXPECT_EQ("Hello World!", res->body);
  2136. }
  2137. {
  2138. Client cli("::1", PORT);
  2139. auto res = cli.Get("/1");
  2140. ASSERT_TRUE(res);
  2141. EXPECT_EQ(StatusCode::OK_200, res->status);
  2142. EXPECT_EQ("Hello World!", res->body);
  2143. }
  2144. }
  2145. TEST(BindServerTest, BindAndListenSeparately) {
  2146. Server svr;
  2147. int port = svr.bind_to_any_port("0.0.0.0");
  2148. ASSERT_TRUE(svr.is_valid());
  2149. ASSERT_TRUE(port > 0);
  2150. svr.stop();
  2151. }
  2152. #ifdef CPPHTTPLIB_SSL_ENABLED
  2153. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2154. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2155. CLIENT_CA_CERT_DIR);
  2156. int port = svr.bind_to_any_port("0.0.0.0");
  2157. ASSERT_TRUE(svr.is_valid());
  2158. ASSERT_TRUE(port > 0);
  2159. svr.stop();
  2160. }
  2161. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2162. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2163. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2164. int port = svr.bind_to_any_port("0.0.0.0");
  2165. ASSERT_TRUE(svr.is_valid());
  2166. ASSERT_TRUE(port > 0);
  2167. svr.stop();
  2168. }
  2169. TEST(BindServerTest, UpdateCertsPem) {
  2170. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2171. int port = svr.bind_to_any_port("0.0.0.0");
  2172. ASSERT_TRUE(svr.is_valid());
  2173. ASSERT_TRUE(port > 0);
  2174. // Read PEM files
  2175. std::string cert_pem, key_pem, ca_pem;
  2176. read_file(SERVER_CERT_FILE, cert_pem);
  2177. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2178. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2179. // Update server certificates using PEM API
  2180. ASSERT_TRUE(
  2181. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2182. ASSERT_TRUE(svr.is_valid());
  2183. svr.stop();
  2184. }
  2185. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2186. // Start server with client CA (enables client auth)
  2187. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2188. ASSERT_TRUE(svr.is_valid());
  2189. bool handler_called = false;
  2190. svr.Get("/test", [&](const Request &req, Response &res) {
  2191. handler_called = true;
  2192. // Verify client certificate is present
  2193. auto cert = req.peer_cert();
  2194. EXPECT_TRUE(static_cast<bool>(cert));
  2195. res.set_content("ok", "text/plain");
  2196. });
  2197. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2198. auto se = detail::scope_exit([&] {
  2199. svr.stop();
  2200. t.join();
  2201. ASSERT_FALSE(svr.is_running());
  2202. });
  2203. svr.wait_until_ready();
  2204. // Read PEM files
  2205. std::string cert_pem, key_pem, ca_pem;
  2206. read_file(SERVER_CERT_FILE, cert_pem);
  2207. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2208. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2209. // Update server certificates and client CA using PEM API while server running
  2210. ASSERT_TRUE(
  2211. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2212. // Connect with client certificate
  2213. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2214. cli.enable_server_certificate_verification(false);
  2215. cli.set_connection_timeout(30);
  2216. auto res = cli.Get("/test");
  2217. ASSERT_TRUE(res);
  2218. ASSERT_EQ(StatusCode::OK_200, res->status);
  2219. ASSERT_TRUE(handler_called);
  2220. EXPECT_EQ("ok", res->body);
  2221. }
  2222. #endif
  2223. TEST(ErrorHandlerTest, ContentLength) {
  2224. Server svr;
  2225. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2226. res.status = StatusCode::OK_200;
  2227. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2228. "text/html"); // <= Content-Length still 13
  2229. });
  2230. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2231. res.set_content("Hello World!\n", "text/plain");
  2232. res.status = 524;
  2233. });
  2234. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2235. auto se = detail::scope_exit([&] {
  2236. svr.stop();
  2237. thread.join();
  2238. ASSERT_FALSE(svr.is_running());
  2239. });
  2240. svr.wait_until_ready();
  2241. {
  2242. Client cli(HOST, PORT);
  2243. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2244. ASSERT_TRUE(res);
  2245. EXPECT_EQ(StatusCode::OK_200, res->status);
  2246. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2247. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2248. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2249. }
  2250. }
  2251. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2252. TEST(ExceptionTest, WithoutExceptionHandler) {
  2253. Server svr;
  2254. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2255. throw std::runtime_error("exception...");
  2256. });
  2257. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2258. throw std::runtime_error("exception\r\n...");
  2259. });
  2260. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2261. auto se = detail::scope_exit([&] {
  2262. svr.stop();
  2263. listen_thread.join();
  2264. ASSERT_FALSE(svr.is_running());
  2265. });
  2266. svr.wait_until_ready();
  2267. Client cli("localhost", PORT);
  2268. {
  2269. auto res = cli.Get("/exception");
  2270. ASSERT_TRUE(res);
  2271. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2272. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2273. }
  2274. {
  2275. auto res = cli.Get("/unknown");
  2276. ASSERT_TRUE(res);
  2277. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2278. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2279. }
  2280. }
  2281. TEST(ExceptionTest, WithExceptionHandler) {
  2282. Server svr;
  2283. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2284. std::exception_ptr ep) {
  2285. EXPECT_FALSE(ep == nullptr);
  2286. try {
  2287. std::rethrow_exception(ep);
  2288. } catch (std::exception &e) {
  2289. EXPECT_EQ("abc", std::string(e.what()));
  2290. } catch (...) {}
  2291. res.status = StatusCode::InternalServerError_500;
  2292. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2293. "text/html"); // <= Content-Length still 13 at this point
  2294. });
  2295. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2296. res.set_content("Hello World!\n", "text/plain");
  2297. throw std::runtime_error("abc");
  2298. });
  2299. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2300. auto se = detail::scope_exit([&] {
  2301. svr.stop();
  2302. thread.join();
  2303. ASSERT_FALSE(svr.is_running());
  2304. });
  2305. svr.wait_until_ready();
  2306. for (size_t i = 0; i < 10; i++) {
  2307. Client cli(HOST, PORT);
  2308. for (size_t j = 0; j < 100; j++) {
  2309. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2310. ASSERT_TRUE(res);
  2311. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2312. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2313. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2314. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2315. }
  2316. cli.set_keep_alive(true);
  2317. for (size_t j = 0; j < 100; j++) {
  2318. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2319. ASSERT_TRUE(res);
  2320. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2321. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2322. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2323. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2324. }
  2325. }
  2326. }
  2327. TEST(ExceptionTest, AndErrorHandler) {
  2328. Server svr;
  2329. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2330. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2331. });
  2332. svr.set_exception_handler(
  2333. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2334. EXPECT_FALSE(ep == nullptr);
  2335. try {
  2336. std::rethrow_exception(ep);
  2337. } catch (std::exception &e) {
  2338. res.set_content(e.what(), "text/html");
  2339. } catch (...) {}
  2340. res.status = StatusCode::InternalServerError_500;
  2341. });
  2342. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2343. throw std::runtime_error("EXCEPTION");
  2344. });
  2345. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2346. res.set_content("ERROR", "text/html");
  2347. res.status = StatusCode::InternalServerError_500;
  2348. });
  2349. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2350. auto se = detail::scope_exit([&] {
  2351. svr.stop();
  2352. thread.join();
  2353. ASSERT_FALSE(svr.is_running());
  2354. });
  2355. svr.wait_until_ready();
  2356. Client cli(HOST, PORT);
  2357. {
  2358. auto res = cli.Get("/exception");
  2359. ASSERT_TRUE(res);
  2360. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2361. EXPECT_EQ("EXCEPTION", res->body);
  2362. }
  2363. {
  2364. auto res = cli.Get("/error");
  2365. ASSERT_TRUE(res);
  2366. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2367. EXPECT_EQ("ERROR", res->body);
  2368. }
  2369. {
  2370. auto res = cli.Get("/invalid");
  2371. ASSERT_TRUE(res);
  2372. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2373. EXPECT_EQ("NOT_FOUND", res->body);
  2374. }
  2375. }
  2376. #endif
  2377. TEST(NoContentTest, ContentLength) {
  2378. Server svr;
  2379. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2380. res.status = StatusCode::NoContent_204;
  2381. });
  2382. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2383. auto se = detail::scope_exit([&] {
  2384. svr.stop();
  2385. thread.join();
  2386. ASSERT_FALSE(svr.is_running());
  2387. });
  2388. svr.wait_until_ready();
  2389. {
  2390. Client cli(HOST, PORT);
  2391. auto res = cli.Get("/hi");
  2392. ASSERT_TRUE(res);
  2393. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2394. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2395. }
  2396. }
  2397. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2398. #ifdef CPPHTTPLIB_SSL_ENABLED
  2399. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2400. ASSERT_TRUE(svr.is_valid());
  2401. #else
  2402. Server svr;
  2403. #endif
  2404. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2405. if (req.path == "/routing_handler") {
  2406. res.set_header("PRE_ROUTING", "on");
  2407. res.set_content("Routing Handler", "text/plain");
  2408. return httplib::Server::HandlerResponse::Handled;
  2409. }
  2410. return httplib::Server::HandlerResponse::Unhandled;
  2411. });
  2412. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2413. res.set_content("Error", "text/html");
  2414. });
  2415. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2416. if (req.path == "/routing_handler") {
  2417. res.set_header("POST_ROUTING", "on");
  2418. }
  2419. });
  2420. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2421. res.set_content("Hello World!\n", "text/plain");
  2422. });
  2423. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2424. auto se = detail::scope_exit([&] {
  2425. svr.stop();
  2426. thread.join();
  2427. ASSERT_FALSE(svr.is_running());
  2428. });
  2429. svr.wait_until_ready();
  2430. {
  2431. #ifdef CPPHTTPLIB_SSL_ENABLED
  2432. SSLClient cli(HOST, PORT);
  2433. cli.enable_server_certificate_verification(false);
  2434. #else
  2435. Client cli(HOST, PORT);
  2436. #endif
  2437. auto res = cli.Get("/routing_handler");
  2438. ASSERT_TRUE(res);
  2439. EXPECT_EQ(StatusCode::OK_200, res->status);
  2440. EXPECT_EQ("Routing Handler", res->body);
  2441. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2442. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2443. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2444. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2445. }
  2446. {
  2447. #ifdef CPPHTTPLIB_SSL_ENABLED
  2448. SSLClient cli(HOST, PORT);
  2449. cli.enable_server_certificate_verification(false);
  2450. #else
  2451. Client cli(HOST, PORT);
  2452. #endif
  2453. auto res = cli.Get("/hi");
  2454. ASSERT_TRUE(res);
  2455. EXPECT_EQ(StatusCode::OK_200, res->status);
  2456. EXPECT_EQ("Hello World!\n", res->body);
  2457. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2458. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2459. }
  2460. {
  2461. #ifdef CPPHTTPLIB_SSL_ENABLED
  2462. SSLClient cli(HOST, PORT);
  2463. cli.enable_server_certificate_verification(false);
  2464. #else
  2465. Client cli(HOST, PORT);
  2466. #endif
  2467. auto res = cli.Get("/aaa");
  2468. ASSERT_TRUE(res);
  2469. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2470. EXPECT_EQ("Error", res->body);
  2471. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2472. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2473. }
  2474. }
  2475. TEST(RequestHandlerTest, PreRequestHandler) {
  2476. auto route_path = "/user/:user";
  2477. Server svr;
  2478. svr.Get("/hi", [](const Request &, Response &res) {
  2479. res.set_content("hi", "text/plain");
  2480. });
  2481. svr.Get(route_path, [](const Request &req, Response &res) {
  2482. res.set_content(req.path_params.at("user"), "text/plain");
  2483. });
  2484. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2485. if (req.matched_route == route_path) {
  2486. auto user = req.path_params.at("user");
  2487. if (user != "john") {
  2488. res.status = StatusCode::Forbidden_403;
  2489. res.set_content("error", "text/html");
  2490. return Server::HandlerResponse::Handled;
  2491. }
  2492. }
  2493. return Server::HandlerResponse::Unhandled;
  2494. });
  2495. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2496. auto se = detail::scope_exit([&] {
  2497. svr.stop();
  2498. thread.join();
  2499. ASSERT_FALSE(svr.is_running());
  2500. });
  2501. svr.wait_until_ready();
  2502. Client cli(HOST, PORT);
  2503. {
  2504. auto res = cli.Get("/hi");
  2505. ASSERT_TRUE(res);
  2506. EXPECT_EQ(StatusCode::OK_200, res->status);
  2507. EXPECT_EQ("hi", res->body);
  2508. }
  2509. {
  2510. auto res = cli.Get("/user/john");
  2511. ASSERT_TRUE(res);
  2512. EXPECT_EQ(StatusCode::OK_200, res->status);
  2513. EXPECT_EQ("john", res->body);
  2514. }
  2515. {
  2516. auto res = cli.Get("/user/invalid-user");
  2517. ASSERT_TRUE(res);
  2518. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2519. EXPECT_EQ("error", res->body);
  2520. }
  2521. }
  2522. TEST(AnyTest, BasicOperations) {
  2523. // Default construction
  2524. httplib::any a;
  2525. EXPECT_FALSE(a.has_value());
  2526. // Value construction and any_cast (pointer form, noexcept)
  2527. httplib::any b(42);
  2528. EXPECT_TRUE(b.has_value());
  2529. auto *p = httplib::any_cast<int>(&b);
  2530. ASSERT_NE(nullptr, p);
  2531. EXPECT_EQ(42, *p);
  2532. // Type mismatch → nullptr
  2533. auto *q = httplib::any_cast<std::string>(&b);
  2534. EXPECT_EQ(nullptr, q);
  2535. // any_cast (value form) succeeds
  2536. EXPECT_EQ(42, httplib::any_cast<int>(b));
  2537. // any_cast (value form) throws on type mismatch
  2538. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2539. EXPECT_THROW(httplib::any_cast<std::string>(b), httplib::bad_any_cast);
  2540. #endif
  2541. // Copy
  2542. httplib::any c = b;
  2543. EXPECT_EQ(42, httplib::any_cast<int>(c));
  2544. // Move
  2545. httplib::any d = std::move(c);
  2546. EXPECT_EQ(42, httplib::any_cast<int>(d));
  2547. // Assignment with different type
  2548. b = std::string("hello");
  2549. EXPECT_EQ("hello", httplib::any_cast<std::string>(b));
  2550. // Reset
  2551. b.reset();
  2552. EXPECT_FALSE(b.has_value());
  2553. }
  2554. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2555. struct AuthCtx {
  2556. std::string user_id;
  2557. };
  2558. Server svr;
  2559. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2560. res.user_data["auth"] = AuthCtx{"alice"};
  2561. return Server::HandlerResponse::Unhandled;
  2562. });
  2563. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2564. auto *ctx = httplib::any_cast<AuthCtx>(&res.user_data["auth"]);
  2565. ASSERT_NE(nullptr, ctx);
  2566. res.set_content("Hello " + ctx->user_id, "text/plain");
  2567. });
  2568. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2569. auto se = detail::scope_exit([&] {
  2570. svr.stop();
  2571. thread.join();
  2572. ASSERT_FALSE(svr.is_running());
  2573. });
  2574. svr.wait_until_ready();
  2575. Client cli(HOST, PORT);
  2576. auto res = cli.Get("/me");
  2577. ASSERT_TRUE(res);
  2578. EXPECT_EQ(StatusCode::OK_200, res->status);
  2579. EXPECT_EQ("Hello alice", res->body);
  2580. }
  2581. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2582. struct RoleCtx {
  2583. std::string role;
  2584. };
  2585. Server svr;
  2586. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2587. res.user_data["role"] = RoleCtx{"admin"};
  2588. return Server::HandlerResponse::Unhandled;
  2589. });
  2590. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2591. auto *ctx = httplib::any_cast<RoleCtx>(&res.user_data["role"]);
  2592. ASSERT_NE(nullptr, ctx);
  2593. res.set_content(ctx->role, "text/plain");
  2594. });
  2595. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2596. auto se = detail::scope_exit([&] {
  2597. svr.stop();
  2598. thread.join();
  2599. ASSERT_FALSE(svr.is_running());
  2600. });
  2601. svr.wait_until_ready();
  2602. Client cli(HOST, PORT);
  2603. auto res = cli.Get("/role");
  2604. ASSERT_TRUE(res);
  2605. EXPECT_EQ(StatusCode::OK_200, res->status);
  2606. EXPECT_EQ("admin", res->body);
  2607. }
  2608. TEST(InvalidFormatTest, StatusCode) {
  2609. Server svr;
  2610. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2611. res.set_content("Hello World!\n", "text/plain");
  2612. res.status = 9999; // Status should be a three-digit code...
  2613. });
  2614. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2615. auto se = detail::scope_exit([&] {
  2616. svr.stop();
  2617. thread.join();
  2618. ASSERT_FALSE(svr.is_running());
  2619. });
  2620. svr.wait_until_ready();
  2621. {
  2622. Client cli(HOST, PORT);
  2623. auto res = cli.Get("/hi");
  2624. ASSERT_FALSE(res);
  2625. }
  2626. }
  2627. TEST(URLFragmentTest, WithFragment) {
  2628. Server svr;
  2629. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2630. EXPECT_TRUE(req.target == "/hi");
  2631. });
  2632. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2633. auto se = detail::scope_exit([&] {
  2634. svr.stop();
  2635. thread.join();
  2636. ASSERT_FALSE(svr.is_running());
  2637. });
  2638. svr.wait_until_ready();
  2639. {
  2640. Client cli(HOST, PORT);
  2641. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2642. EXPECT_TRUE(res);
  2643. EXPECT_EQ(StatusCode::OK_200, res->status);
  2644. res = cli.Get("/hi%23key1=val1=key2=val2");
  2645. EXPECT_TRUE(res);
  2646. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2647. }
  2648. }
  2649. TEST(HeaderWriter, SetHeaderWriter) {
  2650. Server svr;
  2651. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2652. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2653. return detail::write_headers(strm, hdrs);
  2654. });
  2655. svr.Get("/hi", [](const Request &req, Response &res) {
  2656. auto it = req.headers.find("CustomClientHeader");
  2657. EXPECT_TRUE(it != req.headers.end());
  2658. EXPECT_EQ(it->second, "CustomClientValue");
  2659. res.set_content("Hello World!\n", "text/plain");
  2660. });
  2661. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2662. auto se = detail::scope_exit([&] {
  2663. svr.stop();
  2664. thread.join();
  2665. ASSERT_FALSE(svr.is_running());
  2666. });
  2667. svr.wait_until_ready();
  2668. {
  2669. Client cli(HOST, PORT);
  2670. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2671. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2672. return detail::write_headers(strm, hdrs);
  2673. });
  2674. auto res = cli.Get("/hi");
  2675. EXPECT_TRUE(res);
  2676. EXPECT_EQ(StatusCode::OK_200, res->status);
  2677. auto it = res->headers.find("CustomServerHeader");
  2678. EXPECT_TRUE(it != res->headers.end());
  2679. EXPECT_EQ(it->second, "CustomServerValue");
  2680. }
  2681. }
  2682. class ServerTest : public ::testing::Test {
  2683. protected:
  2684. ServerTest()
  2685. : cli_(HOST, PORT)
  2686. #ifdef CPPHTTPLIB_SSL_ENABLED
  2687. ,
  2688. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2689. #endif
  2690. {
  2691. #ifdef CPPHTTPLIB_SSL_ENABLED
  2692. cli_.enable_server_certificate_verification(false);
  2693. #endif
  2694. // Allow LARGE_DATA (100MB) responses
  2695. cli_.set_payload_max_length(200 * 1024 * 1024);
  2696. }
  2697. virtual void SetUp() {
  2698. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2699. svr_.set_payload_max_length(200 * 1024 * 1024);
  2700. svr_.set_mount_point("/", "./www");
  2701. svr_.set_mount_point("/mount", "./www2");
  2702. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2703. svr_.Get("/hi",
  2704. [&](const Request & /*req*/, Response &res) {
  2705. res.set_content("Hello World!", "text/plain");
  2706. })
  2707. .Get("/file_content",
  2708. [&](const Request & /*req*/, Response &res) {
  2709. res.set_file_content("./www/dir/test.html");
  2710. })
  2711. .Get("/file_content_with_content_type",
  2712. [&](const Request & /*req*/, Response &res) {
  2713. res.set_file_content("./www/file", "text/plain");
  2714. })
  2715. .Get("/invalid_file_content",
  2716. [&](const Request & /*req*/, Response &res) {
  2717. res.set_file_content("./www/dir/invalid_file_path");
  2718. })
  2719. .Get("/http_response_splitting",
  2720. [&](const Request & /*req*/, Response &res) {
  2721. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2722. EXPECT_EQ(0U, res.headers.size());
  2723. EXPECT_FALSE(res.has_header("a"));
  2724. res.set_header("a", "1\nSet-Cookie: a=1");
  2725. EXPECT_EQ(0U, res.headers.size());
  2726. EXPECT_FALSE(res.has_header("a"));
  2727. res.set_header("a", "1\rSet-Cookie: a=1");
  2728. EXPECT_EQ(0U, res.headers.size());
  2729. EXPECT_FALSE(res.has_header("a"));
  2730. res.set_header("a\r\nb", "0");
  2731. EXPECT_EQ(0U, res.headers.size());
  2732. EXPECT_FALSE(res.has_header("a"));
  2733. res.set_header("a\rb", "0");
  2734. EXPECT_EQ(0U, res.headers.size());
  2735. EXPECT_FALSE(res.has_header("a"));
  2736. res.set_header("a\nb", "0");
  2737. EXPECT_EQ(0U, res.headers.size());
  2738. EXPECT_FALSE(res.has_header("a"));
  2739. res.set_redirect("1\r\nSet-Cookie: a=1");
  2740. EXPECT_EQ(0U, res.headers.size());
  2741. EXPECT_FALSE(res.has_header("Location"));
  2742. })
  2743. .Get("/slow",
  2744. [&](const Request & /*req*/, Response &res) {
  2745. std::this_thread::sleep_for(std::chrono::seconds(2));
  2746. res.set_content("slow", "text/plain");
  2747. })
  2748. #if 0
  2749. .Post("/slowpost",
  2750. [&](const Request & /*req*/, Response &res) {
  2751. std::this_thread::sleep_for(std::chrono::seconds(2));
  2752. res.set_content("slow", "text/plain");
  2753. })
  2754. #endif
  2755. .Get("/remote_addr",
  2756. [&](const Request &req, Response &res) {
  2757. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2758. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2759. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2760. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2761. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2762. #endif
  2763. res.set_content(req.remote_addr, "text/plain");
  2764. })
  2765. .Get("/local_addr",
  2766. [&](const Request &req, Response &res) {
  2767. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2768. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2769. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2770. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2771. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2772. #endif
  2773. auto local_addr = req.local_addr;
  2774. auto local_port = std::to_string(req.local_port);
  2775. res.set_content(local_addr.append(":").append(local_port),
  2776. "text/plain");
  2777. })
  2778. .Get("/endwith%",
  2779. [&](const Request & /*req*/, Response &res) {
  2780. res.set_content("Hello World!", "text/plain");
  2781. })
  2782. .Get("/a\\+\\+b",
  2783. [&](const Request &req, Response &res) {
  2784. ASSERT_TRUE(req.has_param("a +b"));
  2785. auto val = req.get_param_value("a +b");
  2786. res.set_content(val, "text/plain");
  2787. })
  2788. .Get("/", [&](const Request & /*req*/,
  2789. Response &res) { res.set_redirect("/hi"); })
  2790. .Post("/1",
  2791. [](const Request & /*req*/, Response &res) {
  2792. res.set_redirect("/2", StatusCode::SeeOther_303);
  2793. })
  2794. .Get("/2",
  2795. [](const Request & /*req*/, Response &res) {
  2796. res.set_content("redirected.", "text/plain");
  2797. res.status = StatusCode::OK_200;
  2798. })
  2799. .Post("/person",
  2800. [&](const Request &req, Response &res) {
  2801. if (req.has_param("name") && req.has_param("note")) {
  2802. persons_[req.get_param_value("name")] =
  2803. req.get_param_value("note");
  2804. } else {
  2805. res.status = StatusCode::BadRequest_400;
  2806. }
  2807. })
  2808. .Put("/person",
  2809. [&](const Request &req, Response &res) {
  2810. if (req.has_param("name") && req.has_param("note")) {
  2811. persons_[req.get_param_value("name")] =
  2812. req.get_param_value("note");
  2813. } else {
  2814. res.status = StatusCode::BadRequest_400;
  2815. }
  2816. })
  2817. .Get("/person/(.*)",
  2818. [&](const Request &req, Response &res) {
  2819. string name = req.matches[1];
  2820. if (persons_.find(name) != persons_.end()) {
  2821. auto note = persons_[name];
  2822. res.set_content(note, "text/plain");
  2823. } else {
  2824. res.status = StatusCode::NotFound_404;
  2825. }
  2826. })
  2827. .Delete("/person",
  2828. [&](const Request &req, Response &res) {
  2829. if (req.has_param("name")) {
  2830. string name = req.get_param_value("name");
  2831. if (persons_.find(name) != persons_.end()) {
  2832. persons_.erase(name);
  2833. res.set_content("DELETED", "text/plain");
  2834. } else {
  2835. res.status = StatusCode::NotFound_404;
  2836. }
  2837. } else {
  2838. res.status = StatusCode::BadRequest_400;
  2839. }
  2840. })
  2841. .Post("/x-www-form-urlencoded-json",
  2842. [&](const Request &req, Response &res) {
  2843. auto json = req.get_param_value("json");
  2844. ASSERT_EQ(JSON_DATA, json);
  2845. res.set_content(json, "appliation/json");
  2846. res.status = StatusCode::OK_200;
  2847. })
  2848. .Get("/streamed-chunked",
  2849. [&](const Request & /*req*/, Response &res) {
  2850. res.set_chunked_content_provider(
  2851. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2852. sink.os << "123";
  2853. sink.os << "456";
  2854. sink.os << "789";
  2855. sink.done();
  2856. return true;
  2857. });
  2858. })
  2859. .Get("/streamed-chunked-with-prohibited-trailer",
  2860. [&](const Request & /*req*/, Response &res) {
  2861. auto i = new int(0);
  2862. // Declare both a prohibited trailer (Content-Length) and an
  2863. // allowed one
  2864. res.set_header("Trailer", "Content-Length, X-Allowed");
  2865. res.set_chunked_content_provider(
  2866. "text/plain",
  2867. [i](size_t /*offset*/, DataSink &sink) {
  2868. switch (*i) {
  2869. case 0: sink.os << "123"; break;
  2870. case 1: sink.os << "456"; break;
  2871. case 2: sink.os << "789"; break;
  2872. case 3: {
  2873. sink.done_with_trailer(
  2874. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2875. } break;
  2876. }
  2877. (*i)++;
  2878. return true;
  2879. },
  2880. [i](bool success) {
  2881. EXPECT_TRUE(success);
  2882. delete i;
  2883. });
  2884. })
  2885. .Get("/streamed-chunked2",
  2886. [&](const Request & /*req*/, Response &res) {
  2887. auto i = new int(0);
  2888. res.set_chunked_content_provider(
  2889. "text/plain",
  2890. [i](size_t /*offset*/, DataSink &sink) {
  2891. switch (*i) {
  2892. case 0: sink.os << "123"; break;
  2893. case 1: sink.os << "456"; break;
  2894. case 2: sink.os << "789"; break;
  2895. case 3: sink.done(); break;
  2896. }
  2897. (*i)++;
  2898. return true;
  2899. },
  2900. [i](bool success) {
  2901. EXPECT_TRUE(success);
  2902. delete i;
  2903. });
  2904. })
  2905. .Get("/streamed-chunked-with-trailer",
  2906. [&](const Request & /*req*/, Response &res) {
  2907. auto i = new int(0);
  2908. res.set_header("Trailer", "Dummy1, Dummy2");
  2909. res.set_chunked_content_provider(
  2910. "text/plain",
  2911. [i](size_t /*offset*/, DataSink &sink) {
  2912. switch (*i) {
  2913. case 0: sink.os << "123"; break;
  2914. case 1: sink.os << "456"; break;
  2915. case 2: sink.os << "789"; break;
  2916. case 3: {
  2917. sink.done_with_trailer(
  2918. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2919. } break;
  2920. }
  2921. (*i)++;
  2922. return true;
  2923. },
  2924. [i](bool success) {
  2925. EXPECT_TRUE(success);
  2926. delete i;
  2927. });
  2928. })
  2929. .Get("/streamed",
  2930. [&](const Request & /*req*/, Response &res) {
  2931. res.set_content_provider(
  2932. 6, "text/plain",
  2933. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2934. sink.os << (offset < 3 ? "a" : "b");
  2935. return true;
  2936. });
  2937. })
  2938. .Get("/streamed-with-range",
  2939. [&](const Request &req, Response &res) {
  2940. auto data = new std::string("abcdefg");
  2941. res.set_content_provider(
  2942. data->size(), "text/plain",
  2943. [data](size_t offset, size_t length, DataSink &sink) {
  2944. size_t DATA_CHUNK_SIZE = 4;
  2945. const auto &d = *data;
  2946. auto out_len =
  2947. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2948. auto ret =
  2949. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2950. EXPECT_TRUE(ret);
  2951. return true;
  2952. },
  2953. [data, &req](bool success) {
  2954. EXPECT_EQ(success, !req.has_param("error"));
  2955. delete data;
  2956. });
  2957. })
  2958. .Get("/streamed-cancel",
  2959. [&](const Request & /*req*/, Response &res) {
  2960. res.set_content_provider(
  2961. size_t(-1), "text/plain",
  2962. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2963. sink.os << "data_chunk";
  2964. return true;
  2965. });
  2966. })
  2967. .Get("/regex-with-delimiter",
  2968. [&](const Request &req, Response & /*res*/) {
  2969. ASSERT_TRUE(req.has_param("key"));
  2970. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2971. })
  2972. .Get("/with-range",
  2973. [&](const Request & /*req*/, Response &res) {
  2974. res.set_content("abcdefg", "text/plain");
  2975. })
  2976. .Get("/test-start-time",
  2977. [&](const Request &req, Response & /*res*/) {
  2978. EXPECT_NE(req.start_time_,
  2979. std::chrono::steady_clock::time_point::min());
  2980. })
  2981. .Get("/with-range-customized-response",
  2982. [&](const Request & /*req*/, Response &res) {
  2983. res.status = StatusCode::BadRequest_400;
  2984. res.set_content(JSON_DATA, "application/json");
  2985. })
  2986. .Post("/chunked",
  2987. [&](const Request &req, Response & /*res*/) {
  2988. EXPECT_EQ(req.body, "dechunked post body");
  2989. })
  2990. .Post("/large-chunked",
  2991. [&](const Request &req, Response & /*res*/) {
  2992. std::string expected(6 * 30 * 1024u, 'a');
  2993. EXPECT_EQ(req.body, expected);
  2994. })
  2995. .Post("/multipart",
  2996. [&](const Request &req, Response & /*res*/) {
  2997. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2998. req.form.get_field_count("text2") +
  2999. req.form.get_field_count("file3") +
  3000. req.form.get_field_count("file4"));
  3001. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3002. req.form.get_file_count("file2"));
  3003. ASSERT_TRUE(!req.form.has_file("???"));
  3004. ASSERT_TRUE(!req.form.has_field("???"));
  3005. ASSERT_TRUE(req.body.empty());
  3006. {
  3007. const auto &text = req.form.get_field("text1");
  3008. EXPECT_EQ("text default", text);
  3009. }
  3010. {
  3011. const auto &text = req.form.get_field("text2");
  3012. EXPECT_EQ("aωb", text);
  3013. }
  3014. {
  3015. const auto &file = req.form.get_file("file1");
  3016. EXPECT_EQ("hello.txt", file.filename);
  3017. EXPECT_EQ("text/plain", file.content_type);
  3018. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3019. }
  3020. {
  3021. const auto &file = req.form.get_file("file2");
  3022. EXPECT_EQ("world.json", file.filename);
  3023. EXPECT_EQ("application/json", file.content_type);
  3024. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3025. }
  3026. {
  3027. const auto &text = req.form.get_field("file3");
  3028. EXPECT_EQ(0u, text.size());
  3029. }
  3030. {
  3031. const auto &text = req.form.get_field("file4");
  3032. EXPECT_EQ(0u, text.size());
  3033. }
  3034. })
  3035. .Post("/multipart/multi_file_values",
  3036. [&](const Request &req, Response & /*res*/) {
  3037. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3038. req.form.get_field_count("multi_text1"));
  3039. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3040. ASSERT_TRUE(!req.form.has_file("???"));
  3041. ASSERT_TRUE(!req.form.has_field("???"));
  3042. ASSERT_TRUE(req.body.empty());
  3043. {
  3044. const auto &text = req.form.get_field("text");
  3045. EXPECT_EQ("default text", text);
  3046. }
  3047. {
  3048. const auto &text1_values = req.form.get_fields("multi_text1");
  3049. EXPECT_EQ(2u, text1_values.size());
  3050. EXPECT_EQ("aaaaa", text1_values[0]);
  3051. EXPECT_EQ("bbbbb", text1_values[1]);
  3052. }
  3053. {
  3054. const auto &file1_values = req.form.get_files("multi_file1");
  3055. EXPECT_EQ(2u, file1_values.size());
  3056. auto file1 = file1_values[0];
  3057. EXPECT_EQ(file1.filename, "hello.txt");
  3058. EXPECT_EQ(file1.content_type, "text/plain");
  3059. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3060. auto file2 = file1_values[1];
  3061. EXPECT_EQ(file2.filename, "world.json");
  3062. EXPECT_EQ(file2.content_type, "application/json");
  3063. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3064. }
  3065. })
  3066. .Post("/empty",
  3067. [&](const Request &req, Response &res) {
  3068. EXPECT_EQ(req.body, "");
  3069. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3070. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3071. res.set_content("empty", "text/plain");
  3072. })
  3073. .Post("/empty-no-content-type",
  3074. [&](const Request &req, Response &res) {
  3075. EXPECT_EQ(req.body, "");
  3076. EXPECT_FALSE(req.has_header("Content-Type"));
  3077. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3078. res.set_content("empty-no-content-type", "text/plain");
  3079. })
  3080. .Post("/path-only",
  3081. [&](const Request &req, Response &res) {
  3082. EXPECT_EQ(req.body, "");
  3083. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3084. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3085. res.set_content("path-only", "text/plain");
  3086. })
  3087. .Post("/path-headers-only",
  3088. [&](const Request &req, Response &res) {
  3089. EXPECT_EQ(req.body, "");
  3090. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3091. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3092. EXPECT_EQ("world", req.get_header_value("hello"));
  3093. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3094. res.set_content("path-headers-only", "text/plain");
  3095. })
  3096. .Post("/post-large",
  3097. [&](const Request &req, Response &res) {
  3098. EXPECT_EQ(req.body, LARGE_DATA);
  3099. res.set_content(req.body, "text/plain");
  3100. })
  3101. .Post("/post-loopback",
  3102. [&](const Request &, Response &res,
  3103. ContentReader const &content_reader) {
  3104. std::string body;
  3105. content_reader([&](const char *data, size_t data_length) {
  3106. body.append(data, data_length);
  3107. return true;
  3108. });
  3109. res.set_content(body, "text/plain");
  3110. })
  3111. .Put("/put-loopback",
  3112. [&](const Request &, Response &res,
  3113. ContentReader const &content_reader) {
  3114. std::string body;
  3115. content_reader([&](const char *data, size_t data_length) {
  3116. body.append(data, data_length);
  3117. return true;
  3118. });
  3119. res.set_content(body, "text/plain");
  3120. })
  3121. .Patch("/patch-loopback",
  3122. [&](const Request &, Response &res,
  3123. ContentReader const &content_reader) {
  3124. std::string body;
  3125. content_reader([&](const char *data, size_t data_length) {
  3126. body.append(data, data_length);
  3127. return true;
  3128. });
  3129. res.set_content(body, "text/plain");
  3130. })
  3131. .Put("/empty-no-content-type",
  3132. [&](const Request &req, Response &res) {
  3133. EXPECT_EQ(req.body, "");
  3134. EXPECT_FALSE(req.has_header("Content-Type"));
  3135. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3136. res.set_content("empty-no-content-type", "text/plain");
  3137. })
  3138. .Put("/put",
  3139. [&](const Request &req, Response &res) {
  3140. EXPECT_EQ(req.body, "PUT");
  3141. res.set_content(req.body, "text/plain");
  3142. })
  3143. .Put("/put-large",
  3144. [&](const Request &req, Response &res) {
  3145. EXPECT_EQ(req.body, LARGE_DATA);
  3146. res.set_content(req.body, "text/plain");
  3147. })
  3148. .Patch("/patch",
  3149. [&](const Request &req, Response &res) {
  3150. EXPECT_EQ(req.body, "PATCH");
  3151. res.set_content(req.body, "text/plain");
  3152. })
  3153. .Delete("/delete",
  3154. [&](const Request & /*req*/, Response &res) {
  3155. res.set_content("DELETE", "text/plain");
  3156. })
  3157. .Delete("/delete-body",
  3158. [&](const Request &req, Response &res) {
  3159. EXPECT_EQ(req.body, "content");
  3160. res.set_content(req.body, "text/plain");
  3161. })
  3162. .Options(R"(\*)",
  3163. [&](const Request & /*req*/, Response &res) {
  3164. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3165. })
  3166. .Get("/request-target",
  3167. [&](const Request &req, Response & /*res*/) {
  3168. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3169. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3170. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3171. })
  3172. .Get("/long-query-value",
  3173. [&](const Request &req, Response & /*res*/) {
  3174. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3175. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3176. })
  3177. .Get("/too-long-query-value",
  3178. [&](const Request &req, Response & /*res*/) {
  3179. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3180. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3181. })
  3182. .Get("/array-param",
  3183. [&](const Request &req, Response & /*res*/) {
  3184. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3185. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3186. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3187. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3188. })
  3189. .Post("/validate-no-multiple-headers",
  3190. [&](const Request &req, Response & /*res*/) {
  3191. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3192. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3193. })
  3194. .Post("/content_receiver",
  3195. [&](const Request &req, Response &res,
  3196. const ContentReader &content_reader) {
  3197. if (req.is_multipart_form_data()) {
  3198. std::vector<FormData> items;
  3199. content_reader(
  3200. [&](const FormData &file) {
  3201. items.push_back(file);
  3202. return true;
  3203. },
  3204. [&](const char *data, size_t data_length) {
  3205. items.back().content.append(data, data_length);
  3206. return true;
  3207. });
  3208. EXPECT_EQ(5u, items.size());
  3209. {
  3210. const auto &file = get_file_value(items, "text1");
  3211. EXPECT_TRUE(file.filename.empty());
  3212. EXPECT_EQ("text default", file.content);
  3213. }
  3214. {
  3215. const auto &file = get_file_value(items, "text2");
  3216. EXPECT_TRUE(file.filename.empty());
  3217. EXPECT_EQ("aωb", file.content);
  3218. }
  3219. {
  3220. const auto &file = get_file_value(items, "file1");
  3221. EXPECT_EQ("hello.txt", file.filename);
  3222. EXPECT_EQ("text/plain", file.content_type);
  3223. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3224. }
  3225. {
  3226. const auto &file = get_file_value(items, "file2");
  3227. EXPECT_EQ("world.json", file.filename);
  3228. EXPECT_EQ("application/json", file.content_type);
  3229. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3230. }
  3231. {
  3232. const auto &file = get_file_value(items, "file3");
  3233. EXPECT_TRUE(file.filename.empty());
  3234. EXPECT_EQ("application/octet-stream", file.content_type);
  3235. EXPECT_EQ(0u, file.content.size());
  3236. }
  3237. } else {
  3238. std::string body;
  3239. content_reader([&](const char *data, size_t data_length) {
  3240. EXPECT_EQ(7U, data_length);
  3241. body.append(data, data_length);
  3242. return true;
  3243. });
  3244. EXPECT_EQ(body, "content");
  3245. res.set_content(body, "text/plain");
  3246. }
  3247. })
  3248. .Put("/content_receiver",
  3249. [&](const Request & /*req*/, Response &res,
  3250. const ContentReader &content_reader) {
  3251. std::string body;
  3252. content_reader([&](const char *data, size_t data_length) {
  3253. body.append(data, data_length);
  3254. return true;
  3255. });
  3256. EXPECT_EQ(body, "content");
  3257. res.set_content(body, "text/plain");
  3258. })
  3259. .Patch("/content_receiver",
  3260. [&](const Request & /*req*/, Response &res,
  3261. const ContentReader &content_reader) {
  3262. std::string body;
  3263. content_reader([&](const char *data, size_t data_length) {
  3264. body.append(data, data_length);
  3265. return true;
  3266. });
  3267. EXPECT_EQ(body, "content");
  3268. res.set_content(body, "text/plain");
  3269. })
  3270. .Post("/query-string-and-body",
  3271. [&](const Request &req, Response & /*res*/) {
  3272. ASSERT_TRUE(req.has_param("key"));
  3273. EXPECT_EQ(req.get_param_value("key"), "value");
  3274. EXPECT_EQ(req.body, "content");
  3275. })
  3276. .Get("/last-request",
  3277. [&](const Request &req, Response & /*res*/) {
  3278. EXPECT_EQ("close", req.get_header_value("Connection"));
  3279. })
  3280. .Get(R"(/redirect/(\d+))",
  3281. [&](const Request &req, Response &res) {
  3282. auto num = std::stoi(req.matches[1]) + 1;
  3283. std::string url = "/redirect/" + std::to_string(num);
  3284. res.set_redirect(url);
  3285. })
  3286. .Post("/binary",
  3287. [&](const Request &req, Response &res) {
  3288. EXPECT_EQ(4U, req.body.size());
  3289. EXPECT_EQ("application/octet-stream",
  3290. req.get_header_value("Content-Type"));
  3291. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3292. res.set_content(req.body, "application/octet-stream");
  3293. })
  3294. .Put("/binary",
  3295. [&](const Request &req, Response &res) {
  3296. EXPECT_EQ(4U, req.body.size());
  3297. EXPECT_EQ("application/octet-stream",
  3298. req.get_header_value("Content-Type"));
  3299. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3300. res.set_content(req.body, "application/octet-stream");
  3301. })
  3302. .Patch("/binary",
  3303. [&](const Request &req, Response &res) {
  3304. EXPECT_EQ(4U, req.body.size());
  3305. EXPECT_EQ("application/octet-stream",
  3306. req.get_header_value("Content-Type"));
  3307. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3308. res.set_content(req.body, "application/octet-stream");
  3309. })
  3310. .Delete("/binary",
  3311. [&](const Request &req, Response &res) {
  3312. EXPECT_EQ(4U, req.body.size());
  3313. EXPECT_EQ("application/octet-stream",
  3314. req.get_header_value("Content-Type"));
  3315. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3316. res.set_content(req.body, "application/octet-stream");
  3317. })
  3318. .Get("/issue1772",
  3319. [&](const Request & /*req*/, Response &res) {
  3320. res.status = 401;
  3321. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3322. })
  3323. .Delete("/issue609",
  3324. [](const httplib::Request &, httplib::Response &res,
  3325. const httplib::ContentReader &) {
  3326. res.set_content("ok", "text/plain");
  3327. })
  3328. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3329. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3330. .Get("/compress",
  3331. [&](const Request & /*req*/, Response &res) {
  3332. res.set_content(
  3333. "12345678901234567890123456789012345678901234567890123456789"
  3334. "01234567890123456789012345678901234567890",
  3335. "text/plain");
  3336. })
  3337. .Get("/compress-with-charset",
  3338. [&](const Request & /*req*/, Response &res) {
  3339. res.set_content(
  3340. "12345678901234567890123456789012345678901234567890123456789"
  3341. "01234567890123456789012345678901234567890",
  3342. "application/json; charset=utf-8");
  3343. })
  3344. .Get("/nocompress",
  3345. [&](const Request & /*req*/, Response &res) {
  3346. res.set_content(
  3347. "12345678901234567890123456789012345678901234567890123456789"
  3348. "01234567890123456789012345678901234567890",
  3349. "application/octet-stream");
  3350. })
  3351. .Post("/compress-multipart",
  3352. [&](const Request &req, Response & /*res*/) {
  3353. EXPECT_EQ(2u, req.form.fields.size());
  3354. ASSERT_TRUE(!req.form.has_field("???"));
  3355. {
  3356. const auto &text = req.form.get_field("key1");
  3357. EXPECT_EQ("test", text);
  3358. }
  3359. {
  3360. const auto &text = req.form.get_field("key2");
  3361. EXPECT_EQ("--abcdefg123", text);
  3362. }
  3363. })
  3364. #endif
  3365. ;
  3366. persons_["john"] = "programmer";
  3367. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3368. svr_.wait_until_ready();
  3369. }
  3370. virtual void TearDown() {
  3371. svr_.stop();
  3372. if (!request_threads_.empty()) {
  3373. std::this_thread::sleep_for(std::chrono::seconds(1));
  3374. for (auto &t : request_threads_) {
  3375. t.join();
  3376. }
  3377. }
  3378. t_.join();
  3379. }
  3380. map<string, string> persons_;
  3381. #ifdef CPPHTTPLIB_SSL_ENABLED
  3382. SSLClient cli_;
  3383. SSLServer svr_;
  3384. #else
  3385. Client cli_;
  3386. Server svr_;
  3387. #endif
  3388. thread t_;
  3389. std::vector<thread> request_threads_;
  3390. };
  3391. TEST_F(ServerTest, GetMethod200) {
  3392. auto res = cli_.Get("/hi");
  3393. ASSERT_TRUE(res);
  3394. EXPECT_EQ("HTTP/1.1", res->version);
  3395. EXPECT_EQ(StatusCode::OK_200, res->status);
  3396. EXPECT_EQ("OK", res->reason);
  3397. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3398. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3399. EXPECT_EQ("Hello World!", res->body);
  3400. }
  3401. TEST_F(ServerTest, GetEmptyFile) {
  3402. auto res = cli_.Get("/empty_file");
  3403. ASSERT_TRUE(res);
  3404. EXPECT_EQ(StatusCode::OK_200, res->status);
  3405. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3406. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3407. EXPECT_EQ("", res->body);
  3408. }
  3409. TEST_F(ServerTest, GetFileContent) {
  3410. auto res = cli_.Get("/file_content");
  3411. ASSERT_TRUE(res);
  3412. EXPECT_EQ(StatusCode::OK_200, res->status);
  3413. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3414. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3415. EXPECT_EQ("test.html", res->body);
  3416. }
  3417. TEST_F(ServerTest, GetFileContentWithRange) {
  3418. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3419. ASSERT_TRUE(res);
  3420. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3421. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3422. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3423. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3424. EXPECT_EQ("est", res->body);
  3425. }
  3426. TEST_F(ServerTest, GetFileContentWithContentType) {
  3427. auto res = cli_.Get("/file_content_with_content_type");
  3428. ASSERT_TRUE(res);
  3429. EXPECT_EQ(StatusCode::OK_200, res->status);
  3430. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3431. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3432. EXPECT_EQ("file\n", res->body);
  3433. }
  3434. TEST_F(ServerTest, GetInvalidFileContent) {
  3435. auto res = cli_.Get("/invalid_file_content");
  3436. ASSERT_TRUE(res);
  3437. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3438. }
  3439. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3440. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3441. ASSERT_TRUE(res);
  3442. EXPECT_EQ("HTTP/1.1", res->version);
  3443. EXPECT_EQ(StatusCode::OK_200, res->status);
  3444. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3445. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3446. EXPECT_EQ("Hello World!", res->body);
  3447. }
  3448. TEST_F(ServerTest, GetMethod302) {
  3449. auto res = cli_.Get("/");
  3450. ASSERT_TRUE(res);
  3451. EXPECT_EQ(StatusCode::Found_302, res->status);
  3452. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3453. }
  3454. TEST_F(ServerTest, GetMethod302Redirect) {
  3455. cli_.set_follow_location(true);
  3456. auto res = cli_.Get("/");
  3457. ASSERT_TRUE(res);
  3458. EXPECT_EQ(StatusCode::OK_200, res->status);
  3459. EXPECT_EQ("Hello World!", res->body);
  3460. EXPECT_EQ("/hi", res->location);
  3461. }
  3462. TEST_F(ServerTest, GetMethod404) {
  3463. auto res = cli_.Get("/invalid");
  3464. ASSERT_TRUE(res);
  3465. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3466. }
  3467. TEST_F(ServerTest, HeadMethod200) {
  3468. auto res = cli_.Head("/hi");
  3469. ASSERT_TRUE(res);
  3470. EXPECT_EQ(StatusCode::OK_200, res->status);
  3471. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3472. EXPECT_TRUE(res->body.empty());
  3473. }
  3474. TEST_F(ServerTest, HeadMethod200Static) {
  3475. auto res = cli_.Head("/mount/dir/index.html");
  3476. ASSERT_TRUE(res);
  3477. EXPECT_EQ(StatusCode::OK_200, res->status);
  3478. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3479. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3480. EXPECT_TRUE(res->body.empty());
  3481. }
  3482. TEST_F(ServerTest, HeadMethod404) {
  3483. auto res = cli_.Head("/invalid");
  3484. ASSERT_TRUE(res);
  3485. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3486. EXPECT_TRUE(res->body.empty());
  3487. }
  3488. TEST_F(ServerTest, GetMethodPersonJohn) {
  3489. auto res = cli_.Get("/person/john");
  3490. ASSERT_TRUE(res);
  3491. EXPECT_EQ(StatusCode::OK_200, res->status);
  3492. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3493. EXPECT_EQ("programmer", res->body);
  3494. }
  3495. TEST_F(ServerTest, PostMethod1) {
  3496. auto res = cli_.Get("/person/john1");
  3497. ASSERT_TRUE(res);
  3498. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3499. res = cli_.Post("/person", "name=john1&note=coder",
  3500. "application/x-www-form-urlencoded");
  3501. ASSERT_TRUE(res);
  3502. ASSERT_EQ(StatusCode::OK_200, res->status);
  3503. res = cli_.Get("/person/john1");
  3504. ASSERT_TRUE(res);
  3505. ASSERT_EQ(StatusCode::OK_200, res->status);
  3506. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3507. ASSERT_EQ("coder", res->body);
  3508. }
  3509. TEST_F(ServerTest, PostMethod2) {
  3510. auto res = cli_.Get("/person/john2");
  3511. ASSERT_TRUE(res);
  3512. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3513. Params params;
  3514. params.emplace("name", "john2");
  3515. params.emplace("note", "coder");
  3516. res = cli_.Post("/person", params);
  3517. ASSERT_TRUE(res);
  3518. ASSERT_EQ(StatusCode::OK_200, res->status);
  3519. res = cli_.Get("/person/john2");
  3520. ASSERT_TRUE(res);
  3521. ASSERT_EQ(StatusCode::OK_200, res->status);
  3522. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3523. ASSERT_EQ("coder", res->body);
  3524. }
  3525. TEST_F(ServerTest, PutMethod3) {
  3526. auto res = cli_.Get("/person/john3");
  3527. ASSERT_TRUE(res);
  3528. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3529. Params params;
  3530. params.emplace("name", "john3");
  3531. params.emplace("note", "coder");
  3532. res = cli_.Put("/person", params);
  3533. ASSERT_TRUE(res);
  3534. ASSERT_EQ(StatusCode::OK_200, res->status);
  3535. res = cli_.Get("/person/john3");
  3536. ASSERT_TRUE(res);
  3537. ASSERT_EQ(StatusCode::OK_200, res->status);
  3538. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3539. ASSERT_EQ("coder", res->body);
  3540. }
  3541. TEST_F(ServerTest, DeleteMethod1) {
  3542. auto res = cli_.Get("/person/john4");
  3543. ASSERT_TRUE(res);
  3544. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3545. Params params;
  3546. params.emplace("name", "john4");
  3547. params.emplace("note", "coder");
  3548. res = cli_.Post("/person", params);
  3549. ASSERT_TRUE(res);
  3550. ASSERT_EQ(StatusCode::OK_200, res->status);
  3551. res = cli_.Get("/person/john4");
  3552. ASSERT_TRUE(res);
  3553. ASSERT_EQ(StatusCode::OK_200, res->status);
  3554. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3555. ASSERT_EQ("coder", res->body);
  3556. Params delete_params;
  3557. delete_params.emplace("name", "john4");
  3558. res = cli_.Delete("/person", delete_params);
  3559. ASSERT_TRUE(res);
  3560. ASSERT_EQ(StatusCode::OK_200, res->status);
  3561. ASSERT_EQ("DELETED", res->body);
  3562. res = cli_.Get("/person/john4");
  3563. ASSERT_TRUE(res);
  3564. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3565. }
  3566. TEST_F(ServerTest, DeleteMethod2) {
  3567. auto res = cli_.Get("/person/john5");
  3568. ASSERT_TRUE(res);
  3569. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3570. Params params;
  3571. params.emplace("name", "john5");
  3572. params.emplace("note", "developer");
  3573. res = cli_.Post("/person", params);
  3574. ASSERT_TRUE(res);
  3575. ASSERT_EQ(StatusCode::OK_200, res->status);
  3576. res = cli_.Get("/person/john5");
  3577. ASSERT_TRUE(res);
  3578. ASSERT_EQ(StatusCode::OK_200, res->status);
  3579. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3580. ASSERT_EQ("developer", res->body);
  3581. Params delete_params;
  3582. delete_params.emplace("name", "john5");
  3583. Headers headers;
  3584. headers.emplace("Custom-Header", "test-value");
  3585. res = cli_.Delete("/person", headers, delete_params);
  3586. ASSERT_TRUE(res);
  3587. ASSERT_EQ(StatusCode::OK_200, res->status);
  3588. ASSERT_EQ("DELETED", res->body);
  3589. res = cli_.Get("/person/john5");
  3590. ASSERT_TRUE(res);
  3591. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3592. }
  3593. TEST_F(ServerTest, DeleteMethod3) {
  3594. auto res = cli_.Get("/person/john6");
  3595. ASSERT_TRUE(res);
  3596. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3597. Params params;
  3598. params.emplace("name", "john6");
  3599. params.emplace("note", "tester");
  3600. res = cli_.Post("/person", params);
  3601. ASSERT_TRUE(res);
  3602. ASSERT_EQ(StatusCode::OK_200, res->status);
  3603. res = cli_.Get("/person/john6");
  3604. ASSERT_TRUE(res);
  3605. ASSERT_EQ(StatusCode::OK_200, res->status);
  3606. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3607. ASSERT_EQ("tester", res->body);
  3608. Params delete_params;
  3609. delete_params.emplace("name", "john6");
  3610. Headers headers;
  3611. headers.emplace("Custom-Header", "test-value");
  3612. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3613. ASSERT_TRUE(res);
  3614. ASSERT_EQ(StatusCode::OK_200, res->status);
  3615. ASSERT_EQ("DELETED", res->body);
  3616. res = cli_.Get("/person/john6");
  3617. ASSERT_TRUE(res);
  3618. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3619. }
  3620. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3621. Params params;
  3622. params.emplace("json", JSON_DATA);
  3623. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3624. ASSERT_TRUE(res);
  3625. ASSERT_EQ(StatusCode::OK_200, res->status);
  3626. ASSERT_EQ(JSON_DATA, res->body);
  3627. }
  3628. TEST_F(ServerTest, PostEmptyContent) {
  3629. auto res = cli_.Post("/empty", "", "text/plain");
  3630. ASSERT_TRUE(res);
  3631. ASSERT_EQ(StatusCode::OK_200, res->status);
  3632. ASSERT_EQ("empty", res->body);
  3633. }
  3634. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3635. auto res = cli_.Post("/empty-no-content-type");
  3636. ASSERT_TRUE(res);
  3637. ASSERT_EQ(StatusCode::OK_200, res->status);
  3638. ASSERT_EQ("empty-no-content-type", res->body);
  3639. }
  3640. TEST_F(ServerTest, PostPathOnly) {
  3641. auto res = cli_.Post("/path-only");
  3642. ASSERT_TRUE(res);
  3643. ASSERT_EQ(StatusCode::OK_200, res->status);
  3644. ASSERT_EQ("path-only", res->body);
  3645. }
  3646. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3647. auto res = cli_.Post("/path-headers-only",
  3648. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3649. ASSERT_TRUE(res);
  3650. ASSERT_EQ(StatusCode::OK_200, res->status);
  3651. ASSERT_EQ("path-headers-only", res->body);
  3652. }
  3653. TEST_F(ServerTest, PostLarge) {
  3654. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3655. ASSERT_TRUE(res);
  3656. ASSERT_EQ(StatusCode::OK_200, res->status);
  3657. EXPECT_EQ(LARGE_DATA, res->body);
  3658. }
  3659. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3660. auto res = cli_.Put("/empty-no-content-type");
  3661. ASSERT_TRUE(res);
  3662. ASSERT_EQ(StatusCode::OK_200, res->status);
  3663. ASSERT_EQ("empty-no-content-type", res->body);
  3664. }
  3665. TEST_F(ServerTest, GetMethodDir) {
  3666. auto res = cli_.Get("/dir/");
  3667. ASSERT_TRUE(res);
  3668. EXPECT_EQ(StatusCode::OK_200, res->status);
  3669. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3670. auto body = R"(<html>
  3671. <head>
  3672. </head>
  3673. <body>
  3674. <a href="/dir/test.html">Test</a>
  3675. <a href="/hi">hi</a>
  3676. </body>
  3677. </html>
  3678. )";
  3679. EXPECT_EQ(body, res->body);
  3680. }
  3681. TEST_F(ServerTest, GetMethodDirTest) {
  3682. auto res = cli_.Get("/dir/test.html");
  3683. ASSERT_TRUE(res);
  3684. EXPECT_EQ(StatusCode::OK_200, res->status);
  3685. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3686. EXPECT_EQ("test.html", res->body);
  3687. }
  3688. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3689. auto res = cli_.Get("/dir/../dir/test.html");
  3690. ASSERT_TRUE(res);
  3691. EXPECT_EQ(StatusCode::OK_200, res->status);
  3692. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3693. EXPECT_EQ("test.html", res->body);
  3694. }
  3695. TEST_F(ServerTest, GetMethodInvalidPath) {
  3696. auto res = cli_.Get("/dir/../test.html");
  3697. ASSERT_TRUE(res);
  3698. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3699. }
  3700. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3701. auto res = cli_.Get("/../www/dir/test.html");
  3702. ASSERT_TRUE(res);
  3703. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3704. }
  3705. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3706. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3707. ASSERT_TRUE(res);
  3708. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3709. }
  3710. TEST_F(ServerTest, GetMethodDirMountTest) {
  3711. auto res = cli_.Get("/mount/dir/test.html");
  3712. ASSERT_TRUE(res);
  3713. EXPECT_EQ(StatusCode::OK_200, res->status);
  3714. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3715. EXPECT_EQ("test.html", res->body);
  3716. }
  3717. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3718. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3719. ASSERT_TRUE(res);
  3720. EXPECT_EQ(StatusCode::OK_200, res->status);
  3721. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3722. EXPECT_EQ("test.html", res->body);
  3723. }
  3724. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3725. auto res = cli_.Get("/mount/dir/../test.html");
  3726. ASSERT_TRUE(res);
  3727. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3728. }
  3729. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3730. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3731. ASSERT_TRUE(res);
  3732. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3733. }
  3734. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3735. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3736. ASSERT_TRUE(res);
  3737. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3738. }
  3739. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3740. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3741. ASSERT_TRUE(res);
  3742. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3743. }
  3744. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3745. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3746. ASSERT_TRUE(res);
  3747. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3748. }
  3749. TEST_F(ServerTest, PostMethod303) {
  3750. auto res = cli_.Post("/1", "body", "text/plain");
  3751. ASSERT_TRUE(res);
  3752. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3753. EXPECT_EQ("/2", res->get_header_value("Location"));
  3754. }
  3755. TEST_F(ServerTest, PostMethod303Redirect) {
  3756. cli_.set_follow_location(true);
  3757. auto res = cli_.Post("/1", "body", "text/plain");
  3758. ASSERT_TRUE(res);
  3759. EXPECT_EQ(StatusCode::OK_200, res->status);
  3760. EXPECT_EQ("redirected.", res->body);
  3761. EXPECT_EQ("/2", res->location);
  3762. }
  3763. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3764. auto res = cli_.Get("/dir/test.abcde");
  3765. ASSERT_TRUE(res);
  3766. EXPECT_EQ(StatusCode::OK_200, res->status);
  3767. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3768. EXPECT_EQ("abcde", res->body);
  3769. }
  3770. TEST_F(ServerTest, StaticFileRange) {
  3771. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3772. ASSERT_TRUE(res);
  3773. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3774. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3775. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3776. EXPECT_EQ(true, res->has_header("Content-Range"));
  3777. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3778. EXPECT_EQ(std::string("cd"), res->body);
  3779. }
  3780. TEST_F(ServerTest, StaticFileRanges) {
  3781. auto res =
  3782. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3783. ASSERT_TRUE(res);
  3784. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3785. EXPECT_TRUE(
  3786. res->get_header_value("Content-Type")
  3787. .find(
  3788. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3789. 0);
  3790. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3791. }
  3792. TEST_F(ServerTest, StaticFileRangeHead) {
  3793. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3794. ASSERT_TRUE(res);
  3795. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3796. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3797. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3798. EXPECT_EQ(true, res->has_header("Content-Range"));
  3799. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3800. }
  3801. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3802. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3803. ASSERT_TRUE(res);
  3804. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3805. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3806. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3807. EXPECT_EQ(true, res->has_header("Content-Range"));
  3808. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3809. res->get_header_value("Content-Range"));
  3810. EXPECT_EQ("LAST\n", res->body);
  3811. }
  3812. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3813. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3814. ASSERT_TRUE(res);
  3815. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3816. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3817. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3818. EXPECT_EQ(true, res->has_header("Content-Range"));
  3819. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3820. }
  3821. TEST_F(ServerTest, StaticFileBigFile) {
  3822. auto res = cli_.Get("/dir/1MB.txt");
  3823. ASSERT_TRUE(res);
  3824. EXPECT_EQ(StatusCode::OK_200, res->status);
  3825. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3826. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3827. }
  3828. TEST_F(ServerTest, InvalidBaseDirMount) {
  3829. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3830. }
  3831. TEST_F(ServerTest, Binary) {
  3832. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3833. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3834. "application/octet-stream");
  3835. ASSERT_TRUE(res);
  3836. ASSERT_EQ(StatusCode::OK_200, res->status);
  3837. ASSERT_EQ(4U, res->body.size());
  3838. res = cli_.Put("/binary", binary.data(), binary.size(),
  3839. "application/octet-stream");
  3840. ASSERT_TRUE(res);
  3841. ASSERT_EQ(StatusCode::OK_200, res->status);
  3842. ASSERT_EQ(4U, res->body.size());
  3843. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3844. "application/octet-stream");
  3845. ASSERT_TRUE(res);
  3846. ASSERT_EQ(StatusCode::OK_200, res->status);
  3847. ASSERT_EQ(4U, res->body.size());
  3848. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3849. "application/octet-stream");
  3850. ASSERT_TRUE(res);
  3851. ASSERT_EQ(StatusCode::OK_200, res->status);
  3852. ASSERT_EQ(4U, res->body.size());
  3853. }
  3854. TEST_F(ServerTest, BinaryString) {
  3855. auto binary = std::string("\x00\x01\x02\x03", 4);
  3856. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3857. ASSERT_TRUE(res);
  3858. ASSERT_EQ(StatusCode::OK_200, res->status);
  3859. ASSERT_EQ(4U, res->body.size());
  3860. res = cli_.Put("/binary", binary, "application/octet-stream");
  3861. ASSERT_TRUE(res);
  3862. ASSERT_EQ(StatusCode::OK_200, res->status);
  3863. ASSERT_EQ(4U, res->body.size());
  3864. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3865. ASSERT_TRUE(res);
  3866. ASSERT_EQ(StatusCode::OK_200, res->status);
  3867. ASSERT_EQ(4U, res->body.size());
  3868. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3869. ASSERT_TRUE(res);
  3870. ASSERT_EQ(StatusCode::OK_200, res->status);
  3871. ASSERT_EQ(4U, res->body.size());
  3872. }
  3873. TEST_F(ServerTest, EmptyRequest) {
  3874. auto res = cli_.Get("");
  3875. ASSERT_TRUE(!res);
  3876. EXPECT_EQ(Error::Connection, res.error());
  3877. }
  3878. TEST_F(ServerTest, LongRequest) {
  3879. std::string request;
  3880. for (size_t i = 0; i < 545; i++) {
  3881. request += "/TooLongRequest";
  3882. }
  3883. request += "OK";
  3884. auto res = cli_.Get(request.c_str());
  3885. ASSERT_TRUE(res);
  3886. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3887. }
  3888. TEST_F(ServerTest, TooLongRequest) {
  3889. std::string request;
  3890. for (size_t i = 0; i < 546; i++) {
  3891. request += "/TooLongRequest";
  3892. }
  3893. request += "_NG";
  3894. auto start = std::chrono::high_resolution_clock::now();
  3895. cli_.set_keep_alive(true);
  3896. auto res = cli_.Get(request.c_str());
  3897. auto end = std::chrono::high_resolution_clock::now();
  3898. auto elapsed =
  3899. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3900. .count();
  3901. ASSERT_TRUE(res);
  3902. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3903. EXPECT_LE(elapsed, 1000);
  3904. EXPECT_EQ("close", res->get_header_value("Connection"));
  3905. EXPECT_FALSE(cli_.is_socket_open());
  3906. }
  3907. TEST_F(ServerTest, AlmostTooLongRequest) {
  3908. // test for #2046 - URI length check shouldn't include other content on req
  3909. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3910. // leading /, space, HTTP/1.1)
  3911. std::string request =
  3912. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3913. auto res = cli_.Get(request.c_str());
  3914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3915. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3916. }
  3917. TEST_F(ServerTest, LongHeader) {
  3918. Request req;
  3919. req.method = "GET";
  3920. req.path = "/hi";
  3921. std::string host_and_port;
  3922. host_and_port += HOST;
  3923. host_and_port += ":";
  3924. host_and_port += std::to_string(PORT);
  3925. req.headers.emplace("Host", host_and_port.c_str());
  3926. req.headers.emplace("Accept", "*/*");
  3927. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3928. req.headers.emplace(
  3929. "Header-Name",
  3930. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3931. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3932. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3933. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3934. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3935. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3936. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3937. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3938. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3939. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3940. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3941. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3942. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3943. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3944. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3945. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3946. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3947. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3948. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3949. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3950. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3951. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3952. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3953. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3954. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3955. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3956. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3957. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3958. "@@@@@@@@@@@@@@@@");
  3959. auto res = std::make_shared<Response>();
  3960. auto error = Error::Success;
  3961. auto ret = cli_.send(req, *res, error);
  3962. ASSERT_TRUE(ret);
  3963. EXPECT_EQ(StatusCode::OK_200, res->status);
  3964. }
  3965. TEST_F(ServerTest, LongQueryValue) {
  3966. auto start = std::chrono::high_resolution_clock::now();
  3967. cli_.set_keep_alive(true);
  3968. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3969. auto end = std::chrono::high_resolution_clock::now();
  3970. auto elapsed =
  3971. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3972. .count();
  3973. ASSERT_TRUE(res);
  3974. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3975. EXPECT_LE(elapsed, 1000);
  3976. EXPECT_EQ("close", res->get_header_value("Connection"));
  3977. EXPECT_FALSE(cli_.is_socket_open());
  3978. }
  3979. TEST_F(ServerTest, TooLongQueryValue) {
  3980. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3981. ASSERT_FALSE(res);
  3982. EXPECT_EQ(Error::Read, res.error());
  3983. }
  3984. TEST_F(ServerTest, TooLongHeader) {
  3985. Request req;
  3986. req.method = "GET";
  3987. req.path = "/hi";
  3988. std::string host_and_port;
  3989. host_and_port += HOST;
  3990. host_and_port += ":";
  3991. host_and_port += std::to_string(PORT);
  3992. req.headers.emplace("Host", host_and_port.c_str());
  3993. req.headers.emplace("Accept", "*/*");
  3994. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3995. req.headers.emplace(
  3996. "Header-Name",
  3997. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3998. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3999. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4000. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4001. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4002. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4003. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4004. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4005. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4006. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4007. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4008. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4009. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4010. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4011. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4012. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4013. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4014. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4015. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4016. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4017. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4018. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4019. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4020. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4021. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4022. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4023. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4024. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4025. "@@@@@@@@@@@@@@@@@");
  4026. auto res = std::make_shared<Response>();
  4027. auto error = Error::Success;
  4028. auto ret = cli_.send(req, *res, error);
  4029. ASSERT_TRUE(ret);
  4030. EXPECT_EQ(StatusCode::OK_200, res->status);
  4031. }
  4032. TEST_F(ServerTest, HeaderCountAtLimit) {
  4033. // Test with headers just under the 100 limit
  4034. httplib::Headers headers;
  4035. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4036. // This should keep us just under the 100 header limit
  4037. for (int i = 0; i < 95; i++) {
  4038. std::string name = "X-Test-Header-" + std::to_string(i);
  4039. std::string value = "value" + std::to_string(i);
  4040. headers.emplace(name, value);
  4041. }
  4042. // This should work fine as we're under the limit
  4043. auto res = cli_.Get("/hi", headers);
  4044. EXPECT_TRUE(res);
  4045. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4046. }
  4047. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4048. // Test with many headers to exceed the 100 limit
  4049. httplib::Headers headers;
  4050. // Add 150 headers to definitely exceed the 100 limit
  4051. for (int i = 0; i < 150; i++) {
  4052. std::string name = "X-Test-Header-" + std::to_string(i);
  4053. std::string value = "value" + std::to_string(i);
  4054. headers.emplace(name, value);
  4055. }
  4056. // This should fail due to exceeding header count limit
  4057. cli_.set_keep_alive(true);
  4058. auto res = cli_.Get("/hi", headers);
  4059. // The server should respond with 400 Bad Request
  4060. ASSERT_TRUE(res);
  4061. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4062. EXPECT_EQ("close", res->get_header_value("Connection"));
  4063. EXPECT_FALSE(cli_.is_socket_open());
  4064. }
  4065. TEST_F(ServerTest, PercentEncoding) {
  4066. auto res = cli_.Get("/e%6edwith%");
  4067. ASSERT_TRUE(res);
  4068. EXPECT_EQ(StatusCode::OK_200, res->status);
  4069. }
  4070. TEST_F(ServerTest, PercentEncodingUnicode) {
  4071. auto res = cli_.Get("/e%u006edwith%");
  4072. ASSERT_TRUE(res);
  4073. EXPECT_EQ(StatusCode::OK_200, res->status);
  4074. }
  4075. TEST_F(ServerTest, InvalidPercentEncoding) {
  4076. auto res = cli_.Get("/%endwith%");
  4077. ASSERT_TRUE(res);
  4078. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4079. }
  4080. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4081. auto res = cli_.Get("/%uendwith%");
  4082. ASSERT_TRUE(res);
  4083. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4084. }
  4085. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4086. auto res = cli_.Get("/hello?aaa=bbb%");
  4087. ASSERT_TRUE(res);
  4088. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4089. }
  4090. TEST_F(ServerTest, PlusSignEncoding) {
  4091. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4092. ASSERT_TRUE(res);
  4093. EXPECT_EQ(StatusCode::OK_200, res->status);
  4094. EXPECT_EQ("a +b", res->body);
  4095. }
  4096. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4097. // This test simulates a potential DoS attack using many headers
  4098. // to verify our security fix prevents memory exhaustion
  4099. httplib::Headers attack_headers;
  4100. // Attempt to add many headers like an attacker would (200 headers to far
  4101. // exceed limit)
  4102. for (int i = 0; i < 200; i++) {
  4103. std::string name = "X-Attack-Header-" + std::to_string(i);
  4104. std::string value = "attack_payload_" + std::to_string(i);
  4105. attack_headers.emplace(name, value);
  4106. }
  4107. // Try to POST with excessive headers
  4108. cli_.set_keep_alive(true);
  4109. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4110. // Should either fail or return 400 Bad Request due to security limit
  4111. if (res) {
  4112. // If we get a response, it should be 400 Bad Request
  4113. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4114. EXPECT_EQ("close", res->get_header_value("Connection"));
  4115. }
  4116. EXPECT_FALSE(cli_.is_socket_open());
  4117. }
  4118. TEST_F(ServerTest, MultipartFormData) {
  4119. UploadFormDataItems items = {
  4120. {"text1", "text default", "", ""},
  4121. {"text2", "aωb", "", ""},
  4122. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4123. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4124. {"file3", "", "", "application/octet-stream"},
  4125. {"file4", "", "", " application/json tmp-string "}};
  4126. auto res = cli_.Post("/multipart", items);
  4127. ASSERT_TRUE(res);
  4128. EXPECT_EQ(StatusCode::OK_200, res->status);
  4129. }
  4130. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4131. UploadFormDataItems items = {
  4132. {"text", "default text", "", ""},
  4133. {"multi_text1", "aaaaa", "", ""},
  4134. {"multi_text1", "bbbbb", "", ""},
  4135. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4136. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4137. "application/json"},
  4138. };
  4139. auto res = cli_.Post("/multipart/multi_file_values", items);
  4140. ASSERT_TRUE(res);
  4141. EXPECT_EQ(StatusCode::OK_200, res->status);
  4142. }
  4143. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4144. auto res = cli_.Get("/hi");
  4145. ASSERT_TRUE(res);
  4146. EXPECT_EQ(StatusCode::OK_200, res->status);
  4147. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4148. EXPECT_EQ("Hello World!", res->body);
  4149. }
  4150. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4151. Request req;
  4152. req.method = "POST";
  4153. req.path = "/chunked";
  4154. std::string host_and_port;
  4155. host_and_port += HOST;
  4156. host_and_port += ":";
  4157. host_and_port += std::to_string(PORT);
  4158. req.headers.emplace("Host", host_and_port.c_str());
  4159. req.headers.emplace("Accept", "*/*");
  4160. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4161. req.headers.emplace("Content-Type", "text/plain");
  4162. req.headers.emplace("Content-Length", "0");
  4163. req.headers.emplace(
  4164. "Transfer-Encoding",
  4165. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4166. // Client does not chunk, so make a chunked body manually.
  4167. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4168. auto res = std::make_shared<Response>();
  4169. auto error = Error::Success;
  4170. auto ret = cli_.send(req, *res, error);
  4171. ASSERT_TRUE(ret);
  4172. EXPECT_EQ(StatusCode::OK_200, res->status);
  4173. }
  4174. TEST_F(ServerTest, GetStreamed2) {
  4175. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4176. ASSERT_TRUE(res);
  4177. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4178. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4179. EXPECT_EQ(true, res->has_header("Content-Range"));
  4180. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4181. EXPECT_EQ(std::string("ab"), res->body);
  4182. }
  4183. TEST_F(ServerTest, GetStreamed) {
  4184. auto res = cli_.Get("/streamed");
  4185. ASSERT_TRUE(res);
  4186. EXPECT_EQ(StatusCode::OK_200, res->status);
  4187. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4188. EXPECT_EQ(std::string("aaabbb"), res->body);
  4189. }
  4190. TEST_F(ServerTest, GetStreamedWithRange1) {
  4191. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4192. ASSERT_TRUE(res);
  4193. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4194. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4195. EXPECT_EQ(true, res->has_header("Content-Range"));
  4196. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4197. EXPECT_EQ(std::string("def"), res->body);
  4198. }
  4199. TEST_F(ServerTest, GetStreamedWithRange2) {
  4200. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4201. ASSERT_TRUE(res);
  4202. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4203. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4204. EXPECT_EQ(true, res->has_header("Content-Range"));
  4205. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4206. EXPECT_EQ(std::string("bcdefg"), res->body);
  4207. }
  4208. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4209. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4210. ASSERT_TRUE(res);
  4211. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4212. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4213. EXPECT_EQ(true, res->has_header("Content-Range"));
  4214. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4215. EXPECT_EQ(std::string("efg"), res->body);
  4216. }
  4217. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4218. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4219. ASSERT_TRUE(res);
  4220. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4221. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4222. EXPECT_EQ(false, res->has_header("Content-Range"));
  4223. EXPECT_EQ(0U, res->body.size());
  4224. }
  4225. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4226. auto res = cli_.Get("/streamed-with-range",
  4227. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4228. "92233720368547758079223372036854775807"}});
  4229. ASSERT_TRUE(res);
  4230. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4231. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4232. EXPECT_EQ(false, res->has_header("Content-Range"));
  4233. EXPECT_EQ(0U, res->body.size());
  4234. }
  4235. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4236. auto res = cli_.Get(
  4237. "/with-range",
  4238. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4239. {"Accept-Encoding", ""}});
  4240. ASSERT_TRUE(res);
  4241. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4242. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4243. EXPECT_EQ(true, res->has_header("Content-Range"));
  4244. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4245. EXPECT_EQ(std::string("abcdefg"), res->body);
  4246. }
  4247. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4248. auto res = cli_.Get("/with-range", {
  4249. {"Range", "bytes=0-"},
  4250. {"Accept-Encoding", ""},
  4251. });
  4252. ASSERT_TRUE(res);
  4253. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4254. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4255. EXPECT_EQ(true, res->has_header("Content-Range"));
  4256. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4257. EXPECT_EQ(std::string("abcdefg"), res->body);
  4258. }
  4259. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4260. auto res =
  4261. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4262. ASSERT_TRUE(res);
  4263. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4264. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4265. EXPECT_EQ(false, res->has_header("Content-Range"));
  4266. EXPECT_EQ(267U, res->body.size());
  4267. // Check that both range contents are present
  4268. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4269. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4270. // Check that Content-Range headers are present for both ranges
  4271. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4272. std::string::npos);
  4273. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4274. std::string::npos);
  4275. }
  4276. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4277. Ranges ranges;
  4278. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4279. ranges.emplace_back(0, -1);
  4280. }
  4281. auto res =
  4282. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4283. ASSERT_TRUE(res);
  4284. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4285. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4286. EXPECT_EQ(false, res->has_header("Content-Range"));
  4287. EXPECT_EQ(0U, res->body.size());
  4288. }
  4289. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4290. auto res =
  4291. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4292. ASSERT_TRUE(res);
  4293. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4294. EXPECT_EQ(5U, res->body.size());
  4295. // Check that overlapping ranges are coalesced into a single range
  4296. EXPECT_EQ("bcdef", res->body);
  4297. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4298. // Should be single range, not multipart
  4299. EXPECT_TRUE(res->has_header("Content-Range"));
  4300. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4301. }
  4302. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4303. auto res =
  4304. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4305. ASSERT_TRUE(res);
  4306. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4307. EXPECT_EQ(268U, res->body.size());
  4308. // Check that both range contents are present
  4309. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4310. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4311. // Check that Content-Range headers are present for both ranges
  4312. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4313. std::string::npos);
  4314. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4315. std::string::npos);
  4316. }
  4317. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4318. auto res =
  4319. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4320. ASSERT_TRUE(res);
  4321. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4322. EXPECT_EQ(269U, res->body.size());
  4323. // Check that both duplicate range contents are present
  4324. size_t first_abc = res->body.find("abc\r\n");
  4325. EXPECT_TRUE(first_abc != std::string::npos);
  4326. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4327. EXPECT_TRUE(second_abc != std::string::npos);
  4328. // Check that Content-Range headers are present for both ranges
  4329. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4330. EXPECT_TRUE(first_range != std::string::npos);
  4331. size_t second_range =
  4332. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4333. EXPECT_TRUE(second_range != std::string::npos);
  4334. }
  4335. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4336. auto res = cli_.Get("/streamed-with-range?error",
  4337. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4338. ASSERT_TRUE(res);
  4339. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4340. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4341. EXPECT_EQ(false, res->has_header("Content-Range"));
  4342. EXPECT_EQ(0U, res->body.size());
  4343. }
  4344. TEST_F(ServerTest, GetStreamedEndless) {
  4345. uint64_t offset = 0;
  4346. auto res = cli_.Get("/streamed-cancel",
  4347. [&](const char * /*data*/, uint64_t data_length) {
  4348. if (offset < 100) {
  4349. offset += data_length;
  4350. return true;
  4351. }
  4352. return false;
  4353. });
  4354. ASSERT_TRUE(!res);
  4355. EXPECT_EQ(Error::Canceled, res.error());
  4356. }
  4357. TEST_F(ServerTest, ClientStop) {
  4358. std::atomic_size_t count{4};
  4359. std::vector<std::thread> threads;
  4360. for (auto i = count.load(); i != 0; --i) {
  4361. threads.emplace_back([&]() {
  4362. auto res = cli_.Get("/streamed-cancel",
  4363. [&](const char *, uint64_t) { return true; });
  4364. --count;
  4365. ASSERT_TRUE(!res);
  4366. EXPECT_TRUE(res.error() == Error::Canceled ||
  4367. res.error() == Error::Read || res.error() == Error::Write);
  4368. });
  4369. }
  4370. std::this_thread::sleep_for(std::chrono::seconds(2));
  4371. while (count != 0) {
  4372. cli_.stop();
  4373. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4374. }
  4375. for (auto &t : threads) {
  4376. t.join();
  4377. }
  4378. }
  4379. TEST_F(ServerTest, GetWithRange1) {
  4380. auto res = cli_.Get("/with-range", {
  4381. make_range_header({{3, 5}}),
  4382. {"Accept-Encoding", ""},
  4383. });
  4384. ASSERT_TRUE(res);
  4385. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4386. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4387. EXPECT_EQ(true, res->has_header("Content-Range"));
  4388. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4389. EXPECT_EQ(std::string("def"), res->body);
  4390. }
  4391. TEST_F(ServerTest, GetWithRange2) {
  4392. auto res = cli_.Get("/with-range", {
  4393. make_range_header({{1, -1}}),
  4394. {"Accept-Encoding", ""},
  4395. });
  4396. ASSERT_TRUE(res);
  4397. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4398. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4399. EXPECT_EQ(true, res->has_header("Content-Range"));
  4400. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4401. EXPECT_EQ(std::string("bcdefg"), res->body);
  4402. }
  4403. TEST_F(ServerTest, GetWithRange3) {
  4404. auto res = cli_.Get("/with-range", {
  4405. make_range_header({{0, 0}}),
  4406. {"Accept-Encoding", ""},
  4407. });
  4408. ASSERT_TRUE(res);
  4409. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4410. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4411. EXPECT_EQ(true, res->has_header("Content-Range"));
  4412. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4413. EXPECT_EQ(std::string("a"), res->body);
  4414. }
  4415. TEST_F(ServerTest, GetWithRange4) {
  4416. auto res = cli_.Get("/with-range", {
  4417. make_range_header({{-1, 2}}),
  4418. {"Accept-Encoding", ""},
  4419. });
  4420. ASSERT_TRUE(res);
  4421. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4422. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4423. EXPECT_EQ(true, res->has_header("Content-Range"));
  4424. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4425. EXPECT_EQ(std::string("fg"), res->body);
  4426. }
  4427. TEST_F(ServerTest, GetWithRange5) {
  4428. auto res = cli_.Get("/with-range", {
  4429. make_range_header({{0, 5}}),
  4430. {"Accept-Encoding", ""},
  4431. });
  4432. ASSERT_TRUE(res);
  4433. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4434. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4435. EXPECT_EQ(true, res->has_header("Content-Range"));
  4436. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4437. EXPECT_EQ(std::string("abcdef"), res->body);
  4438. }
  4439. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4440. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4441. ASSERT_TRUE(res);
  4442. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4443. }
  4444. TEST_F(ServerTest, GetWithRangeMultipart) {
  4445. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4446. ASSERT_TRUE(res);
  4447. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4448. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4449. EXPECT_EQ(false, res->has_header("Content-Range"));
  4450. EXPECT_EQ(267U, res->body.size());
  4451. }
  4452. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4453. auto res =
  4454. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4455. ASSERT_TRUE(res);
  4456. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4457. }
  4458. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4459. auto res = cli_.Get("/with-range-customized-response",
  4460. {{make_range_header({{1, 2}})}});
  4461. ASSERT_TRUE(res);
  4462. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4463. EXPECT_EQ(true, res->has_header("Content-Length"));
  4464. EXPECT_EQ(false, res->has_header("Content-Range"));
  4465. EXPECT_EQ(JSON_DATA, res->body);
  4466. }
  4467. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4468. auto res = cli_.Get("/with-range-customized-response",
  4469. {{make_range_header({{1, 2}, {4, 5}})}});
  4470. ASSERT_TRUE(res);
  4471. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4472. EXPECT_EQ(true, res->has_header("Content-Length"));
  4473. EXPECT_EQ(false, res->has_header("Content-Range"));
  4474. EXPECT_EQ(JSON_DATA, res->body);
  4475. }
  4476. TEST_F(ServerTest, Issue1772) {
  4477. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4478. ASSERT_TRUE(res);
  4479. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4480. }
  4481. TEST_F(ServerTest, Issue609) {
  4482. auto res = cli_.Delete("/issue609");
  4483. ASSERT_TRUE(res);
  4484. EXPECT_EQ(StatusCode::OK_200, res->status);
  4485. EXPECT_EQ(std::string("ok"), res->body);
  4486. }
  4487. TEST_F(ServerTest, GetStreamedChunked) {
  4488. auto res = cli_.Get("/streamed-chunked");
  4489. ASSERT_TRUE(res);
  4490. EXPECT_EQ(StatusCode::OK_200, res->status);
  4491. EXPECT_EQ(std::string("123456789"), res->body);
  4492. }
  4493. TEST_F(ServerTest, GetStreamedChunked2) {
  4494. auto res = cli_.Get("/streamed-chunked2");
  4495. ASSERT_TRUE(res);
  4496. EXPECT_EQ(StatusCode::OK_200, res->status);
  4497. EXPECT_EQ(std::string("123456789"), res->body);
  4498. }
  4499. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4500. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4501. ASSERT_TRUE(res);
  4502. EXPECT_EQ(StatusCode::OK_200, res->status);
  4503. EXPECT_EQ(std::string("123456789"), res->body);
  4504. EXPECT_TRUE(res->has_header("Trailer"));
  4505. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4506. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4507. // Trailers are now stored separately from headers (security fix)
  4508. EXPECT_EQ(2U, res->trailers.size());
  4509. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4510. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4511. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4512. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4513. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4514. // Verify trailers are NOT in headers (security verification)
  4515. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4516. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4517. }
  4518. TEST_F(ServerTest, LargeChunkedPost) {
  4519. Request req;
  4520. req.method = "POST";
  4521. req.path = "/large-chunked";
  4522. std::string host_and_port;
  4523. host_and_port += HOST;
  4524. host_and_port += ":";
  4525. host_and_port += std::to_string(PORT);
  4526. req.headers.emplace("Host", host_and_port.c_str());
  4527. req.headers.emplace("Accept", "*/*");
  4528. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4529. req.headers.emplace("Content-Type", "text/plain");
  4530. req.headers.emplace("Content-Length", "0");
  4531. req.headers.emplace("Transfer-Encoding", "chunked");
  4532. std::string long_string(30 * 1024u, 'a');
  4533. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4534. // Attempt to make a large enough post to exceed OS buffers, to test that
  4535. // the server handles short reads if the full chunk data isn't available.
  4536. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4537. auto res = std::make_shared<Response>();
  4538. auto error = Error::Success;
  4539. auto ret = cli_.send(req, *res, error);
  4540. ASSERT_TRUE(ret);
  4541. EXPECT_EQ(StatusCode::OK_200, res->status);
  4542. }
  4543. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4544. auto res = cli_.Get("/remote_addr");
  4545. ASSERT_TRUE(res);
  4546. EXPECT_EQ(StatusCode::OK_200, res->status);
  4547. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4548. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4549. }
  4550. TEST_F(ServerTest, GetMethodLocalAddr) {
  4551. auto res = cli_.Get("/local_addr");
  4552. ASSERT_TRUE(res);
  4553. EXPECT_EQ(StatusCode::OK_200, res->status);
  4554. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4555. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4556. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4557. }
  4558. TEST_F(ServerTest, HTTPResponseSplitting) {
  4559. auto res = cli_.Get("/http_response_splitting");
  4560. ASSERT_TRUE(res);
  4561. EXPECT_EQ(StatusCode::OK_200, res->status);
  4562. }
  4563. TEST_F(ServerTest, SlowRequest) {
  4564. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4565. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4566. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4567. }
  4568. #if 0
  4569. TEST_F(ServerTest, SlowPost) {
  4570. char buffer[64 * 1024];
  4571. memset(buffer, 0x42, sizeof(buffer));
  4572. auto res = cli_.Post(
  4573. "/slowpost", 64 * 1024 * 1024,
  4574. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4575. auto ret = sink.write(buffer, sizeof(buffer));
  4576. EXPECT_TRUE(ret);
  4577. return true;
  4578. },
  4579. "text/plain");
  4580. ASSERT_TRUE(res);
  4581. EXPECT_EQ(StatusCode::OK_200, res->status);
  4582. }
  4583. TEST_F(ServerTest, SlowPostFail) {
  4584. char buffer[64 * 1024];
  4585. memset(buffer, 0x42, sizeof(buffer));
  4586. cli_.set_write_timeout(std::chrono::seconds(0));
  4587. auto res = cli_.Post(
  4588. "/slowpost", 64 * 1024 * 1024,
  4589. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4590. sink.write(buffer, sizeof(buffer));
  4591. return true;
  4592. },
  4593. "text/plain");
  4594. ASSERT_TRUE(!res);
  4595. EXPECT_EQ(Error::Write, res.error());
  4596. }
  4597. #endif
  4598. TEST_F(ServerTest, Put) {
  4599. auto res = cli_.Put("/put", "PUT", "text/plain");
  4600. ASSERT_TRUE(res);
  4601. EXPECT_EQ(StatusCode::OK_200, res->status);
  4602. EXPECT_EQ("PUT", res->body);
  4603. }
  4604. TEST_F(ServerTest, PutWithContentProvider) {
  4605. auto res = cli_.Put(
  4606. "/put", 3,
  4607. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4608. sink.os << "PUT";
  4609. return true;
  4610. },
  4611. "text/plain");
  4612. ASSERT_TRUE(res);
  4613. EXPECT_EQ(StatusCode::OK_200, res->status);
  4614. EXPECT_EQ("PUT", res->body);
  4615. }
  4616. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4617. auto res = cli_.Post(
  4618. "/post", 42,
  4619. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4620. return false;
  4621. },
  4622. "text/plain");
  4623. ASSERT_TRUE(!res);
  4624. EXPECT_EQ(Error::Canceled, res.error());
  4625. }
  4626. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4627. auto res = cli_.Put(
  4628. "/put",
  4629. [](size_t /*offset*/, DataSink &sink) {
  4630. sink.os << "PUT";
  4631. sink.done();
  4632. return true;
  4633. },
  4634. "text/plain");
  4635. ASSERT_TRUE(res);
  4636. EXPECT_EQ(StatusCode::OK_200, res->status);
  4637. EXPECT_EQ("PUT", res->body);
  4638. }
  4639. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4640. auto res = cli_.Post(
  4641. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4642. "text/plain");
  4643. ASSERT_TRUE(!res);
  4644. EXPECT_EQ(Error::Canceled, res.error());
  4645. }
  4646. TEST_F(ServerTest, PostLoopBack) {
  4647. std::string body;
  4648. auto res = cli_.Post(
  4649. "/post-loopback", 9,
  4650. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4651. EXPECT_EQ(9u, length);
  4652. sink.write("123", 3);
  4653. sink.write("456", 3);
  4654. sink.write("789", 3);
  4655. return true;
  4656. },
  4657. "text/plain",
  4658. [&body](const char *data, size_t data_length) {
  4659. body.append(data, data_length);
  4660. return true;
  4661. });
  4662. ASSERT_TRUE(res);
  4663. EXPECT_EQ(StatusCode::OK_200, res->status);
  4664. EXPECT_EQ("123456789", body);
  4665. }
  4666. TEST_F(ServerTest, PutLoopBack) {
  4667. std::string body;
  4668. auto res = cli_.Put(
  4669. "/put-loopback", 9,
  4670. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4671. EXPECT_EQ(9u, length);
  4672. sink.write("123", 3);
  4673. sink.write("456", 3);
  4674. sink.write("789", 3);
  4675. return true;
  4676. },
  4677. "text/plain",
  4678. [&body](const char *data, size_t data_length) {
  4679. body.append(data, data_length);
  4680. return true;
  4681. });
  4682. ASSERT_TRUE(res);
  4683. EXPECT_EQ(StatusCode::OK_200, res->status);
  4684. EXPECT_EQ("123456789", body);
  4685. }
  4686. TEST_F(ServerTest, PatchLoopBack) {
  4687. std::string body;
  4688. auto res = cli_.Patch(
  4689. "/patch-loopback", 9,
  4690. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4691. EXPECT_EQ(9u, length);
  4692. sink.write("123", 3);
  4693. sink.write("456", 3);
  4694. sink.write("789", 3);
  4695. return true;
  4696. },
  4697. "text/plain",
  4698. [&body](const char *data, size_t data_length) {
  4699. body.append(data, data_length);
  4700. return true;
  4701. });
  4702. ASSERT_TRUE(res);
  4703. EXPECT_EQ(StatusCode::OK_200, res->status);
  4704. EXPECT_EQ("123456789", body);
  4705. }
  4706. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4707. std::string body;
  4708. auto res = cli_.Post(
  4709. "/post-loopback",
  4710. [](size_t /*offset*/, DataSink &sink) {
  4711. sink.write("123", 3);
  4712. sink.write("456", 3);
  4713. sink.write("789", 3);
  4714. sink.done();
  4715. return true;
  4716. },
  4717. "text/plain",
  4718. [&body](const char *data, size_t data_length) {
  4719. body.append(data, data_length);
  4720. return true;
  4721. });
  4722. ASSERT_TRUE(res);
  4723. EXPECT_EQ(StatusCode::OK_200, res->status);
  4724. EXPECT_EQ("123456789", body);
  4725. }
  4726. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4727. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4728. cli_.set_compress(true);
  4729. auto res = cli_.Put(
  4730. "/put", 3,
  4731. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4732. sink.os << "PUT";
  4733. return true;
  4734. },
  4735. "text/plain");
  4736. ASSERT_TRUE(res);
  4737. EXPECT_EQ(StatusCode::OK_200, res->status);
  4738. EXPECT_EQ("PUT", res->body);
  4739. }
  4740. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4741. cli_.set_compress(true);
  4742. auto res = cli_.Post(
  4743. "/post", 42,
  4744. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4745. return false;
  4746. },
  4747. "text/plain");
  4748. ASSERT_TRUE(!res);
  4749. EXPECT_EQ(Error::Canceled, res.error());
  4750. }
  4751. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4752. cli_.set_compress(true);
  4753. auto res = cli_.Put(
  4754. "/put",
  4755. [](size_t /*offset*/, DataSink &sink) {
  4756. sink.os << "PUT";
  4757. sink.done();
  4758. return true;
  4759. },
  4760. "text/plain");
  4761. ASSERT_TRUE(res);
  4762. EXPECT_EQ(StatusCode::OK_200, res->status);
  4763. EXPECT_EQ("PUT", res->body);
  4764. }
  4765. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4766. cli_.set_compress(true);
  4767. auto res = cli_.Post(
  4768. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4769. "text/plain");
  4770. ASSERT_TRUE(!res);
  4771. EXPECT_EQ(Error::Canceled, res.error());
  4772. }
  4773. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4774. cli_.set_compress(true);
  4775. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4776. ASSERT_TRUE(res);
  4777. EXPECT_EQ(StatusCode::OK_200, res->status);
  4778. EXPECT_EQ(LARGE_DATA, res->body);
  4779. }
  4780. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4781. #ifdef CPPHTTPLIB_SSL_ENABLED
  4782. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4783. Client cli(s.c_str());
  4784. cli.enable_server_certificate_verification(false);
  4785. #else
  4786. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4787. Client cli(s.c_str());
  4788. #endif
  4789. cli.set_compress(true);
  4790. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4791. ASSERT_TRUE(res);
  4792. EXPECT_EQ(StatusCode::OK_200, res->status);
  4793. EXPECT_EQ(LARGE_DATA, res->body);
  4794. // The compressed size should be less than a 10th of the original. May vary
  4795. // depending on the zlib library.
  4796. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4797. static_cast<uint64_t>(10 * 1024 * 1024));
  4798. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4799. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  4800. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  4801. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4802. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4803. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  4804. #endif
  4805. }
  4806. TEST_F(ServerTest, PutContentWithDeflate) {
  4807. cli_.set_compress(false);
  4808. Headers headers;
  4809. headers.emplace("Content-Encoding", "deflate");
  4810. // PUT in deflate format:
  4811. auto res = cli_.Put("/put", headers,
  4812. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4813. ASSERT_TRUE(res);
  4814. EXPECT_EQ(StatusCode::OK_200, res->status);
  4815. EXPECT_EQ("PUT", res->body);
  4816. }
  4817. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4818. Headers headers;
  4819. headers.emplace("Accept-Encoding", "gzip, deflate");
  4820. auto res = cli_.Get("/streamed-chunked", headers);
  4821. ASSERT_TRUE(res);
  4822. EXPECT_EQ(StatusCode::OK_200, res->status);
  4823. EXPECT_EQ(std::string("123456789"), res->body);
  4824. }
  4825. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4826. Headers headers;
  4827. headers.emplace("Accept-Encoding", "gzip, deflate");
  4828. auto res = cli_.Get("/streamed-chunked2", headers);
  4829. ASSERT_TRUE(res);
  4830. EXPECT_EQ(StatusCode::OK_200, res->status);
  4831. EXPECT_EQ(std::string("123456789"), res->body);
  4832. }
  4833. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4834. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4835. ASSERT_TRUE(res);
  4836. EXPECT_EQ(StatusCode::OK_200, res->status);
  4837. }
  4838. TEST(GzipDecompressor, ChunkedDecompression) {
  4839. std::string data;
  4840. for (size_t i = 0; i < 32 * 1024; ++i) {
  4841. data.push_back(static_cast<char>('a' + i % 26));
  4842. }
  4843. std::string compressed_data;
  4844. {
  4845. httplib::detail::gzip_compressor compressor;
  4846. bool result = compressor.compress(
  4847. data.data(), data.size(),
  4848. /*last=*/true,
  4849. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4850. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4851. compressed_data_size);
  4852. return true;
  4853. });
  4854. ASSERT_TRUE(result);
  4855. }
  4856. std::string decompressed_data;
  4857. {
  4858. httplib::detail::gzip_decompressor decompressor;
  4859. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4860. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4861. size_t chunk_size = 130;
  4862. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4863. chunk_begin += chunk_size) {
  4864. size_t current_chunk_size =
  4865. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4866. bool result = decompressor.decompress(
  4867. compressed_data.data() + chunk_begin, current_chunk_size,
  4868. [&](const char *decompressed_data_chunk,
  4869. size_t decompressed_data_chunk_size) {
  4870. decompressed_data.insert(decompressed_data.size(),
  4871. decompressed_data_chunk,
  4872. decompressed_data_chunk_size);
  4873. return true;
  4874. });
  4875. ASSERT_TRUE(result);
  4876. }
  4877. }
  4878. ASSERT_EQ(data, decompressed_data);
  4879. }
  4880. TEST(GzipDecompressor, DeflateDecompression) {
  4881. std::string original_text = "Raw deflate without gzip";
  4882. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4883. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4884. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4885. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4886. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4887. std::string decompressed_data;
  4888. {
  4889. httplib::detail::gzip_decompressor decompressor;
  4890. bool result = decompressor.decompress(
  4891. compressed_data.data(), compressed_data.size(),
  4892. [&](const char *decompressed_data_chunk,
  4893. size_t decompressed_data_chunk_size) {
  4894. decompressed_data.insert(decompressed_data.size(),
  4895. decompressed_data_chunk,
  4896. decompressed_data_chunk_size);
  4897. return true;
  4898. });
  4899. ASSERT_TRUE(result);
  4900. }
  4901. ASSERT_EQ(original_text, decompressed_data);
  4902. }
  4903. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4904. std::string original_text = "Raw deflate without gzip";
  4905. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4906. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4907. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4908. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4909. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4910. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4911. std::string decompressed_data;
  4912. {
  4913. httplib::detail::gzip_decompressor decompressor;
  4914. bool result = decompressor.decompress(
  4915. compressed_data.data(), compressed_data.size(),
  4916. [&](const char *decompressed_data_chunk,
  4917. size_t decompressed_data_chunk_size) {
  4918. decompressed_data.insert(decompressed_data.size(),
  4919. decompressed_data_chunk,
  4920. decompressed_data_chunk_size);
  4921. return true;
  4922. });
  4923. ASSERT_TRUE(result);
  4924. }
  4925. ASSERT_EQ(original_text, decompressed_data);
  4926. }
  4927. #endif
  4928. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4929. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4930. Headers headers;
  4931. headers.emplace("Accept-Encoding", "br");
  4932. auto res = cli_.Get("/streamed-chunked", headers);
  4933. ASSERT_TRUE(res);
  4934. EXPECT_EQ(StatusCode::OK_200, res->status);
  4935. EXPECT_EQ(std::string("123456789"), res->body);
  4936. }
  4937. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4938. Headers headers;
  4939. headers.emplace("Accept-Encoding", "br");
  4940. auto res = cli_.Get("/streamed-chunked2", headers);
  4941. ASSERT_TRUE(res);
  4942. EXPECT_EQ(StatusCode::OK_200, res->status);
  4943. EXPECT_EQ(std::string("123456789"), res->body);
  4944. }
  4945. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  4946. cli_.set_compress(true);
  4947. auto res = cli_.Put(
  4948. "/put", 3,
  4949. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4950. sink.os << "PUT";
  4951. return true;
  4952. },
  4953. "text/plain");
  4954. ASSERT_TRUE(res);
  4955. EXPECT_EQ(StatusCode::OK_200, res->status);
  4956. EXPECT_EQ("PUT", res->body);
  4957. }
  4958. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  4959. cli_.set_compress(true);
  4960. auto res = cli_.Put(
  4961. "/put",
  4962. [](size_t /*offset*/, DataSink &sink) {
  4963. sink.os << "PUT";
  4964. sink.done();
  4965. return true;
  4966. },
  4967. "text/plain");
  4968. ASSERT_TRUE(res);
  4969. EXPECT_EQ(StatusCode::OK_200, res->status);
  4970. EXPECT_EQ("PUT", res->body);
  4971. }
  4972. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  4973. cli_.set_compress(true);
  4974. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4975. ASSERT_TRUE(res);
  4976. EXPECT_EQ(StatusCode::OK_200, res->status);
  4977. EXPECT_EQ(LARGE_DATA, res->body);
  4978. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  4979. }
  4980. #endif
  4981. TEST_F(ServerTest, Patch) {
  4982. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4983. ASSERT_TRUE(res);
  4984. EXPECT_EQ(StatusCode::OK_200, res->status);
  4985. EXPECT_EQ("PATCH", res->body);
  4986. }
  4987. TEST_F(ServerTest, Delete) {
  4988. auto res = cli_.Delete("/delete");
  4989. ASSERT_TRUE(res);
  4990. EXPECT_EQ(StatusCode::OK_200, res->status);
  4991. EXPECT_EQ("DELETE", res->body);
  4992. }
  4993. TEST_F(ServerTest, DeleteContentReceiver) {
  4994. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4995. ASSERT_TRUE(res);
  4996. EXPECT_EQ(StatusCode::OK_200, res->status);
  4997. EXPECT_EQ("content", res->body);
  4998. }
  4999. TEST_F(ServerTest, Options) {
  5000. auto res = cli_.Options("*");
  5001. ASSERT_TRUE(res);
  5002. EXPECT_EQ(StatusCode::OK_200, res->status);
  5003. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5004. EXPECT_TRUE(res->body.empty());
  5005. }
  5006. TEST_F(ServerTest, URL) {
  5007. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5008. ASSERT_TRUE(res);
  5009. EXPECT_EQ(StatusCode::OK_200, res->status);
  5010. }
  5011. TEST_F(ServerTest, ArrayParam) {
  5012. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5013. ASSERT_TRUE(res);
  5014. EXPECT_EQ(StatusCode::OK_200, res->status);
  5015. }
  5016. TEST_F(ServerTest, NoMultipleHeaders) {
  5017. Headers headers = {{"Content-Length", "5"}};
  5018. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5019. "text/plain");
  5020. ASSERT_TRUE(res);
  5021. EXPECT_EQ(StatusCode::OK_200, res->status);
  5022. }
  5023. TEST_F(ServerTest, PostContentReceiver) {
  5024. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5025. ASSERT_TRUE(res);
  5026. ASSERT_EQ(StatusCode::OK_200, res->status);
  5027. ASSERT_EQ("content", res->body);
  5028. }
  5029. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5030. UploadFormDataItems items = {
  5031. {"text1", "text default", "", ""},
  5032. {"text2", "aωb", "", ""},
  5033. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5034. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5035. {"file3", "", "", "application/octet-stream"},
  5036. };
  5037. auto res = cli_.Post("/content_receiver", items);
  5038. ASSERT_TRUE(res);
  5039. EXPECT_EQ(StatusCode::OK_200, res->status);
  5040. }
  5041. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5042. UploadFormDataItems items = {
  5043. {"text1", "text default", "", ""},
  5044. {"text2", "aωb", "", ""},
  5045. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5046. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5047. {"file3", "", "", "application/octet-stream"},
  5048. };
  5049. auto boundary = std::string("+++++");
  5050. std::string body;
  5051. for (const auto &item : items) {
  5052. body += "--" + boundary + "\r\n";
  5053. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5054. if (!item.filename.empty()) {
  5055. body += "; filename=\"" + item.filename + "\"";
  5056. }
  5057. body += "\r\n";
  5058. if (!item.content_type.empty()) {
  5059. body += "Content-Type: " + item.content_type + "\r\n";
  5060. }
  5061. body += "\r\n";
  5062. body += item.content + "\r\n";
  5063. }
  5064. body += "--" + boundary + "--\r\n";
  5065. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5066. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5067. ASSERT_TRUE(res);
  5068. EXPECT_EQ(StatusCode::OK_200, res->status);
  5069. }
  5070. TEST_F(ServerTest, PostContentReceiverGzip) {
  5071. cli_.set_compress(true);
  5072. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5073. ASSERT_TRUE(res);
  5074. ASSERT_EQ(StatusCode::OK_200, res->status);
  5075. ASSERT_EQ("content", res->body);
  5076. }
  5077. TEST_F(ServerTest, PutContentReceiver) {
  5078. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5079. ASSERT_TRUE(res);
  5080. ASSERT_EQ(StatusCode::OK_200, res->status);
  5081. ASSERT_EQ("content", res->body);
  5082. }
  5083. TEST_F(ServerTest, PatchContentReceiver) {
  5084. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5085. ASSERT_TRUE(res);
  5086. ASSERT_EQ(StatusCode::OK_200, res->status);
  5087. ASSERT_EQ("content", res->body);
  5088. }
  5089. template <typename ClientType>
  5090. void TestWithHeadersAndContentReceiver(
  5091. ClientType &cli,
  5092. std::function<Result(ClientType &, const std::string &, const Headers &,
  5093. const std::string &, const std::string &,
  5094. ContentReceiver, DownloadProgress)>
  5095. request_func) {
  5096. Headers headers;
  5097. headers.emplace("X-Custom-Header", "test-value");
  5098. std::string received_body;
  5099. auto res = request_func(
  5100. cli, "/content_receiver", headers, "content", "application/json",
  5101. [&](const char *data, size_t data_length) {
  5102. received_body.append(data, data_length);
  5103. return true;
  5104. },
  5105. nullptr);
  5106. ASSERT_TRUE(res);
  5107. EXPECT_EQ(StatusCode::OK_200, res->status);
  5108. EXPECT_EQ("content", received_body);
  5109. }
  5110. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5111. #ifdef CPPHTTPLIB_SSL_ENABLED
  5112. using ClientT = SSLClient;
  5113. #else
  5114. using ClientT = Client;
  5115. #endif
  5116. TestWithHeadersAndContentReceiver<ClientT>(
  5117. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5118. const std::string &body, const std::string &content_type,
  5119. ContentReceiver receiver, DownloadProgress progress) {
  5120. return cli.Post(path, headers, body, content_type, receiver, progress);
  5121. });
  5122. }
  5123. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5124. #ifdef CPPHTTPLIB_SSL_ENABLED
  5125. using ClientT = SSLClient;
  5126. #else
  5127. using ClientT = Client;
  5128. #endif
  5129. TestWithHeadersAndContentReceiver<ClientT>(
  5130. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5131. const std::string &body, const std::string &content_type,
  5132. ContentReceiver receiver, DownloadProgress progress) {
  5133. return cli.Put(path, headers, body, content_type, receiver, progress);
  5134. });
  5135. }
  5136. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5137. #ifdef CPPHTTPLIB_SSL_ENABLED
  5138. using ClientT = SSLClient;
  5139. #else
  5140. using ClientT = Client;
  5141. #endif
  5142. TestWithHeadersAndContentReceiver<ClientT>(
  5143. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5144. const std::string &body, const std::string &content_type,
  5145. ContentReceiver receiver, DownloadProgress progress) {
  5146. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5147. });
  5148. }
  5149. template <typename ClientType>
  5150. void TestWithHeadersAndContentReceiverWithProgress(
  5151. ClientType &cli,
  5152. std::function<Result(ClientType &, const std::string &, const Headers &,
  5153. const std::string &, const std::string &,
  5154. ContentReceiver, DownloadProgress)>
  5155. request_func) {
  5156. Headers headers;
  5157. headers.emplace("X-Test-Header", "progress-test");
  5158. std::string received_body;
  5159. auto progress_called = false;
  5160. auto res = request_func(
  5161. cli, "/content_receiver", headers, "content", "text/plain",
  5162. [&](const char *data, size_t data_length) {
  5163. received_body.append(data, data_length);
  5164. return true;
  5165. },
  5166. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5167. progress_called = true;
  5168. return true;
  5169. });
  5170. ASSERT_TRUE(res);
  5171. EXPECT_EQ(StatusCode::OK_200, res->status);
  5172. EXPECT_EQ("content", received_body);
  5173. EXPECT_TRUE(progress_called);
  5174. }
  5175. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5176. #ifdef CPPHTTPLIB_SSL_ENABLED
  5177. using ClientT = SSLClient;
  5178. #else
  5179. using ClientT = Client;
  5180. #endif
  5181. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5182. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5183. const std::string &body, const std::string &content_type,
  5184. ContentReceiver receiver, DownloadProgress progress) {
  5185. return cli.Post(path, headers, body, content_type, receiver, progress);
  5186. });
  5187. }
  5188. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5189. #ifdef CPPHTTPLIB_SSL_ENABLED
  5190. using ClientT = SSLClient;
  5191. #else
  5192. using ClientT = Client;
  5193. #endif
  5194. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5195. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5196. const std::string &body, const std::string &content_type,
  5197. ContentReceiver receiver, DownloadProgress progress) {
  5198. return cli.Put(path, headers, body, content_type, receiver, progress);
  5199. });
  5200. }
  5201. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5202. #ifdef CPPHTTPLIB_SSL_ENABLED
  5203. using ClientT = SSLClient;
  5204. #else
  5205. using ClientT = Client;
  5206. #endif
  5207. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5208. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5209. const std::string &body, const std::string &content_type,
  5210. ContentReceiver receiver, DownloadProgress progress) {
  5211. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5212. });
  5213. }
  5214. template <typename ClientType>
  5215. void TestWithHeadersAndContentReceiverError(
  5216. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5217. const Headers &, const std::string &,
  5218. const std::string &, ContentReceiver)>
  5219. request_func) {
  5220. Headers headers;
  5221. headers.emplace("X-Error-Test", "true");
  5222. std::string received_body;
  5223. auto receiver_failed = false;
  5224. auto res =
  5225. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5226. [&](const char *data, size_t data_length) {
  5227. received_body.append(data, data_length);
  5228. receiver_failed = true;
  5229. return false;
  5230. });
  5231. ASSERT_FALSE(res);
  5232. EXPECT_TRUE(receiver_failed);
  5233. }
  5234. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5235. #ifdef CPPHTTPLIB_SSL_ENABLED
  5236. using ClientT = SSLClient;
  5237. #else
  5238. using ClientT = Client;
  5239. #endif
  5240. TestWithHeadersAndContentReceiverError<ClientT>(
  5241. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5242. const std::string &body, const std::string &content_type,
  5243. ContentReceiver receiver) {
  5244. return cli.Post(path, headers, body, content_type, receiver);
  5245. });
  5246. }
  5247. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5248. #ifdef CPPHTTPLIB_SSL_ENABLED
  5249. using ClientT = SSLClient;
  5250. #else
  5251. using ClientT = Client;
  5252. #endif
  5253. TestWithHeadersAndContentReceiverError<ClientT>(
  5254. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5255. const std::string &body, const std::string &content_type,
  5256. ContentReceiver receiver) {
  5257. return cli.Put(path, headers, body, content_type, receiver);
  5258. });
  5259. }
  5260. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5261. #ifdef CPPHTTPLIB_SSL_ENABLED
  5262. using ClientT = SSLClient;
  5263. #else
  5264. using ClientT = Client;
  5265. #endif
  5266. TestWithHeadersAndContentReceiverError<ClientT>(
  5267. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5268. const std::string &body, const std::string &content_type,
  5269. ContentReceiver receiver) {
  5270. return cli.Patch(path, headers, body, content_type, receiver);
  5271. });
  5272. }
  5273. TEST_F(ServerTest, PostQueryStringAndBody) {
  5274. auto res =
  5275. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5276. ASSERT_TRUE(res);
  5277. ASSERT_EQ(StatusCode::OK_200, res->status);
  5278. }
  5279. TEST_F(ServerTest, HTTP2Magic) {
  5280. Request req;
  5281. req.method = "PRI";
  5282. req.path = "*";
  5283. req.body = "SM";
  5284. auto res = std::make_shared<Response>();
  5285. auto error = Error::Success;
  5286. auto ret = cli_.send(req, *res, error);
  5287. ASSERT_TRUE(ret);
  5288. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5289. }
  5290. TEST_F(ServerTest, KeepAlive) {
  5291. auto res = cli_.Get("/hi");
  5292. ASSERT_TRUE(res);
  5293. EXPECT_EQ(StatusCode::OK_200, res->status);
  5294. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5295. EXPECT_EQ("Hello World!", res->body);
  5296. res = cli_.Get("/hi");
  5297. ASSERT_TRUE(res);
  5298. EXPECT_EQ(StatusCode::OK_200, res->status);
  5299. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5300. EXPECT_EQ("Hello World!", res->body);
  5301. res = cli_.Get("/hi");
  5302. ASSERT_TRUE(res);
  5303. EXPECT_EQ(StatusCode::OK_200, res->status);
  5304. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5305. EXPECT_EQ("Hello World!", res->body);
  5306. res = cli_.Get("/not-exist");
  5307. ASSERT_TRUE(res);
  5308. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5309. res = cli_.Post("/empty", "", "text/plain");
  5310. ASSERT_TRUE(res);
  5311. EXPECT_EQ(StatusCode::OK_200, res->status);
  5312. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5313. EXPECT_EQ("empty", res->body);
  5314. EXPECT_EQ("close", res->get_header_value("Connection"));
  5315. res = cli_.Post(
  5316. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5317. "text/plain");
  5318. ASSERT_TRUE(res);
  5319. EXPECT_EQ(StatusCode::OK_200, res->status);
  5320. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5321. EXPECT_EQ("empty", res->body);
  5322. cli_.set_keep_alive(false);
  5323. res = cli_.Get("/last-request");
  5324. ASSERT_TRUE(res);
  5325. EXPECT_EQ(StatusCode::OK_200, res->status);
  5326. EXPECT_EQ("close", res->get_header_value("Connection"));
  5327. }
  5328. TEST_F(ServerTest, TooManyRedirect) {
  5329. cli_.set_follow_location(true);
  5330. auto res = cli_.Get("/redirect/0");
  5331. ASSERT_TRUE(!res);
  5332. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5333. }
  5334. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5335. Request req;
  5336. req.method = "FOOBAR";
  5337. req.path = "/hi";
  5338. cli_.set_keep_alive(true);
  5339. auto res = cli_.send(req);
  5340. ASSERT_TRUE(res);
  5341. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5342. EXPECT_EQ("close", res->get_header_value("Connection"));
  5343. EXPECT_FALSE(cli_.is_socket_open());
  5344. }
  5345. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5346. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5347. TEST_F(ServerTest, Gzip) {
  5348. Headers headers;
  5349. headers.emplace("Accept-Encoding", "gzip, deflate");
  5350. auto res = cli_.Get("/compress", headers);
  5351. ASSERT_TRUE(res);
  5352. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5353. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5354. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5355. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5356. "7890123456789012345678901234567890",
  5357. res->body);
  5358. EXPECT_EQ(StatusCode::OK_200, res->status);
  5359. }
  5360. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5361. Headers headers;
  5362. headers.emplace("Accept-Encoding", "gzip, deflate");
  5363. auto res = cli_.Get("/compress-with-charset", headers);
  5364. ASSERT_TRUE(res);
  5365. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5366. EXPECT_EQ("application/json; charset=utf-8",
  5367. res->get_header_value("Content-Type"));
  5368. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5369. "7890123456789012345678901234567890",
  5370. res->body);
  5371. EXPECT_EQ(StatusCode::OK_200, res->status);
  5372. }
  5373. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5374. Headers headers;
  5375. headers.emplace("Accept-Encoding", "");
  5376. auto res = cli_.Get("/compress", headers);
  5377. ASSERT_TRUE(res);
  5378. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5379. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5380. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5381. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5382. "7890123456789012345678901234567890",
  5383. res->body);
  5384. EXPECT_EQ(StatusCode::OK_200, res->status);
  5385. }
  5386. TEST_F(ServerTest, GzipWithContentReceiver) {
  5387. Headers headers;
  5388. headers.emplace("Accept-Encoding", "gzip, deflate");
  5389. std::string body;
  5390. auto res = cli_.Get("/compress", headers,
  5391. [&](const char *data, uint64_t data_length) {
  5392. EXPECT_EQ(100U, data_length);
  5393. body.append(data, data_length);
  5394. return true;
  5395. });
  5396. ASSERT_TRUE(res);
  5397. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5398. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5399. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5400. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5401. "7890123456789012345678901234567890",
  5402. body);
  5403. EXPECT_EQ(StatusCode::OK_200, res->status);
  5404. }
  5405. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5406. Headers headers;
  5407. headers.emplace("Accept-Encoding", "gzip, deflate");
  5408. cli_.set_decompress(false);
  5409. auto res = cli_.Get("/compress", headers);
  5410. ASSERT_TRUE(res);
  5411. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5412. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5413. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5414. EXPECT_EQ(33U, res->body.size());
  5415. EXPECT_EQ(StatusCode::OK_200, res->status);
  5416. }
  5417. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5418. Headers headers;
  5419. headers.emplace("Accept-Encoding", "");
  5420. std::string body;
  5421. auto res = cli_.Get("/compress", headers,
  5422. [&](const char *data, uint64_t data_length) {
  5423. EXPECT_EQ(100U, data_length);
  5424. body.append(data, data_length);
  5425. return true;
  5426. });
  5427. ASSERT_TRUE(res);
  5428. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5429. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5430. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5431. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5432. "7890123456789012345678901234567890",
  5433. body);
  5434. EXPECT_EQ(StatusCode::OK_200, res->status);
  5435. }
  5436. TEST_F(ServerTest, NoGzip) {
  5437. Headers headers;
  5438. headers.emplace("Accept-Encoding", "gzip, deflate");
  5439. auto res = cli_.Get("/nocompress", headers);
  5440. ASSERT_TRUE(res);
  5441. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5442. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5443. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5444. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5445. "7890123456789012345678901234567890",
  5446. res->body);
  5447. EXPECT_EQ(StatusCode::OK_200, res->status);
  5448. }
  5449. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5450. Headers headers;
  5451. headers.emplace("Accept-Encoding", "gzip, deflate");
  5452. std::string body;
  5453. auto res = cli_.Get("/nocompress", headers,
  5454. [&](const char *data, uint64_t data_length) {
  5455. EXPECT_EQ(100U, data_length);
  5456. body.append(data, data_length);
  5457. return true;
  5458. });
  5459. ASSERT_TRUE(res);
  5460. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5461. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5462. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5463. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5464. "7890123456789012345678901234567890",
  5465. body);
  5466. EXPECT_EQ(StatusCode::OK_200, res->status);
  5467. }
  5468. TEST_F(ServerTest, MultipartFormDataGzip) {
  5469. UploadFormDataItems items = {
  5470. {"key1", "test", "", ""},
  5471. {"key2", "--abcdefg123", "", ""},
  5472. };
  5473. cli_.set_compress(true);
  5474. auto res = cli_.Post("/compress-multipart", items);
  5475. ASSERT_TRUE(res);
  5476. EXPECT_EQ(StatusCode::OK_200, res->status);
  5477. }
  5478. #endif
  5479. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5480. TEST_F(ServerTest, Brotli) {
  5481. Headers headers;
  5482. headers.emplace("Accept-Encoding", "br");
  5483. auto res = cli_.Get("/compress", headers);
  5484. ASSERT_TRUE(res);
  5485. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5486. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5487. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5488. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5489. "7890123456789012345678901234567890",
  5490. res->body);
  5491. EXPECT_EQ(StatusCode::OK_200, res->status);
  5492. }
  5493. #endif
  5494. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5495. TEST_F(ServerTest, Zstd) {
  5496. Headers headers;
  5497. headers.emplace("Accept-Encoding", "zstd");
  5498. auto res = cli_.Get("/compress", headers);
  5499. ASSERT_TRUE(res);
  5500. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5501. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5502. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5503. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5504. "7890123456789012345678901234567890",
  5505. res->body);
  5506. EXPECT_EQ(StatusCode::OK_200, res->status);
  5507. }
  5508. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5509. Headers headers;
  5510. headers.emplace("Accept-Encoding", "");
  5511. auto res = cli_.Get("/compress", headers);
  5512. ASSERT_TRUE(res);
  5513. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5514. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5515. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5516. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5517. "7890123456789012345678901234567890",
  5518. res->body);
  5519. EXPECT_EQ(StatusCode::OK_200, res->status);
  5520. }
  5521. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5522. Headers headers;
  5523. headers.emplace("Accept-Encoding", "zstd");
  5524. std::string body;
  5525. auto res = cli_.Get("/compress", headers,
  5526. [&](const char *data, uint64_t data_length) {
  5527. EXPECT_EQ(100U, data_length);
  5528. body.append(data, data_length);
  5529. return true;
  5530. });
  5531. ASSERT_TRUE(res);
  5532. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5533. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5534. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5535. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5536. "7890123456789012345678901234567890",
  5537. body);
  5538. EXPECT_EQ(StatusCode::OK_200, res->status);
  5539. }
  5540. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5541. Headers headers;
  5542. headers.emplace("Accept-Encoding", "zstd");
  5543. cli_.set_decompress(false);
  5544. auto res = cli_.Get("/compress", headers);
  5545. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5546. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5547. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5548. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5549. ASSERT_TRUE(res);
  5550. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5551. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5552. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5553. EXPECT_EQ(StatusCode::OK_200, res->status);
  5554. ASSERT_EQ(26U, res->body.size());
  5555. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5556. 0);
  5557. }
  5558. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5559. Headers headers;
  5560. headers.emplace("Accept-Encoding", "");
  5561. std::string body;
  5562. auto res = cli_.Get("/compress", headers,
  5563. [&](const char *data, uint64_t data_length) {
  5564. EXPECT_EQ(100U, data_length);
  5565. body.append(data, data_length);
  5566. return true;
  5567. });
  5568. ASSERT_TRUE(res);
  5569. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5570. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5571. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5572. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5573. "7890123456789012345678901234567890",
  5574. body);
  5575. EXPECT_EQ(StatusCode::OK_200, res->status);
  5576. }
  5577. TEST_F(ServerTest, NoZstd) {
  5578. Headers headers;
  5579. headers.emplace("Accept-Encoding", "zstd");
  5580. auto res = cli_.Get("/nocompress", headers);
  5581. ASSERT_TRUE(res);
  5582. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5583. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5584. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5585. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5586. "7890123456789012345678901234567890",
  5587. res->body);
  5588. EXPECT_EQ(StatusCode::OK_200, res->status);
  5589. }
  5590. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5591. Headers headers;
  5592. headers.emplace("Accept-Encoding", "zstd");
  5593. std::string body;
  5594. auto res = cli_.Get("/nocompress", headers,
  5595. [&](const char *data, uint64_t data_length) {
  5596. EXPECT_EQ(100U, data_length);
  5597. body.append(data, data_length);
  5598. return true;
  5599. });
  5600. ASSERT_TRUE(res);
  5601. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5602. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5603. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5604. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5605. "7890123456789012345678901234567890",
  5606. body);
  5607. EXPECT_EQ(StatusCode::OK_200, res->status);
  5608. }
  5609. // TODO: How to enable zstd ??
  5610. TEST_F(ServerTest, MultipartFormDataZstd) {
  5611. UploadFormDataItems items = {
  5612. {"key1", "test", "", ""},
  5613. {"key2", "--abcdefg123", "", ""},
  5614. };
  5615. Headers headers;
  5616. headers.emplace("Accept-Encoding", "zstd");
  5617. cli_.set_compress(true);
  5618. auto res = cli_.Post("/compress-multipart", headers, items);
  5619. ASSERT_TRUE(res);
  5620. EXPECT_EQ(StatusCode::OK_200, res->status);
  5621. }
  5622. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5623. Headers headers;
  5624. headers.emplace("Accept-Encoding", "zstd");
  5625. cli_.set_compress(true);
  5626. auto res = cli_.Put(
  5627. "/put", headers, 3,
  5628. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5629. sink.os << "PUT";
  5630. return true;
  5631. },
  5632. "text/plain");
  5633. ASSERT_TRUE(res);
  5634. EXPECT_EQ(StatusCode::OK_200, res->status);
  5635. EXPECT_EQ("PUT", res->body);
  5636. }
  5637. // Pre-compression logging tests
  5638. TEST_F(ServerTest, PreCompressionLogging) {
  5639. // Test data for compression (matches the actual /compress endpoint content)
  5640. const std::string test_content =
  5641. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5642. "3456789012345678901234567890";
  5643. // Variables to capture logging data
  5644. std::string pre_compression_body;
  5645. std::string pre_compression_content_type;
  5646. std::string pre_compression_content_encoding;
  5647. std::string post_compression_body;
  5648. std::string post_compression_content_type;
  5649. std::string post_compression_content_encoding;
  5650. // Set up pre-compression logger
  5651. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5652. const Response &res) {
  5653. pre_compression_body = res.body;
  5654. pre_compression_content_type = res.get_header_value("Content-Type");
  5655. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5656. });
  5657. // Set up post-compression logger
  5658. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5659. post_compression_body = res.body;
  5660. post_compression_content_type = res.get_header_value("Content-Type");
  5661. post_compression_content_encoding =
  5662. res.get_header_value("Content-Encoding");
  5663. });
  5664. // Test with gzip compression
  5665. Headers headers;
  5666. headers.emplace("Accept-Encoding", "gzip");
  5667. auto res = cli_.Get("/compress", headers);
  5668. // Verify response was compressed
  5669. ASSERT_TRUE(res);
  5670. EXPECT_EQ(StatusCode::OK_200, res->status);
  5671. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5672. // Verify pre-compression logger captured uncompressed content
  5673. EXPECT_EQ(test_content, pre_compression_body);
  5674. EXPECT_EQ("text/plain", pre_compression_content_type);
  5675. EXPECT_TRUE(pre_compression_content_encoding
  5676. .empty()); // No encoding header before compression
  5677. // Verify post-compression logger captured compressed content
  5678. EXPECT_NE(test_content,
  5679. post_compression_body); // Should be different after compression
  5680. EXPECT_EQ("text/plain", post_compression_content_type);
  5681. EXPECT_EQ("gzip", post_compression_content_encoding);
  5682. // Verify compressed content is smaller
  5683. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5684. }
  5685. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5686. const std::string test_content =
  5687. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5688. "3456789012345678901234567890";
  5689. std::string pre_compression_body;
  5690. std::string post_compression_body;
  5691. svr_.set_pre_compression_logger(
  5692. [&](const Request & /*req*/, const Response &res) {
  5693. pre_compression_body = res.body;
  5694. });
  5695. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5696. post_compression_body = res.body;
  5697. });
  5698. Headers headers;
  5699. headers.emplace("Accept-Encoding", "br");
  5700. auto res = cli_.Get("/compress", headers);
  5701. ASSERT_TRUE(res);
  5702. EXPECT_EQ(StatusCode::OK_200, res->status);
  5703. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5704. // Verify pre-compression content is uncompressed
  5705. EXPECT_EQ(test_content, pre_compression_body);
  5706. // Verify post-compression content is compressed
  5707. EXPECT_NE(test_content, post_compression_body);
  5708. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5709. }
  5710. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5711. const std::string test_content =
  5712. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5713. "3456789012345678901234567890";
  5714. std::string pre_compression_body;
  5715. std::string post_compression_body;
  5716. svr_.set_pre_compression_logger(
  5717. [&](const Request & /*req*/, const Response &res) {
  5718. pre_compression_body = res.body;
  5719. });
  5720. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5721. post_compression_body = res.body;
  5722. });
  5723. // Request without compression (use /nocompress endpoint)
  5724. Headers headers;
  5725. auto res = cli_.Get("/nocompress", headers);
  5726. ASSERT_TRUE(res);
  5727. EXPECT_EQ(StatusCode::OK_200, res->status);
  5728. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5729. // Pre-compression logger should not be called when no compression is applied
  5730. EXPECT_TRUE(
  5731. pre_compression_body.empty()); // Pre-compression logger not called
  5732. EXPECT_EQ(
  5733. test_content,
  5734. post_compression_body); // Post-compression logger captures final content
  5735. }
  5736. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5737. const std::string test_content =
  5738. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5739. "3456789012345678901234567890";
  5740. std::string pre_compression_body;
  5741. bool pre_logger_called = false;
  5742. // Set only pre-compression logger
  5743. svr_.set_pre_compression_logger(
  5744. [&](const Request & /*req*/, const Response &res) {
  5745. pre_compression_body = res.body;
  5746. pre_logger_called = true;
  5747. });
  5748. Headers headers;
  5749. headers.emplace("Accept-Encoding", "gzip");
  5750. auto res = cli_.Get("/compress", headers);
  5751. ASSERT_TRUE(res);
  5752. EXPECT_EQ(StatusCode::OK_200, res->status);
  5753. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5754. // Verify pre-compression logger was called
  5755. EXPECT_TRUE(pre_logger_called);
  5756. EXPECT_EQ(test_content, pre_compression_body);
  5757. }
  5758. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5759. {
  5760. // Test with Expect: 100-continue header - success case
  5761. // Server returns 100 Continue, client sends body, server returns 200 OK
  5762. Request req;
  5763. req.method = "POST";
  5764. req.path = "/post-large";
  5765. req.set_header("Expect", "100-continue");
  5766. req.body = LARGE_DATA;
  5767. Response res;
  5768. auto error = Error::Success;
  5769. cli_.set_keep_alive(true);
  5770. auto ret = cli_.send(req, res, error);
  5771. EXPECT_TRUE(ret);
  5772. EXPECT_EQ(StatusCode::OK_200, res.status);
  5773. EXPECT_EQ(LARGE_DATA, res.body);
  5774. }
  5775. {
  5776. // Test with Expect: 100-continue header - error case
  5777. // Client should not send the body when server returns an error
  5778. Request req;
  5779. req.method = "POST";
  5780. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5781. req.set_header("Expect", "100-continue");
  5782. req.body = LARGE_DATA;
  5783. Response res;
  5784. auto error = Error::Success;
  5785. auto start = std::chrono::high_resolution_clock::now();
  5786. cli_.set_keep_alive(true);
  5787. auto ret = cli_.send(req, res, error);
  5788. auto end = std::chrono::high_resolution_clock::now();
  5789. auto elapsed =
  5790. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5791. .count();
  5792. // With Expect: 100-continue, request completes successfully but with error
  5793. EXPECT_TRUE(ret);
  5794. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5795. EXPECT_EQ("close", res.get_header_value("Connection"));
  5796. EXPECT_FALSE(cli_.is_socket_open());
  5797. EXPECT_LE(elapsed, 200);
  5798. }
  5799. {
  5800. // Send an extra GET request to ensure error recovery without hanging
  5801. Request req;
  5802. req.method = "GET";
  5803. req.path = "/hi";
  5804. auto start = std::chrono::high_resolution_clock::now();
  5805. auto res = cli_.send(req);
  5806. auto end = std::chrono::high_resolution_clock::now();
  5807. auto elapsed =
  5808. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5809. .count();
  5810. ASSERT_TRUE(res);
  5811. EXPECT_EQ(StatusCode::OK_200, res->status);
  5812. EXPECT_EQ("Hello World!", res->body);
  5813. EXPECT_LE(elapsed, 500);
  5814. }
  5815. }
  5816. TEST(ZstdDecompressor, ChunkedDecompression) {
  5817. std::string data;
  5818. for (size_t i = 0; i < 32 * 1024; ++i) {
  5819. data.push_back(static_cast<char>('a' + i % 26));
  5820. }
  5821. std::string compressed_data;
  5822. {
  5823. httplib::detail::zstd_compressor compressor;
  5824. bool result = compressor.compress(
  5825. data.data(), data.size(),
  5826. /*last=*/true,
  5827. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5828. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5829. compressed_data_size);
  5830. return true;
  5831. });
  5832. ASSERT_TRUE(result);
  5833. }
  5834. std::string decompressed_data;
  5835. {
  5836. httplib::detail::zstd_decompressor decompressor;
  5837. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5838. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5839. size_t chunk_size = 130;
  5840. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5841. chunk_begin += chunk_size) {
  5842. size_t current_chunk_size =
  5843. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5844. bool result = decompressor.decompress(
  5845. compressed_data.data() + chunk_begin, current_chunk_size,
  5846. [&](const char *decompressed_data_chunk,
  5847. size_t decompressed_data_chunk_size) {
  5848. decompressed_data.insert(decompressed_data.size(),
  5849. decompressed_data_chunk,
  5850. decompressed_data_chunk_size);
  5851. return true;
  5852. });
  5853. ASSERT_TRUE(result);
  5854. }
  5855. }
  5856. ASSERT_EQ(data, decompressed_data);
  5857. }
  5858. TEST(ZstdDecompressor, Decompress) {
  5859. std::string original_text = "Compressed with ZSTD";
  5860. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5861. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5862. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5863. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5864. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5865. std::string decompressed_data;
  5866. {
  5867. httplib::detail::zstd_decompressor decompressor;
  5868. bool result = decompressor.decompress(
  5869. compressed_data.data(), compressed_data.size(),
  5870. [&](const char *decompressed_data_chunk,
  5871. size_t decompressed_data_chunk_size) {
  5872. decompressed_data.insert(decompressed_data.size(),
  5873. decompressed_data_chunk,
  5874. decompressed_data_chunk_size);
  5875. return true;
  5876. });
  5877. ASSERT_TRUE(result);
  5878. }
  5879. ASSERT_EQ(original_text, decompressed_data);
  5880. }
  5881. #endif
  5882. // Sends a raw request to a server listening at HOST:PORT.
  5883. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5884. std::string *resp = nullptr) {
  5885. auto error = Error::Success;
  5886. auto client_sock = detail::create_client_socket(
  5887. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5888. /*connection_timeout_sec=*/5, 0,
  5889. /*read_timeout_sec=*/5, 0,
  5890. /*write_timeout_sec=*/5, 0, std::string(), error);
  5891. if (client_sock == INVALID_SOCKET) { return false; }
  5892. auto ret = detail::process_client_socket(
  5893. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5894. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5895. if (req.size() !=
  5896. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5897. return false;
  5898. }
  5899. char buf[512];
  5900. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5901. while (line_reader.getline()) {
  5902. if (resp) { *resp += line_reader.ptr(); }
  5903. }
  5904. return true;
  5905. });
  5906. detail::close_socket(client_sock);
  5907. return ret;
  5908. }
  5909. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5910. Server svr;
  5911. std::string header_value;
  5912. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5913. header_value = req.get_header_value("foo");
  5914. res.set_content("ok", "text/plain");
  5915. });
  5916. thread t = thread([&] { svr.listen(HOST, PORT); });
  5917. auto se = detail::scope_exit([&] {
  5918. svr.stop();
  5919. t.join();
  5920. ASSERT_FALSE(svr.is_running());
  5921. });
  5922. svr.wait_until_ready();
  5923. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5924. // like characters are not treated the same - use vertical tab and escape.
  5925. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5926. "foo: \t \v bar \x1B\t \r\n"
  5927. "Connection: close\r\n"
  5928. "\r\n";
  5929. std::string res;
  5930. ASSERT_TRUE(send_request(5, req, &res));
  5931. EXPECT_EQ(header_value, "");
  5932. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5933. }
  5934. // Sends a raw request and verifies that there isn't a crash or exception.
  5935. static void test_raw_request(const std::string &req,
  5936. std::string *out = nullptr) {
  5937. Server svr;
  5938. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5939. res.set_content("ok", "text/plain");
  5940. });
  5941. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5942. res.set_content("ok", "text/plain");
  5943. });
  5944. svr.Get("/header_field_value_check",
  5945. [&](const Request & /*req*/, Response &res) {
  5946. res.set_content("ok", "text/plain");
  5947. });
  5948. // Server read timeout must be longer than the client read timeout for the
  5949. // bug to reproduce, probably to force the server to process a request
  5950. // without a trailing blank line.
  5951. const time_t client_read_timeout_sec = 1;
  5952. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5953. bool listen_thread_ok = false;
  5954. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5955. auto se = detail::scope_exit([&] {
  5956. svr.stop();
  5957. t.join();
  5958. ASSERT_FALSE(svr.is_running());
  5959. EXPECT_TRUE(listen_thread_ok);
  5960. });
  5961. svr.wait_until_ready();
  5962. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5963. }
  5964. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5965. // A certain header line causes an exception if the header property is parsed
  5966. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5967. test_raw_request(
  5968. "GET /hi HTTP/1.1\r\n"
  5969. " : "
  5970. " "
  5971. " ");
  5972. }
  5973. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5974. // A certain header line causes an exception if the header property *name* is
  5975. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5976. // greedy matcher and requires backtracking when there are a lot of ":"
  5977. // characters.
  5978. // This occurs with libc++ but not libstdc++.
  5979. test_raw_request(
  5980. "GET /hi HTTP/1.1\r\n"
  5981. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5982. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5983. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5984. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5985. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5986. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5987. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5988. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5989. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5990. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5991. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5992. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5993. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5994. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5995. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5996. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5997. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5998. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5999. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6000. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6001. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6002. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6003. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6004. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6005. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6006. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6007. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6008. "&&&%%%");
  6009. }
  6010. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6011. // Make sure this doesn't crash the server.
  6012. // In a previous version of the header line regex, the "\r" rendered the line
  6013. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6014. // a new position where the leading white space ended and the field value
  6015. // began.
  6016. // The crash occurs with libc++ but not libstdc++.
  6017. test_raw_request("GET /hi HTTP/1.1\r\n"
  6018. "a:" +
  6019. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6020. "\r\n"
  6021. "\r\n");
  6022. }
  6023. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6024. std::string out;
  6025. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6026. "Content-Type: text/plain\r\n"
  6027. "Transfer-Encoding: chunked\r\n"
  6028. "\r\n"
  6029. "nothex\r\n",
  6030. &out);
  6031. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6032. }
  6033. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6034. std::string out;
  6035. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6036. "Content-Type: text/plain\r\n"
  6037. "Transfer-Encoding: chunked\r\n"
  6038. "\r\n"
  6039. "3\r\n"
  6040. "xyz\r\n"
  6041. "NaN\r\n",
  6042. &out);
  6043. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6044. }
  6045. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6046. std::string out;
  6047. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6048. "Content-Type: text/plain\r\n"
  6049. "Transfer-Encoding: chunked\r\n"
  6050. "\r\n"
  6051. // Length is too large for 64 bits.
  6052. "1ffffffffffffffff\r\n"
  6053. "xyz\r\n",
  6054. &out);
  6055. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6056. }
  6057. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6058. test_raw_request("GET /hi HTTP/1.1\r\n"
  6059. "Content-Type: text/plain\r\n\r");
  6060. }
  6061. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6062. std::string out;
  6063. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6064. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6065. }
  6066. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6067. Server svr;
  6068. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6069. EXPECT_TRUE(!req.remote_addr.empty());
  6070. });
  6071. thread t = thread([&] { svr.listen(HOST, PORT); });
  6072. auto se = detail::scope_exit([&] {
  6073. svr.stop();
  6074. t.join();
  6075. ASSERT_FALSE(svr.is_running());
  6076. });
  6077. svr.wait_until_ready();
  6078. // Send an invalid request line to trigger Bad Request
  6079. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6080. std::string out;
  6081. ASSERT_TRUE(send_request(5, bad_req, &out));
  6082. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6083. }
  6084. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6085. std::string out;
  6086. std::string request(
  6087. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6088. test_raw_request(request, &out);
  6089. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6090. }
  6091. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6092. std::string out;
  6093. std::string request(
  6094. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6095. test_raw_request(request, &out);
  6096. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6097. }
  6098. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6099. std::string out;
  6100. std::string request(
  6101. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6102. test_raw_request(request, &out);
  6103. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6104. }
  6105. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6106. std::string out;
  6107. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6108. "Test: \r\n\r\n",
  6109. &out);
  6110. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6111. }
  6112. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6113. Server svr;
  6114. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6115. res.set_header("Cache-Control", "no-cache");
  6116. res.set_chunked_content_provider(
  6117. "text/event-stream", [](size_t offset, DataSink &sink) {
  6118. std::string s = "data:";
  6119. s += std::to_string(offset);
  6120. s += "\n\n";
  6121. auto ret = sink.write(s.data(), s.size());
  6122. EXPECT_TRUE(ret);
  6123. std::this_thread::sleep_for(std::chrono::seconds(1));
  6124. return true;
  6125. });
  6126. });
  6127. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6128. svr.wait_until_ready();
  6129. Client client(HOST, PORT);
  6130. const Headers headers = {{"Accept", "text/event-stream"}};
  6131. auto get_thread = std::thread([&client, &headers]() {
  6132. auto res = client.Get(
  6133. "/events", headers,
  6134. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6135. });
  6136. auto se = detail::scope_exit([&] {
  6137. svr.stop();
  6138. get_thread.join();
  6139. listen_thread.join();
  6140. ASSERT_FALSE(svr.is_running());
  6141. });
  6142. // Give GET time to get a few messages.
  6143. std::this_thread::sleep_for(std::chrono::seconds(2));
  6144. }
  6145. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6146. httplib::Server svr;
  6147. svr.Post("/hi",
  6148. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6149. res.status = StatusCode::OK_200;
  6150. });
  6151. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6152. svr.wait_until_ready();
  6153. Client cli(HOST, PORT);
  6154. auto res = cli.Post("/hi", "data", "text/plain");
  6155. ASSERT_TRUE(res);
  6156. EXPECT_EQ(StatusCode::OK_200, res->status);
  6157. svr.stop();
  6158. thread.join();
  6159. ASSERT_FALSE(svr.is_running());
  6160. res = cli.Post("/hi", "data", "text/plain");
  6161. ASSERT_FALSE(res);
  6162. }
  6163. TEST(ServerStopTest, ListenFailure) {
  6164. Server svr;
  6165. auto t = thread([&]() {
  6166. auto ret = svr.listen("????", PORT);
  6167. EXPECT_FALSE(ret);
  6168. });
  6169. svr.wait_until_ready();
  6170. svr.stop();
  6171. t.join();
  6172. }
  6173. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6174. TEST(ServerStopTest, Decommision) {
  6175. Server svr;
  6176. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6177. for (int i = 0; i < 4; i++) {
  6178. auto is_even = !(i % 2);
  6179. std::thread t{[&] {
  6180. try {
  6181. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6182. if (is_even) {
  6183. throw std::runtime_error("Some thing that happens to go wrong.");
  6184. }
  6185. svr.listen(HOST, PORT);
  6186. } catch (...) { svr.decommission(); }
  6187. }};
  6188. svr.wait_until_ready();
  6189. // Server is up
  6190. {
  6191. Client cli(HOST, PORT);
  6192. auto res = cli.Get("/hi");
  6193. if (is_even) {
  6194. EXPECT_FALSE(res);
  6195. } else {
  6196. EXPECT_TRUE(res);
  6197. EXPECT_EQ("hi...", res->body);
  6198. }
  6199. }
  6200. svr.stop();
  6201. t.join();
  6202. // Server is down...
  6203. {
  6204. Client cli(HOST, PORT);
  6205. auto res = cli.Get("/hi");
  6206. EXPECT_FALSE(res);
  6207. }
  6208. }
  6209. }
  6210. #endif
  6211. // Helper function for string body upload progress tests
  6212. template <typename SetupHandler, typename ClientCall>
  6213. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6214. ClientCall &&client_call,
  6215. const string &body) {
  6216. Server svr;
  6217. setup_handler(svr);
  6218. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6219. auto se = detail::scope_exit([&] {
  6220. svr.stop();
  6221. t.join();
  6222. });
  6223. svr.wait_until_ready();
  6224. Client cli(HOST, PORT);
  6225. vector<uint64_t> progress_values;
  6226. bool progress_called = false;
  6227. auto res =
  6228. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6229. progress_values.push_back(current);
  6230. progress_called = true;
  6231. return true;
  6232. });
  6233. ASSERT_TRUE(res);
  6234. EXPECT_EQ(200, res->status);
  6235. EXPECT_TRUE(progress_called);
  6236. }
  6237. TEST(UploadProgressTest, PostStringBodyBasic) {
  6238. TestStringBodyUploadProgress(
  6239. [](Server &svr) {
  6240. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6241. res.set_content("received", "text/plain");
  6242. });
  6243. },
  6244. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6245. return cli.Post("/test", body, "text/plain", progress_callback);
  6246. },
  6247. "test data for upload progress");
  6248. }
  6249. TEST(UploadProgressTest, PutStringBodyBasic) {
  6250. TestStringBodyUploadProgress(
  6251. [](Server &svr) {
  6252. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6253. res.set_content("put received", "text/plain");
  6254. });
  6255. },
  6256. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6257. return cli.Put("/test", body, "text/plain", progress_callback);
  6258. },
  6259. "put test data for upload progress");
  6260. }
  6261. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6262. TestStringBodyUploadProgress(
  6263. [](Server &svr) {
  6264. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6265. res.set_content("patch received", "text/plain");
  6266. });
  6267. },
  6268. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6269. return cli.Patch("/test", body, "text/plain", progress_callback);
  6270. },
  6271. "patch test data for upload progress");
  6272. }
  6273. // Helper function for content provider upload progress tests
  6274. template <typename SetupHandler, typename ClientCall>
  6275. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6276. ClientCall &&client_call) {
  6277. Server svr;
  6278. setup_handler(svr);
  6279. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6280. auto se = detail::scope_exit([&] {
  6281. svr.stop();
  6282. t.join();
  6283. });
  6284. svr.wait_until_ready();
  6285. Client cli(HOST, PORT);
  6286. vector<uint64_t> progress_values;
  6287. auto res =
  6288. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6289. progress_values.push_back(current);
  6290. return true;
  6291. });
  6292. ASSERT_TRUE(res);
  6293. EXPECT_EQ(200, res->status);
  6294. EXPECT_FALSE(progress_values.empty());
  6295. }
  6296. TEST(UploadProgressTest, PostContentProviderProgress) {
  6297. TestContentProviderUploadProgress(
  6298. [](Server &svr) {
  6299. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6300. res.set_content("provider received", "text/plain");
  6301. });
  6302. },
  6303. [](Client &cli, UploadProgress progress_callback) {
  6304. return cli.Post(
  6305. "/test", 10,
  6306. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6307. sink.os << "test data";
  6308. return true;
  6309. },
  6310. "text/plain", progress_callback);
  6311. });
  6312. }
  6313. // Helper function for multipart upload progress tests
  6314. template <typename SetupHandler, typename ClientCall>
  6315. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6316. ClientCall &&client_call,
  6317. const string &endpoint) {
  6318. Server svr;
  6319. setup_handler(svr);
  6320. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6321. auto se = detail::scope_exit([&] {
  6322. svr.stop();
  6323. t.join();
  6324. });
  6325. svr.wait_until_ready();
  6326. Client cli(HOST, PORT);
  6327. vector<uint64_t> progress_values;
  6328. UploadFormDataItems items = {
  6329. {"field1", "value1", "", ""},
  6330. {"field2", "longer value for progress tracking test", "", ""},
  6331. {"file1", "file content data for upload progress", "test.txt",
  6332. "text/plain"}};
  6333. auto res = client_call(cli, endpoint, items,
  6334. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6335. progress_values.push_back(current);
  6336. return true;
  6337. });
  6338. ASSERT_TRUE(res);
  6339. EXPECT_EQ(200, res->status);
  6340. EXPECT_FALSE(progress_values.empty());
  6341. }
  6342. TEST(UploadProgressTest, PostMultipartProgress) {
  6343. TestMultipartUploadProgress(
  6344. [](Server &svr) {
  6345. svr.Post("/multipart", [](const Request &req, Response &res) {
  6346. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6347. res.set_content("multipart received", "text/plain");
  6348. });
  6349. },
  6350. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6351. UploadProgress progress_callback) {
  6352. return cli.Post(endpoint, items, progress_callback);
  6353. },
  6354. "/multipart");
  6355. }
  6356. // Helper function for basic download progress tests
  6357. template <typename SetupHandler, typename ClientCall>
  6358. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6359. ClientCall &&client_call, const string &endpoint,
  6360. size_t expected_content_size) {
  6361. Server svr;
  6362. setup_handler(svr);
  6363. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6364. auto se = detail::scope_exit([&] {
  6365. svr.stop();
  6366. t.join();
  6367. });
  6368. svr.wait_until_ready();
  6369. Client cli(HOST, PORT);
  6370. vector<uint64_t> progress_values;
  6371. auto res = client_call(cli, endpoint,
  6372. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6373. progress_values.push_back(current);
  6374. return true;
  6375. });
  6376. ASSERT_TRUE(res);
  6377. EXPECT_EQ(200, res->status);
  6378. EXPECT_FALSE(progress_values.empty());
  6379. EXPECT_EQ(expected_content_size, res->body.size());
  6380. }
  6381. TEST(DownloadProgressTest, GetBasic) {
  6382. TestBasicDownloadProgress(
  6383. [](Server &svr) {
  6384. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6385. string content(1000, 'D');
  6386. res.set_content(content, "text/plain");
  6387. });
  6388. },
  6389. [](Client &cli, const string &endpoint,
  6390. DownloadProgress progress_callback) {
  6391. return cli.Get(endpoint, progress_callback);
  6392. },
  6393. "/download", 1000u);
  6394. }
  6395. // Helper function for content receiver download progress tests
  6396. template <typename SetupHandler, typename ClientCall>
  6397. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6398. ClientCall &&client_call,
  6399. const string &endpoint,
  6400. size_t expected_content_size) {
  6401. Server svr;
  6402. setup_handler(svr);
  6403. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6404. auto se = detail::scope_exit([&] {
  6405. svr.stop();
  6406. t.join();
  6407. });
  6408. svr.wait_until_ready();
  6409. Client cli(HOST, PORT);
  6410. vector<uint64_t> progress_values;
  6411. string received_body;
  6412. auto res = client_call(
  6413. cli, endpoint,
  6414. [&](const char *data, size_t data_length) -> bool {
  6415. received_body.append(data, data_length);
  6416. return true;
  6417. },
  6418. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6419. progress_values.push_back(current);
  6420. return true;
  6421. });
  6422. ASSERT_TRUE(res);
  6423. EXPECT_EQ(200, res->status);
  6424. EXPECT_FALSE(progress_values.empty());
  6425. EXPECT_EQ(expected_content_size, received_body.size());
  6426. EXPECT_TRUE(res->body.empty());
  6427. }
  6428. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6429. TestContentReceiverDownloadProgress(
  6430. [](Server &svr) {
  6431. svr.Get("/download-receiver",
  6432. [](const Request & /*req*/, Response &res) {
  6433. string content(2000, 'R');
  6434. res.set_content(content, "text/plain");
  6435. });
  6436. },
  6437. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6438. DownloadProgress progress_callback) {
  6439. return cli.Get(endpoint, content_receiver, progress_callback);
  6440. },
  6441. "/download-receiver", 2000u);
  6442. }
  6443. TEST(StreamingTest, NoContentLengthStreaming) {
  6444. Server svr;
  6445. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6446. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6447. if (offset < 6) {
  6448. sink.os << (offset < 3 ? "a" : "b");
  6449. } else {
  6450. sink.done();
  6451. }
  6452. return true;
  6453. });
  6454. });
  6455. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6456. auto listen_se = detail::scope_exit([&] {
  6457. svr.stop();
  6458. listen_thread.join();
  6459. ASSERT_FALSE(svr.is_running());
  6460. });
  6461. svr.wait_until_ready();
  6462. Client client(HOST, PORT);
  6463. auto get_thread = std::thread([&client]() {
  6464. std::string s;
  6465. auto res =
  6466. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6467. s += std::string(data, len);
  6468. return true;
  6469. });
  6470. ASSERT_TRUE(res);
  6471. EXPECT_EQ(StatusCode::OK_200, res->status);
  6472. EXPECT_EQ("aaabbb", s);
  6473. });
  6474. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6475. // Give GET time to get a few messages.
  6476. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6477. }
  6478. TEST(MountTest, Unmount) {
  6479. Server svr;
  6480. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6481. auto se = detail::scope_exit([&] {
  6482. svr.stop();
  6483. listen_thread.join();
  6484. ASSERT_FALSE(svr.is_running());
  6485. });
  6486. svr.wait_until_ready();
  6487. Client cli("localhost", PORT);
  6488. svr.set_mount_point("/mount2", "./www2");
  6489. auto res = cli.Get("/");
  6490. ASSERT_TRUE(res);
  6491. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6492. res = cli.Get("/mount2/dir/test.html");
  6493. ASSERT_TRUE(res);
  6494. EXPECT_EQ(StatusCode::OK_200, res->status);
  6495. svr.set_mount_point("/", "./www");
  6496. res = cli.Get("/dir/");
  6497. ASSERT_TRUE(res);
  6498. EXPECT_EQ(StatusCode::OK_200, res->status);
  6499. svr.remove_mount_point("/");
  6500. res = cli.Get("/dir/");
  6501. ASSERT_TRUE(res);
  6502. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6503. svr.remove_mount_point("/mount2");
  6504. res = cli.Get("/mount2/dir/test.html");
  6505. ASSERT_TRUE(res);
  6506. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6507. }
  6508. TEST(MountTest, Redicect) {
  6509. Server svr;
  6510. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6511. auto se = detail::scope_exit([&] {
  6512. svr.stop();
  6513. listen_thread.join();
  6514. ASSERT_FALSE(svr.is_running());
  6515. });
  6516. svr.set_mount_point("/", "./www");
  6517. svr.wait_until_ready();
  6518. Client cli("localhost", PORT);
  6519. auto res = cli.Get("/dir/");
  6520. ASSERT_TRUE(res);
  6521. EXPECT_EQ(StatusCode::OK_200, res->status);
  6522. res = cli.Get("/dir");
  6523. ASSERT_TRUE(res);
  6524. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6525. res = cli.Get("/file");
  6526. ASSERT_TRUE(res);
  6527. EXPECT_EQ(StatusCode::OK_200, res->status);
  6528. res = cli.Get("/file/");
  6529. ASSERT_TRUE(res);
  6530. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6531. cli.set_follow_location(true);
  6532. res = cli.Get("/dir");
  6533. ASSERT_TRUE(res);
  6534. EXPECT_EQ(StatusCode::OK_200, res->status);
  6535. }
  6536. TEST(MountTest, MultibytesPathName) {
  6537. Server svr;
  6538. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6539. auto se = detail::scope_exit([&] {
  6540. svr.stop();
  6541. listen_thread.join();
  6542. ASSERT_FALSE(svr.is_running());
  6543. });
  6544. svr.set_mount_point("/", "./www");
  6545. svr.wait_until_ready();
  6546. Client cli("localhost", PORT);
  6547. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6548. ASSERT_TRUE(res);
  6549. EXPECT_EQ(StatusCode::OK_200, res->status);
  6550. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6551. }
  6552. TEST(KeepAliveTest, ReadTimeout) {
  6553. Server svr;
  6554. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6555. std::this_thread::sleep_for(std::chrono::seconds(2));
  6556. res.set_content("a", "text/plain");
  6557. });
  6558. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6559. res.set_content("b", "text/plain");
  6560. });
  6561. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6562. auto se = detail::scope_exit([&] {
  6563. svr.stop();
  6564. listen_thread.join();
  6565. ASSERT_FALSE(svr.is_running());
  6566. });
  6567. svr.wait_until_ready();
  6568. Client cli("localhost", PORT);
  6569. cli.set_keep_alive(true);
  6570. cli.set_read_timeout(std::chrono::seconds(1));
  6571. auto resa = cli.Get("/a");
  6572. ASSERT_FALSE(resa);
  6573. EXPECT_EQ(Error::Read, resa.error());
  6574. auto resb = cli.Get("/b");
  6575. ASSERT_TRUE(resb);
  6576. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6577. EXPECT_EQ("b", resb->body);
  6578. }
  6579. TEST(KeepAliveTest, MaxCount) {
  6580. size_t keep_alive_max_count = 3;
  6581. Server svr;
  6582. svr.set_keep_alive_max_count(keep_alive_max_count);
  6583. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6584. res.set_content("Hello World!", "text/plain");
  6585. });
  6586. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6587. auto se = detail::scope_exit([&] {
  6588. svr.stop();
  6589. listen_thread.join();
  6590. ASSERT_FALSE(svr.is_running());
  6591. });
  6592. svr.wait_until_ready();
  6593. Client cli(HOST, PORT);
  6594. cli.set_keep_alive(true);
  6595. for (size_t i = 0; i < 5; i++) {
  6596. auto result = cli.Get("/hi");
  6597. ASSERT_TRUE(result);
  6598. EXPECT_EQ(StatusCode::OK_200, result->status);
  6599. if (i == keep_alive_max_count - 1) {
  6600. EXPECT_EQ("close", result->get_header_value("Connection"));
  6601. } else {
  6602. EXPECT_FALSE(result->has_header("Connection"));
  6603. }
  6604. }
  6605. }
  6606. TEST(KeepAliveTest, Issue1041) {
  6607. Server svr;
  6608. svr.set_keep_alive_timeout(3);
  6609. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6610. res.set_content("Hello World!", "text/plain");
  6611. });
  6612. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6613. auto se = detail::scope_exit([&] {
  6614. svr.stop();
  6615. listen_thread.join();
  6616. ASSERT_FALSE(svr.is_running());
  6617. });
  6618. svr.wait_until_ready();
  6619. Client cli(HOST, PORT);
  6620. cli.set_keep_alive(true);
  6621. auto result = cli.Get("/hi");
  6622. ASSERT_TRUE(result);
  6623. EXPECT_EQ(StatusCode::OK_200, result->status);
  6624. std::this_thread::sleep_for(std::chrono::seconds(5));
  6625. result = cli.Get("/hi");
  6626. ASSERT_TRUE(result);
  6627. EXPECT_EQ(StatusCode::OK_200, result->status);
  6628. }
  6629. TEST(KeepAliveTest, Issue1959) {
  6630. Server svr;
  6631. svr.set_keep_alive_timeout(5);
  6632. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6633. res.set_content("a", "text/plain");
  6634. });
  6635. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6636. auto se = detail::scope_exit([&] {
  6637. if (!svr.is_running()) return;
  6638. svr.stop();
  6639. listen_thread.join();
  6640. ASSERT_FALSE(svr.is_running());
  6641. });
  6642. svr.wait_until_ready();
  6643. Client cli("localhost", PORT);
  6644. cli.set_keep_alive(true);
  6645. using namespace std::chrono;
  6646. auto start = steady_clock::now();
  6647. cli.Get("/a");
  6648. svr.stop();
  6649. listen_thread.join();
  6650. auto end = steady_clock::now();
  6651. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6652. EXPECT_LT(elapsed, 5000);
  6653. }
  6654. #ifdef CPPHTTPLIB_SSL_ENABLED
  6655. TEST(KeepAliveTest, SSLClientReconnection) {
  6656. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6657. ASSERT_TRUE(svr.is_valid());
  6658. svr.set_keep_alive_timeout(1);
  6659. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6660. res.set_content("Hello World!", "text/plain");
  6661. });
  6662. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6663. auto se = detail::scope_exit([&] {
  6664. svr.stop();
  6665. listen_thread.join();
  6666. ASSERT_FALSE(svr.is_running());
  6667. });
  6668. svr.wait_until_ready();
  6669. SSLClient cli(HOST, PORT);
  6670. cli.enable_server_certificate_verification(false);
  6671. cli.set_keep_alive(true);
  6672. auto result = cli.Get("/hi");
  6673. ASSERT_TRUE(result);
  6674. EXPECT_EQ(StatusCode::OK_200, result->status);
  6675. result = cli.Get("/hi");
  6676. ASSERT_TRUE(result);
  6677. EXPECT_EQ(StatusCode::OK_200, result->status);
  6678. std::this_thread::sleep_for(std::chrono::seconds(2));
  6679. // Recoonect
  6680. result = cli.Get("/hi");
  6681. ASSERT_TRUE(result);
  6682. EXPECT_EQ(StatusCode::OK_200, result->status);
  6683. result = cli.Get("/hi");
  6684. ASSERT_TRUE(result);
  6685. EXPECT_EQ(StatusCode::OK_200, result->status);
  6686. }
  6687. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6688. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6689. ASSERT_TRUE(svr.is_valid());
  6690. svr.set_keep_alive_timeout(1);
  6691. std::string content = "reconnect";
  6692. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6693. res.set_content("Hello World!", "text/plain");
  6694. });
  6695. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6696. auto se = detail::scope_exit([&] {
  6697. svr.stop();
  6698. listen_thread.join();
  6699. ASSERT_FALSE(svr.is_running());
  6700. });
  6701. svr.wait_until_ready();
  6702. SSLClient cli(HOST, PORT);
  6703. cli.enable_server_certificate_verification(false);
  6704. cli.set_keep_alive(true);
  6705. auto result = cli.Post(
  6706. "/hi", content.size(),
  6707. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6708. sink.write(content.c_str(), content.size());
  6709. return true;
  6710. },
  6711. "text/plain");
  6712. ASSERT_TRUE(result);
  6713. EXPECT_EQ(200, result->status);
  6714. std::this_thread::sleep_for(std::chrono::seconds(2));
  6715. // Recoonect
  6716. result = cli.Post(
  6717. "/hi", content.size(),
  6718. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6719. sink.write(content.c_str(), content.size());
  6720. return true;
  6721. },
  6722. "text/plain");
  6723. ASSERT_TRUE(result);
  6724. EXPECT_EQ(200, result->status);
  6725. result = cli.Post(
  6726. "/hi", content.size(),
  6727. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6728. sink.write(content.c_str(), content.size());
  6729. return true;
  6730. },
  6731. "text/plain");
  6732. ASSERT_TRUE(result);
  6733. EXPECT_EQ(200, result->status);
  6734. }
  6735. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6736. using namespace httplib::tls;
  6737. {
  6738. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6739. ASSERT_TRUE(svr.is_valid());
  6740. svr.Get("/sni", [&](const Request &req, Response &res) {
  6741. std::string expected = req.sni();
  6742. EXPECT_EQ(expected, req.get_param_value("expected"));
  6743. res.set_content("ok", "text/plain");
  6744. });
  6745. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6746. auto se = detail::scope_exit([&] {
  6747. svr.stop();
  6748. listen_thread.join();
  6749. ASSERT_FALSE(svr.is_running());
  6750. });
  6751. svr.wait_until_ready();
  6752. {
  6753. SSLClient cli("localhost", PORT);
  6754. cli.enable_server_certificate_verification(false);
  6755. auto res = cli.Get("/sni?expected=localhost");
  6756. ASSERT_TRUE(res);
  6757. }
  6758. {
  6759. SSLClient cli("::1", PORT);
  6760. cli.enable_server_certificate_verification(false);
  6761. auto res = cli.Get("/sni?expected=");
  6762. // NOTE: This may fail if the server is listening on IPv4 only
  6763. // (e.g., when localhost resolves to 127.0.0.1 only)
  6764. if (res) {
  6765. EXPECT_EQ(StatusCode::OK_200, res->status);
  6766. } else {
  6767. EXPECT_EQ(Error::Connection, res.error());
  6768. }
  6769. }
  6770. }
  6771. }
  6772. #endif
  6773. TEST(ClientProblemDetectionTest, ContentProvider) {
  6774. Server svr;
  6775. size_t content_length = 1024 * 1024;
  6776. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6777. res.set_content_provider(
  6778. content_length, "text/plain",
  6779. [&](size_t offset, size_t length, DataSink &sink) {
  6780. auto out_len = std::min(length, static_cast<size_t>(1024));
  6781. std::string out(out_len, '@');
  6782. sink.write(out.data(), out_len);
  6783. return offset < 4096;
  6784. },
  6785. [](bool success) { ASSERT_FALSE(success); });
  6786. });
  6787. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6788. res.set_content_provider(
  6789. 0, "text/plain",
  6790. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6791. EXPECT_TRUE(false);
  6792. return true;
  6793. },
  6794. [](bool success) { ASSERT_FALSE(success); });
  6795. });
  6796. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", 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("localhost", PORT);
  6804. {
  6805. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6806. size_t /*data_length*/) { return false; });
  6807. ASSERT_FALSE(res);
  6808. }
  6809. {
  6810. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6811. size_t /*data_length*/) { return false; });
  6812. ASSERT_TRUE(res);
  6813. }
  6814. }
  6815. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6816. Server svr;
  6817. svr.set_error_handler([](Request const &, Response &res) -> void {
  6818. res.set_chunked_content_provider(
  6819. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6820. sink.os << "hello";
  6821. sink.os << "world";
  6822. sink.done();
  6823. return true;
  6824. });
  6825. });
  6826. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6827. auto se = detail::scope_exit([&] {
  6828. svr.stop();
  6829. listen_thread.join();
  6830. ASSERT_FALSE(svr.is_running());
  6831. });
  6832. svr.wait_until_ready();
  6833. Client cli("localhost", PORT);
  6834. auto res = cli.Get("/");
  6835. ASSERT_TRUE(res);
  6836. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6837. EXPECT_EQ("helloworld", res->body);
  6838. }
  6839. TEST(LongPollingTest, ClientCloseDetection) {
  6840. Server svr;
  6841. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6842. res.set_chunked_content_provider(
  6843. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6844. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6845. sink.os << "hello";
  6846. auto count = 10;
  6847. while (count > 0 && sink.is_writable()) {
  6848. this_thread::sleep_for(chrono::milliseconds(10));
  6849. count--;
  6850. }
  6851. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6852. return true;
  6853. });
  6854. });
  6855. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6856. auto se = detail::scope_exit([&] {
  6857. svr.stop();
  6858. listen_thread.join();
  6859. ASSERT_FALSE(svr.is_running());
  6860. });
  6861. svr.wait_until_ready();
  6862. Client cli("localhost", PORT);
  6863. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6864. EXPECT_EQ("hello", string(data, data_length));
  6865. return false; // close the socket immediately.
  6866. });
  6867. ASSERT_FALSE(res);
  6868. }
  6869. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  6870. Server svr;
  6871. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6872. res.set_chunked_content_provider(
  6873. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6874. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6875. sink.os << "hello";
  6876. EXPECT_TRUE(sink.os.good());
  6877. // Wait for the client to close the connection
  6878. auto count = 10;
  6879. while (count > 0 && sink.is_writable()) {
  6880. this_thread::sleep_for(chrono::milliseconds(10));
  6881. count--;
  6882. }
  6883. // After client disconnect, write repeatedly until the socket
  6884. // write actually fails (small writes may be absorbed by the
  6885. // kernel buffer)
  6886. std::string chunk(1024, 'x');
  6887. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  6888. sink.os << chunk;
  6889. }
  6890. EXPECT_TRUE(sink.os.fail());
  6891. return true;
  6892. });
  6893. });
  6894. auto port = svr.bind_to_any_port("localhost");
  6895. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  6896. auto se = detail::scope_exit([&] {
  6897. svr.stop();
  6898. listen_thread.join();
  6899. ASSERT_FALSE(svr.is_running());
  6900. });
  6901. svr.wait_until_ready();
  6902. Client cli("localhost", port);
  6903. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6904. EXPECT_EQ("hello", string(data, data_length));
  6905. return false; // close the socket immediately.
  6906. });
  6907. ASSERT_FALSE(res);
  6908. }
  6909. TEST(GetWithParametersTest, GetWithParameters) {
  6910. Server svr;
  6911. svr.Get("/", [&](const Request &req, Response &) {
  6912. EXPECT_EQ("world", req.get_param_value("hello"));
  6913. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6914. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6915. });
  6916. svr.Get("/params", [&](const Request &req, Response &) {
  6917. EXPECT_EQ("world", req.get_param_value("hello"));
  6918. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6919. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6920. });
  6921. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6922. EXPECT_EQ("resource-id", req.matches[1]);
  6923. EXPECT_EQ("foo", req.get_param_value("param1"));
  6924. EXPECT_EQ("bar", req.get_param_value("param2"));
  6925. });
  6926. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6927. EXPECT_EQ("user-id", req.path_params.at("id"));
  6928. EXPECT_EQ("foo", req.get_param_value("param1"));
  6929. EXPECT_EQ("bar", req.get_param_value("param2"));
  6930. });
  6931. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6932. auto se = detail::scope_exit([&] {
  6933. svr.stop();
  6934. listen_thread.join();
  6935. ASSERT_FALSE(svr.is_running());
  6936. });
  6937. svr.wait_until_ready();
  6938. {
  6939. Client cli(HOST, PORT);
  6940. Params params;
  6941. params.emplace("hello", "world");
  6942. params.emplace("hello2", "world2");
  6943. params.emplace("hello3", "world3");
  6944. auto res = cli.Get("/", params, Headers{});
  6945. ASSERT_TRUE(res);
  6946. EXPECT_EQ(StatusCode::OK_200, res->status);
  6947. }
  6948. {
  6949. Client cli(HOST, PORT);
  6950. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6951. ASSERT_TRUE(res);
  6952. EXPECT_EQ(StatusCode::OK_200, res->status);
  6953. }
  6954. {
  6955. Client cli(HOST, PORT);
  6956. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6957. ASSERT_TRUE(res);
  6958. EXPECT_EQ(StatusCode::OK_200, res->status);
  6959. }
  6960. {
  6961. Client cli(HOST, PORT);
  6962. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6963. ASSERT_TRUE(res);
  6964. EXPECT_EQ(StatusCode::OK_200, res->status);
  6965. }
  6966. }
  6967. TEST(GetWithParametersTest, GetWithParameters2) {
  6968. Server svr;
  6969. svr.Get("/", [&](const Request &req, Response &res) {
  6970. auto text = req.get_param_value("hello");
  6971. res.set_content(text, "text/plain");
  6972. });
  6973. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6974. auto se = detail::scope_exit([&] {
  6975. svr.stop();
  6976. listen_thread.join();
  6977. ASSERT_FALSE(svr.is_running());
  6978. });
  6979. svr.wait_until_ready();
  6980. Client cli("localhost", PORT);
  6981. Params params;
  6982. params.emplace("hello", "world");
  6983. std::string body;
  6984. auto res = cli.Get("/", params, Headers{},
  6985. [&](const char *data, size_t data_length) {
  6986. body.append(data, data_length);
  6987. return true;
  6988. });
  6989. ASSERT_TRUE(res);
  6990. EXPECT_EQ(StatusCode::OK_200, res->status);
  6991. EXPECT_EQ("world", body);
  6992. }
  6993. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6994. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6995. auto host = "httpcan.org";
  6996. auto path = std::string{"/range/32"};
  6997. #else
  6998. auto host = "nghttp2.org";
  6999. auto path = std::string{"/httpbin/range/32"};
  7000. #endif
  7001. #ifdef CPPHTTPLIB_SSL_ENABLED
  7002. SSLClient cli(host);
  7003. #else
  7004. Client cli(host);
  7005. #endif
  7006. cli.set_default_headers({make_range_header({{1, 10}})});
  7007. cli.set_connection_timeout(5);
  7008. {
  7009. auto res = cli.Get(path);
  7010. ASSERT_TRUE(res);
  7011. EXPECT_EQ("bcdefghijk", res->body);
  7012. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7013. }
  7014. {
  7015. auto res = cli.Get(path);
  7016. ASSERT_TRUE(res);
  7017. EXPECT_EQ("bcdefghijk", res->body);
  7018. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7019. }
  7020. }
  7021. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7022. Server svr;
  7023. svr.set_default_headers({{"Hello", "World"}});
  7024. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7025. res.set_content("ok", "text/plain");
  7026. });
  7027. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7028. auto se = detail::scope_exit([&] {
  7029. svr.stop();
  7030. listen_thread.join();
  7031. ASSERT_FALSE(svr.is_running());
  7032. });
  7033. svr.wait_until_ready();
  7034. Client cli("localhost", PORT);
  7035. auto res = cli.Get("/");
  7036. ASSERT_TRUE(res);
  7037. EXPECT_EQ(StatusCode::OK_200, res->status);
  7038. EXPECT_EQ("ok", res->body);
  7039. EXPECT_EQ("World", res->get_header_value("Hello"));
  7040. }
  7041. #ifdef CPPHTTPLIB_SSL_ENABLED
  7042. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7043. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7044. ASSERT_TRUE(svr.is_valid());
  7045. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7046. std::this_thread::sleep_for(std::chrono::seconds(2));
  7047. res.set_content("a", "text/plain");
  7048. });
  7049. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7050. res.set_content("b", "text/plain");
  7051. });
  7052. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7053. auto se = detail::scope_exit([&] {
  7054. svr.stop();
  7055. listen_thread.join();
  7056. ASSERT_FALSE(svr.is_running());
  7057. });
  7058. svr.wait_until_ready();
  7059. SSLClient cli("localhost", PORT);
  7060. cli.enable_server_certificate_verification(false);
  7061. cli.set_keep_alive(true);
  7062. cli.set_read_timeout(std::chrono::seconds(1));
  7063. auto resa = cli.Get("/a");
  7064. ASSERT_TRUE(!resa);
  7065. EXPECT_EQ(Error::Read, resa.error());
  7066. auto resb = cli.Get("/b");
  7067. ASSERT_TRUE(resb);
  7068. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7069. EXPECT_EQ("b", resb->body);
  7070. }
  7071. #endif
  7072. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7073. protected:
  7074. ServerTestWithAI_PASSIVE()
  7075. : cli_(HOST, PORT)
  7076. #ifdef CPPHTTPLIB_SSL_ENABLED
  7077. ,
  7078. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7079. #endif
  7080. {
  7081. #ifdef CPPHTTPLIB_SSL_ENABLED
  7082. cli_.enable_server_certificate_verification(false);
  7083. #endif
  7084. }
  7085. virtual void SetUp() {
  7086. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7087. res.set_content("Hello World!", "text/plain");
  7088. });
  7089. t_ = thread(
  7090. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7091. svr_.wait_until_ready();
  7092. }
  7093. virtual void TearDown() {
  7094. svr_.stop();
  7095. t_.join();
  7096. }
  7097. #ifdef CPPHTTPLIB_SSL_ENABLED
  7098. SSLClient cli_;
  7099. SSLServer svr_;
  7100. #else
  7101. Client cli_;
  7102. Server svr_;
  7103. #endif
  7104. thread t_;
  7105. };
  7106. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7107. auto res = cli_.Get("/hi");
  7108. ASSERT_TRUE(res);
  7109. EXPECT_EQ(StatusCode::OK_200, res->status);
  7110. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7111. EXPECT_EQ("Hello World!", res->body);
  7112. }
  7113. class ServerUpDownTest : public ::testing::Test {
  7114. protected:
  7115. ServerUpDownTest() : cli_(HOST, PORT) {}
  7116. virtual void SetUp() {
  7117. t_ = thread([&]() {
  7118. svr_.bind_to_any_port(HOST);
  7119. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7120. ASSERT_TRUE(svr_.listen_after_bind());
  7121. });
  7122. svr_.wait_until_ready();
  7123. }
  7124. virtual void TearDown() {
  7125. svr_.stop();
  7126. t_.join();
  7127. }
  7128. Client cli_;
  7129. Server svr_;
  7130. thread t_;
  7131. };
  7132. TEST_F(ServerUpDownTest, QuickStartStop) {
  7133. // Should not crash, especially when run with
  7134. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7135. }
  7136. class PayloadMaxLengthTest : public ::testing::Test {
  7137. protected:
  7138. PayloadMaxLengthTest()
  7139. : cli_(HOST, PORT)
  7140. #ifdef CPPHTTPLIB_SSL_ENABLED
  7141. ,
  7142. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7143. #endif
  7144. {
  7145. #ifdef CPPHTTPLIB_SSL_ENABLED
  7146. cli_.enable_server_certificate_verification(false);
  7147. #endif
  7148. }
  7149. virtual void SetUp() {
  7150. svr_.set_payload_max_length(8);
  7151. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7152. res.set_content("test", "text/plain");
  7153. });
  7154. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7155. svr_.wait_until_ready();
  7156. }
  7157. virtual void TearDown() {
  7158. svr_.stop();
  7159. t_.join();
  7160. }
  7161. #ifdef CPPHTTPLIB_SSL_ENABLED
  7162. SSLClient cli_;
  7163. SSLServer svr_;
  7164. #else
  7165. Client cli_;
  7166. Server svr_;
  7167. #endif
  7168. thread t_;
  7169. };
  7170. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7171. auto res = cli_.Post("/test", "123456789", "text/plain");
  7172. ASSERT_TRUE(res);
  7173. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7174. res = cli_.Post("/test", "12345678", "text/plain");
  7175. ASSERT_TRUE(res);
  7176. EXPECT_EQ(StatusCode::OK_200, res->status);
  7177. }
  7178. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7179. // Test chunked encoding with payload exceeding the 8-byte limit
  7180. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7181. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7182. ASSERT_TRUE(res);
  7183. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7184. }
  7185. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7186. // Test chunked encoding with payload within the 8-byte limit
  7187. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7188. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7189. ASSERT_TRUE(res);
  7190. EXPECT_EQ(StatusCode::OK_200, res->status);
  7191. }
  7192. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7193. // Test using send_request to send chunked data exceeding payload limit
  7194. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7195. "Host: " +
  7196. std::string(HOST) + ":" + std::to_string(PORT) +
  7197. "\r\n"
  7198. "Transfer-Encoding: chunked\r\n"
  7199. "Connection: close\r\n"
  7200. "\r\n"
  7201. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7202. "0123456789\r\n"
  7203. "0\r\n" // End chunk
  7204. "\r\n";
  7205. std::string response;
  7206. bool result = send_request(1, chunked_request, &response);
  7207. if (!result) {
  7208. // If send_request fails, it might be because the server closed the
  7209. // connection due to payload limit enforcement, which is acceptable
  7210. SUCCEED()
  7211. << "Server rejected oversized chunked request (connection closed)";
  7212. } else {
  7213. // If we got a response, check if it's an error response or connection was
  7214. // closed early Short response length indicates connection was closed due to
  7215. // payload limit
  7216. if (response.length() <= 10) {
  7217. SUCCEED() << "Server closed connection for oversized chunked request";
  7218. } else {
  7219. // Check for error status codes
  7220. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7221. response.find("Payload Too Large") != std::string::npos ||
  7222. response.find("400") != std::string::npos);
  7223. }
  7224. }
  7225. }
  7226. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7227. // Test request without Content-Length header exceeding payload limit
  7228. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7229. "Host: " +
  7230. std::string(HOST) + ":" +
  7231. std::to_string(PORT) +
  7232. "\r\n"
  7233. "Connection: close\r\n"
  7234. "\r\n";
  7235. // Add payload exceeding the 8-byte limit
  7236. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7237. request_without_content_length += large_payload;
  7238. std::string response;
  7239. bool result = send_request(1, request_without_content_length, &response);
  7240. if (!result) {
  7241. // If send_request fails, server likely closed connection due to payload
  7242. // limit
  7243. SUCCEED() << "Server rejected oversized request without Content-Length "
  7244. "(connection closed)";
  7245. } else {
  7246. // Check if server responded with error or closed connection early
  7247. if (response.length() <= 10) {
  7248. SUCCEED() << "Server closed connection for oversized request without "
  7249. "Content-Length";
  7250. } else {
  7251. // Check for error status codes
  7252. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7253. response.find("Payload Too Large") != std::string::npos ||
  7254. response.find("400") != std::string::npos);
  7255. }
  7256. }
  7257. }
  7258. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7259. // Test request without Content-Length header within payload limit
  7260. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7261. "Host: " +
  7262. std::string(HOST) + ":" +
  7263. std::to_string(PORT) +
  7264. "\r\n"
  7265. "Connection: close\r\n"
  7266. "\r\n";
  7267. // Add payload within the 8-byte limit
  7268. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7269. request_without_content_length += small_payload;
  7270. std::string response;
  7271. bool result = send_request(1, request_without_content_length, &response);
  7272. // For requests without Content-Length, the server may have different behavior
  7273. // The key is that it should not reject due to payload limit for small
  7274. // payloads
  7275. if (result) {
  7276. // Check for any HTTP response (success or error, but not connection closed)
  7277. if (response.length() > 10) {
  7278. SUCCEED()
  7279. << "Server processed request without Content-Length within limit";
  7280. } else {
  7281. // Short response might indicate connection closed, which is acceptable
  7282. SUCCEED() << "Server closed connection for request without "
  7283. "Content-Length (acceptable behavior)";
  7284. }
  7285. } else {
  7286. // Connection failure might be due to protocol requirements
  7287. SUCCEED() << "Connection issue with request without Content-Length "
  7288. "(environment-specific)";
  7289. }
  7290. }
  7291. class LargePayloadMaxLengthTest : public ::testing::Test {
  7292. protected:
  7293. LargePayloadMaxLengthTest()
  7294. : cli_(HOST, PORT)
  7295. #ifdef CPPHTTPLIB_SSL_ENABLED
  7296. ,
  7297. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7298. #endif
  7299. {
  7300. #ifdef CPPHTTPLIB_SSL_ENABLED
  7301. cli_.enable_server_certificate_verification(false);
  7302. #endif
  7303. }
  7304. virtual void SetUp() {
  7305. // Set 10MB payload limit
  7306. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7307. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7308. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7309. res.set_content("Large payload test", "text/plain");
  7310. });
  7311. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7312. svr_.wait_until_ready();
  7313. }
  7314. virtual void TearDown() {
  7315. svr_.stop();
  7316. t_.join();
  7317. }
  7318. #ifdef CPPHTTPLIB_SSL_ENABLED
  7319. SSLClient cli_;
  7320. SSLServer svr_;
  7321. #else
  7322. Client cli_;
  7323. Server svr_;
  7324. #endif
  7325. thread t_;
  7326. };
  7327. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7328. // Test chunked encoding with payload within 10MB limit
  7329. std::string medium_payload(5 * 1024 * 1024,
  7330. 'A'); // 5MB payload, within 10MB limit
  7331. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7332. ASSERT_TRUE(res);
  7333. EXPECT_EQ(StatusCode::OK_200, res->status);
  7334. }
  7335. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7336. // Test chunked encoding with payload exceeding 10MB limit
  7337. std::string large_payload(12 * 1024 * 1024,
  7338. 'B'); // 12MB payload, exceeds 10MB limit
  7339. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7340. // Server may either return 413 or close the connection
  7341. if (res) {
  7342. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7343. } else {
  7344. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7345. }
  7346. }
  7347. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7348. // Test request without Content-Length header within 10MB limit
  7349. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7350. "Host: " +
  7351. std::string(HOST) + ":" +
  7352. std::to_string(PORT) +
  7353. "\r\n"
  7354. "Connection: close\r\n"
  7355. "\r\n";
  7356. // Add 1MB payload (within 10MB limit)
  7357. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7358. request_without_content_length += medium_payload;
  7359. std::string response;
  7360. bool result = send_request(5, request_without_content_length, &response);
  7361. if (result) {
  7362. // Should get a proper HTTP response for payloads within limit
  7363. if (response.length() > 10) {
  7364. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7365. "10MB limit";
  7366. } else {
  7367. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7368. "Content-Length)";
  7369. }
  7370. } else {
  7371. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7372. }
  7373. }
  7374. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7375. // Test request without Content-Length header exceeding 10MB limit
  7376. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7377. "Host: " +
  7378. std::string(HOST) + ":" +
  7379. std::to_string(PORT) +
  7380. "\r\n"
  7381. "Connection: close\r\n"
  7382. "\r\n";
  7383. // Add 12MB payload (exceeds 10MB limit)
  7384. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7385. request_without_content_length += large_payload;
  7386. std::string response;
  7387. bool result = send_request(10, request_without_content_length, &response);
  7388. if (!result) {
  7389. // Server should close connection due to payload limit
  7390. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7391. "(connection closed)";
  7392. } else {
  7393. // Check for error response
  7394. if (response.length() <= 10) {
  7395. SUCCEED()
  7396. << "Server closed connection for 12MB request exceeding 10MB limit";
  7397. } else {
  7398. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7399. response.find("Payload Too Large") != std::string::npos ||
  7400. response.find("400") != std::string::npos);
  7401. }
  7402. }
  7403. }
  7404. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7405. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7406. // path.
  7407. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7408. Server svr;
  7409. const size_t LIMIT = 64 * 1024; // 64KB
  7410. svr.set_payload_max_length(LIMIT);
  7411. size_t total = 0;
  7412. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7413. const ContentReader &content_reader) {
  7414. content_reader([&](const char * /*data*/, size_t len) {
  7415. total += len;
  7416. return true;
  7417. });
  7418. res.status = 200;
  7419. res.set_content("stream_ok", "text/plain");
  7420. });
  7421. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7422. auto se = detail::scope_exit([&] {
  7423. svr.stop();
  7424. thread.join();
  7425. ASSERT_FALSE(svr.is_running());
  7426. });
  7427. svr.wait_until_ready();
  7428. // Prepare 256KB raw data and gzip-compress it
  7429. std::string raw(256 * 1024, 'A');
  7430. std::string gz;
  7431. {
  7432. z_stream zs{};
  7433. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7434. Z_DEFAULT_STRATEGY);
  7435. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7436. zs.avail_in = static_cast<uInt>(raw.size());
  7437. char outbuf[4096];
  7438. int ret;
  7439. do {
  7440. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7441. zs.avail_out = sizeof(outbuf);
  7442. ret = deflate(&zs, Z_FINISH);
  7443. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7444. } while (ret != Z_STREAM_END);
  7445. deflateEnd(&zs);
  7446. }
  7447. Client cli(HOST, PORT);
  7448. cli.set_connection_timeout(std::chrono::seconds(5));
  7449. Headers headers = {{"Content-Encoding", "gzip"}};
  7450. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7451. "application/octet-stream");
  7452. ASSERT_TRUE(res);
  7453. // Server must reject oversized decompressed payloads with 413.
  7454. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7455. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7456. EXPECT_LE(total, LIMIT);
  7457. }
  7458. #endif
  7459. // Regression test for DoS vulnerability: a malicious server sending a response
  7460. // without Content-Length header must not cause unbounded memory consumption on
  7461. // the client side. The client should stop reading after a reasonable limit,
  7462. // similar to the server-side set_payload_max_length protection.
  7463. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7464. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7465. #ifndef _WIN32
  7466. signal(SIGPIPE, SIG_IGN);
  7467. #endif
  7468. auto server_thread = std::thread([] {
  7469. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7470. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7471. default_socket_options(srv);
  7472. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7473. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7474. sockaddr_in addr{};
  7475. addr.sin_family = AF_INET;
  7476. addr.sin_port = htons(PORT + 2);
  7477. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7478. int opt = 1;
  7479. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7480. #ifdef _WIN32
  7481. reinterpret_cast<const char *>(&opt),
  7482. #else
  7483. &opt,
  7484. #endif
  7485. sizeof(opt));
  7486. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7487. ::listen(srv, 1);
  7488. sockaddr_in cli_addr{};
  7489. socklen_t cli_len = sizeof(cli_addr);
  7490. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7491. if (cli != INVALID_SOCKET) {
  7492. char buf[4096];
  7493. ::recv(cli, buf, sizeof(buf), 0);
  7494. // Malicious response: no Content-Length, no chunked encoding
  7495. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7496. "Connection: close\r\n"
  7497. "\r\n";
  7498. ::send(cli,
  7499. #ifdef _WIN32
  7500. static_cast<const char *>(response_header.c_str()),
  7501. static_cast<int>(response_header.size()),
  7502. #else
  7503. response_header.c_str(), response_header.size(),
  7504. #endif
  7505. 0);
  7506. // Send 10MB of data
  7507. std::string chunk(64 * 1024, 'A');
  7508. size_t total_sent = 0;
  7509. while (total_sent < MALICIOUS_DATA_SIZE) {
  7510. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7511. auto sent = ::send(cli,
  7512. #ifdef _WIN32
  7513. static_cast<const char *>(chunk.c_str()),
  7514. static_cast<int>(to_send),
  7515. #else
  7516. chunk.c_str(), to_send,
  7517. #endif
  7518. 0);
  7519. if (sent <= 0) break;
  7520. total_sent += static_cast<size_t>(sent);
  7521. }
  7522. detail::close_socket(cli);
  7523. }
  7524. detail::close_socket(srv);
  7525. });
  7526. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7527. size_t total_read = 0;
  7528. {
  7529. Client cli("127.0.0.1", PORT + 2);
  7530. cli.set_read_timeout(5, 0);
  7531. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7532. auto stream = cli.open_stream("GET", "/malicious");
  7533. ASSERT_TRUE(stream.is_valid());
  7534. char buffer[64 * 1024];
  7535. ssize_t n;
  7536. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7537. total_read += static_cast<size_t>(n);
  7538. }
  7539. } // StreamHandle and Client destroyed here, closing the socket
  7540. server_thread.join();
  7541. // With set_payload_max_length, the client must stop reading before consuming
  7542. // all 10MB. The read loop should be cut off at or near the configured limit.
  7543. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7544. << "Client read " << total_read << " bytes, exceeding the configured "
  7545. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7546. }
  7547. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7548. // the entire response body without truncation.
  7549. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7550. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7551. #ifndef _WIN32
  7552. signal(SIGPIPE, SIG_IGN);
  7553. #endif
  7554. auto server_thread = std::thread([] {
  7555. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7556. default_socket_options(srv);
  7557. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7558. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7559. sockaddr_in addr{};
  7560. addr.sin_family = AF_INET;
  7561. addr.sin_port = htons(PORT + 2);
  7562. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7563. int opt = 1;
  7564. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7565. #ifdef _WIN32
  7566. reinterpret_cast<const char *>(&opt),
  7567. #else
  7568. &opt,
  7569. #endif
  7570. sizeof(opt));
  7571. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7572. ::listen(srv, 1);
  7573. sockaddr_in cli_addr{};
  7574. socklen_t cli_len = sizeof(cli_addr);
  7575. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7576. if (cli != INVALID_SOCKET) {
  7577. char buf[4096];
  7578. ::recv(cli, buf, sizeof(buf), 0);
  7579. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7580. "Connection: close\r\n"
  7581. "\r\n";
  7582. ::send(cli,
  7583. #ifdef _WIN32
  7584. static_cast<const char *>(response_header.c_str()),
  7585. static_cast<int>(response_header.size()),
  7586. #else
  7587. response_header.c_str(), response_header.size(),
  7588. #endif
  7589. 0);
  7590. std::string chunk(64 * 1024, 'A');
  7591. size_t total_sent = 0;
  7592. while (total_sent < DATA_SIZE) {
  7593. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7594. auto sent = ::send(cli,
  7595. #ifdef _WIN32
  7596. static_cast<const char *>(chunk.c_str()),
  7597. static_cast<int>(to_send),
  7598. #else
  7599. chunk.c_str(), to_send,
  7600. #endif
  7601. 0);
  7602. if (sent <= 0) break;
  7603. total_sent += static_cast<size_t>(sent);
  7604. }
  7605. #ifdef _WIN32
  7606. ::shutdown(cli, SD_SEND);
  7607. #else
  7608. ::shutdown(cli, SHUT_WR);
  7609. #endif
  7610. // Drain until the client closes its end, ensuring all data is delivered
  7611. char drain[1024];
  7612. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7613. detail::close_socket(cli);
  7614. }
  7615. detail::close_socket(srv);
  7616. });
  7617. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7618. size_t total_read = 0;
  7619. {
  7620. Client cli("127.0.0.1", PORT + 2);
  7621. cli.set_read_timeout(5, 0);
  7622. cli.set_payload_max_length(0); // 0 means no limit
  7623. auto stream = cli.open_stream("GET", "/data");
  7624. ASSERT_TRUE(stream.is_valid());
  7625. char buffer[64 * 1024];
  7626. ssize_t n;
  7627. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7628. total_read += static_cast<size_t>(n);
  7629. }
  7630. }
  7631. server_thread.join();
  7632. EXPECT_EQ(total_read, DATA_SIZE)
  7633. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7634. << " bytes without truncation, but only read " << total_read << " bytes.";
  7635. }
  7636. // Verify that content_receiver bypasses the default payload_max_length,
  7637. // allowing streaming downloads larger than 100MB without requiring an explicit
  7638. // set_payload_max_length call.
  7639. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  7640. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7641. #ifndef _WIN32
  7642. signal(SIGPIPE, SIG_IGN);
  7643. #endif
  7644. auto server_thread = std::thread([] {
  7645. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7646. default_socket_options(srv);
  7647. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7648. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7649. sockaddr_in addr{};
  7650. addr.sin_family = AF_INET;
  7651. addr.sin_port = htons(PORT + 2);
  7652. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7653. int opt = 1;
  7654. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7655. #ifdef _WIN32
  7656. reinterpret_cast<const char *>(&opt),
  7657. #else
  7658. &opt,
  7659. #endif
  7660. sizeof(opt));
  7661. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7662. ::listen(srv, 1);
  7663. sockaddr_in cli_addr{};
  7664. socklen_t cli_len = sizeof(cli_addr);
  7665. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7666. if (cli != INVALID_SOCKET) {
  7667. char buf[4096];
  7668. ::recv(cli, buf, sizeof(buf), 0);
  7669. // Response with Content-Length larger than default 100MB limit
  7670. auto content_length = std::to_string(DATA_SIZE);
  7671. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7672. "Content-Length: " +
  7673. content_length +
  7674. "\r\n"
  7675. "Connection: close\r\n"
  7676. "\r\n";
  7677. ::send(cli,
  7678. #ifdef _WIN32
  7679. static_cast<const char *>(response_header.c_str()),
  7680. static_cast<int>(response_header.size()),
  7681. #else
  7682. response_header.c_str(), response_header.size(),
  7683. #endif
  7684. 0);
  7685. std::string chunk(64 * 1024, 'A');
  7686. size_t total_sent = 0;
  7687. while (total_sent < DATA_SIZE) {
  7688. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7689. auto sent = ::send(cli,
  7690. #ifdef _WIN32
  7691. static_cast<const char *>(chunk.c_str()),
  7692. static_cast<int>(to_send),
  7693. #else
  7694. chunk.c_str(), to_send,
  7695. #endif
  7696. 0);
  7697. if (sent <= 0) break;
  7698. total_sent += static_cast<size_t>(sent);
  7699. }
  7700. detail::close_socket(cli);
  7701. }
  7702. detail::close_socket(srv);
  7703. });
  7704. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7705. size_t total_received = 0;
  7706. {
  7707. Client cli("127.0.0.1", PORT + 2);
  7708. cli.set_read_timeout(10, 0);
  7709. // Do NOT call set_payload_max_length — use the default 100MB limit
  7710. auto res =
  7711. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7712. total_received += data_length;
  7713. return true;
  7714. });
  7715. ASSERT_TRUE(res);
  7716. EXPECT_EQ(StatusCode::OK_200, res->status);
  7717. }
  7718. server_thread.join();
  7719. EXPECT_EQ(total_received, DATA_SIZE)
  7720. << "With content_receiver, the client should read all " << DATA_SIZE
  7721. << " bytes despite the default 100MB payload_max_length, but only read "
  7722. << total_received << " bytes.";
  7723. }
  7724. // Verify that an explicit set_payload_max_length smaller than the response is
  7725. // enforced even when a content_receiver is used.
  7726. TEST(ClientVulnerabilityTest,
  7727. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  7728. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7729. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  7730. #ifndef _WIN32
  7731. signal(SIGPIPE, SIG_IGN);
  7732. #endif
  7733. auto server_thread = std::thread([] {
  7734. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7735. default_socket_options(srv);
  7736. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7737. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7738. sockaddr_in addr{};
  7739. addr.sin_family = AF_INET;
  7740. addr.sin_port = htons(PORT + 2);
  7741. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7742. int opt = 1;
  7743. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7744. #ifdef _WIN32
  7745. reinterpret_cast<const char *>(&opt),
  7746. #else
  7747. &opt,
  7748. #endif
  7749. sizeof(opt));
  7750. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7751. ::listen(srv, 1);
  7752. sockaddr_in cli_addr{};
  7753. socklen_t cli_len = sizeof(cli_addr);
  7754. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7755. if (cli != INVALID_SOCKET) {
  7756. char buf[4096];
  7757. ::recv(cli, buf, sizeof(buf), 0);
  7758. auto content_length = std::to_string(DATA_SIZE);
  7759. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7760. "Content-Length: " +
  7761. content_length +
  7762. "\r\n"
  7763. "Connection: close\r\n"
  7764. "\r\n";
  7765. ::send(cli,
  7766. #ifdef _WIN32
  7767. static_cast<const char *>(response_header.c_str()),
  7768. static_cast<int>(response_header.size()),
  7769. #else
  7770. response_header.c_str(), response_header.size(),
  7771. #endif
  7772. 0);
  7773. std::string chunk(64 * 1024, 'A');
  7774. size_t total_sent = 0;
  7775. while (total_sent < DATA_SIZE) {
  7776. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7777. auto sent = ::send(cli,
  7778. #ifdef _WIN32
  7779. static_cast<const char *>(chunk.c_str()),
  7780. static_cast<int>(to_send),
  7781. #else
  7782. chunk.c_str(), to_send,
  7783. #endif
  7784. 0);
  7785. if (sent <= 0) break;
  7786. total_sent += static_cast<size_t>(sent);
  7787. }
  7788. detail::close_socket(cli);
  7789. }
  7790. detail::close_socket(srv);
  7791. });
  7792. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7793. size_t total_received = 0;
  7794. {
  7795. Client cli("127.0.0.1", PORT + 2);
  7796. cli.set_read_timeout(10, 0);
  7797. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  7798. auto res =
  7799. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7800. total_received += data_length;
  7801. return true;
  7802. });
  7803. // Should fail because 200MB exceeds the explicit 150MB limit
  7804. EXPECT_FALSE(res);
  7805. }
  7806. server_thread.join();
  7807. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  7808. << "Client with content_receiver should respect the explicit "
  7809. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  7810. << total_received << " bytes.";
  7811. }
  7812. // Verify that an explicit set_payload_max_length larger than the response
  7813. // allows the content_receiver to read all data successfully.
  7814. TEST(ClientVulnerabilityTest,
  7815. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  7816. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7817. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  7818. #ifndef _WIN32
  7819. signal(SIGPIPE, SIG_IGN);
  7820. #endif
  7821. auto server_thread = std::thread([] {
  7822. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7823. default_socket_options(srv);
  7824. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7825. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7826. sockaddr_in addr{};
  7827. addr.sin_family = AF_INET;
  7828. addr.sin_port = htons(PORT + 2);
  7829. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7830. int opt = 1;
  7831. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7832. #ifdef _WIN32
  7833. reinterpret_cast<const char *>(&opt),
  7834. #else
  7835. &opt,
  7836. #endif
  7837. sizeof(opt));
  7838. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7839. ::listen(srv, 1);
  7840. sockaddr_in cli_addr{};
  7841. socklen_t cli_len = sizeof(cli_addr);
  7842. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7843. if (cli != INVALID_SOCKET) {
  7844. char buf[4096];
  7845. ::recv(cli, buf, sizeof(buf), 0);
  7846. auto content_length = std::to_string(DATA_SIZE);
  7847. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7848. "Content-Length: " +
  7849. content_length +
  7850. "\r\n"
  7851. "Connection: close\r\n"
  7852. "\r\n";
  7853. ::send(cli,
  7854. #ifdef _WIN32
  7855. static_cast<const char *>(response_header.c_str()),
  7856. static_cast<int>(response_header.size()),
  7857. #else
  7858. response_header.c_str(), response_header.size(),
  7859. #endif
  7860. 0);
  7861. std::string chunk(64 * 1024, 'A');
  7862. size_t total_sent = 0;
  7863. while (total_sent < DATA_SIZE) {
  7864. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7865. auto sent = ::send(cli,
  7866. #ifdef _WIN32
  7867. static_cast<const char *>(chunk.c_str()),
  7868. static_cast<int>(to_send),
  7869. #else
  7870. chunk.c_str(), to_send,
  7871. #endif
  7872. 0);
  7873. if (sent <= 0) break;
  7874. total_sent += static_cast<size_t>(sent);
  7875. }
  7876. #ifdef _WIN32
  7877. ::shutdown(cli, SD_SEND);
  7878. #else
  7879. ::shutdown(cli, SHUT_WR);
  7880. #endif
  7881. char drain[1024];
  7882. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7883. detail::close_socket(cli);
  7884. }
  7885. detail::close_socket(srv);
  7886. });
  7887. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7888. size_t total_received = 0;
  7889. {
  7890. Client cli("127.0.0.1", PORT + 2);
  7891. cli.set_read_timeout(10, 0);
  7892. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  7893. auto res =
  7894. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7895. total_received += data_length;
  7896. return true;
  7897. });
  7898. ASSERT_TRUE(res);
  7899. EXPECT_EQ(StatusCode::OK_200, res->status);
  7900. }
  7901. server_thread.join();
  7902. EXPECT_EQ(total_received, DATA_SIZE)
  7903. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  7904. << " bytes (larger than " << DATA_SIZE
  7905. << " bytes response), content_receiver should read all data, but only "
  7906. "read "
  7907. << total_received << " bytes.";
  7908. }
  7909. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  7910. // Regression test for "zip bomb" attack on the client side: a malicious server
  7911. // sends a small gzip-compressed response that decompresses to a huge payload.
  7912. // The client must enforce payload_max_length on the decompressed size.
  7913. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  7914. constexpr size_t DECOMPRESSED_SIZE =
  7915. 10 * 1024 * 1024; // 10MB after decompression
  7916. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7917. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  7918. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  7919. std::string compressed;
  7920. {
  7921. httplib::detail::gzip_compressor compressor;
  7922. bool ok =
  7923. compressor.compress(uncompressed.data(), uncompressed.size(),
  7924. /*last=*/true, [&](const char *buf, size_t len) {
  7925. compressed.append(buf, len);
  7926. return true;
  7927. });
  7928. ASSERT_TRUE(ok);
  7929. }
  7930. // Sanity: compressed data should be much smaller than the decompressed size
  7931. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  7932. #ifndef _WIN32
  7933. signal(SIGPIPE, SIG_IGN);
  7934. #endif
  7935. // Set up the listening socket in the main thread so the server is guaranteed
  7936. // to be ready before the client connects (eliminates race condition).
  7937. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7938. default_socket_options(srv);
  7939. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7940. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7941. sockaddr_in addr{};
  7942. addr.sin_family = AF_INET;
  7943. addr.sin_port = htons(PORT + 3);
  7944. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7945. int opt = 1;
  7946. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7947. #ifdef _WIN32
  7948. reinterpret_cast<const char *>(&opt),
  7949. #else
  7950. &opt,
  7951. #endif
  7952. sizeof(opt));
  7953. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  7954. ASSERT_EQ(0, ::listen(srv, 1));
  7955. auto server_thread = std::thread([&compressed, srv] {
  7956. sockaddr_in cli_addr{};
  7957. socklen_t cli_len = sizeof(cli_addr);
  7958. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7959. if (cli != INVALID_SOCKET) {
  7960. // Read the full HTTP request (until \r\n\r\n)
  7961. char buf[4096];
  7962. size_t total = 0;
  7963. while (total < sizeof(buf)) {
  7964. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  7965. if (n <= 0) break;
  7966. total += static_cast<size_t>(n);
  7967. // Check for end of headers
  7968. if (total >= 4) {
  7969. std::string req(buf, total);
  7970. if (req.find("\r\n\r\n") != std::string::npos) break;
  7971. }
  7972. }
  7973. // Malicious response: gzip-compressed body, no Content-Length
  7974. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7975. "Content-Encoding: gzip\r\n"
  7976. "Connection: close\r\n"
  7977. "\r\n";
  7978. ::send(cli,
  7979. #ifdef _WIN32
  7980. static_cast<const char *>(response_header.c_str()),
  7981. static_cast<int>(response_header.size()),
  7982. #else
  7983. response_header.c_str(), response_header.size(),
  7984. #endif
  7985. 0);
  7986. // Send the compressed payload (small on the wire, huge when decompressed)
  7987. size_t total_sent = 0;
  7988. while (total_sent < compressed.size()) {
  7989. auto to_send = std::min(compressed.size() - total_sent,
  7990. static_cast<size_t>(64 * 1024));
  7991. auto sent =
  7992. ::send(cli,
  7993. #ifdef _WIN32
  7994. static_cast<const char *>(compressed.c_str() + total_sent),
  7995. static_cast<int>(to_send),
  7996. #else
  7997. compressed.c_str() + total_sent, to_send,
  7998. #endif
  7999. 0);
  8000. if (sent <= 0) break;
  8001. total_sent += static_cast<size_t>(sent);
  8002. }
  8003. detail::close_socket(cli);
  8004. }
  8005. });
  8006. auto se = detail::scope_exit([&] {
  8007. detail::close_socket(srv);
  8008. server_thread.join();
  8009. });
  8010. size_t total_decompressed = 0;
  8011. {
  8012. Client cli("127.0.0.1", PORT + 3);
  8013. cli.set_read_timeout(5, 0);
  8014. cli.set_decompress(true);
  8015. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8016. auto stream = cli.open_stream("GET", "/zipbomb");
  8017. ASSERT_TRUE(stream.is_valid());
  8018. char buffer[64 * 1024];
  8019. ssize_t n;
  8020. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8021. total_decompressed += static_cast<size_t>(n);
  8022. }
  8023. }
  8024. // The decompressed size must be capped by payload_max_length. Without
  8025. // protection, the client would decompress the full 10MB from a tiny
  8026. // compressed payload, enabling a zip bomb DoS attack.
  8027. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8028. << "Client decompressed " << total_decompressed
  8029. << " bytes from a gzip response. The decompressed size should be "
  8030. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8031. }
  8032. #endif
  8033. TEST(HostAndPortPropertiesTest, NoSSL) {
  8034. httplib::Client cli("www.google.com", 1234);
  8035. ASSERT_EQ("www.google.com", cli.host());
  8036. ASSERT_EQ(1234, cli.port());
  8037. }
  8038. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8039. httplib::Client cli("www.google.com:1234");
  8040. ASSERT_EQ("www.google.com", cli.host());
  8041. ASSERT_EQ(1234, cli.port());
  8042. }
  8043. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8044. // Port number that overflows int — should not crash, client becomes invalid
  8045. httplib::Client cli("http://www.google.com:99999999999999999999");
  8046. ASSERT_FALSE(cli.is_valid());
  8047. }
  8048. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8049. // Port 99999 exceeds valid range (1-65535) — should not crash
  8050. httplib::Client cli("http://www.google.com:99999");
  8051. ASSERT_FALSE(cli.is_valid());
  8052. }
  8053. #ifdef CPPHTTPLIB_SSL_ENABLED
  8054. TEST(HostAndPortPropertiesTest, SSL) {
  8055. httplib::SSLClient cli("www.google.com");
  8056. ASSERT_EQ("www.google.com", cli.host());
  8057. ASSERT_EQ(443, cli.port());
  8058. }
  8059. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8060. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8061. std::string cert;
  8062. read_file(CA_CERT_FILE, cert);
  8063. httplib::SSLClient httplib_client("www.google.com");
  8064. // Load CA store first time
  8065. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8066. // Load CA store second time (update)
  8067. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8068. // Verify client is still valid and can make connections
  8069. httplib_client.enable_server_certificate_verification(true);
  8070. auto res = httplib_client.Get("/");
  8071. ASSERT_TRUE(res);
  8072. // Google may return 200 or 301 depending on various factors
  8073. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8074. res->status == StatusCode::MovedPermanently_301);
  8075. }
  8076. TEST(SSLClientTest, ServerNameIndication_Online) {
  8077. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  8078. auto host = "httpcan.org";
  8079. auto path = std::string{"/get"};
  8080. #else
  8081. auto host = "nghttp2.org";
  8082. auto path = std::string{"/httpbin/get"};
  8083. #endif
  8084. SSLClient cli(host, 443);
  8085. auto res = cli.Get(path);
  8086. ASSERT_TRUE(res);
  8087. ASSERT_EQ(StatusCode::OK_200, res->status);
  8088. }
  8089. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8090. // Use a site that will cause SSL verification failure due to self-signed cert
  8091. SSLClient cli("self-signed.badssl.com", 443);
  8092. cli.enable_server_certificate_verification(true);
  8093. auto res = cli.Get("/");
  8094. ASSERT_TRUE(!res);
  8095. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8096. // Verify backend error is captured for SSLServerVerification
  8097. // This occurs when certificate verification fails
  8098. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8099. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8100. EXPECT_NE(0UL, res.ssl_backend_error());
  8101. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8102. // For OpenSSL, ssl_error is 0 for verification errors
  8103. EXPECT_EQ(0, res.ssl_error());
  8104. #if !defined(_WIN32) || \
  8105. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8106. // On non-Windows or when Windows Schannel is disabled, the error comes
  8107. // from OpenSSL's verification
  8108. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8109. res.ssl_backend_error());
  8110. #endif
  8111. #endif
  8112. }
  8113. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8114. // Use a site where hostname doesn't match the certificate
  8115. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8116. SSLClient cli("wrong.host.badssl.com", 443);
  8117. cli.enable_server_certificate_verification(true);
  8118. cli.enable_server_hostname_verification(true);
  8119. auto res = cli.Get("/");
  8120. ASSERT_TRUE(!res);
  8121. // The error type depends on when hostname verification occurs:
  8122. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8123. // - Mbed TLS: SSLServerVerification (during handshake)
  8124. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8125. res.error() == Error::SSLServerVerification);
  8126. // Verify backend error is captured for hostname verification failure
  8127. EXPECT_NE(0UL, res.ssl_backend_error());
  8128. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8129. // For OpenSSL, ssl_error is 0 for verification errors
  8130. EXPECT_EQ(0, res.ssl_error());
  8131. #if !defined(_WIN32) || \
  8132. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8133. // On non-Windows or when Windows Schannel is disabled, the error comes
  8134. // from OpenSSL's hostname verification
  8135. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8136. res.ssl_backend_error());
  8137. #endif
  8138. #endif
  8139. }
  8140. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8141. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8142. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8143. SSLClient cli("www.google.com", 443);
  8144. cli.enable_server_certificate_verification(true);
  8145. auto res = cli.Get("/");
  8146. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8147. }
  8148. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8149. SSLClient cli("www.google.com", 443);
  8150. cli.enable_server_certificate_verification(true);
  8151. cli.enable_windows_certificate_verification(false);
  8152. auto res = cli.Get("/");
  8153. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8154. }
  8155. #endif
  8156. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8157. Client cli("https://google.com");
  8158. auto res = cli.Get("/");
  8159. ASSERT_TRUE(res);
  8160. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8161. }
  8162. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8163. SSLClient cli("google.com");
  8164. cli.set_ca_cert_path(CA_CERT_FILE);
  8165. auto res = cli.Get("/");
  8166. ASSERT_TRUE(res);
  8167. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8168. }
  8169. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8170. SSLClient cli("google.com");
  8171. cli.enable_server_certificate_verification(true);
  8172. cli.set_ca_cert_path("hello");
  8173. auto res = cli.Get("/");
  8174. ASSERT_TRUE(!res);
  8175. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8176. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8177. // should be set
  8178. EXPECT_EQ(0, res.ssl_error());
  8179. // Verify backend error is captured for SSLLoadingCerts
  8180. // This error occurs when loading CA certificates fails
  8181. EXPECT_NE(0UL, res.ssl_backend_error());
  8182. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8183. // OpenSSL specific error codes:
  8184. // > openssl errstr 0x80000002
  8185. // error:80000002:system library::No such file or directory
  8186. // > openssl errstr 0xA000126
  8187. // error:0A000126:SSL routines::unexpected eof while reading
  8188. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8189. res.ssl_backend_error() == 0xA000126);
  8190. #endif
  8191. }
  8192. TEST(SSLClientTest, ServerCertificateVerification4) {
  8193. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8194. ASSERT_TRUE(svr.is_valid());
  8195. svr.Get("/test", [&](const Request &, Response &res) {
  8196. res.set_content("test", "text/plain");
  8197. svr.stop();
  8198. ASSERT_TRUE(true);
  8199. });
  8200. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8201. auto se = detail::scope_exit([&] {
  8202. t.join();
  8203. ASSERT_FALSE(svr.is_running());
  8204. });
  8205. svr.wait_until_ready();
  8206. SSLClient cli("127.0.0.1", PORT);
  8207. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8208. cli.enable_server_certificate_verification(true);
  8209. cli.set_connection_timeout(30);
  8210. auto res = cli.Get("/test");
  8211. ASSERT_TRUE(res);
  8212. ASSERT_EQ(StatusCode::OK_200, res->status);
  8213. }
  8214. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8215. std::string cert;
  8216. read_file(CA_CERT_FILE, cert);
  8217. SSLClient cli("google.com");
  8218. cli.load_ca_cert_store(cert.data(), cert.size());
  8219. const auto res = cli.Get("/");
  8220. ASSERT_TRUE(res);
  8221. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8222. }
  8223. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8224. // clang-format off
  8225. static constexpr char cert[] =
  8226. "GlobalSign Root CA\n"
  8227. "==================\n"
  8228. "-----BEGIN CERTIFICATE-----\n"
  8229. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8230. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8231. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8232. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8233. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8234. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8235. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8236. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8237. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8238. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8239. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8240. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8241. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8242. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8243. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8244. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8245. "-----END CERTIFICATE-----\n";
  8246. // clang-format on
  8247. SSLClient cli("google.com");
  8248. cli.load_ca_cert_store(cert, sizeof(cert));
  8249. const auto res = cli.Get("/");
  8250. ASSERT_TRUE(res);
  8251. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8252. }
  8253. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8254. SSLClient cli("www.youtube.com");
  8255. cli.set_ca_cert_path(CA_CERT_FILE);
  8256. cli.enable_server_certificate_verification(true);
  8257. cli.set_follow_location(true);
  8258. auto res = cli.Get("/");
  8259. ASSERT_TRUE(res);
  8260. ASSERT_EQ(StatusCode::OK_200, res->status);
  8261. }
  8262. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8263. SSLClient cli("wWw.YouTube.Com");
  8264. cli.set_ca_cert_path(CA_CERT_FILE);
  8265. cli.enable_server_certificate_verification(true);
  8266. cli.enable_server_hostname_verification(true);
  8267. cli.set_follow_location(true);
  8268. auto res = cli.Get("/");
  8269. ASSERT_TRUE(res);
  8270. ASSERT_EQ(StatusCode::OK_200, res->status);
  8271. }
  8272. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8273. SSLClient cli("gOoGlE.COm");
  8274. cli.enable_server_certificate_verification(true);
  8275. cli.enable_server_hostname_verification(true);
  8276. cli.set_follow_location(true);
  8277. auto res = cli.Get("/");
  8278. ASSERT_TRUE(res);
  8279. ASSERT_EQ(StatusCode::OK_200, res->status);
  8280. }
  8281. TEST(SSLClientTest, Issue2004_Online) {
  8282. Client client("https://google.com");
  8283. client.set_follow_location(true);
  8284. auto res = client.Get("/");
  8285. ASSERT_TRUE(res);
  8286. ASSERT_EQ(StatusCode::OK_200, res->status);
  8287. auto body = res->body;
  8288. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8289. }
  8290. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8291. // Create SSLClient with invalid cert/key to make is_valid() return false
  8292. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8293. "nonexistent_key.pem");
  8294. // is_valid() should be false due to cert loading failure
  8295. ASSERT_FALSE(cli.is_valid());
  8296. auto res = cli.Get("/");
  8297. ASSERT_FALSE(res);
  8298. EXPECT_EQ(Error::SSLConnection, res.error());
  8299. }
  8300. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8301. // Test for Issue #2251: SSL error not properly reported when client cert
  8302. // and key paths are swapped or mismatched
  8303. // This simulates the scenario where user accidentally swaps the cert and key
  8304. // files
  8305. // Using client cert file as private key and vice versa (completely wrong)
  8306. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8307. // Should fail validation due to cert/key mismatch
  8308. ASSERT_FALSE(cli.is_valid());
  8309. // Attempt to make a request should fail with proper error
  8310. auto res = cli.Get("/");
  8311. ASSERT_FALSE(res);
  8312. EXPECT_EQ(Error::SSLConnection, res.error());
  8313. // SSL error should be recorded in the Result object (this is the key fix for
  8314. // Issue #2251)
  8315. auto backend_error = res.ssl_backend_error();
  8316. EXPECT_NE(0u, backend_error);
  8317. }
  8318. // Tests cert/key mismatch detection at the TLS context level
  8319. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8320. // Test that using mismatched cert/key causes connection failure.
  8321. // We verify this at the SSLClient level rather than through internal
  8322. // TLS API functions.
  8323. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8324. cli.enable_server_certificate_verification(false);
  8325. cli.set_connection_timeout(2);
  8326. // The mismatch should cause a connection or handshake error
  8327. auto res = cli.Get("/test");
  8328. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8329. // Either way, the request should fail
  8330. EXPECT_FALSE(res);
  8331. }
  8332. #endif
  8333. #if 0
  8334. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8335. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8336. ASSERT_TRUE(cli != nullptr);
  8337. cli->set_address_family(AF_INET6);
  8338. cli->set_interface("en0");
  8339. auto res = cli->Get("/get");
  8340. ASSERT_TRUE(res);
  8341. ASSERT_EQ(StatusCode::OK_200, res->status);
  8342. }
  8343. #endif
  8344. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8345. #ifdef CPPHTTPLIB_SSL_ENABLED
  8346. void ClientCertPresent(
  8347. const std::string &client_cert_file,
  8348. const std::string &client_private_key_file,
  8349. const std::string &client_encrypted_private_key_pass = std::string()) {
  8350. using namespace httplib::tls;
  8351. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8352. CLIENT_CA_CERT_DIR);
  8353. ASSERT_TRUE(svr.is_valid());
  8354. svr.Get("/test", [&](const Request &req, Response &res) {
  8355. res.set_content("test", "text/plain");
  8356. auto cert = req.peer_cert();
  8357. ASSERT_TRUE(static_cast<bool>(cert));
  8358. std::string common_name = cert.subject_cn();
  8359. EXPECT_EQ("Common Name", common_name);
  8360. });
  8361. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8362. auto se = detail::scope_exit([&] {
  8363. svr.stop();
  8364. t.join();
  8365. ASSERT_FALSE(svr.is_running());
  8366. });
  8367. svr.wait_until_ready();
  8368. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8369. client_encrypted_private_key_pass);
  8370. cli.enable_server_certificate_verification(false);
  8371. cli.set_connection_timeout(30);
  8372. auto res = cli.Get("/test");
  8373. ASSERT_TRUE(res);
  8374. ASSERT_EQ(StatusCode::OK_200, res->status);
  8375. }
  8376. TEST(SSLClientServerTest, ClientCertPresent) {
  8377. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8378. }
  8379. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8380. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8381. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8382. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8383. }
  8384. // PEM memory-based constructor tests (works with all TLS backends)
  8385. void PemMemoryClientCertPresent(
  8386. const std::string &client_cert_file,
  8387. const std::string &client_private_key_file,
  8388. const std::string &client_encrypted_private_key_pass = std::string()) {
  8389. // Read PEM files into memory
  8390. std::string server_cert_pem, server_key_pem;
  8391. std::string client_ca_pem;
  8392. std::string client_cert_pem, client_key_pem;
  8393. read_file(SERVER_CERT_FILE, server_cert_pem);
  8394. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8395. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8396. read_file(client_cert_file, client_cert_pem);
  8397. read_file(client_private_key_file, client_key_pem);
  8398. // Create server with PEM memory
  8399. SSLServer::PemMemory server_pem = {
  8400. server_cert_pem.c_str(),
  8401. server_cert_pem.size(),
  8402. server_key_pem.c_str(),
  8403. server_key_pem.size(),
  8404. client_ca_pem.c_str(),
  8405. client_ca_pem.size(),
  8406. nullptr // no password for server key
  8407. };
  8408. SSLServer svr(server_pem);
  8409. ASSERT_TRUE(svr.is_valid());
  8410. svr.Get("/test", [&](const Request &, Response &res) {
  8411. res.set_content("test", "text/plain");
  8412. });
  8413. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8414. auto se = detail::scope_exit([&] {
  8415. svr.stop();
  8416. t.join();
  8417. ASSERT_FALSE(svr.is_running());
  8418. });
  8419. svr.wait_until_ready();
  8420. // Create client with PEM memory
  8421. const char *password = client_encrypted_private_key_pass.empty()
  8422. ? nullptr
  8423. : client_encrypted_private_key_pass.c_str();
  8424. SSLClient::PemMemory client_pem = {
  8425. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8426. client_key_pem.size(), password};
  8427. SSLClient cli(HOST, PORT, client_pem);
  8428. cli.enable_server_certificate_verification(false);
  8429. cli.set_connection_timeout(30);
  8430. auto res = cli.Get("/test");
  8431. ASSERT_TRUE(res);
  8432. ASSERT_EQ(StatusCode::OK_200, res->status);
  8433. }
  8434. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8435. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8436. }
  8437. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8438. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8439. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8440. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8441. }
  8442. TEST(SSLClientServerTest, ClientCertMissing) {
  8443. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8444. CLIENT_CA_CERT_DIR);
  8445. ASSERT_TRUE(svr.is_valid());
  8446. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8447. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8448. auto se = detail::scope_exit([&] {
  8449. svr.stop();
  8450. t.join();
  8451. ASSERT_FALSE(svr.is_running());
  8452. });
  8453. svr.wait_until_ready();
  8454. SSLClient cli(HOST, PORT);
  8455. cli.set_connection_timeout(30);
  8456. auto res = cli.Get("/test");
  8457. ASSERT_TRUE(!res);
  8458. // When client cert is missing and server requires it, connection fails
  8459. // Error type depends on backend implementation
  8460. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8461. res.error() == Error::SSLConnection);
  8462. // Verify backend error is captured
  8463. // Note: This test may have different error codes depending on the exact
  8464. // verification failure
  8465. EXPECT_NE(0UL, res.ssl_backend_error());
  8466. }
  8467. TEST(SSLClientServerTest, TrustDirOptional) {
  8468. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8469. ASSERT_TRUE(svr.is_valid());
  8470. svr.Get("/test", [&](const Request &, Response &res) {
  8471. res.set_content("test", "text/plain");
  8472. });
  8473. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8474. auto se = detail::scope_exit([&] {
  8475. svr.stop();
  8476. t.join();
  8477. ASSERT_FALSE(svr.is_running());
  8478. });
  8479. svr.wait_until_ready();
  8480. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8481. cli.enable_server_certificate_verification(false);
  8482. cli.set_connection_timeout(30);
  8483. auto res = cli.Get("/test");
  8484. ASSERT_TRUE(res);
  8485. ASSERT_EQ(StatusCode::OK_200, res->status);
  8486. }
  8487. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8488. class NoListenSSLServer : public SSLServer {
  8489. public:
  8490. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8491. const char *client_ca_cert_file_path,
  8492. const char *client_ca_cert_dir_path = nullptr)
  8493. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8494. client_ca_cert_dir_path),
  8495. stop_(false) {}
  8496. std::atomic_bool stop_;
  8497. private:
  8498. bool process_and_close_socket(socket_t /*sock*/) override {
  8499. // Don't create SSL context
  8500. while (!stop_.load()) {
  8501. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8502. }
  8503. return true;
  8504. }
  8505. };
  8506. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8507. CLIENT_CA_CERT_FILE);
  8508. ASSERT_TRUE(svr.is_valid());
  8509. svr.Get("/test", [&](const Request &, Response &res) {
  8510. res.set_content("test", "text/plain");
  8511. });
  8512. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8513. auto se = detail::scope_exit([&] {
  8514. svr.stop_ = true;
  8515. svr.stop();
  8516. t.join();
  8517. ASSERT_FALSE(svr.is_running());
  8518. });
  8519. svr.wait_until_ready();
  8520. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8521. cli.enable_server_certificate_verification(false);
  8522. cli.set_connection_timeout(1);
  8523. auto res = cli.Get("/test");
  8524. ASSERT_TRUE(!res);
  8525. EXPECT_EQ(Error::SSLConnection, res.error());
  8526. // Timeout results in WantRead error code (maps to backend-specific value)
  8527. EXPECT_NE(0, res.ssl_error());
  8528. }
  8529. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8530. // Test SSLServer with client certificate verification using the standard
  8531. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8532. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8533. CLIENT_CA_CERT_DIR);
  8534. ASSERT_TRUE(svr.is_valid());
  8535. svr.Get("/test", [&](const Request &req, Response &res) {
  8536. res.set_content("test", "text/plain");
  8537. auto cert = req.peer_cert();
  8538. ASSERT_TRUE(static_cast<bool>(cert));
  8539. auto common_name = cert.subject_cn();
  8540. EXPECT_EQ("Common Name", common_name);
  8541. });
  8542. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8543. auto se = detail::scope_exit([&] {
  8544. svr.stop();
  8545. t.join();
  8546. ASSERT_FALSE(svr.is_running());
  8547. });
  8548. svr.wait_until_ready();
  8549. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8550. cli.enable_server_certificate_verification(false);
  8551. cli.set_connection_timeout(30);
  8552. auto res = cli.Get("/test");
  8553. ASSERT_TRUE(res);
  8554. ASSERT_EQ(StatusCode::OK_200, res->status);
  8555. }
  8556. // Test verify_hostname for both OpenSSL and MbedTLS backends
  8557. // Verifies that wildcard matching and exact matching work consistently
  8558. TEST(SSLClientServerTest, TlsVerifyHostname) {
  8559. using namespace httplib::tls;
  8560. // We need a running server to test against
  8561. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8562. ASSERT_TRUE(svr.is_valid());
  8563. svr.Get("/test", [](const Request &, Response &res) {
  8564. res.set_content("ok", "text/plain");
  8565. });
  8566. thread t([&]() { svr.listen(HOST, PORT); });
  8567. auto se = detail::scope_exit([&] {
  8568. svr.stop();
  8569. t.join();
  8570. });
  8571. svr.wait_until_ready();
  8572. bool verify_callback_called = false;
  8573. bool verify_result_wrong = false;
  8574. SSLClient cli(HOST, PORT);
  8575. cli.enable_server_certificate_verification(true);
  8576. cli.set_ca_cert_path(CA_CERT_FILE);
  8577. cli.set_connection_timeout(5);
  8578. // Note: Test certificate has CN="Common Name", not "localhost"
  8579. bool verify_result_cn = false;
  8580. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8581. verify_callback_called = true;
  8582. if (!ctx.cert) return false;
  8583. // Test 1: "Common Name" should match (our test server cert CN)
  8584. verify_result_cn = ctx.check_hostname("Common Name");
  8585. // Test 2: wrong hostname should not match
  8586. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  8587. return true; // Accept for the purpose of this test
  8588. });
  8589. auto res = cli.Get("/test");
  8590. // The request may succeed or fail depending on cert configuration
  8591. // but the callback should have been called
  8592. ASSERT_TRUE(verify_callback_called)
  8593. << "Verify callback should have been called";
  8594. // CN="Common Name" should match our test certificate
  8595. EXPECT_TRUE(verify_result_cn)
  8596. << "verify_hostname should match 'Common Name' (certificate CN)";
  8597. // Wrong hostname should not match
  8598. EXPECT_FALSE(verify_result_wrong)
  8599. << "verify_hostname should not match 'wronghost.example.com'";
  8600. }
  8601. #endif
  8602. // mbedTLS-specific callback constructor test
  8603. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8604. #ifdef CPPHTTPLIB_SSL_ENABLED
  8605. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8606. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8607. ASSERT_TRUE(svr.is_valid());
  8608. // Set up a handler to verify client certificate is present
  8609. bool client_cert_verified = false;
  8610. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8611. // Verify that client certificate was provided
  8612. client_cert_verified = true;
  8613. res.set_content("success", "text/plain");
  8614. });
  8615. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8616. auto se = detail::scope_exit([&] {
  8617. svr.stop();
  8618. t.join();
  8619. ASSERT_FALSE(svr.is_running());
  8620. });
  8621. svr.wait_until_ready();
  8622. // Client with certificate
  8623. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8624. cli.enable_server_certificate_verification(false);
  8625. cli.set_connection_timeout(30);
  8626. auto res = cli.Get("/test");
  8627. ASSERT_TRUE(res);
  8628. ASSERT_EQ(StatusCode::OK_200, res->status);
  8629. ASSERT_TRUE(client_cert_verified);
  8630. EXPECT_EQ("success", res->body);
  8631. }
  8632. #endif
  8633. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  8634. // backends
  8635. #ifdef CPPHTTPLIB_SSL_ENABLED
  8636. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  8637. using namespace httplib::tls;
  8638. // Test that when client CA cert file is provided,
  8639. // the server properly requests and validates client certificates
  8640. // Create a server with client authentication
  8641. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8642. ASSERT_TRUE(svr.is_valid());
  8643. bool handler_called = false;
  8644. svr.Get("/test", [&](const Request &req, Response &res) {
  8645. handler_called = true;
  8646. // Verify that a client certificate was provided
  8647. auto cert = req.peer_cert();
  8648. ASSERT_TRUE(static_cast<bool>(cert));
  8649. // Get the issuer name
  8650. std::string issuer_str = cert.issuer_name();
  8651. ASSERT_FALSE(issuer_str.empty());
  8652. // The client certificate should be issued by our test CA
  8653. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  8654. res.set_content("authenticated", "text/plain");
  8655. });
  8656. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8657. auto se = detail::scope_exit([&] {
  8658. svr.stop();
  8659. t.join();
  8660. ASSERT_FALSE(svr.is_running());
  8661. });
  8662. svr.wait_until_ready();
  8663. // Connect with a client certificate issued by the CA
  8664. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8665. cli.enable_server_certificate_verification(false);
  8666. cli.set_connection_timeout(30);
  8667. auto res = cli.Get("/test");
  8668. ASSERT_TRUE(res);
  8669. ASSERT_EQ(StatusCode::OK_200, res->status);
  8670. ASSERT_TRUE(handler_called);
  8671. EXPECT_EQ("authenticated", res->body);
  8672. }
  8673. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  8674. using namespace httplib::tls;
  8675. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8676. ASSERT_TRUE(svr.is_valid());
  8677. svr.Get("/test", [](const Request &, Response &res) {
  8678. res.set_content("ok", "text/plain");
  8679. });
  8680. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8681. auto se = detail::scope_exit([&] {
  8682. svr.stop();
  8683. t.join();
  8684. });
  8685. svr.wait_until_ready();
  8686. SSLClient cli(HOST, PORT);
  8687. cli.enable_server_certificate_verification(false);
  8688. cli.set_connection_timeout(30);
  8689. bool cert_checked = false;
  8690. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8691. if (ctx.cert) {
  8692. auto sans = ctx.sans();
  8693. // Test certificate may or may not have SANs - just verify the API
  8694. // works If SANs exist, verify the types are valid
  8695. for (const auto &san : sans) {
  8696. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  8697. san.type == SanType::EMAIL || san.type == SanType::URI ||
  8698. san.type == SanType::OTHER);
  8699. EXPECT_FALSE(san.value.empty());
  8700. }
  8701. cert_checked = true;
  8702. }
  8703. return true;
  8704. });
  8705. auto res = cli.Get("/test");
  8706. ASSERT_TRUE(res);
  8707. EXPECT_TRUE(cert_checked);
  8708. }
  8709. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  8710. using namespace httplib::tls;
  8711. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8712. ASSERT_TRUE(svr.is_valid());
  8713. svr.Get("/test", [](const Request &, Response &res) {
  8714. res.set_content("ok", "text/plain");
  8715. });
  8716. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8717. auto se = detail::scope_exit([&] {
  8718. svr.stop();
  8719. t.join();
  8720. });
  8721. svr.wait_until_ready();
  8722. SSLClient cli(HOST, PORT);
  8723. cli.enable_server_certificate_verification(false);
  8724. cli.set_connection_timeout(30);
  8725. bool validity_checked = false;
  8726. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8727. if (ctx.cert) {
  8728. time_t not_before = 0, not_after = 0;
  8729. bool result = ctx.validity(not_before, not_after);
  8730. EXPECT_TRUE(result);
  8731. // Verify that not_before < now < not_after for a valid cert
  8732. time_t now = time(nullptr);
  8733. EXPECT_LT(not_before, now);
  8734. EXPECT_GT(not_after, now);
  8735. validity_checked = true;
  8736. }
  8737. return true;
  8738. });
  8739. auto res = cli.Get("/test");
  8740. ASSERT_TRUE(res);
  8741. EXPECT_TRUE(validity_checked);
  8742. }
  8743. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  8744. using namespace httplib::tls;
  8745. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8746. ASSERT_TRUE(svr.is_valid());
  8747. svr.Get("/test", [](const Request &, Response &res) {
  8748. res.set_content("ok", "text/plain");
  8749. });
  8750. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8751. auto se = detail::scope_exit([&] {
  8752. svr.stop();
  8753. t.join();
  8754. });
  8755. svr.wait_until_ready();
  8756. SSLClient cli(HOST, PORT);
  8757. cli.enable_server_certificate_verification(false);
  8758. cli.set_connection_timeout(30);
  8759. bool serial_checked = false;
  8760. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8761. if (ctx.cert) {
  8762. std::string serial = ctx.serial();
  8763. EXPECT_FALSE(serial.empty());
  8764. // Serial should be a hex string
  8765. for (char c : serial) {
  8766. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  8767. (c >= 'a' && c <= 'f'));
  8768. }
  8769. serial_checked = true;
  8770. }
  8771. return true;
  8772. });
  8773. auto res = cli.Get("/test");
  8774. ASSERT_TRUE(res);
  8775. EXPECT_TRUE(serial_checked);
  8776. }
  8777. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  8778. // Test 1: Valid CA file - no error should be recorded
  8779. {
  8780. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8781. CLIENT_CA_CERT_FILE);
  8782. ASSERT_TRUE(svr.is_valid());
  8783. // With valid setup, last_ssl_error should be 0
  8784. EXPECT_EQ(0, svr.ssl_last_error());
  8785. }
  8786. // Test 2: Invalid CA file content
  8787. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  8788. {
  8789. // Create a temporary file with completely invalid content
  8790. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  8791. {
  8792. std::ofstream ofs(temp_invalid_ca);
  8793. ofs << "This is not a certificate file at all\n";
  8794. ofs << "Just plain text content\n";
  8795. }
  8796. // Create server with invalid CA file
  8797. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  8798. // Clean up temporary file
  8799. std::remove(temp_invalid_ca);
  8800. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  8801. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  8802. // Note: SSL_CTX_load_verify_locations typically fails first,
  8803. // but our error handling code path is still exercised
  8804. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  8805. }
  8806. }
  8807. TEST(VerifyCallbackTest, VerifyContextFields) {
  8808. using namespace httplib::tls;
  8809. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8810. ASSERT_TRUE(svr.is_valid());
  8811. svr.Get("/test", [](const Request &, Response &res) {
  8812. res.set_content("ok", "text/plain");
  8813. });
  8814. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8815. auto se = detail::scope_exit([&] {
  8816. svr.stop();
  8817. t.join();
  8818. });
  8819. svr.wait_until_ready();
  8820. SSLClient cli(HOST, PORT);
  8821. cli.enable_server_certificate_verification(false);
  8822. cli.set_connection_timeout(30);
  8823. int callback_count = 0;
  8824. bool saw_leaf_cert = false;
  8825. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8826. if (ctx.cert) {
  8827. callback_count++;
  8828. // We should see at least one certificate (the leaf)
  8829. std::string cn = ctx.subject_cn();
  8830. if (!cn.empty()) { saw_leaf_cert = true; }
  8831. // Verify context fields are populated
  8832. EXPECT_NE(ctx.session, nullptr);
  8833. EXPECT_GE(ctx.depth, 0);
  8834. }
  8835. return true;
  8836. });
  8837. auto res = cli.Get("/test");
  8838. ASSERT_TRUE(res);
  8839. EXPECT_GT(callback_count, 0);
  8840. EXPECT_TRUE(saw_leaf_cert);
  8841. }
  8842. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  8843. using httplib::tls::TlsError;
  8844. // Test that verify_error_to_string returns empty for success
  8845. std::string success_str = TlsError::verify_error_to_string(0);
  8846. EXPECT_TRUE(success_str.empty());
  8847. // Test that verify_error_to_string returns non-empty for error codes
  8848. // Using a common error code (certificate expired)
  8849. std::string error_str =
  8850. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  8851. EXPECT_FALSE(error_str.empty());
  8852. }
  8853. TEST(SessionVerifierTest, CertificateAccepted) {
  8854. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8855. ASSERT_TRUE(svr.is_valid());
  8856. svr.Get("/test", [](const Request &, Response &res) {
  8857. res.set_content("ok", "text/plain");
  8858. });
  8859. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8860. auto se = detail::scope_exit([&] {
  8861. svr.stop();
  8862. t.join();
  8863. });
  8864. svr.wait_until_ready();
  8865. SSLClient cli(HOST, PORT);
  8866. cli.enable_server_certificate_verification(false);
  8867. cli.set_connection_timeout(30);
  8868. bool callback_called = false;
  8869. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8870. EXPECT_NE(session, nullptr);
  8871. callback_called = true;
  8872. return SSLVerifierResponse::CertificateAccepted;
  8873. });
  8874. auto res = cli.Get("/test");
  8875. ASSERT_TRUE(res);
  8876. EXPECT_EQ(200, res->status);
  8877. EXPECT_TRUE(callback_called);
  8878. }
  8879. TEST(SessionVerifierTest, CertificateRejected) {
  8880. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8881. ASSERT_TRUE(svr.is_valid());
  8882. svr.Get("/test", [](const Request &, Response &res) {
  8883. res.set_content("ok", "text/plain");
  8884. });
  8885. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8886. auto se = detail::scope_exit([&] {
  8887. svr.stop();
  8888. t.join();
  8889. });
  8890. svr.wait_until_ready();
  8891. SSLClient cli(HOST, PORT);
  8892. cli.enable_server_certificate_verification(false);
  8893. cli.set_connection_timeout(30);
  8894. bool callback_called = false;
  8895. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8896. EXPECT_NE(session, nullptr);
  8897. callback_called = true;
  8898. return SSLVerifierResponse::CertificateRejected;
  8899. });
  8900. auto res = cli.Get("/test");
  8901. EXPECT_FALSE(res);
  8902. EXPECT_TRUE(callback_called);
  8903. }
  8904. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  8905. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8906. ASSERT_TRUE(svr.is_valid());
  8907. svr.Get("/test", [](const Request &, Response &res) {
  8908. res.set_content("ok", "text/plain");
  8909. });
  8910. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8911. auto se = detail::scope_exit([&] {
  8912. svr.stop();
  8913. t.join();
  8914. });
  8915. svr.wait_until_ready();
  8916. // NoDecisionMade with verification disabled should succeed (no default check)
  8917. SSLClient cli(HOST, PORT);
  8918. cli.enable_server_certificate_verification(false);
  8919. cli.set_connection_timeout(30);
  8920. bool callback_called = false;
  8921. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8922. EXPECT_NE(session, nullptr);
  8923. callback_called = true;
  8924. return SSLVerifierResponse::NoDecisionMade;
  8925. });
  8926. auto res = cli.Get("/test");
  8927. ASSERT_TRUE(res);
  8928. EXPECT_EQ(200, res->status);
  8929. EXPECT_TRUE(callback_called);
  8930. }
  8931. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  8932. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8933. ASSERT_TRUE(svr.is_valid());
  8934. svr.Get("/test", [](const Request &, Response &res) {
  8935. res.set_content("ok", "text/plain");
  8936. });
  8937. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8938. auto se = detail::scope_exit([&] {
  8939. svr.stop();
  8940. t.join();
  8941. });
  8942. svr.wait_until_ready();
  8943. // NoDecisionMade with verification enabled should fail (self-signed cert).
  8944. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  8945. // so we only check that the request fails, not whether the callback was
  8946. // called.
  8947. SSLClient cli(HOST, PORT);
  8948. cli.enable_server_certificate_verification(true);
  8949. cli.set_connection_timeout(30);
  8950. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8951. EXPECT_NE(session, nullptr);
  8952. return SSLVerifierResponse::NoDecisionMade;
  8953. });
  8954. auto res = cli.Get("/test");
  8955. EXPECT_FALSE(res);
  8956. }
  8957. TEST(SSLClientServerTest, ClientCAListFromPem) {
  8958. // Test SSL server using PemMemory constructor with client CA certificates
  8959. // Read PEM files
  8960. std::string server_cert_pem, server_key_pem, client_ca_pem;
  8961. read_file(SERVER_CERT_FILE, server_cert_pem);
  8962. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8963. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8964. // Create SSLServer with PemMemory constructor including client CA
  8965. SSLServer::PemMemory server_pem = {
  8966. server_cert_pem.c_str(),
  8967. server_cert_pem.size(),
  8968. server_key_pem.c_str(),
  8969. server_key_pem.size(),
  8970. client_ca_pem.c_str(),
  8971. client_ca_pem.size(),
  8972. nullptr // no password for server key
  8973. };
  8974. SSLServer svr(server_pem);
  8975. ASSERT_TRUE(svr.is_valid());
  8976. // No SSL error should be recorded for valid setup
  8977. EXPECT_EQ(0, svr.ssl_last_error());
  8978. // Set up server endpoints
  8979. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  8980. res.set_content("ok", "text/plain");
  8981. });
  8982. // Start server in a thread
  8983. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  8984. svr.wait_until_ready();
  8985. // Connect with client certificate (using constructor with paths)
  8986. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8987. cli.enable_server_certificate_verification(false);
  8988. auto res = cli.Get("/test-pem-ca");
  8989. ASSERT_TRUE(res);
  8990. EXPECT_EQ(200, res->status);
  8991. EXPECT_EQ("ok", res->body);
  8992. svr.stop();
  8993. server_thread.join();
  8994. }
  8995. #endif
  8996. #ifdef _WIN32
  8997. TEST(CleanupTest, WSACleanup) {
  8998. int ret = WSACleanup();
  8999. ASSERT_EQ(0, ret);
  9000. }
  9001. #endif
  9002. #ifndef CPPHTTPLIB_SSL_ENABLED
  9003. TEST(NoSSLSupport, SimpleInterface) {
  9004. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  9005. }
  9006. #endif
  9007. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9008. TEST(InvalidScheme, SimpleInterface) {
  9009. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  9010. }
  9011. #endif
  9012. TEST(NoScheme, SimpleInterface) {
  9013. Client cli("yahoo.com:80");
  9014. ASSERT_TRUE(cli.is_valid());
  9015. }
  9016. TEST(SendAPI, SimpleInterface_Online) {
  9017. Client cli("http://yahoo.com");
  9018. Request req;
  9019. req.method = "GET";
  9020. req.path = "/";
  9021. auto res = cli.send(req);
  9022. ASSERT_TRUE(res);
  9023. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9024. }
  9025. TEST(SendAPI, WithParamsInRequest) {
  9026. Server svr;
  9027. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  9028. EXPECT_TRUE(req.has_param("test"));
  9029. EXPECT_EQ("test_value", req.get_param_value("test"));
  9030. });
  9031. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  9032. auto se = detail::scope_exit([&] {
  9033. svr.stop();
  9034. t.join();
  9035. ASSERT_FALSE(svr.is_running());
  9036. });
  9037. svr.wait_until_ready();
  9038. Client cli(HOST, PORT);
  9039. {
  9040. Request req;
  9041. req.method = "GET";
  9042. req.path = "/";
  9043. req.params.emplace("test", "test_value");
  9044. auto res = cli.send(req);
  9045. ASSERT_TRUE(res);
  9046. }
  9047. {
  9048. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  9049. ASSERT_TRUE(res);
  9050. }
  9051. }
  9052. TEST(ClientImplMethods, GetSocketTest) {
  9053. httplib::Server svr;
  9054. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9055. res.status = StatusCode::OK_200;
  9056. });
  9057. auto port = svr.bind_to_any_port("127.0.0.1");
  9058. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9059. auto se = detail::scope_exit([&] {
  9060. svr.stop();
  9061. thread.join();
  9062. ASSERT_FALSE(svr.is_running());
  9063. });
  9064. svr.wait_until_ready();
  9065. {
  9066. httplib::Client cli("127.0.0.1", port);
  9067. cli.set_keep_alive(true);
  9068. // Use the behavior of cpp-httplib of opening the connection
  9069. // only when the first request happens. If that changes,
  9070. // this test would be obsolete.
  9071. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9072. // This also implicitly tests the server. But other tests would fail much
  9073. // earlier than this one to be considered.
  9074. auto res = cli.Get("/");
  9075. ASSERT_TRUE(res);
  9076. EXPECT_EQ(StatusCode::OK_200, res->status);
  9077. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9078. }
  9079. }
  9080. #ifdef CPPHTTPLIB_SSL_ENABLED
  9081. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9082. Client cli("http://yahoo.com");
  9083. auto res = cli.Get("/");
  9084. ASSERT_TRUE(res);
  9085. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9086. cli.set_follow_location(true);
  9087. res = cli.Get("/");
  9088. ASSERT_TRUE(res);
  9089. EXPECT_EQ(StatusCode::OK_200, res->status);
  9090. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9091. }
  9092. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9093. Client cli("https://yahoo.com");
  9094. auto res = cli.Get("/");
  9095. ASSERT_TRUE(res);
  9096. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9097. cli.set_follow_location(true);
  9098. res = cli.Get("/");
  9099. ASSERT_TRUE(res);
  9100. EXPECT_EQ(StatusCode::OK_200, res->status);
  9101. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9102. }
  9103. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9104. Client cli("https://yahoo.com");
  9105. auto res = cli.Get("/");
  9106. ASSERT_TRUE(res);
  9107. ASSERT_FALSE(!res);
  9108. ASSERT_TRUE(res);
  9109. ASSERT_FALSE(res == nullptr);
  9110. ASSERT_TRUE(res != nullptr);
  9111. EXPECT_EQ(Error::Success, res.error());
  9112. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9113. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9114. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9115. cli.set_follow_location(true);
  9116. res = cli.Get("/");
  9117. ASSERT_TRUE(res);
  9118. EXPECT_EQ(Error::Success, res.error());
  9119. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9120. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9121. EXPECT_EQ(StatusCode::OK_200, res->status);
  9122. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9123. }
  9124. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9125. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9126. Client cli("https://cdnjs.cloudflare.com");
  9127. auto res =
  9128. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9129. ASSERT_TRUE(res);
  9130. EXPECT_EQ(StatusCode::OK_200, res->status);
  9131. EXPECT_EQ(287630U, res->body.size());
  9132. EXPECT_EQ("application/javascript; charset=utf-8",
  9133. res->get_header_value("Content-Type"));
  9134. }
  9135. #endif
  9136. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9137. #undef REDIR_HOST // Silence compiler warning
  9138. #define REDIR_HOST "https://httpbingo.org"
  9139. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9140. Client cli(REDIR_HOST);
  9141. cli.set_follow_location(true);
  9142. auto res =
  9143. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9144. ASSERT_TRUE(res);
  9145. EXPECT_EQ(StatusCode::OK_200, res->status);
  9146. }
  9147. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9148. Client cli(REDIR_HOST);
  9149. cli.set_follow_location(true);
  9150. Params params;
  9151. params.emplace("url", "http://example.com");
  9152. params.emplace("status_code", "302");
  9153. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9154. ASSERT_TRUE(res);
  9155. EXPECT_EQ(StatusCode::OK_200, res->status);
  9156. }
  9157. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9158. Client cli(REDIR_HOST);
  9159. cli.set_follow_location(true);
  9160. Params params;
  9161. params.emplace("url", "http://example.com");
  9162. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9163. ASSERT_TRUE(res);
  9164. EXPECT_EQ(StatusCode::OK_200, res->status);
  9165. }
  9166. TEST(HttpToHttpsRedirectTest, CertFile) {
  9167. auto ssl_port = PORT + 1;
  9168. Server svr;
  9169. ASSERT_TRUE(svr.is_valid());
  9170. svr.Get("/index", [&](const Request &, Response &res) {
  9171. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9172. "/index");
  9173. svr.stop();
  9174. });
  9175. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9176. ASSERT_TRUE(ssl_svr.is_valid());
  9177. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9178. res.set_content("test", "text/plain");
  9179. ssl_svr.stop();
  9180. });
  9181. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9182. thread t2 =
  9183. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9184. auto se = detail::scope_exit([&] {
  9185. t2.join();
  9186. t.join();
  9187. ASSERT_FALSE(svr.is_running());
  9188. });
  9189. svr.wait_until_ready();
  9190. ssl_svr.wait_until_ready();
  9191. Client cli("127.0.0.1", PORT);
  9192. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9193. cli.enable_server_certificate_verification(true);
  9194. cli.set_follow_location(true);
  9195. cli.set_connection_timeout(30);
  9196. auto res = cli.Get("/index");
  9197. ASSERT_TRUE(res);
  9198. ASSERT_EQ(StatusCode::OK_200, res->status);
  9199. }
  9200. TEST(SSLClientRedirectTest, CertFile) {
  9201. auto ssl_port = PORT + 1;
  9202. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9203. ASSERT_TRUE(ssl_svr1.is_valid());
  9204. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9205. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9206. "/index");
  9207. ssl_svr1.stop();
  9208. });
  9209. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9210. ASSERT_TRUE(ssl_svr2.is_valid());
  9211. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9212. res.set_content("test", "text/plain");
  9213. ssl_svr2.stop();
  9214. });
  9215. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9216. thread t2 =
  9217. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9218. auto se = detail::scope_exit([&] {
  9219. t2.join();
  9220. t.join();
  9221. ASSERT_FALSE(ssl_svr1.is_running());
  9222. });
  9223. ssl_svr1.wait_until_ready();
  9224. ssl_svr2.wait_until_ready();
  9225. SSLClient cli("127.0.0.1", PORT);
  9226. std::string cert;
  9227. read_file(SERVER_CERT2_FILE, cert);
  9228. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9229. cli.enable_server_certificate_verification(true);
  9230. cli.set_follow_location(true);
  9231. cli.set_connection_timeout(30);
  9232. auto res = cli.Get("/index");
  9233. ASSERT_TRUE(res);
  9234. ASSERT_EQ(StatusCode::OK_200, res->status);
  9235. }
  9236. #endif
  9237. #ifdef CPPHTTPLIB_SSL_ENABLED
  9238. // Test that set_ca_cert_store() skips system certs (consistent with
  9239. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9240. // should be trusted - system certs should NOT be loaded.
  9241. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9242. // Load a specific cert that is NOT a system CA cert
  9243. std::string cert;
  9244. read_file(SERVER_CERT2_FILE, cert);
  9245. SSLClient cli("google.com");
  9246. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9247. cli.enable_server_certificate_verification(true);
  9248. // This should FAIL because:
  9249. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9250. // 2. System certs should NOT be loaded when custom store is set
  9251. // If system certs WERE loaded, this would succeed
  9252. auto res = cli.Get("/");
  9253. ASSERT_FALSE(res);
  9254. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9255. }
  9256. TEST(MultipartFormDataTest, LargeData) {
  9257. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9258. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9259. const ContentReader &content_reader) {
  9260. if (req.is_multipart_form_data()) {
  9261. std::vector<FormData> items;
  9262. content_reader(
  9263. [&](const FormData &file) {
  9264. items.push_back(file);
  9265. return true;
  9266. },
  9267. [&](const char *data, size_t data_length) {
  9268. items.back().content.append(data, data_length);
  9269. return true;
  9270. });
  9271. EXPECT_TRUE(std::string(items[0].name) == "document");
  9272. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9273. EXPECT_TRUE(items[0].filename == "2MB_data");
  9274. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9275. EXPECT_TRUE(items[1].name == "hello");
  9276. EXPECT_TRUE(items[1].content == "world");
  9277. EXPECT_TRUE(items[1].filename == "");
  9278. EXPECT_TRUE(items[1].content_type == "");
  9279. } else {
  9280. std::string body;
  9281. content_reader([&](const char *data, size_t data_length) {
  9282. body.append(data, data_length);
  9283. return true;
  9284. });
  9285. }
  9286. });
  9287. auto port = svr.bind_to_any_port(HOST);
  9288. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9289. auto se = detail::scope_exit([&] {
  9290. svr.stop();
  9291. t.join();
  9292. ASSERT_FALSE(svr.is_running());
  9293. });
  9294. svr.wait_until_ready();
  9295. {
  9296. std::string data(1024 * 1024 * 2, '.');
  9297. std::stringstream buffer;
  9298. buffer << data;
  9299. SSLClient cli(HOST, port);
  9300. cli.enable_server_certificate_verification(false);
  9301. UploadFormDataItems items{
  9302. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9303. {"hello", "world", "", ""},
  9304. };
  9305. auto res = cli.Post("/post", items);
  9306. ASSERT_TRUE(res);
  9307. ASSERT_EQ(StatusCode::OK_200, res->status);
  9308. }
  9309. }
  9310. TEST(MultipartFormDataTest, DataProviderItems) {
  9311. std::random_device seed_gen;
  9312. std::mt19937 random(seed_gen());
  9313. std::string rand1;
  9314. rand1.resize(1000);
  9315. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9316. std::string rand2;
  9317. rand2.resize(3000);
  9318. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9319. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9320. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9321. const ContentReader &content_reader) {
  9322. ASSERT_FALSE(req.is_multipart_form_data());
  9323. std::string body;
  9324. content_reader([&](const char *data, size_t data_length) {
  9325. body.append(data, data_length);
  9326. return true;
  9327. });
  9328. EXPECT_EQ(body, "");
  9329. });
  9330. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9331. const ContentReader &content_reader) {
  9332. ASSERT_TRUE(req.is_multipart_form_data());
  9333. std::vector<FormData> items;
  9334. content_reader(
  9335. [&](const FormData &file) {
  9336. items.push_back(file);
  9337. return true;
  9338. },
  9339. [&](const char *data, size_t data_length) {
  9340. items.back().content.append(data, data_length);
  9341. return true;
  9342. });
  9343. ASSERT_TRUE(items.size() == 2);
  9344. EXPECT_EQ(std::string(items[0].name), "name1");
  9345. EXPECT_EQ(items[0].content, "Testing123");
  9346. EXPECT_EQ(items[0].filename, "filename1");
  9347. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9348. EXPECT_EQ(items[1].name, "name2");
  9349. EXPECT_EQ(items[1].content, "Testing456");
  9350. EXPECT_EQ(items[1].filename, "");
  9351. EXPECT_EQ(items[1].content_type, "");
  9352. });
  9353. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9354. const ContentReader &content_reader) {
  9355. ASSERT_TRUE(req.is_multipart_form_data());
  9356. std::vector<FormData> items;
  9357. content_reader(
  9358. [&](const FormData &file) {
  9359. items.push_back(file);
  9360. return true;
  9361. },
  9362. [&](const char *data, size_t data_length) {
  9363. items.back().content.append(data, data_length);
  9364. return true;
  9365. });
  9366. ASSERT_TRUE(items.size() == 2);
  9367. EXPECT_EQ(items[0].name, "name3");
  9368. EXPECT_EQ(items[0].content, rand1);
  9369. EXPECT_EQ(items[0].filename, "filename3");
  9370. EXPECT_EQ(items[0].content_type, "");
  9371. EXPECT_EQ(items[1].name, "name4");
  9372. EXPECT_EQ(items[1].content, rand2);
  9373. EXPECT_EQ(items[1].filename, "filename4");
  9374. EXPECT_EQ(items[1].content_type, "");
  9375. });
  9376. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9377. const ContentReader &content_reader) {
  9378. ASSERT_TRUE(req.is_multipart_form_data());
  9379. std::vector<FormData> items;
  9380. content_reader(
  9381. [&](const FormData &file) {
  9382. items.push_back(file);
  9383. return true;
  9384. },
  9385. [&](const char *data, size_t data_length) {
  9386. items.back().content.append(data, data_length);
  9387. return true;
  9388. });
  9389. ASSERT_TRUE(items.size() == 4);
  9390. EXPECT_EQ(std::string(items[0].name), "name1");
  9391. EXPECT_EQ(items[0].content, "Testing123");
  9392. EXPECT_EQ(items[0].filename, "filename1");
  9393. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9394. EXPECT_EQ(items[1].name, "name2");
  9395. EXPECT_EQ(items[1].content, "Testing456");
  9396. EXPECT_EQ(items[1].filename, "");
  9397. EXPECT_EQ(items[1].content_type, "");
  9398. EXPECT_EQ(items[2].name, "name3");
  9399. EXPECT_EQ(items[2].content, rand1);
  9400. EXPECT_EQ(items[2].filename, "filename3");
  9401. EXPECT_EQ(items[2].content_type, "");
  9402. EXPECT_EQ(items[3].name, "name4");
  9403. EXPECT_EQ(items[3].content, rand2);
  9404. EXPECT_EQ(items[3].filename, "filename4");
  9405. EXPECT_EQ(items[3].content_type, "");
  9406. });
  9407. auto port = svr.bind_to_any_port("localhost");
  9408. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9409. auto se = detail::scope_exit([&] {
  9410. svr.stop();
  9411. t.join();
  9412. ASSERT_FALSE(svr.is_running());
  9413. });
  9414. svr.wait_until_ready();
  9415. {
  9416. SSLClient cli("localhost", port);
  9417. cli.enable_server_certificate_verification(false);
  9418. UploadFormDataItems items{
  9419. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9420. {"name2", "Testing456", "", ""}, // not a file
  9421. };
  9422. {
  9423. auto res = cli.Post("/post-none", {}, {}, {});
  9424. ASSERT_TRUE(res);
  9425. ASSERT_EQ(StatusCode::OK_200, res->status);
  9426. }
  9427. FormDataProviderItems providers;
  9428. {
  9429. auto res =
  9430. cli.Post("/post-items", {}, items, providers); // empty providers
  9431. ASSERT_TRUE(res);
  9432. ASSERT_EQ(StatusCode::OK_200, res->status);
  9433. }
  9434. providers.push_back({"name3",
  9435. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9436. // test the offset is given correctly at each step
  9437. if (!offset)
  9438. sink.os.write(rand1.data(), 30);
  9439. else if (offset == 30)
  9440. sink.os.write(rand1.data() + 30, 300);
  9441. else if (offset == 330)
  9442. sink.os.write(rand1.data() + 330, 670);
  9443. else if (offset == rand1.size())
  9444. sink.done();
  9445. return true;
  9446. },
  9447. "filename3",
  9448. {}});
  9449. providers.push_back({"name4",
  9450. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9451. // test the offset is given correctly at each step
  9452. if (!offset)
  9453. sink.os.write(rand2.data(), 2000);
  9454. else if (offset == 2000)
  9455. sink.os.write(rand2.data() + 2000, 1);
  9456. else if (offset == 2001)
  9457. sink.os.write(rand2.data() + 2001, 999);
  9458. else if (offset == rand2.size())
  9459. sink.done();
  9460. return true;
  9461. },
  9462. "filename4",
  9463. {}});
  9464. {
  9465. auto res = cli.Post("/post-providers", {}, {}, providers);
  9466. ASSERT_TRUE(res);
  9467. ASSERT_EQ(StatusCode::OK_200, res->status);
  9468. }
  9469. {
  9470. auto res = cli.Post("/post-both", {}, items, providers);
  9471. ASSERT_TRUE(res);
  9472. ASSERT_EQ(StatusCode::OK_200, res->status);
  9473. }
  9474. }
  9475. }
  9476. TEST(MultipartFormDataTest, BadHeader) {
  9477. Server svr;
  9478. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9479. res.set_content("ok", "text/plain");
  9480. });
  9481. thread t = thread([&] { svr.listen(HOST, PORT); });
  9482. auto se = detail::scope_exit([&] {
  9483. svr.stop();
  9484. t.join();
  9485. ASSERT_FALSE(svr.is_running());
  9486. });
  9487. svr.wait_until_ready();
  9488. const std::string body =
  9489. "This is the preamble. It is to be ignored, though it\r\n"
  9490. "is a handy place for composition agents to include an\r\n"
  9491. "explanatory note to non-MIME conformant readers.\r\n"
  9492. "\r\n"
  9493. "\r\n"
  9494. "--simple boundary\r\n"
  9495. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9496. ": BAD...\r\n"
  9497. "\r\n"
  9498. "value1\r\n"
  9499. "--simple boundary\r\n"
  9500. "Content-Disposition: form-data; name=\"field2\"; "
  9501. "filename=\"example.txt\"\r\n"
  9502. "\r\n"
  9503. "value2\r\n"
  9504. "--simple boundary--\r\n"
  9505. "This is the epilogue. It is also to be ignored.\r\n";
  9506. std::string content_type =
  9507. R"(multipart/form-data; boundary="simple boundary")";
  9508. Client cli(HOST, PORT);
  9509. auto res = cli.Post("/post", body, content_type.c_str());
  9510. ASSERT_TRUE(res);
  9511. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9512. }
  9513. TEST(MultipartFormDataTest, WithPreamble) {
  9514. Server svr;
  9515. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9516. res.set_content("ok", "text/plain");
  9517. });
  9518. thread t = thread([&] { svr.listen(HOST, PORT); });
  9519. auto se = detail::scope_exit([&] {
  9520. svr.stop();
  9521. t.join();
  9522. ASSERT_FALSE(svr.is_running());
  9523. });
  9524. svr.wait_until_ready();
  9525. const std::string body =
  9526. "This is the preamble. It is to be ignored, though it\r\n"
  9527. "is a handy place for composition agents to include an\r\n"
  9528. "explanatory note to non-MIME conformant readers.\r\n"
  9529. "\r\n"
  9530. "\r\n"
  9531. "--simple boundary\r\n"
  9532. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9533. "\r\n"
  9534. "value1\r\n"
  9535. "--simple boundary\r\n"
  9536. "Content-Disposition: form-data; name=\"field2\"; "
  9537. "filename=\"example.txt\"\r\n"
  9538. "\r\n"
  9539. "value2\r\n"
  9540. "--simple boundary--\r\n"
  9541. "This is the epilogue. It is also to be ignored.\r\n";
  9542. std::string content_type =
  9543. R"(multipart/form-data; boundary="simple boundary")";
  9544. Client cli(HOST, PORT);
  9545. auto res = cli.Post("/post", body, content_type.c_str());
  9546. ASSERT_TRUE(res);
  9547. EXPECT_EQ(StatusCode::OK_200, res->status);
  9548. }
  9549. TEST(MultipartFormDataTest, PostCustomBoundary) {
  9550. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9551. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  9552. const ContentReader &content_reader) {
  9553. if (req.is_multipart_form_data()) {
  9554. std::vector<FormData> items;
  9555. content_reader(
  9556. [&](const FormData &file) {
  9557. items.push_back(file);
  9558. return true;
  9559. },
  9560. [&](const char *data, size_t data_length) {
  9561. items.back().content.append(data, data_length);
  9562. return true;
  9563. });
  9564. EXPECT_TRUE(std::string(items[0].name) == "document");
  9565. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9566. EXPECT_TRUE(items[0].filename == "2MB_data");
  9567. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9568. EXPECT_TRUE(items[1].name == "hello");
  9569. EXPECT_TRUE(items[1].content == "world");
  9570. EXPECT_TRUE(items[1].filename == "");
  9571. EXPECT_TRUE(items[1].content_type == "");
  9572. } else {
  9573. std::string body;
  9574. content_reader([&](const char *data, size_t data_length) {
  9575. body.append(data, data_length);
  9576. return true;
  9577. });
  9578. }
  9579. });
  9580. auto port = svr.bind_to_any_port("localhost");
  9581. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9582. auto se = detail::scope_exit([&] {
  9583. svr.stop();
  9584. t.join();
  9585. ASSERT_FALSE(svr.is_running());
  9586. });
  9587. svr.wait_until_ready();
  9588. {
  9589. std::string data(1024 * 1024 * 2, '.');
  9590. std::stringstream buffer;
  9591. buffer << data;
  9592. SSLClient cli("localhost", port);
  9593. cli.enable_server_certificate_verification(false);
  9594. UploadFormDataItems items{
  9595. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9596. {"hello", "world", "", ""},
  9597. };
  9598. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9599. ASSERT_TRUE(res);
  9600. ASSERT_EQ(StatusCode::OK_200, res->status);
  9601. }
  9602. }
  9603. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9604. std::string data(1024 * 1024 * 2, '&');
  9605. std::stringstream buffer;
  9606. buffer << data;
  9607. Client cli("https://localhost:8080");
  9608. UploadFormDataItems items{
  9609. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9610. {"hello", "world", "", ""},
  9611. };
  9612. for (const char &c : " \t\r\n") {
  9613. auto res =
  9614. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9615. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9616. ASSERT_FALSE(res);
  9617. }
  9618. }
  9619. TEST(MultipartFormDataTest, PutFormData) {
  9620. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9621. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9622. const ContentReader &content_reader) {
  9623. if (req.is_multipart_form_data()) {
  9624. std::vector<FormData> items;
  9625. content_reader(
  9626. [&](const FormData &file) {
  9627. items.push_back(file);
  9628. return true;
  9629. },
  9630. [&](const char *data, size_t data_length) {
  9631. items.back().content.append(data, data_length);
  9632. return true;
  9633. });
  9634. EXPECT_TRUE(std::string(items[0].name) == "document");
  9635. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9636. EXPECT_TRUE(items[0].filename == "2MB_data");
  9637. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9638. EXPECT_TRUE(items[1].name == "hello");
  9639. EXPECT_TRUE(items[1].content == "world");
  9640. EXPECT_TRUE(items[1].filename == "");
  9641. EXPECT_TRUE(items[1].content_type == "");
  9642. } else {
  9643. std::string body;
  9644. content_reader([&](const char *data, size_t data_length) {
  9645. body.append(data, data_length);
  9646. return true;
  9647. });
  9648. }
  9649. });
  9650. auto port = svr.bind_to_any_port("localhost");
  9651. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9652. auto se = detail::scope_exit([&] {
  9653. svr.stop();
  9654. t.join();
  9655. ASSERT_FALSE(svr.is_running());
  9656. });
  9657. svr.wait_until_ready();
  9658. {
  9659. std::string data(1024 * 1024 * 2, '&');
  9660. std::stringstream buffer;
  9661. buffer << data;
  9662. SSLClient cli("localhost", port);
  9663. cli.enable_server_certificate_verification(false);
  9664. UploadFormDataItems items{
  9665. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9666. {"hello", "world", "", ""},
  9667. };
  9668. auto res = cli.Put("/put", items);
  9669. ASSERT_TRUE(res);
  9670. ASSERT_EQ(StatusCode::OK_200, res->status);
  9671. }
  9672. }
  9673. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  9674. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9675. svr.Put("/put_customboundary",
  9676. [&](const Request &req, const Response & /*res*/,
  9677. const ContentReader &content_reader) {
  9678. if (req.is_multipart_form_data()) {
  9679. std::vector<FormData> items;
  9680. content_reader(
  9681. [&](const FormData &file) {
  9682. items.push_back(file);
  9683. return true;
  9684. },
  9685. [&](const char *data, size_t data_length) {
  9686. items.back().content.append(data, data_length);
  9687. return true;
  9688. });
  9689. EXPECT_TRUE(std::string(items[0].name) == "document");
  9690. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9691. EXPECT_TRUE(items[0].filename == "2MB_data");
  9692. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9693. EXPECT_TRUE(items[1].name == "hello");
  9694. EXPECT_TRUE(items[1].content == "world");
  9695. EXPECT_TRUE(items[1].filename == "");
  9696. EXPECT_TRUE(items[1].content_type == "");
  9697. } else {
  9698. std::string body;
  9699. content_reader([&](const char *data, size_t data_length) {
  9700. body.append(data, data_length);
  9701. return true;
  9702. });
  9703. }
  9704. });
  9705. auto port = svr.bind_to_any_port("localhost");
  9706. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9707. auto se = detail::scope_exit([&] {
  9708. svr.stop();
  9709. t.join();
  9710. ASSERT_FALSE(svr.is_running());
  9711. });
  9712. svr.wait_until_ready();
  9713. {
  9714. std::string data(1024 * 1024 * 2, '&');
  9715. std::stringstream buffer;
  9716. buffer << data;
  9717. SSLClient cli("localhost", port);
  9718. cli.enable_server_certificate_verification(false);
  9719. UploadFormDataItems items{
  9720. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9721. {"hello", "world", "", ""},
  9722. };
  9723. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  9724. ASSERT_TRUE(res);
  9725. ASSERT_EQ(StatusCode::OK_200, res->status);
  9726. }
  9727. }
  9728. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  9729. std::string data(1024 * 1024 * 2, '&');
  9730. std::stringstream buffer;
  9731. buffer << data;
  9732. Client cli("https://localhost:8080");
  9733. cli.enable_server_certificate_verification(false);
  9734. UploadFormDataItems items{
  9735. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9736. {"hello", "world", "", ""},
  9737. };
  9738. for (const char &c : " \t\r\n") {
  9739. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  9740. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9741. ASSERT_FALSE(res);
  9742. }
  9743. }
  9744. TEST(MultipartFormDataTest, AlternateFilename) {
  9745. auto handled = false;
  9746. Server svr;
  9747. svr.Post("/test", [&](const Request &req, Response &res) {
  9748. ASSERT_EQ(2u, req.form.files.size());
  9749. ASSERT_EQ(1u, req.form.fields.size());
  9750. // Test files
  9751. const auto &file1 = req.form.get_file("file1");
  9752. ASSERT_EQ("file1", file1.name);
  9753. ASSERT_EQ("A.txt", file1.filename);
  9754. ASSERT_EQ("text/plain", file1.content_type);
  9755. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  9756. const auto &file2 = req.form.get_file("file2");
  9757. ASSERT_EQ("file2", file2.name);
  9758. ASSERT_EQ("a.html", file2.filename);
  9759. ASSERT_EQ("text/html", file2.content_type);
  9760. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  9761. file2.content);
  9762. // Test text field
  9763. const auto &text = req.form.get_field("text");
  9764. ASSERT_EQ("text default", text);
  9765. res.set_content("ok", "text/plain");
  9766. handled = true;
  9767. });
  9768. thread t = thread([&] { svr.listen(HOST, PORT); });
  9769. auto se = detail::scope_exit([&] {
  9770. svr.stop();
  9771. t.join();
  9772. ASSERT_FALSE(svr.is_running());
  9773. ASSERT_TRUE(handled);
  9774. });
  9775. svr.wait_until_ready();
  9776. auto req = "POST /test HTTP/1.1\r\n"
  9777. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9778. "Content-Length: 399\r\n"
  9779. "\r\n"
  9780. "----------\r\n"
  9781. "Content-Disposition: form-data; name=\"text\"\r\n"
  9782. "\r\n"
  9783. "text default\r\n"
  9784. "----------\r\n"
  9785. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  9786. "filename=\"a.txt\"; name=\"file1\"\r\n"
  9787. "Content-Type: text/plain\r\n"
  9788. "\r\n"
  9789. "Content of a.txt.\r\n"
  9790. "\r\n"
  9791. "----------\r\n"
  9792. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  9793. "\"a.html\"\r\n"
  9794. "Content-Type: text/html\r\n"
  9795. "\r\n"
  9796. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  9797. "\r\n"
  9798. "------------\r\n";
  9799. ASSERT_TRUE(send_request(1, req));
  9800. }
  9801. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  9802. auto handled = false;
  9803. Server svr;
  9804. svr.Post("/test", [&](const Request &req, Response &res) {
  9805. // Case-insensitive "utf-8''" prefix with a long value
  9806. const auto &file = req.form.get_file("file1");
  9807. ASSERT_EQ("file1", file.name);
  9808. // 8000 chars exercises both the Content-Disposition parser and the
  9809. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  9810. // Prior to the fix, std::regex_match on this header would cause O(N)
  9811. // stack recursion in libstdc++, leading to SIGSEGV.
  9812. std::string expected_filename(8000, 'A');
  9813. ASSERT_EQ(expected_filename, file.filename);
  9814. res.set_content("ok", "text/plain");
  9815. handled = true;
  9816. });
  9817. thread t = thread([&] { svr.listen(HOST, PORT); });
  9818. auto se = detail::scope_exit([&] {
  9819. svr.stop();
  9820. t.join();
  9821. ASSERT_FALSE(svr.is_running());
  9822. ASSERT_TRUE(handled);
  9823. });
  9824. svr.wait_until_ready();
  9825. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  9826. // Regression test for GHSA-qq6v-r583-3h69
  9827. std::string long_filename(8000, 'A');
  9828. std::string body = "----------\r\n"
  9829. "Content-Disposition: form-data; name=\"file1\"; "
  9830. "filename*=\"Utf-8''" +
  9831. long_filename +
  9832. "\"\r\n"
  9833. "\r\n"
  9834. "hello\r\n"
  9835. "------------\r\n";
  9836. auto req = "POST /test HTTP/1.1\r\n"
  9837. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9838. "Content-Length: " +
  9839. std::to_string(body.size()) + "\r\n\r\n" + body;
  9840. ASSERT_TRUE(send_request(1, req));
  9841. }
  9842. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  9843. auto handled = false;
  9844. Server svr;
  9845. svr.Post("/test", [&](const Request &req, Response &) {
  9846. ASSERT_EQ(2u, req.form.fields.size());
  9847. const auto &text1 = req.form.get_field("text1");
  9848. ASSERT_EQ("text1", text1);
  9849. const auto &text2 = req.form.get_field("text2");
  9850. ASSERT_EQ("text2", text2);
  9851. handled = true;
  9852. });
  9853. thread t = thread([&] { svr.listen(HOST, PORT); });
  9854. auto se = detail::scope_exit([&] {
  9855. svr.stop();
  9856. t.join();
  9857. ASSERT_FALSE(svr.is_running());
  9858. ASSERT_TRUE(handled);
  9859. });
  9860. svr.wait_until_ready();
  9861. auto req = "POST /test HTTP/1.1\r\n"
  9862. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9863. "Content-Length: 146\r\n"
  9864. "\r\n----------\r\n"
  9865. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9866. "\r\n"
  9867. "text1"
  9868. "\r\n----------\r\n"
  9869. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9870. "\r\n"
  9871. "text2"
  9872. "\r\n------------";
  9873. std::string response;
  9874. ASSERT_TRUE(send_request(1, req, &response));
  9875. ASSERT_EQ("200", response.substr(9, 3));
  9876. }
  9877. TEST(MultipartFormDataTest, ContentLength) {
  9878. auto handled = false;
  9879. Server svr;
  9880. svr.Post("/test", [&](const Request &req, Response &) {
  9881. ASSERT_EQ(2u, req.form.fields.size());
  9882. const auto &text1 = req.form.get_field("text1");
  9883. ASSERT_EQ("text1", text1);
  9884. const auto &text2 = req.form.get_field("text2");
  9885. ASSERT_EQ("text2", text2);
  9886. handled = true;
  9887. });
  9888. thread t = thread([&] { svr.listen(HOST, PORT); });
  9889. auto se = detail::scope_exit([&] {
  9890. svr.stop();
  9891. t.join();
  9892. ASSERT_FALSE(svr.is_running());
  9893. ASSERT_TRUE(handled);
  9894. });
  9895. svr.wait_until_ready();
  9896. auto req = "POST /test HTTP/1.1\r\n"
  9897. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9898. "Content-Length: 167\r\n"
  9899. "\r\n----------\r\n"
  9900. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9901. "Content-Length: 5\r\n"
  9902. "\r\n"
  9903. "text1"
  9904. "\r\n----------\r\n"
  9905. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9906. "\r\n"
  9907. "text2"
  9908. "\r\n------------\r\n";
  9909. std::string response;
  9910. ASSERT_TRUE(send_request(1, req, &response));
  9911. ASSERT_EQ("200", response.substr(9, 3));
  9912. }
  9913. TEST(MultipartFormDataTest, AccessPartHeaders) {
  9914. auto handled = false;
  9915. Server svr;
  9916. svr.Post("/test", [&](const Request &req, Response &) {
  9917. ASSERT_EQ(2u, req.form.fields.size());
  9918. const auto &text1 = req.form.get_field("text1");
  9919. ASSERT_EQ("text1", text1);
  9920. // TODO: Add header access for text fields if needed
  9921. const auto &text2 = req.form.get_field("text2");
  9922. ASSERT_EQ("text2", text2);
  9923. // TODO: Header access for text fields needs to be implemented
  9924. // auto &headers = it->second.headers;
  9925. // ASSERT_EQ(3U, headers.size());
  9926. // auto custom_header = headers.find("x-whatever");
  9927. // ASSERT_TRUE(custom_header != headers.end());
  9928. // ASSERT_NE("customvalue", custom_header->second);
  9929. // ASSERT_EQ("CustomValue", custom_header->second);
  9930. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  9931. handled = true;
  9932. });
  9933. thread t = thread([&] { svr.listen(HOST, PORT); });
  9934. auto se = detail::scope_exit([&] {
  9935. svr.stop();
  9936. t.join();
  9937. ASSERT_FALSE(svr.is_running());
  9938. ASSERT_TRUE(handled);
  9939. });
  9940. svr.wait_until_ready();
  9941. auto req = "POST /test HTTP/1.1\r\n"
  9942. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9943. "Content-Length: 232\r\n"
  9944. "\r\n----------\r\n"
  9945. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9946. "Content-Length: 5\r\n"
  9947. "X-Test: 1\r\n"
  9948. "\r\n"
  9949. "text1"
  9950. "\r\n----------\r\n"
  9951. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9952. "Content-Type: text/plain\r\n"
  9953. "X-Whatever: CustomValue\r\n"
  9954. "\r\n"
  9955. "text2"
  9956. "\r\n------------\r\n"
  9957. "That should be disregarded. Not even read";
  9958. std::string response;
  9959. ASSERT_TRUE(send_request(1, req, &response));
  9960. ASSERT_EQ("200", response.substr(9, 3));
  9961. }
  9962. TEST(MultipartFormDataTest, LargeHeader) {
  9963. auto handled = false;
  9964. Server svr;
  9965. svr.Post("/test", [&](const Request &req, Response &) {
  9966. ASSERT_EQ(1u, req.form.fields.size());
  9967. const auto &text = req.form.get_field("name1");
  9968. ASSERT_EQ("text1", text);
  9969. handled = true;
  9970. });
  9971. thread t = thread([&] { svr.listen(HOST, PORT); });
  9972. auto se = detail::scope_exit([&] {
  9973. svr.stop();
  9974. t.join();
  9975. ASSERT_FALSE(svr.is_running());
  9976. ASSERT_TRUE(handled);
  9977. });
  9978. svr.wait_until_ready();
  9979. auto boundary = std::string("cpp-httplib-multipart-data");
  9980. std::string content = "--" + boundary +
  9981. "\r\n"
  9982. "Content-Disposition: form-data; name=\"name1\"\r\n"
  9983. "\r\n"
  9984. "text1\r\n"
  9985. "--" +
  9986. boundary + "--\r\n";
  9987. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  9988. "Content-Type: multipart/form-data;boundary=" +
  9989. boundary +
  9990. "\r\n"
  9991. "Content-Length: " +
  9992. std::to_string(content.size()) +
  9993. "\r\n"
  9994. "Dummy-Header: ";
  9995. std::string header_suffix = "\r\n"
  9996. "\r\n";
  9997. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  9998. size_t header_dummy_size =
  9999. read_buff_size -
  10000. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  10001. auto header_dummy = std::string(header_dummy_size, '@');
  10002. auto req = header_prefix + header_dummy + header_suffix + content;
  10003. std::string response;
  10004. ASSERT_TRUE(send_request(1, req, &response));
  10005. ASSERT_EQ("200", response.substr(9, 3));
  10006. }
  10007. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  10008. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  10009. // (not chunked Transfer-Encoding) after the streaming refactor.
  10010. auto handled = false;
  10011. Server svr;
  10012. svr.Post("/upload", [&](const Request &req, Response &res) {
  10013. auto cl_it = req.headers.find("Content-Length");
  10014. EXPECT_TRUE(cl_it != req.headers.end());
  10015. auto te_it = req.headers.find("Transfer-Encoding");
  10016. EXPECT_TRUE(te_it == req.headers.end());
  10017. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  10018. res.set_content("ok", "text/plain");
  10019. handled = true;
  10020. });
  10021. auto port = svr.bind_to_any_port(HOST);
  10022. auto t = thread([&] { svr.listen_after_bind(); });
  10023. auto se = detail::scope_exit([&] {
  10024. svr.stop();
  10025. t.join();
  10026. ASSERT_FALSE(svr.is_running());
  10027. ASSERT_TRUE(handled);
  10028. });
  10029. svr.wait_until_ready();
  10030. UploadFormDataItems items = {
  10031. {"field1", "hello", "", "text/plain"},
  10032. {"file1", "world", "test.txt", "application/octet-stream"},
  10033. };
  10034. Client cli(HOST, port);
  10035. auto res = cli.Post("/upload", {}, items);
  10036. ASSERT_TRUE(res);
  10037. EXPECT_EQ(StatusCode::OK_200, res->status);
  10038. }
  10039. TEST(MultipartFormDataTest, MakeFileProvider) {
  10040. // Verify make_file_provider sends a file's contents correctly.
  10041. const std::string file_content(4096, 'Z');
  10042. const std::string tmp_path = "/tmp/httplib_test_make_file_provider.bin";
  10043. {
  10044. std::ofstream ofs(tmp_path, std::ios::binary);
  10045. ofs.write(file_content.data(),
  10046. static_cast<std::streamsize>(file_content.size()));
  10047. }
  10048. auto handled = false;
  10049. Server svr;
  10050. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  10051. const ContentReader &content_reader) {
  10052. ASSERT_TRUE(req.is_multipart_form_data());
  10053. std::vector<FormData> items;
  10054. content_reader(
  10055. [&](const FormData &file) {
  10056. items.push_back(file);
  10057. return true;
  10058. },
  10059. [&](const char *data, size_t data_length) {
  10060. items.back().content.append(data, data_length);
  10061. return true;
  10062. });
  10063. ASSERT_EQ(1u, items.size());
  10064. EXPECT_EQ("myfile", items[0].name);
  10065. EXPECT_EQ("data.bin", items[0].filename);
  10066. EXPECT_EQ("application/octet-stream", items[0].content_type);
  10067. EXPECT_EQ(file_content, items[0].content);
  10068. handled = true;
  10069. });
  10070. auto port = svr.bind_to_any_port(HOST);
  10071. auto t = thread([&] { svr.listen_after_bind(); });
  10072. auto se = detail::scope_exit([&] {
  10073. svr.stop();
  10074. t.join();
  10075. ASSERT_FALSE(svr.is_running());
  10076. ASSERT_TRUE(handled);
  10077. std::remove(tmp_path.c_str());
  10078. });
  10079. svr.wait_until_ready();
  10080. FormDataProviderItems providers;
  10081. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  10082. "application/octet-stream"));
  10083. Client cli(HOST, port);
  10084. auto res = cli.Post("/upload", {}, {}, providers);
  10085. ASSERT_TRUE(res);
  10086. EXPECT_EQ(StatusCode::OK_200, res->status);
  10087. }
  10088. TEST(MakeFileBodyTest, Basic) {
  10089. const std::string file_content(4096, 'Z');
  10090. const std::string tmp_path = "/tmp/httplib_test_make_file_body.bin";
  10091. {
  10092. std::ofstream ofs(tmp_path, std::ios::binary);
  10093. ofs.write(file_content.data(),
  10094. static_cast<std::streamsize>(file_content.size()));
  10095. }
  10096. auto handled = false;
  10097. Server svr;
  10098. svr.Post("/upload", [&](const Request &req, Response &res) {
  10099. EXPECT_EQ(file_content, req.body);
  10100. handled = true;
  10101. res.status = StatusCode::OK_200;
  10102. });
  10103. auto port = svr.bind_to_any_port(HOST);
  10104. auto t = thread([&] { svr.listen_after_bind(); });
  10105. auto se = detail::scope_exit([&] {
  10106. svr.stop();
  10107. t.join();
  10108. ASSERT_FALSE(svr.is_running());
  10109. ASSERT_TRUE(handled);
  10110. std::remove(tmp_path.c_str());
  10111. });
  10112. svr.wait_until_ready();
  10113. auto fb = make_file_body(tmp_path);
  10114. ASSERT_GT(fb.first, 0u);
  10115. Client cli(HOST, port);
  10116. auto res =
  10117. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  10118. ASSERT_TRUE(res);
  10119. EXPECT_EQ(StatusCode::OK_200, res->status);
  10120. }
  10121. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  10122. static constexpr unsigned int number_of_tasks{1000000};
  10123. std::atomic_uint count{0};
  10124. std::unique_ptr<TaskQueue> task_queue{
  10125. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  10126. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10127. auto queued = task_queue->enqueue(
  10128. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  10129. EXPECT_TRUE(queued);
  10130. }
  10131. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10132. task_queue->shutdown();
  10133. #else
  10134. EXPECT_NO_THROW(task_queue->shutdown());
  10135. #endif
  10136. EXPECT_EQ(number_of_tasks, count.load());
  10137. }
  10138. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  10139. static constexpr unsigned int number_of_tasks{1000000};
  10140. static constexpr unsigned int qlimit{2};
  10141. unsigned int queued_count{0};
  10142. std::atomic_uint count{0};
  10143. std::unique_ptr<TaskQueue> task_queue{
  10144. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  10145. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10146. if (task_queue->enqueue(
  10147. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  10148. queued_count++;
  10149. }
  10150. }
  10151. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10152. task_queue->shutdown();
  10153. #else
  10154. EXPECT_NO_THROW(task_queue->shutdown());
  10155. #endif
  10156. EXPECT_EQ(queued_count, count.load());
  10157. EXPECT_TRUE(queued_count <= number_of_tasks);
  10158. EXPECT_TRUE(queued_count >= qlimit);
  10159. }
  10160. TEST(TaskQueueTest, MaxQueuedRequests) {
  10161. static constexpr unsigned int qlimit{3};
  10162. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  10163. std::condition_variable sem_cv;
  10164. std::mutex sem_mtx;
  10165. int credits = 0;
  10166. bool queued;
  10167. /* Fill up the queue with tasks that will block until we give them credits to
  10168. * complete. */
  10169. for (unsigned int n = 0; n <= qlimit;) {
  10170. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  10171. std::unique_lock<std::mutex> lock(sem_mtx);
  10172. while (credits <= 0) {
  10173. sem_cv.wait(lock);
  10174. }
  10175. /* Consume the credit and signal the test code if they are all gone. */
  10176. if (--credits == 0) { sem_cv.notify_one(); }
  10177. });
  10178. if (n < qlimit) {
  10179. /* The first qlimit enqueues must succeed. */
  10180. EXPECT_TRUE(queued);
  10181. } else {
  10182. /* The last one will succeed only when the worker thread
  10183. * starts and dequeues the first blocking task. Although
  10184. * not necessary for the correctness of this test, we sleep for
  10185. * a short while to avoid busy waiting. */
  10186. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10187. }
  10188. if (queued) { n++; }
  10189. }
  10190. /* Further enqueues must fail since the queue is full. */
  10191. for (auto i = 0; i < 4; i++) {
  10192. queued = task_queue->enqueue([] {});
  10193. EXPECT_FALSE(queued);
  10194. }
  10195. /* Give the credits to allow the previous tasks to complete. */
  10196. {
  10197. std::unique_lock<std::mutex> lock(sem_mtx);
  10198. credits += qlimit + 1;
  10199. }
  10200. sem_cv.notify_all();
  10201. /* Wait for all the credits to be consumed. */
  10202. {
  10203. std::unique_lock<std::mutex> lock(sem_mtx);
  10204. while (credits > 0) {
  10205. sem_cv.wait(lock);
  10206. }
  10207. }
  10208. /* Check that we are able again to enqueue at least qlimit tasks. */
  10209. for (unsigned int i = 0; i < qlimit; i++) {
  10210. queued = task_queue->enqueue([] {});
  10211. EXPECT_TRUE(queued);
  10212. }
  10213. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10214. task_queue->shutdown();
  10215. #else
  10216. EXPECT_NO_THROW(task_queue->shutdown());
  10217. #endif
  10218. }
  10219. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  10220. Server svr;
  10221. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10222. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  10223. });
  10224. svr.Get("/hello", [](const Request &req, Response &res) {
  10225. res.set_content(req.get_param_value("key"), "text/plain");
  10226. });
  10227. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10228. auto se = detail::scope_exit([&] {
  10229. svr.stop();
  10230. thread.join();
  10231. ASSERT_FALSE(svr.is_running());
  10232. });
  10233. svr.wait_until_ready();
  10234. {
  10235. Client cli(HOST, PORT);
  10236. cli.set_follow_location(true);
  10237. auto res = cli.Get("/");
  10238. ASSERT_TRUE(res);
  10239. EXPECT_EQ(StatusCode::OK_200, res->status);
  10240. EXPECT_EQ("val&key2=val2", res->body);
  10241. }
  10242. }
  10243. #endif
  10244. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  10245. Server svr;
  10246. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10247. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  10248. });
  10249. svr.Get("/hello", [](const Request &req, Response &res) {
  10250. res.set_content(req.get_param_value("key"), "text/plain");
  10251. });
  10252. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10253. auto se = detail::scope_exit([&] {
  10254. svr.stop();
  10255. thread.join();
  10256. ASSERT_FALSE(svr.is_running());
  10257. });
  10258. svr.wait_until_ready();
  10259. {
  10260. Client cli(HOST, PORT);
  10261. cli.set_follow_location(true);
  10262. auto res = cli.Get("/");
  10263. ASSERT_TRUE(res);
  10264. EXPECT_EQ(StatusCode::OK_200, res->status);
  10265. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  10266. }
  10267. }
  10268. #ifdef CPPHTTPLIB_SSL_ENABLED
  10269. TEST(RedirectTest, Issue2185_Online) {
  10270. SSLClient client("github.com");
  10271. client.set_follow_location(true);
  10272. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  10273. "Coollab-Windows.zip");
  10274. ASSERT_TRUE(res);
  10275. EXPECT_EQ(StatusCode::OK_200, res->status);
  10276. EXPECT_EQ(9920427U, res->body.size());
  10277. }
  10278. #endif
  10279. TEST(VulnerabilityTest, CRLFInjection) {
  10280. Server svr;
  10281. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  10282. res.set_content("Hello 1", "text/plain");
  10283. });
  10284. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  10285. res.set_content("Hello 2", "text/plain");
  10286. });
  10287. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  10288. res.set_content("Hello 3", "text/plain");
  10289. });
  10290. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  10291. res.set_content("Hello 4", "text/plain");
  10292. });
  10293. svr.set_logger([](const Request &req, const Response & /*res*/) {
  10294. for (const auto &x : req.headers) {
  10295. auto key = x.first;
  10296. EXPECT_STRNE("evil", key.c_str());
  10297. }
  10298. });
  10299. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10300. auto se = detail::scope_exit([&] {
  10301. svr.stop();
  10302. thread.join();
  10303. ASSERT_FALSE(svr.is_running());
  10304. });
  10305. svr.wait_until_ready();
  10306. {
  10307. Client cli(HOST, PORT);
  10308. cli.Post("/test1", "A=B",
  10309. "application/x-www-form-urlencoded\r\nevil: hello1");
  10310. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  10311. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  10312. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  10313. }
  10314. }
  10315. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  10316. auto server_thread = std::thread([] {
  10317. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10318. default_socket_options(srv);
  10319. sockaddr_in addr{};
  10320. addr.sin_family = AF_INET;
  10321. addr.sin_port = htons(PORT + 1);
  10322. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10323. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10324. ::listen(srv, 1);
  10325. sockaddr_in cli_addr{};
  10326. socklen_t cli_len = sizeof(cli_addr);
  10327. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10328. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  10329. std::string buf_all;
  10330. char buf[2048];
  10331. ssize_t n;
  10332. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  10333. buf_all.append(buf, static_cast<size_t>(n));
  10334. size_t pos;
  10335. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  10336. auto request_block = buf_all.substr(0, pos + 4); // include separator
  10337. auto e = request_block.find("\r\n");
  10338. if (e != std::string::npos) {
  10339. auto request_line = request_block.substr(0, e);
  10340. std::string msg =
  10341. "CRLF injection detected in request line: '" + request_line + "'";
  10342. EXPECT_FALSE(true) << msg;
  10343. }
  10344. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  10345. ::send(cli,
  10346. #ifdef _WIN32
  10347. static_cast<const char *>(resp.c_str()),
  10348. static_cast<int>(resp.size()),
  10349. #else
  10350. resp.c_str(), resp.size(),
  10351. #endif
  10352. 0);
  10353. buf_all.erase(0, pos + 4);
  10354. }
  10355. }
  10356. detail::close_socket(cli);
  10357. detail::close_socket(srv);
  10358. });
  10359. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10360. auto cli = Client("127.0.0.1", PORT + 1);
  10361. auto headers = Headers{
  10362. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  10363. {"Connection", "keep-alive"}};
  10364. auto res = cli.Get("/hi", headers);
  10365. EXPECT_FALSE(res);
  10366. EXPECT_EQ(Error::InvalidHeaders, res.error());
  10367. server_thread.join();
  10368. }
  10369. TEST(PathParamsTest, StaticMatch) {
  10370. const auto pattern = "/users/all";
  10371. detail::PathParamsMatcher matcher(pattern);
  10372. Request request;
  10373. request.path = "/users/all";
  10374. ASSERT_TRUE(matcher.match(request));
  10375. std::unordered_map<std::string, std::string> expected_params = {};
  10376. EXPECT_EQ(request.path_params, expected_params);
  10377. }
  10378. TEST(PathParamsTest, StaticMismatch) {
  10379. const auto pattern = "/users/all";
  10380. detail::PathParamsMatcher matcher(pattern);
  10381. Request request;
  10382. request.path = "/users/1";
  10383. ASSERT_FALSE(matcher.match(request));
  10384. }
  10385. TEST(PathParamsTest, SingleParamInTheMiddle) {
  10386. const auto pattern = "/users/:id/subscriptions";
  10387. detail::PathParamsMatcher matcher(pattern);
  10388. Request request;
  10389. request.path = "/users/42/subscriptions";
  10390. ASSERT_TRUE(matcher.match(request));
  10391. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10392. EXPECT_EQ(request.path_params, expected_params);
  10393. }
  10394. TEST(PathParamsTest, SingleParamInTheEnd) {
  10395. const auto pattern = "/users/:id";
  10396. detail::PathParamsMatcher matcher(pattern);
  10397. Request request;
  10398. request.path = "/users/24";
  10399. ASSERT_TRUE(matcher.match(request));
  10400. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  10401. EXPECT_EQ(request.path_params, expected_params);
  10402. }
  10403. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  10404. const auto pattern = "/users/:id/";
  10405. detail::PathParamsMatcher matcher(pattern);
  10406. Request request;
  10407. request.path = "/users/42/";
  10408. ASSERT_TRUE(matcher.match(request));
  10409. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10410. EXPECT_EQ(request.path_params, expected_params);
  10411. }
  10412. TEST(PathParamsTest, EmptyParam) {
  10413. const auto pattern = "/users/:id/";
  10414. detail::PathParamsMatcher matcher(pattern);
  10415. Request request;
  10416. request.path = "/users//";
  10417. ASSERT_TRUE(matcher.match(request));
  10418. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10419. EXPECT_EQ(request.path_params, expected_params);
  10420. }
  10421. TEST(PathParamsTest, FragmentMismatch) {
  10422. const auto pattern = "/users/:id/";
  10423. detail::PathParamsMatcher matcher(pattern);
  10424. Request request;
  10425. request.path = "/admins/24/";
  10426. ASSERT_FALSE(matcher.match(request));
  10427. }
  10428. TEST(PathParamsTest, ExtraFragments) {
  10429. const auto pattern = "/users/:id";
  10430. detail::PathParamsMatcher matcher(pattern);
  10431. Request request;
  10432. request.path = "/users/42/subscriptions";
  10433. ASSERT_FALSE(matcher.match(request));
  10434. }
  10435. TEST(PathParamsTest, MissingTrailingParam) {
  10436. const auto pattern = "/users/:id";
  10437. detail::PathParamsMatcher matcher(pattern);
  10438. Request request;
  10439. request.path = "/users";
  10440. ASSERT_FALSE(matcher.match(request));
  10441. }
  10442. TEST(PathParamsTest, MissingParamInTheMiddle) {
  10443. const auto pattern = "/users/:id/subscriptions";
  10444. detail::PathParamsMatcher matcher(pattern);
  10445. Request request;
  10446. request.path = "/users/subscriptions";
  10447. ASSERT_FALSE(matcher.match(request));
  10448. }
  10449. TEST(PathParamsTest, MultipleParams) {
  10450. const auto pattern = "/users/:userid/subscriptions/:subid";
  10451. detail::PathParamsMatcher matcher(pattern);
  10452. Request request;
  10453. request.path = "/users/42/subscriptions/2";
  10454. ASSERT_TRUE(matcher.match(request));
  10455. std::unordered_map<std::string, std::string> expected_params = {
  10456. {"userid", "42"}, {"subid", "2"}};
  10457. EXPECT_EQ(request.path_params, expected_params);
  10458. }
  10459. TEST(PathParamsTest, SequenceOfParams) {
  10460. const auto pattern = "/values/:x/:y/:z";
  10461. detail::PathParamsMatcher matcher(pattern);
  10462. Request request;
  10463. request.path = "/values/1/2/3";
  10464. ASSERT_TRUE(matcher.match(request));
  10465. std::unordered_map<std::string, std::string> expected_params = {
  10466. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  10467. EXPECT_EQ(request.path_params, expected_params);
  10468. }
  10469. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  10470. const auto pattern = "/prefix:suffix";
  10471. detail::PathParamsMatcher matcher(pattern);
  10472. Request request;
  10473. request.path = "/prefix:suffix";
  10474. ASSERT_TRUE(matcher.match(request));
  10475. const std::unordered_map<std::string, std::string> expected_params = {};
  10476. EXPECT_EQ(request.path_params, expected_params);
  10477. }
  10478. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  10479. // If ipv6 regex working, regex match codepath is taken.
  10480. // else port will default to 80 in Client impl
  10481. int clientImplMagicPort = 80;
  10482. int port = 4321;
  10483. // above ports must be different to avoid false negative
  10484. EXPECT_NE(clientImplMagicPort, port);
  10485. std::string ipV6TestURL = "http://[ff06::c3]";
  10486. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  10487. CLIENT_PRIVATE_KEY_FILE);
  10488. EXPECT_EQ(cli.port(), port);
  10489. }
  10490. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  10491. auto file_path = "./www/dir/index.html";
  10492. auto dir_path = "./www/dir";
  10493. detail::FileStat stat_file(file_path);
  10494. EXPECT_TRUE(stat_file.is_file());
  10495. EXPECT_FALSE(stat_file.is_dir());
  10496. detail::FileStat stat_dir(dir_path);
  10497. EXPECT_FALSE(stat_dir.is_file());
  10498. EXPECT_TRUE(stat_dir.is_dir());
  10499. }
  10500. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  10501. // IPv4 with default HTTP port (80)
  10502. EXPECT_EQ("example.com",
  10503. detail::make_host_and_port_string("example.com", 80, false));
  10504. // IPv4 with default HTTPS port (443)
  10505. EXPECT_EQ("example.com",
  10506. detail::make_host_and_port_string("example.com", 443, true));
  10507. // IPv4 with non-default HTTP port
  10508. EXPECT_EQ("example.com:8080",
  10509. detail::make_host_and_port_string("example.com", 8080, false));
  10510. // IPv4 with non-default HTTPS port
  10511. EXPECT_EQ("example.com:8443",
  10512. detail::make_host_and_port_string("example.com", 8443, true));
  10513. // IPv6 with default HTTP port (80)
  10514. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  10515. // IPv6 with default HTTPS port (443)
  10516. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  10517. // IPv6 with non-default HTTP port
  10518. EXPECT_EQ("[::1]:8080",
  10519. detail::make_host_and_port_string("::1", 8080, false));
  10520. // IPv6 with non-default HTTPS port
  10521. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  10522. // IPv6 full address with default port
  10523. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  10524. detail::make_host_and_port_string(
  10525. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  10526. // IPv6 full address with non-default port
  10527. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  10528. detail::make_host_and_port_string(
  10529. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  10530. // IPv6 localhost with non-default port
  10531. EXPECT_EQ("[::1]:3000",
  10532. detail::make_host_and_port_string("::1", 3000, false));
  10533. // IPv6 with zone ID (link-local address) with default port
  10534. EXPECT_EQ("[fe80::1%eth0]",
  10535. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  10536. // IPv6 with zone ID (link-local address) with non-default port
  10537. EXPECT_EQ("[fe80::1%eth0]:8080",
  10538. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  10539. // Edge case: Port 443 with is_ssl=false (should add port)
  10540. EXPECT_EQ("example.com:443",
  10541. detail::make_host_and_port_string("example.com", 443, false));
  10542. // Edge case: Port 80 with is_ssl=true (should add port)
  10543. EXPECT_EQ("example.com:80",
  10544. detail::make_host_and_port_string("example.com", 80, true));
  10545. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  10546. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  10547. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  10548. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  10549. // Security fix: Already bracketed IPv6 should not get double brackets
  10550. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  10551. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  10552. EXPECT_EQ("[::1]:8080",
  10553. detail::make_host_and_port_string("[::1]", 8080, false));
  10554. EXPECT_EQ("[2001:db8::1]:8080",
  10555. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  10556. EXPECT_EQ("[fe80::1%eth0]",
  10557. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  10558. EXPECT_EQ("[fe80::1%eth0]:8080",
  10559. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  10560. // Edge case: Empty host (should return as-is)
  10561. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  10562. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  10563. // This is a known limitation but shouldn't crash
  10564. EXPECT_EQ("[host:name]",
  10565. detail::make_host_and_port_string("host:name", 80, false));
  10566. // Port number edge cases (no validation, but should not crash)
  10567. EXPECT_EQ("example.com:0",
  10568. detail::make_host_and_port_string("example.com", 0, false));
  10569. EXPECT_EQ("example.com:-1",
  10570. detail::make_host_and_port_string("example.com", -1, false));
  10571. EXPECT_EQ("example.com:65535",
  10572. detail::make_host_and_port_string("example.com", 65535, false));
  10573. EXPECT_EQ("example.com:65536",
  10574. detail::make_host_and_port_string("example.com", 65536, false));
  10575. }
  10576. #ifdef CPPHTTPLIB_SSL_ENABLED
  10577. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  10578. httplib::SSLClient cli("roblox.com", 443);
  10579. cli.set_follow_location(true);
  10580. auto res = cli.Get("/");
  10581. ASSERT_TRUE(res);
  10582. EXPECT_EQ(StatusCode::OK_200, res->status);
  10583. }
  10584. #endif
  10585. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  10586. Server svr;
  10587. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10588. EXPECT_EQ(res.status, 400);
  10589. });
  10590. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10591. auto se = detail::scope_exit([&] {
  10592. svr.stop();
  10593. thread.join();
  10594. ASSERT_FALSE(svr.is_running());
  10595. });
  10596. svr.wait_until_ready();
  10597. Client cli(HOST, PORT);
  10598. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  10599. }
  10600. TEST(InvalidHeaderCharsTest, is_field_name) {
  10601. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  10602. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  10603. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  10604. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  10605. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  10606. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  10607. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  10608. EXPECT_FALSE(detail::fields::is_field_name(""));
  10609. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  10610. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  10611. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  10612. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  10613. }
  10614. TEST(InvalidHeaderCharsTest, is_field_value) {
  10615. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  10616. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  10617. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  10618. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  10619. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  10620. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  10621. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  10622. EXPECT_TRUE(detail::fields::is_field_value(""));
  10623. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  10624. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  10625. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  10626. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  10627. EXPECT_TRUE(detail::fields::is_field_value("0"));
  10628. }
  10629. TEST(InvalidHeaderCharsTest, OnServer) {
  10630. Server svr;
  10631. svr.Get("/test_name", [&](const Request &req, Response &res) {
  10632. std::string header = "Not Set";
  10633. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10634. res.set_header(header, "value");
  10635. res.set_content("Page Content Page Content", "text/plain");
  10636. });
  10637. svr.Get("/test_value", [&](const Request &req, Response &res) {
  10638. std::string header = "Not Set";
  10639. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10640. res.set_header("X-Test", header);
  10641. res.set_content("Page Content Page Content", "text/plain");
  10642. });
  10643. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10644. auto se = detail::scope_exit([&] {
  10645. svr.stop();
  10646. thread.join();
  10647. ASSERT_FALSE(svr.is_running());
  10648. });
  10649. svr.wait_until_ready();
  10650. Client cli(HOST, PORT);
  10651. {
  10652. auto res = cli.Get(
  10653. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10654. ASSERT_TRUE(res);
  10655. EXPECT_EQ("Page Content Page Content", res->body);
  10656. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10657. }
  10658. {
  10659. auto res = cli.Get(
  10660. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10661. ASSERT_TRUE(res);
  10662. EXPECT_EQ("Page Content Page Content", res->body);
  10663. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10664. }
  10665. }
  10666. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  10667. auto handled = false;
  10668. Server svr;
  10669. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10670. thread t = thread([&] { svr.listen(HOST, PORT); });
  10671. auto se = detail::scope_exit([&] {
  10672. svr.stop();
  10673. t.join();
  10674. ASSERT_FALSE(svr.is_running());
  10675. ASSERT_FALSE(handled);
  10676. });
  10677. svr.wait_until_ready();
  10678. auto req = "POST /test HTTP/1.1\r\n"
  10679. "Content-Length: x\r\n"
  10680. "\r\n";
  10681. std::string response;
  10682. ASSERT_TRUE(send_request(1, req, &response));
  10683. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10684. response.substr(0, response.find("\r\n")));
  10685. }
  10686. #ifndef _WIN32
  10687. TEST(Expect100ContinueTest, ServerClosesConnection) {
  10688. static constexpr char reject[] = "Unauthorized";
  10689. static constexpr char accept[] = "Upload accepted";
  10690. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  10691. Server svr;
  10692. svr.set_expect_100_continue_handler(
  10693. [](const Request & /*req*/, Response &res) {
  10694. res.status = StatusCode::Unauthorized_401;
  10695. res.set_content(reject, "text/plain");
  10696. return res.status;
  10697. });
  10698. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  10699. res.set_content(accept, "text/plain");
  10700. });
  10701. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10702. auto se = detail::scope_exit([&] {
  10703. svr.stop();
  10704. thread.join();
  10705. ASSERT_FALSE(svr.is_running());
  10706. });
  10707. svr.wait_until_ready();
  10708. {
  10709. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  10710. curl_easy_init(), &curl_easy_cleanup};
  10711. ASSERT_NE(curl, nullptr);
  10712. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  10713. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  10714. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  10715. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  10716. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  10717. &curl_slist_free_all};
  10718. ASSERT_NE(list, nullptr);
  10719. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  10720. struct read_data {
  10721. size_t read_size;
  10722. size_t total_size;
  10723. } data = {0, total_size};
  10724. using read_callback_t =
  10725. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10726. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  10727. void *userdata) -> size_t {
  10728. read_data *data = (read_data *)userdata;
  10729. if (!userdata || data->read_size >= data->total_size) { return 0; }
  10730. std::fill_n(ptr, size * nmemb, 'A');
  10731. data->read_size += size * nmemb;
  10732. return size * nmemb;
  10733. };
  10734. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  10735. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  10736. std::vector<char> buffer;
  10737. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  10738. using write_callback_t =
  10739. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10740. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  10741. void *userdata) -> size_t {
  10742. std::vector<char> *buffer = (std::vector<char> *)userdata;
  10743. buffer->reserve(buffer->size() + size * nmemb + 1);
  10744. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  10745. return size * nmemb;
  10746. };
  10747. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  10748. {
  10749. const auto res = curl_easy_perform(curl.get());
  10750. ASSERT_EQ(res, CURLE_OK);
  10751. }
  10752. {
  10753. auto response_code = long{};
  10754. const auto res =
  10755. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  10756. ASSERT_EQ(res, CURLE_OK);
  10757. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  10758. }
  10759. {
  10760. auto dl = curl_off_t{};
  10761. const auto res =
  10762. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  10763. ASSERT_EQ(res, CURLE_OK);
  10764. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  10765. }
  10766. {
  10767. buffer.push_back('\0');
  10768. ASSERT_STRCASEEQ(buffer.data(), reject);
  10769. }
  10770. }
  10771. }
  10772. #endif
  10773. template <typename S, typename C>
  10774. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  10775. svr.Get("/stream", [&](const Request &, Response &res) {
  10776. auto data = new std::string("01234567890123456789");
  10777. res.set_content_provider(
  10778. data->size(), "text/plain",
  10779. [&, data](size_t offset, size_t length, DataSink &sink) {
  10780. const size_t DATA_CHUNK_SIZE = 4;
  10781. const auto &d = *data;
  10782. std::this_thread::sleep_for(std::chrono::seconds(1));
  10783. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  10784. return true;
  10785. },
  10786. [data](bool success) {
  10787. EXPECT_FALSE(success);
  10788. delete data;
  10789. });
  10790. });
  10791. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  10792. auto i = new size_t(0);
  10793. res.set_content_provider(
  10794. "text/plain",
  10795. [i](size_t, DataSink &sink) {
  10796. if (*i < 5) {
  10797. std::this_thread::sleep_for(std::chrono::seconds(1));
  10798. sink.write("abcd", 4);
  10799. (*i)++;
  10800. } else {
  10801. sink.done();
  10802. }
  10803. return true;
  10804. },
  10805. [i](bool success) {
  10806. EXPECT_FALSE(success);
  10807. delete i;
  10808. });
  10809. });
  10810. svr.Get("/chunked", [&](const Request &, Response &res) {
  10811. auto i = new size_t(0);
  10812. res.set_chunked_content_provider(
  10813. "text/plain",
  10814. [i](size_t, DataSink &sink) {
  10815. if (*i < 5) {
  10816. std::this_thread::sleep_for(std::chrono::seconds(1));
  10817. sink.os << "abcd";
  10818. (*i)++;
  10819. } else {
  10820. sink.done();
  10821. }
  10822. return true;
  10823. },
  10824. [i](bool success) {
  10825. EXPECT_FALSE(success);
  10826. delete i;
  10827. });
  10828. });
  10829. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10830. auto se = detail::scope_exit([&] {
  10831. svr.stop();
  10832. listen_thread.join();
  10833. ASSERT_FALSE(svr.is_running());
  10834. });
  10835. svr.wait_until_ready();
  10836. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  10837. {
  10838. auto start = std::chrono::steady_clock::now();
  10839. auto res = cli.Get("/stream");
  10840. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10841. std::chrono::steady_clock::now() - start)
  10842. .count();
  10843. ASSERT_FALSE(res);
  10844. EXPECT_EQ(Error::Read, res.error());
  10845. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10846. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10847. }
  10848. {
  10849. auto start = std::chrono::steady_clock::now();
  10850. auto res = cli.Get("/stream_without_length");
  10851. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10852. std::chrono::steady_clock::now() - start)
  10853. .count();
  10854. ASSERT_FALSE(res);
  10855. EXPECT_EQ(Error::Read, res.error());
  10856. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10857. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10858. }
  10859. {
  10860. auto start = std::chrono::steady_clock::now();
  10861. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  10862. EXPECT_EQ("abcd", string(data, data_length));
  10863. return true;
  10864. });
  10865. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10866. std::chrono::steady_clock::now() - start)
  10867. .count();
  10868. ASSERT_FALSE(res);
  10869. EXPECT_EQ(Error::Read, res.error());
  10870. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10871. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10872. }
  10873. }
  10874. TEST(MaxTimeoutTest, ContentStream) {
  10875. time_t timeout = 2000;
  10876. time_t threshold = 200;
  10877. Server svr;
  10878. Client cli("localhost", PORT);
  10879. max_timeout_test(svr, cli, timeout, threshold);
  10880. }
  10881. #ifdef CPPHTTPLIB_SSL_ENABLED
  10882. TEST(MaxTimeoutTest, ContentStreamSSL) {
  10883. time_t timeout = 2000;
  10884. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  10885. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10886. SSLClient cli("localhost", PORT);
  10887. cli.enable_server_certificate_verification(false);
  10888. max_timeout_test(svr, cli, timeout, threshold);
  10889. }
  10890. #endif
  10891. class EventDispatcher {
  10892. public:
  10893. EventDispatcher() {}
  10894. bool wait_event(DataSink *sink) {
  10895. unique_lock<mutex> lk(m_);
  10896. int id = id_;
  10897. // Wait with timeout to prevent hanging if client disconnects
  10898. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  10899. [&] { return cid_ == id; })) {
  10900. return false; // Timeout occurred
  10901. }
  10902. sink->write(message_.data(), message_.size());
  10903. return true;
  10904. }
  10905. void send_event(const string &message) {
  10906. lock_guard<mutex> lk(m_);
  10907. cid_ = id_++;
  10908. message_ = message;
  10909. cv_.notify_all();
  10910. }
  10911. private:
  10912. mutex m_;
  10913. condition_variable cv_;
  10914. atomic_int id_{0};
  10915. atomic_int cid_{-1};
  10916. string message_;
  10917. };
  10918. TEST(ClientInThreadTest, Issue2068) {
  10919. EventDispatcher ed;
  10920. Server svr;
  10921. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  10922. res.set_chunked_content_provider("text/event-stream",
  10923. [&](size_t /*offset*/, DataSink &sink) {
  10924. return ed.wait_event(&sink);
  10925. });
  10926. });
  10927. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10928. svr.wait_until_ready();
  10929. thread event_thread([&] {
  10930. int id = 0;
  10931. while (svr.is_running()) {
  10932. this_thread::sleep_for(chrono::milliseconds(500));
  10933. std::stringstream ss;
  10934. ss << "data: " << id << "\n\n";
  10935. ed.send_event(ss.str());
  10936. id++;
  10937. }
  10938. });
  10939. auto se = detail::scope_exit([&] {
  10940. svr.stop();
  10941. listen_thread.join();
  10942. event_thread.join();
  10943. ASSERT_FALSE(svr.is_running());
  10944. });
  10945. {
  10946. auto client = detail::make_unique<Client>(HOST, PORT);
  10947. client->set_read_timeout(std::chrono::minutes(10));
  10948. std::atomic<bool> stop{false};
  10949. std::thread t([&] {
  10950. client->Get("/event1",
  10951. [&](const char *, size_t) -> bool { return !stop; });
  10952. });
  10953. std::this_thread::sleep_for(std::chrono::seconds(2));
  10954. stop = true;
  10955. client->stop();
  10956. t.join();
  10957. // Reset client after thread has finished
  10958. client.reset();
  10959. }
  10960. }
  10961. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  10962. auto handled = false;
  10963. Server svr;
  10964. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10965. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10966. auto se = detail::scope_exit([&] {
  10967. svr.stop();
  10968. t.join();
  10969. ASSERT_FALSE(svr.is_running());
  10970. ASSERT_FALSE(handled);
  10971. });
  10972. svr.wait_until_ready();
  10973. // Two Content-Length headers with different values — must be rejected
  10974. auto req = "POST /test HTTP/1.1\r\n"
  10975. "Content-Length: 5\r\n"
  10976. "Content-Length: 10\r\n"
  10977. "\r\n"
  10978. "hello";
  10979. std::string response;
  10980. ASSERT_TRUE(send_request(1, req, &response));
  10981. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10982. response.substr(0, response.find("\r\n")));
  10983. }
  10984. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  10985. auto handled = false;
  10986. Server svr;
  10987. svr.Post("/test", [&](const Request &, Response &res) {
  10988. handled = true;
  10989. res.set_content("ok", "text/plain");
  10990. });
  10991. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10992. auto se = detail::scope_exit([&] {
  10993. svr.stop();
  10994. t.join();
  10995. ASSERT_FALSE(svr.is_running());
  10996. ASSERT_TRUE(handled);
  10997. });
  10998. svr.wait_until_ready();
  10999. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  11000. auto req = "POST /test HTTP/1.1\r\n"
  11001. "Content-Length: 5\r\n"
  11002. "Content-Length: 5\r\n"
  11003. "\r\n"
  11004. "hello";
  11005. std::string response;
  11006. ASSERT_TRUE(send_request(1, req, &response));
  11007. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  11008. }
  11009. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  11010. Server svr;
  11011. svr.Get("/", [](const Request &req, Response &res) {
  11012. EXPECT_EQ(2U, req.trailers.size());
  11013. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  11014. // Denied
  11015. EXPECT_FALSE(req.has_trailer("Content-Length"));
  11016. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  11017. // Accepted
  11018. EXPECT_TRUE(req.has_trailer("X-Hello"));
  11019. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  11020. EXPECT_TRUE(req.has_trailer("X-World"));
  11021. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  11022. res.set_content("ok", "text/plain");
  11023. });
  11024. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11025. auto se = detail::scope_exit([&] {
  11026. svr.stop();
  11027. t.join();
  11028. ASSERT_FALSE(svr.is_running());
  11029. });
  11030. svr.wait_until_ready();
  11031. const std::string req = "GET / HTTP/1.1\r\n"
  11032. "Transfer-Encoding: chunked\r\n"
  11033. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  11034. "\r\n"
  11035. "0\r\n"
  11036. "Content-Length: 10\r\n"
  11037. "Host: internal.local\r\n"
  11038. "Content-Type: malicious/content\r\n"
  11039. "Cookie: any\r\n"
  11040. "Set-Cookie: any\r\n"
  11041. "X-Forwarded-For: attacker.com\r\n"
  11042. "X-Real-Ip: 1.1.1.1\r\n"
  11043. "X-Hello: hello\r\n"
  11044. "X-World: world\r\n"
  11045. "\r\n";
  11046. std::string res;
  11047. ASSERT_TRUE(send_request(1, req, &res));
  11048. }
  11049. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  11050. Server svr;
  11051. std::string observed_remote_addr;
  11052. std::string observed_xff;
  11053. svr.Get("/ip", [&](const Request &req, Response &res) {
  11054. observed_remote_addr = req.remote_addr;
  11055. observed_xff = req.get_header_value("X-Forwarded-For");
  11056. res.set_content("ok", "text/plain");
  11057. });
  11058. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11059. auto se = detail::scope_exit([&] {
  11060. svr.stop();
  11061. t.join();
  11062. ASSERT_FALSE(svr.is_running());
  11063. });
  11064. svr.wait_until_ready();
  11065. Client cli(HOST, PORT);
  11066. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  11067. ASSERT_TRUE(res);
  11068. EXPECT_EQ(StatusCode::OK_200, res->status);
  11069. EXPECT_EQ(observed_xff, "203.0.113.66");
  11070. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11071. observed_remote_addr == "127.0.0.1");
  11072. }
  11073. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  11074. Server svr;
  11075. svr.set_trusted_proxies({"203.0.113.66"});
  11076. std::string observed_remote_addr;
  11077. std::string observed_xff;
  11078. svr.Get("/ip", [&](const Request &req, Response &res) {
  11079. observed_remote_addr = req.remote_addr;
  11080. observed_xff = req.get_header_value("X-Forwarded-For");
  11081. res.set_content("ok", "text/plain");
  11082. });
  11083. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11084. auto se = detail::scope_exit([&] {
  11085. svr.stop();
  11086. t.join();
  11087. ASSERT_FALSE(svr.is_running());
  11088. });
  11089. svr.wait_until_ready();
  11090. Client cli(HOST, PORT);
  11091. auto res = cli.Get("/ip");
  11092. ASSERT_TRUE(res);
  11093. EXPECT_EQ(StatusCode::OK_200, res->status);
  11094. EXPECT_EQ(observed_xff, "");
  11095. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11096. observed_remote_addr == "127.0.0.1");
  11097. }
  11098. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  11099. Server svr;
  11100. svr.set_trusted_proxies({"203.0.113.66"});
  11101. std::string observed_remote_addr;
  11102. std::string observed_xff;
  11103. svr.Get("/ip", [&](const Request &req, Response &res) {
  11104. observed_remote_addr = req.remote_addr;
  11105. observed_xff = req.get_header_value("X-Forwarded-For");
  11106. res.set_content("ok", "text/plain");
  11107. });
  11108. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11109. auto se = detail::scope_exit([&] {
  11110. svr.stop();
  11111. t.join();
  11112. ASSERT_FALSE(svr.is_running());
  11113. });
  11114. svr.wait_until_ready();
  11115. Client cli(HOST, PORT);
  11116. auto res =
  11117. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  11118. ASSERT_TRUE(res);
  11119. EXPECT_EQ(StatusCode::OK_200, res->status);
  11120. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  11121. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11122. }
  11123. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  11124. Server svr;
  11125. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  11126. std::string observed_remote_addr;
  11127. std::string observed_xff;
  11128. svr.Get("/ip", [&](const Request &req, Response &res) {
  11129. observed_remote_addr = req.remote_addr;
  11130. observed_xff = req.get_header_value("X-Forwarded-For");
  11131. res.set_content("ok", "text/plain");
  11132. });
  11133. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11134. auto se = detail::scope_exit([&] {
  11135. svr.stop();
  11136. t.join();
  11137. ASSERT_FALSE(svr.is_running());
  11138. });
  11139. svr.wait_until_ready();
  11140. Client cli(HOST, PORT);
  11141. auto res = cli.Get(
  11142. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11143. ASSERT_TRUE(res);
  11144. EXPECT_EQ(StatusCode::OK_200, res->status);
  11145. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11146. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11147. }
  11148. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  11149. Server svr;
  11150. svr.set_trusted_proxies({"192.0.2.45"});
  11151. std::string observed_remote_addr;
  11152. std::string observed_xff;
  11153. svr.Get("/ip", [&](const Request &req, Response &res) {
  11154. observed_remote_addr = req.remote_addr;
  11155. observed_xff = req.get_header_value("X-Forwarded-For");
  11156. res.set_content("ok", "text/plain");
  11157. });
  11158. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11159. auto se = detail::scope_exit([&] {
  11160. svr.stop();
  11161. t.join();
  11162. ASSERT_FALSE(svr.is_running());
  11163. });
  11164. svr.wait_until_ready();
  11165. Client cli(HOST, PORT);
  11166. auto res =
  11167. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  11168. ASSERT_TRUE(res);
  11169. EXPECT_EQ(StatusCode::OK_200, res->status);
  11170. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  11171. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11172. }
  11173. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  11174. Server svr;
  11175. svr.set_trusted_proxies({"192.0.2.45"});
  11176. std::string observed_remote_addr;
  11177. std::string observed_xff;
  11178. svr.Get("/ip", [&](const Request &req, Response &res) {
  11179. observed_remote_addr = req.remote_addr;
  11180. observed_xff = req.get_header_value("X-Forwarded-For");
  11181. res.set_content("ok", "text/plain");
  11182. });
  11183. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11184. auto se = detail::scope_exit([&] {
  11185. svr.stop();
  11186. t.join();
  11187. ASSERT_FALSE(svr.is_running());
  11188. });
  11189. svr.wait_until_ready();
  11190. Client cli(HOST, PORT);
  11191. auto res = cli.Get(
  11192. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11193. ASSERT_TRUE(res);
  11194. EXPECT_EQ(StatusCode::OK_200, res->status);
  11195. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11196. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11197. }
  11198. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  11199. Server svr;
  11200. svr.set_trusted_proxies({"192.0.2.45"});
  11201. std::string observed_remote_addr;
  11202. std::string observed_xff;
  11203. svr.Get("/ip", [&](const Request &req, Response &res) {
  11204. observed_remote_addr = req.remote_addr;
  11205. observed_xff = req.get_header_value("X-Forwarded-For");
  11206. res.set_content("ok", "text/plain");
  11207. });
  11208. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11209. auto se = detail::scope_exit([&] {
  11210. svr.stop();
  11211. t.join();
  11212. ASSERT_FALSE(svr.is_running());
  11213. });
  11214. svr.wait_until_ready();
  11215. std::string raw_req =
  11216. "GET /ip HTTP/1.1\r\n"
  11217. "Host: localhost\r\n"
  11218. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  11219. "Connection: close\r\n"
  11220. "\r\n";
  11221. std::string out;
  11222. ASSERT_TRUE(send_request(5, raw_req, &out));
  11223. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11224. // Header parser trims surrounding whitespace of the header value
  11225. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  11226. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11227. }
  11228. #ifndef _WIN32
  11229. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  11230. Server svr;
  11231. svr.Post("/post", [&](const Request &req, Response &res) {
  11232. res.set_content(req.body, "text/plain");
  11233. });
  11234. svr.Put("/put", [&](const Request &req, Response &res) {
  11235. res.set_content(req.body, "text/plain");
  11236. });
  11237. svr.Patch("/patch", [&](const Request &req, Response &res) {
  11238. res.set_content(req.body, "text/plain");
  11239. });
  11240. svr.Delete("/delete", [&](const Request &req, Response &res) {
  11241. res.set_content(req.body, "text/plain");
  11242. });
  11243. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11244. auto se = detail::scope_exit([&] {
  11245. svr.stop();
  11246. t.join();
  11247. ASSERT_FALSE(svr.is_running());
  11248. });
  11249. svr.wait_until_ready();
  11250. std::string resp;
  11251. // POST without Content-Length
  11252. ASSERT_TRUE(send_request(5,
  11253. "POST /post HTTP/1.1\r\n"
  11254. "Host: localhost\r\n"
  11255. "Connection: close\r\n"
  11256. "\r\n",
  11257. &resp));
  11258. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11259. // PUT without Content-Length
  11260. resp.clear();
  11261. ASSERT_TRUE(send_request(5,
  11262. "PUT /put HTTP/1.1\r\n"
  11263. "Host: localhost\r\n"
  11264. "Connection: close\r\n"
  11265. "\r\n",
  11266. &resp));
  11267. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11268. // PATCH without Content-Length
  11269. resp.clear();
  11270. ASSERT_TRUE(send_request(5,
  11271. "PATCH /patch HTTP/1.1\r\n"
  11272. "Host: localhost\r\n"
  11273. "Connection: close\r\n"
  11274. "\r\n",
  11275. &resp));
  11276. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11277. // DELETE without Content-Length
  11278. resp.clear();
  11279. ASSERT_TRUE(send_request(5,
  11280. "DELETE /delete HTTP/1.1\r\n"
  11281. "Host: localhost\r\n"
  11282. "Connection: close\r\n"
  11283. "\r\n",
  11284. &resp));
  11285. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11286. }
  11287. #endif
  11288. //==============================================================================
  11289. // open_stream() Tests
  11290. //==============================================================================
  11291. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  11292. std::string result;
  11293. char buf[8192];
  11294. ssize_t n;
  11295. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11296. result.append(buf, static_cast<size_t>(n));
  11297. }
  11298. return result;
  11299. }
  11300. // Mock stream for unit tests
  11301. class MockStream : public Stream {
  11302. public:
  11303. std::string data;
  11304. size_t pos = 0;
  11305. ssize_t error_after = -1; // -1 = no error
  11306. explicit MockStream(const std::string &d, ssize_t err = -1)
  11307. : data(d), error_after(err) {}
  11308. bool is_readable() const override { return true; }
  11309. bool wait_readable() const override { return true; }
  11310. bool wait_writable() const override { return true; }
  11311. ssize_t read(char *ptr, size_t size) override {
  11312. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  11313. if (pos >= data.size()) return 0;
  11314. size_t limit =
  11315. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  11316. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  11317. std::memcpy(ptr, data.data() + pos, to_read);
  11318. pos += to_read;
  11319. return static_cast<ssize_t>(to_read);
  11320. }
  11321. ssize_t write(const char *, size_t) override { return -1; }
  11322. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  11323. ip = "127.0.0.1";
  11324. port = 0;
  11325. }
  11326. void get_local_ip_and_port(std::string &ip, int &port) const override {
  11327. ip = "127.0.0.1";
  11328. port = 0;
  11329. }
  11330. socket_t socket() const override { return INVALID_SOCKET; }
  11331. time_t duration() const override { return 0; }
  11332. };
  11333. TEST(StreamHandleTest, Basic) {
  11334. ClientImpl::StreamHandle handle;
  11335. EXPECT_FALSE(handle.is_valid());
  11336. handle.response = detail::make_unique<Response>();
  11337. handle.error = Error::Connection;
  11338. EXPECT_FALSE(handle.is_valid());
  11339. handle.error = Error::Success;
  11340. EXPECT_TRUE(handle.is_valid());
  11341. }
  11342. TEST(BodyReaderTest, Basic) {
  11343. MockStream stream("Hello, World!");
  11344. detail::BodyReader reader;
  11345. reader.stream = &stream;
  11346. reader.content_length = 13;
  11347. char buf[32];
  11348. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  11349. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  11350. EXPECT_TRUE(reader.eof);
  11351. }
  11352. TEST(BodyReaderTest, NoStream) {
  11353. detail::BodyReader reader;
  11354. char buf[32];
  11355. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11356. EXPECT_EQ(Error::Connection, reader.last_error);
  11357. }
  11358. TEST(BodyReaderTest, Error) {
  11359. MockStream stream("Hello, World!", 5);
  11360. detail::BodyReader reader;
  11361. reader.stream = &stream;
  11362. reader.content_length = 13;
  11363. char buf[32];
  11364. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  11365. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11366. EXPECT_EQ(Error::Read, reader.last_error);
  11367. }
  11368. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  11369. // Mock-based StreamHandle tests relying on private internals are removed.
  11370. class OpenStreamTest : public ::testing::Test {
  11371. protected:
  11372. void SetUp() override {
  11373. svr_.Get("/hello", [](const Request &, Response &res) {
  11374. res.set_content("Hello World!", "text/plain");
  11375. });
  11376. svr_.Get("/large", [](const Request &, Response &res) {
  11377. res.set_content(std::string(10000, 'X'), "text/plain");
  11378. });
  11379. svr_.Get("/chunked", [](const Request &, Response &res) {
  11380. res.set_chunked_content_provider("text/plain",
  11381. [](size_t offset, DataSink &sink) {
  11382. if (offset < 15) {
  11383. sink.write("chunk", 5);
  11384. return true;
  11385. }
  11386. sink.done();
  11387. return true;
  11388. });
  11389. });
  11390. svr_.Get("/compressible", [](const Request &, Response &res) {
  11391. res.set_chunked_content_provider("text/plain", [](size_t offset,
  11392. DataSink &sink) {
  11393. if (offset < 100 * 1024) {
  11394. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  11395. sink.write(chunk.data(), chunk.size());
  11396. return true;
  11397. }
  11398. sink.done();
  11399. return true;
  11400. });
  11401. });
  11402. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  11403. [](const Request & /*req*/, Response &res) {
  11404. auto i = new int(0);
  11405. res.set_header("Trailer", "Content-Length, X-Allowed");
  11406. res.set_chunked_content_provider(
  11407. "text/plain",
  11408. [i](size_t /*offset*/, DataSink &sink) {
  11409. switch (*i) {
  11410. case 0: sink.os << "123"; break;
  11411. case 1: sink.os << "456"; break;
  11412. case 2: sink.os << "789"; break;
  11413. case 3: {
  11414. sink.done_with_trailer(
  11415. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  11416. } break;
  11417. }
  11418. (*i)++;
  11419. return true;
  11420. },
  11421. [i](bool success) {
  11422. EXPECT_TRUE(success);
  11423. delete i;
  11424. });
  11425. });
  11426. // Echo headers endpoint for header-related tests
  11427. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  11428. std::string body;
  11429. for (const auto &h : req.headers) {
  11430. body.append(h.first);
  11431. body.push_back(':');
  11432. body.append(h.second);
  11433. body.push_back('\n');
  11434. }
  11435. res.set_content(body, "text/plain");
  11436. });
  11437. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  11438. std::string body;
  11439. for (const auto &h : req.headers) {
  11440. body.append(h.first);
  11441. body.push_back(':');
  11442. body.append(h.second);
  11443. body.push_back('\n');
  11444. }
  11445. res.set_content(body, "text/plain");
  11446. });
  11447. port_ = svr_.bind_to_any_port("127.0.0.1");
  11448. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11449. svr_.wait_until_ready();
  11450. }
  11451. void TearDown() override {
  11452. svr_.stop();
  11453. if (thread_.joinable()) thread_.join();
  11454. }
  11455. Server svr_;
  11456. std::thread thread_;
  11457. int port_ = 0;
  11458. };
  11459. TEST_F(OpenStreamTest, Basic) {
  11460. Client cli("127.0.0.1", port_);
  11461. auto handle = cli.open_stream("GET", "/hello");
  11462. EXPECT_TRUE(handle.is_valid());
  11463. EXPECT_EQ("Hello World!", read_all(handle));
  11464. }
  11465. TEST_F(OpenStreamTest, SmallBuffer) {
  11466. Client cli("127.0.0.1", port_);
  11467. auto handle = cli.open_stream("GET", "/hello");
  11468. std::string result;
  11469. char buf[4];
  11470. ssize_t n;
  11471. while ((n = handle.read(buf, sizeof(buf))) > 0)
  11472. result.append(buf, static_cast<size_t>(n));
  11473. EXPECT_EQ("Hello World!", result);
  11474. }
  11475. TEST_F(OpenStreamTest, DefaultHeaders) {
  11476. Client cli("127.0.0.1", port_);
  11477. // open_stream GET should include Host, User-Agent and Accept-Encoding
  11478. {
  11479. auto handle = cli.open_stream("GET", "/echo-headers");
  11480. ASSERT_TRUE(handle.is_valid());
  11481. auto body = read_all(handle);
  11482. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  11483. std::string::npos);
  11484. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  11485. std::string::npos);
  11486. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  11487. }
  11488. // open_stream POST with body and no explicit content_type should NOT add
  11489. // text/plain Content-Type (behavior differs from non-streaming path), but
  11490. // should include Content-Length
  11491. {
  11492. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  11493. ASSERT_TRUE(handle.is_valid());
  11494. auto body = read_all(handle);
  11495. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  11496. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  11497. }
  11498. // open_stream POST with explicit Content-Type should preserve it
  11499. {
  11500. auto handle = cli.open_stream("POST", "/echo-headers", {},
  11501. {{"Content-Type", "application/custom"}},
  11502. "{}", "application/custom");
  11503. ASSERT_TRUE(handle.is_valid());
  11504. auto body = read_all(handle);
  11505. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  11506. }
  11507. // User-specified User-Agent must not be overwritten for stream API
  11508. {
  11509. auto handle = cli.open_stream("GET", "/echo-headers", {},
  11510. {{"User-Agent", "MyAgent/1.2"}});
  11511. ASSERT_TRUE(handle.is_valid());
  11512. auto body = read_all(handle);
  11513. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  11514. }
  11515. }
  11516. TEST_F(OpenStreamTest, Large) {
  11517. Client cli("127.0.0.1", port_);
  11518. auto handle = cli.open_stream("GET", "/large");
  11519. EXPECT_EQ(10000u, read_all(handle).size());
  11520. }
  11521. TEST_F(OpenStreamTest, ConnectionError) {
  11522. Client cli("127.0.0.1", 9999);
  11523. auto handle = cli.open_stream("GET", "/hello");
  11524. EXPECT_FALSE(handle.is_valid());
  11525. }
  11526. TEST_F(OpenStreamTest, Chunked) {
  11527. Client cli("127.0.0.1", port_);
  11528. auto handle = cli.open_stream("GET", "/chunked");
  11529. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11530. "Transfer-Encoding") == "chunked");
  11531. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  11532. }
  11533. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  11534. Client cli("127.0.0.1", port_);
  11535. auto handle =
  11536. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  11537. ASSERT_TRUE(handle.is_valid());
  11538. // Consume body to allow trailers to be received/parsed
  11539. auto body = read_all(handle);
  11540. // Explicitly parse trailers (ensure trailers are available for assertion)
  11541. handle.parse_trailers_if_needed();
  11542. EXPECT_EQ(std::string("123456789"), body);
  11543. // The response should include a Trailer header declaring both names
  11544. ASSERT_TRUE(handle.response);
  11545. EXPECT_TRUE(handle.response->has_header("Trailer"));
  11546. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  11547. handle.response->get_header_value("Trailer"));
  11548. // Prohibited trailer must not be present
  11549. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  11550. // Allowed trailer should be present
  11551. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  11552. EXPECT_EQ(std::string("yes"),
  11553. handle.response->get_trailer_value("X-Allowed"));
  11554. // Verify trailers are NOT present as regular headers
  11555. EXPECT_EQ(std::string(""),
  11556. handle.response->get_header_value("Content-Length"));
  11557. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  11558. }
  11559. static std::thread serve_single_response(std::promise<int> &port_promise,
  11560. const std::string &response) {
  11561. return std::thread([&port_promise, response] {
  11562. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11563. default_socket_options(srv);
  11564. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11565. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11566. sockaddr_in addr{};
  11567. addr.sin_family = AF_INET;
  11568. addr.sin_port = htons(0); // Let OS assign a free port
  11569. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11570. int opt = 1;
  11571. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11572. #ifdef _WIN32
  11573. reinterpret_cast<const char *>(&opt),
  11574. #else
  11575. &opt,
  11576. #endif
  11577. sizeof(opt));
  11578. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  11579. ::listen(srv, 1) != 0) {
  11580. port_promise.set_value(-1);
  11581. detail::close_socket(srv);
  11582. return;
  11583. }
  11584. socklen_t addr_len = sizeof(addr);
  11585. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  11586. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  11587. sockaddr_in cli_addr{};
  11588. socklen_t cli_len = sizeof(cli_addr);
  11589. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11590. if (cli != INVALID_SOCKET) {
  11591. char buf[4096];
  11592. ::recv(cli, buf, sizeof(buf), 0);
  11593. ::send(cli,
  11594. #ifdef _WIN32
  11595. static_cast<const char *>(response.c_str()),
  11596. static_cast<int>(response.size()),
  11597. #else
  11598. response.c_str(), response.size(),
  11599. #endif
  11600. 0);
  11601. detail::close_socket(cli);
  11602. }
  11603. detail::close_socket(srv);
  11604. });
  11605. }
  11606. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  11607. #ifndef _WIN32
  11608. signal(SIGPIPE, SIG_IGN);
  11609. #endif
  11610. std::promise<int> port_promise;
  11611. auto port_future = port_promise.get_future();
  11612. auto server_thread =
  11613. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  11614. "Content-Type: text/plain\r\n"
  11615. "Content-Length: not-a-number\r\n"
  11616. "Connection: close\r\n"
  11617. "\r\n"
  11618. "hello");
  11619. auto port = port_future.get();
  11620. ASSERT_GT(port, 0);
  11621. Client cli("127.0.0.1", port);
  11622. auto handle = cli.open_stream("GET", "/");
  11623. EXPECT_FALSE(handle.is_valid());
  11624. server_thread.join();
  11625. }
  11626. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  11627. #ifndef _WIN32
  11628. signal(SIGPIPE, SIG_IGN);
  11629. #endif
  11630. std::promise<int> port_promise;
  11631. auto port_future = port_promise.get_future();
  11632. auto server_thread = serve_single_response(
  11633. port_promise, "HTTP/1.1 200 OK\r\n"
  11634. "Content-Type: text/plain\r\n"
  11635. "Content-Length: 99999999999999999999999999\r\n"
  11636. "Connection: close\r\n"
  11637. "\r\n"
  11638. "hello");
  11639. auto port = port_future.get();
  11640. ASSERT_GT(port, 0);
  11641. // Before the fix, std::stoull would throw std::out_of_range here and
  11642. // crash the process. After the fix, strtoull silently clamps to
  11643. // ULLONG_MAX so the stream opens without crashing. The important thing
  11644. // is that the process does NOT terminate.
  11645. Client cli("127.0.0.1", port);
  11646. auto handle = cli.open_stream("GET", "/");
  11647. EXPECT_TRUE(handle.is_valid());
  11648. server_thread.join();
  11649. }
  11650. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11651. TEST_F(OpenStreamTest, Gzip) {
  11652. Client cli("127.0.0.1", port_);
  11653. auto handle = cli.open_stream("GET", "/compressible", {},
  11654. {{"Accept-Encoding", "gzip"}});
  11655. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  11656. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11657. }
  11658. #endif
  11659. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11660. TEST_F(OpenStreamTest, Brotli) {
  11661. Client cli("127.0.0.1", port_);
  11662. auto handle =
  11663. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  11664. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  11665. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11666. }
  11667. #endif
  11668. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11669. TEST_F(OpenStreamTest, Zstd) {
  11670. Client cli("127.0.0.1", port_);
  11671. auto handle = cli.open_stream("GET", "/compressible", {},
  11672. {{"Accept-Encoding", "zstd"}});
  11673. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  11674. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11675. }
  11676. #endif
  11677. #ifdef CPPHTTPLIB_SSL_ENABLED
  11678. class SSLOpenStreamTest : public ::testing::Test {
  11679. protected:
  11680. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  11681. void SetUp() override {
  11682. svr_.Get("/hello", [](const Request &, Response &res) {
  11683. res.set_content("Hello SSL World!", "text/plain");
  11684. });
  11685. svr_.Get("/chunked", [](const Request &, Response &res) {
  11686. res.set_chunked_content_provider("text/plain",
  11687. [](size_t offset, DataSink &sink) {
  11688. if (offset < 15) {
  11689. sink.write("chunk", 5);
  11690. return true;
  11691. }
  11692. sink.done();
  11693. return true;
  11694. });
  11695. });
  11696. svr_.Post("/echo", [](const Request &req, Response &res) {
  11697. res.set_content(req.body, req.get_header_value("Content-Type"));
  11698. });
  11699. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  11700. std::string body = req.body;
  11701. res.set_chunked_content_provider(
  11702. "text/plain", [body](size_t offset, DataSink &sink) {
  11703. if (offset < body.size()) {
  11704. sink.write(body.data() + offset, body.size() - offset);
  11705. }
  11706. sink.done();
  11707. return true;
  11708. });
  11709. });
  11710. port_ = svr_.bind_to_any_port("127.0.0.1");
  11711. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11712. svr_.wait_until_ready();
  11713. }
  11714. void TearDown() override {
  11715. svr_.stop();
  11716. if (thread_.joinable()) thread_.join();
  11717. }
  11718. SSLServer svr_;
  11719. std::thread thread_;
  11720. int port_ = 0;
  11721. };
  11722. TEST_F(SSLOpenStreamTest, Basic) {
  11723. SSLClient cli("127.0.0.1", port_);
  11724. cli.enable_server_certificate_verification(false);
  11725. auto handle = cli.open_stream("GET", "/hello");
  11726. ASSERT_TRUE(handle.is_valid());
  11727. EXPECT_EQ("Hello SSL World!", read_all(handle));
  11728. }
  11729. TEST_F(SSLOpenStreamTest, Chunked) {
  11730. SSLClient cli("127.0.0.1", port_);
  11731. cli.enable_server_certificate_verification(false);
  11732. auto handle = cli.open_stream("GET", "/chunked");
  11733. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11734. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11735. "Transfer-Encoding") == "chunked");
  11736. auto body = read_all(handle);
  11737. EXPECT_EQ("chunkchunkchunk", body);
  11738. }
  11739. TEST_F(SSLOpenStreamTest, Post) {
  11740. SSLClient cli("127.0.0.1", port_);
  11741. cli.enable_server_certificate_verification(false);
  11742. auto handle =
  11743. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  11744. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11745. EXPECT_EQ(200, handle.response->status);
  11746. auto body = read_all(handle);
  11747. EXPECT_EQ("Hello SSL POST", body);
  11748. }
  11749. TEST_F(SSLOpenStreamTest, PostChunked) {
  11750. SSLClient cli("127.0.0.1", port_);
  11751. cli.enable_server_certificate_verification(false);
  11752. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  11753. "Chunked SSL Data", "text/plain");
  11754. ASSERT_TRUE(handle.is_valid());
  11755. EXPECT_EQ(200, handle.response->status);
  11756. auto body = read_all(handle);
  11757. EXPECT_EQ("Chunked SSL Data", body);
  11758. }
  11759. #endif // CPPHTTPLIB_SSL_ENABLED
  11760. //==============================================================================
  11761. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  11762. // results for various scenarios.
  11763. //==============================================================================
  11764. TEST(ParityTest, GetVsOpenStream) {
  11765. Server svr;
  11766. const std::string path = "/parity";
  11767. const std::string content = "Parity test content: hello world";
  11768. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11769. res.set_content(content, "text/plain");
  11770. });
  11771. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11772. auto se = detail::scope_exit([&] {
  11773. svr.stop();
  11774. t.join();
  11775. ASSERT_FALSE(svr.is_running());
  11776. });
  11777. svr.wait_until_ready();
  11778. Client cli(HOST, PORT);
  11779. // Non-stream path
  11780. auto r1 = cli.Get(path);
  11781. ASSERT_TRUE(r1);
  11782. EXPECT_EQ(StatusCode::OK_200, r1->status);
  11783. // Stream path
  11784. auto h = cli.open_stream("GET", path);
  11785. ASSERT_TRUE(h.is_valid());
  11786. EXPECT_EQ(r1->body, read_all(h));
  11787. }
  11788. // Helper to compress data with provided compressor type T
  11789. template <typename Compressor>
  11790. static std::string compress_payload_for_parity(const std::string &in) {
  11791. std::string out;
  11792. Compressor compressor;
  11793. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  11794. [&](const char *data, size_t n) {
  11795. out.append(data, n);
  11796. return true;
  11797. });
  11798. EXPECT_TRUE(ok);
  11799. return out;
  11800. }
  11801. // Helper function for compression parity tests
  11802. template <typename Compressor>
  11803. static void test_compression_parity(const std::string &original,
  11804. const std::string &path,
  11805. const std::string &encoding) {
  11806. const std::string compressed =
  11807. compress_payload_for_parity<Compressor>(original);
  11808. Server svr;
  11809. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11810. res.set_content(compressed, "application/octet-stream");
  11811. res.set_header("Content-Encoding", encoding);
  11812. });
  11813. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  11814. auto se = detail::scope_exit([&] {
  11815. svr.stop();
  11816. t.join();
  11817. ASSERT_FALSE(svr.is_running());
  11818. });
  11819. svr.wait_until_ready();
  11820. Client cli(HOST, PORT);
  11821. // Non-streaming
  11822. {
  11823. auto res = cli.Get(path);
  11824. ASSERT_TRUE(res);
  11825. EXPECT_EQ(StatusCode::OK_200, res->status);
  11826. EXPECT_EQ(original, res->body);
  11827. }
  11828. // Streaming
  11829. {
  11830. auto h = cli.open_stream("GET", path);
  11831. ASSERT_TRUE(h.is_valid());
  11832. EXPECT_EQ(original, read_all(h));
  11833. }
  11834. }
  11835. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11836. TEST(ParityTest, Gzip) {
  11837. test_compression_parity<detail::gzip_compressor>(
  11838. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  11839. }
  11840. #endif
  11841. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11842. TEST(ParityTest, Brotli) {
  11843. test_compression_parity<detail::brotli_compressor>(
  11844. "Hello, brotli parity test payload", "/parity-br", "br");
  11845. }
  11846. #endif
  11847. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11848. TEST(ParityTest, Zstd) {
  11849. test_compression_parity<detail::zstd_compressor>(
  11850. "Zstandard parity test payload", "/parity-zstd", "zstd");
  11851. }
  11852. #endif
  11853. //==============================================================================
  11854. // New Stream API Tests
  11855. //==============================================================================
  11856. inline std::string read_body(httplib::stream::Result &result) {
  11857. std::string body;
  11858. while (result.next()) {
  11859. body.append(result.data(), result.size());
  11860. }
  11861. return body;
  11862. }
  11863. TEST(ClientConnectionTest, Basic) {
  11864. httplib::ClientConnection conn;
  11865. EXPECT_FALSE(conn.is_open());
  11866. conn.sock = 1;
  11867. EXPECT_TRUE(conn.is_open());
  11868. httplib::ClientConnection conn2(std::move(conn));
  11869. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  11870. conn2.sock = INVALID_SOCKET;
  11871. }
  11872. // Unified test server for all stream::* tests
  11873. class StreamApiTest : public ::testing::Test {
  11874. protected:
  11875. void SetUp() override {
  11876. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11877. res.set_content("Hello World!", "text/plain");
  11878. });
  11879. svr_.Get("/echo-params",
  11880. [](const httplib::Request &req, httplib::Response &res) {
  11881. std::string r;
  11882. for (const auto &p : req.params) {
  11883. if (!r.empty()) r += "&";
  11884. r += p.first + "=" + p.second;
  11885. }
  11886. res.set_content(r, "text/plain");
  11887. });
  11888. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11889. res.set_content(req.body, req.get_header_value("Content-Type"));
  11890. });
  11891. svr_.Post("/echo-headers",
  11892. [](const httplib::Request &req, httplib::Response &res) {
  11893. std::string r;
  11894. for (const auto &h : req.headers)
  11895. r += h.first + ": " + h.second + "\n";
  11896. res.set_content(r, "text/plain");
  11897. });
  11898. svr_.Post("/echo-params",
  11899. [](const httplib::Request &req, httplib::Response &res) {
  11900. std::string r = "params:";
  11901. for (const auto &p : req.params)
  11902. r += p.first + "=" + p.second + ";";
  11903. res.set_content(r + " body:" + req.body, "text/plain");
  11904. });
  11905. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  11906. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  11907. });
  11908. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11909. res.set_content("PUT:" + req.body, "text/plain");
  11910. });
  11911. svr_.Patch("/echo",
  11912. [](const httplib::Request &req, httplib::Response &res) {
  11913. res.set_content("PATCH:" + req.body, "text/plain");
  11914. });
  11915. svr_.Delete(
  11916. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  11917. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  11918. "text/plain");
  11919. });
  11920. svr_.Get("/head-test",
  11921. [](const httplib::Request &, httplib::Response &res) {
  11922. res.set_content("body for HEAD", "text/plain");
  11923. });
  11924. svr_.Options("/options",
  11925. [](const httplib::Request &, httplib::Response &res) {
  11926. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  11927. });
  11928. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  11929. svr_.wait_until_ready();
  11930. }
  11931. void TearDown() override {
  11932. svr_.stop();
  11933. if (thread_.joinable()) thread_.join();
  11934. }
  11935. httplib::Server svr_;
  11936. std::thread thread_;
  11937. };
  11938. // stream::Get tests
  11939. TEST_F(StreamApiTest, GetBasic) {
  11940. httplib::Client cli(HOST, PORT);
  11941. auto result = httplib::stream::Get(cli, "/hello");
  11942. ASSERT_TRUE(result.is_valid());
  11943. EXPECT_EQ(200, result.status());
  11944. EXPECT_EQ("Hello World!", read_body(result));
  11945. }
  11946. TEST_F(StreamApiTest, GetWithParams) {
  11947. httplib::Client cli(HOST, PORT);
  11948. httplib::Params params{{"foo", "bar"}};
  11949. auto result = httplib::stream::Get(cli, "/echo-params", params);
  11950. ASSERT_TRUE(result.is_valid());
  11951. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  11952. }
  11953. TEST_F(StreamApiTest, GetConnectionError) {
  11954. httplib::Client cli(HOST, 9999);
  11955. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  11956. }
  11957. TEST_F(StreamApiTest, Get404) {
  11958. httplib::Client cli(HOST, PORT);
  11959. auto result = httplib::stream::Get(cli, "/nonexistent");
  11960. EXPECT_TRUE(result.is_valid());
  11961. EXPECT_EQ(404, result.status());
  11962. }
  11963. // stream::Post tests
  11964. TEST_F(StreamApiTest, PostBasic) {
  11965. httplib::Client cli(HOST, PORT);
  11966. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  11967. "application/json");
  11968. ASSERT_TRUE(result.is_valid());
  11969. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  11970. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  11971. }
  11972. TEST_F(StreamApiTest, PostWithHeaders) {
  11973. httplib::Client cli(HOST, PORT);
  11974. httplib::Headers headers{{"X-Custom", "value"}};
  11975. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  11976. "text/plain");
  11977. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  11978. }
  11979. TEST_F(StreamApiTest, PostWithParams) {
  11980. httplib::Client cli(HOST, PORT);
  11981. httplib::Params params{{"k", "v"}};
  11982. auto result =
  11983. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  11984. auto body = read_body(result);
  11985. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  11986. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  11987. }
  11988. TEST_F(StreamApiTest, PostLarge) {
  11989. httplib::Client cli(HOST, PORT);
  11990. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  11991. size_t total = 0;
  11992. while (result.next()) {
  11993. total += result.size();
  11994. }
  11995. EXPECT_EQ(100u * 1024u, total);
  11996. }
  11997. // stream::Put/Patch tests
  11998. TEST_F(StreamApiTest, PutAndPatch) {
  11999. httplib::Client cli(HOST, PORT);
  12000. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  12001. EXPECT_EQ("PUT:test", read_body(put));
  12002. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  12003. EXPECT_EQ("PATCH:test", read_body(patch));
  12004. }
  12005. // stream::Delete tests
  12006. TEST_F(StreamApiTest, Delete) {
  12007. httplib::Client cli(HOST, PORT);
  12008. auto del1 = httplib::stream::Delete(cli, "/resource");
  12009. EXPECT_EQ("Deleted", read_body(del1));
  12010. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  12011. EXPECT_EQ("Deleted:data", read_body(del2));
  12012. }
  12013. // stream::Head/Options tests
  12014. TEST_F(StreamApiTest, HeadAndOptions) {
  12015. httplib::Client cli(HOST, PORT);
  12016. auto head = httplib::stream::Head(cli, "/head-test");
  12017. EXPECT_TRUE(head.is_valid());
  12018. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  12019. auto opts = httplib::stream::Options(cli, "/options");
  12020. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  12021. }
  12022. // SSL stream::* tests
  12023. #ifdef CPPHTTPLIB_SSL_ENABLED
  12024. class SSLStreamApiTest : public ::testing::Test {
  12025. protected:
  12026. void SetUp() override {
  12027. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12028. res.set_content("Hello SSL!", "text/plain");
  12029. });
  12030. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12031. res.set_content(req.body, "text/plain");
  12032. });
  12033. port_ = svr_.bind_to_any_port("127.0.0.1");
  12034. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12035. svr_.wait_until_ready();
  12036. }
  12037. void TearDown() override {
  12038. svr_.stop();
  12039. if (thread_.joinable()) thread_.join();
  12040. }
  12041. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  12042. std::thread thread_;
  12043. int port_ = 0;
  12044. };
  12045. TEST_F(SSLStreamApiTest, GetAndPost) {
  12046. httplib::SSLClient cli("127.0.0.1", port_);
  12047. cli.enable_server_certificate_verification(false);
  12048. auto get = httplib::stream::Get(cli, "/hello");
  12049. EXPECT_EQ("Hello SSL!", read_body(get));
  12050. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  12051. EXPECT_EQ("test", read_body(post));
  12052. }
  12053. #endif
  12054. // Tests for Error::Timeout and Error::ConnectionClosed error types
  12055. // These errors are set in SocketStream/SSLSocketStream and propagated through
  12056. // BodyReader
  12057. TEST(ErrorHandlingTest, StreamReadTimeout) {
  12058. // Test that read timeout during streaming is detected
  12059. // Use a large content-length response where server delays mid-stream
  12060. Server svr;
  12061. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12062. // Send a large response with delay in the middle
  12063. res.set_content_provider(
  12064. 1000, // content_length
  12065. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  12066. if (offset < 100) {
  12067. // Send first 100 bytes immediately
  12068. std::string data(100, 'A');
  12069. sink.write(data.c_str(), data.size());
  12070. return true;
  12071. }
  12072. // Then delay longer than client timeout
  12073. std::this_thread::sleep_for(std::chrono::seconds(3));
  12074. std::string data(900, 'B');
  12075. sink.write(data.c_str(), data.size());
  12076. return true;
  12077. });
  12078. });
  12079. auto port = 8091;
  12080. std::thread t([&]() { svr.listen("localhost", port); });
  12081. svr.wait_until_ready();
  12082. Client cli("localhost", port);
  12083. cli.set_read_timeout(1, 0); // 1 second timeout
  12084. auto handle = cli.open_stream("GET", "/slow-stream");
  12085. ASSERT_TRUE(handle.is_valid());
  12086. char buf[256];
  12087. ssize_t total = 0;
  12088. ssize_t n;
  12089. bool got_error = false;
  12090. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12091. total += n;
  12092. }
  12093. if (n < 0) {
  12094. got_error = true;
  12095. // Should be timeout or read error
  12096. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12097. handle.get_read_error() == Error::Read)
  12098. << "Actual error: " << to_string(handle.get_read_error());
  12099. }
  12100. // Either we got an error, or we got less data than expected
  12101. EXPECT_TRUE(got_error || total < 1000)
  12102. << "Expected timeout but got all " << total << " bytes";
  12103. svr.stop();
  12104. t.join();
  12105. }
  12106. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  12107. // Test connection closed detection via BodyReader
  12108. Server svr;
  12109. std::atomic<bool> close_now{false};
  12110. svr.Get("/will-close", [&](const Request &, Response &res) {
  12111. res.set_content_provider(
  12112. 10000, // Large content_length that we won't fully send
  12113. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12114. if (offset < 100) {
  12115. std::string data(100, 'X');
  12116. sink.write(data.c_str(), data.size());
  12117. return true;
  12118. }
  12119. // Wait for signal then abort
  12120. while (!close_now) {
  12121. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12122. }
  12123. return false; // Abort - server will close connection
  12124. });
  12125. });
  12126. auto port = 8092;
  12127. std::thread t([&]() { svr.listen("localhost", port); });
  12128. svr.wait_until_ready();
  12129. Client cli("localhost", port);
  12130. auto handle = cli.open_stream("GET", "/will-close");
  12131. ASSERT_TRUE(handle.is_valid());
  12132. char buf[256];
  12133. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12134. EXPECT_GT(n, 0) << "First read should succeed";
  12135. // Signal server to close
  12136. close_now = true;
  12137. // Keep reading until error or EOF
  12138. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12139. // Keep reading
  12140. }
  12141. // Should get an error since content_length wasn't satisfied
  12142. if (n < 0) {
  12143. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12144. handle.get_read_error() == Error::Read)
  12145. << "Actual error: " << to_string(handle.get_read_error());
  12146. }
  12147. svr.stop();
  12148. t.join();
  12149. }
  12150. #ifdef CPPHTTPLIB_SSL_ENABLED
  12151. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  12152. // Test that read timeout during SSL streaming is detected
  12153. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12154. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12155. res.set_content_provider(
  12156. 1000, "text/plain",
  12157. [](size_t offset, size_t /*length*/, DataSink &sink) {
  12158. if (offset < 100) {
  12159. std::string data(100, 'A');
  12160. sink.write(data.c_str(), data.size());
  12161. return true;
  12162. }
  12163. std::this_thread::sleep_for(std::chrono::seconds(3));
  12164. std::string data(900, 'B');
  12165. sink.write(data.c_str(), data.size());
  12166. return true;
  12167. });
  12168. });
  12169. auto port = 8093;
  12170. std::thread t([&]() { svr.listen("localhost", port); });
  12171. svr.wait_until_ready();
  12172. SSLClient cli("localhost", port);
  12173. cli.enable_server_certificate_verification(false);
  12174. cli.set_read_timeout(1, 0); // 1 second timeout
  12175. auto handle = cli.open_stream("GET", "/slow-stream");
  12176. ASSERT_TRUE(handle.is_valid());
  12177. char buf[256];
  12178. ssize_t total = 0;
  12179. ssize_t n;
  12180. bool got_error = false;
  12181. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12182. total += n;
  12183. }
  12184. if (n < 0) {
  12185. got_error = true;
  12186. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12187. handle.get_read_error() == Error::Read)
  12188. << "Actual error: " << to_string(handle.get_read_error());
  12189. }
  12190. EXPECT_TRUE(got_error || total < 1000)
  12191. << "Expected timeout but got all " << total << " bytes";
  12192. svr.stop();
  12193. t.join();
  12194. }
  12195. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  12196. // Test SSL connection closed detection
  12197. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12198. std::atomic<bool> close_now{false};
  12199. svr.Get("/will-close", [&](const Request &, Response &res) {
  12200. res.set_content_provider(
  12201. 10000, "text/plain",
  12202. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12203. if (offset < 100) {
  12204. std::string data(100, 'X');
  12205. sink.write(data.c_str(), data.size());
  12206. return true;
  12207. }
  12208. while (!close_now) {
  12209. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12210. }
  12211. return false;
  12212. });
  12213. });
  12214. auto port = 8094;
  12215. std::thread t([&]() { svr.listen("localhost", port); });
  12216. svr.wait_until_ready();
  12217. SSLClient cli("localhost", port);
  12218. cli.enable_server_certificate_verification(false);
  12219. auto handle = cli.open_stream("GET", "/will-close");
  12220. ASSERT_TRUE(handle.is_valid());
  12221. char buf[256];
  12222. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12223. EXPECT_GT(n, 0);
  12224. // Signal server to close
  12225. close_now = true;
  12226. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12227. // Keep reading
  12228. }
  12229. if (n < 0) {
  12230. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12231. handle.get_read_error() == Error::Read)
  12232. << "Actual error: " << to_string(handle.get_read_error());
  12233. }
  12234. svr.stop();
  12235. t.join();
  12236. }
  12237. #endif
  12238. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  12239. using namespace httplib;
  12240. // Create a test file
  12241. const char *fname = "etag_testfile.txt";
  12242. const char *content = "etag-content";
  12243. {
  12244. std::ofstream ofs(fname);
  12245. ofs << content;
  12246. ASSERT_TRUE(ofs.good());
  12247. }
  12248. Server svr;
  12249. svr.set_mount_point("/static", ".");
  12250. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12251. svr.wait_until_ready();
  12252. Client cli(HOST, PORT);
  12253. // First request: should get 200 with ETag header
  12254. auto res1 = cli.Get("/static/etag_testfile.txt");
  12255. ASSERT_TRUE(res1);
  12256. ASSERT_EQ(200, res1->status);
  12257. ASSERT_TRUE(res1->has_header("ETag"));
  12258. std::string etag = res1->get_header_value("ETag");
  12259. EXPECT_FALSE(etag.empty());
  12260. // Verify ETag format: W/"hex-hex"
  12261. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  12262. EXPECT_EQ('W', etag[0]);
  12263. EXPECT_EQ('/', etag[1]);
  12264. EXPECT_EQ('"', etag[2]);
  12265. EXPECT_EQ('"', etag.back());
  12266. // Exact match: expect 304 Not Modified
  12267. Headers h2 = {{"If-None-Match", etag}};
  12268. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  12269. ASSERT_TRUE(res2);
  12270. EXPECT_EQ(304, res2->status);
  12271. // Wildcard match: expect 304 Not Modified
  12272. Headers h3 = {{"If-None-Match", "*"}};
  12273. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  12274. ASSERT_TRUE(res3);
  12275. EXPECT_EQ(304, res3->status);
  12276. // Non-matching ETag: expect 200
  12277. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  12278. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  12279. ASSERT_TRUE(res4);
  12280. EXPECT_EQ(200, res4->status);
  12281. // Multiple ETags with one matching: expect 304
  12282. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  12283. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  12284. ASSERT_TRUE(res5);
  12285. EXPECT_EQ(304, res5->status);
  12286. svr.stop();
  12287. t.join();
  12288. std::remove(fname);
  12289. }
  12290. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  12291. using namespace httplib;
  12292. Server svr;
  12293. svr.set_mount_point("/static", ".");
  12294. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12295. svr.wait_until_ready();
  12296. Client cli(HOST, PORT);
  12297. // Send If-None-Match: * to a non-existent file
  12298. Headers h = {{"If-None-Match", "*"}};
  12299. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  12300. ASSERT_TRUE(res);
  12301. EXPECT_EQ(404, res->status);
  12302. svr.stop();
  12303. t.join();
  12304. }
  12305. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  12306. using namespace httplib;
  12307. // Create a test file
  12308. const char *fname = "etag_boundary_testfile.txt";
  12309. const char *content = "boundary-test";
  12310. {
  12311. std::ofstream ofs(fname);
  12312. ofs << content;
  12313. ASSERT_TRUE(ofs.good());
  12314. }
  12315. Server svr;
  12316. svr.set_mount_point("/static", ".");
  12317. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12318. svr.wait_until_ready();
  12319. Client cli(HOST, PORT);
  12320. // Get the actual ETag
  12321. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  12322. ASSERT_TRUE(res1);
  12323. ASSERT_EQ(200, res1->status);
  12324. ASSERT_TRUE(res1->has_header("ETag"));
  12325. std::string etag = res1->get_header_value("ETag");
  12326. // Test 1: Very long ETag value (longer than actual ETag)
  12327. // Should NOT match and return 200 (not trigger out-of-bounds read)
  12328. Headers h1 = {{"If-None-Match", "W/"
  12329. "\"very-long-etag-value-that-is-much-longer-"
  12330. "than-the-actual-etag-value\""}};
  12331. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  12332. ASSERT_TRUE(res2);
  12333. EXPECT_EQ(200, res2->status); // Should not match
  12334. // Test 2: Long string followed by wildcard
  12335. // Should match on "*" and return 304 (without out-of-bounds read on the long
  12336. // string)
  12337. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  12338. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  12339. ASSERT_TRUE(res3);
  12340. EXPECT_EQ(304, res3->status); // Should match on "*"
  12341. // Test 3: Wildcard followed by long string
  12342. // Should match on "*" immediately and return 304
  12343. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  12344. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  12345. ASSERT_TRUE(res4);
  12346. EXPECT_EQ(304, res4->status); // Should match on "*"
  12347. // Test 4: Multiple long non-matching values
  12348. // Should NOT match and return 200 (test that all comparisons are safe)
  12349. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  12350. "W/\"second-long-non-matching-value\", "
  12351. "W/\"third-long-non-matching-value\""}};
  12352. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  12353. ASSERT_TRUE(res5);
  12354. EXPECT_EQ(200, res5->status); // Should not match
  12355. // Test 5: Single character that is not "*" (edge case)
  12356. Headers h5 = {{"If-None-Match", "X"}};
  12357. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  12358. ASSERT_TRUE(res6);
  12359. EXPECT_EQ(200, res6->status); // Should not match
  12360. svr.stop();
  12361. t.join();
  12362. std::remove(fname);
  12363. }
  12364. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  12365. using namespace httplib;
  12366. // Create a test file
  12367. const char *fname = "ims_testfile.txt";
  12368. const char *content = "if-modified-since-test";
  12369. {
  12370. std::ofstream ofs(fname);
  12371. ofs << content;
  12372. ASSERT_TRUE(ofs.good());
  12373. }
  12374. Server svr;
  12375. svr.set_mount_point("/static", ".");
  12376. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12377. svr.wait_until_ready();
  12378. Client cli(HOST, PORT);
  12379. // First request: should get 200 with Last-Modified header
  12380. auto res1 = cli.Get("/static/ims_testfile.txt");
  12381. ASSERT_TRUE(res1);
  12382. ASSERT_EQ(200, res1->status);
  12383. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12384. std::string last_modified = res1->get_header_value("Last-Modified");
  12385. EXPECT_FALSE(last_modified.empty());
  12386. // If-Modified-Since with same time: expect 304
  12387. Headers h2 = {{"If-Modified-Since", last_modified}};
  12388. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  12389. ASSERT_TRUE(res2);
  12390. EXPECT_EQ(304, res2->status);
  12391. // If-Modified-Since with future time: expect 304
  12392. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12393. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  12394. ASSERT_TRUE(res3);
  12395. EXPECT_EQ(304, res3->status);
  12396. // If-Modified-Since with past time: expect 200
  12397. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12398. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  12399. ASSERT_TRUE(res4);
  12400. EXPECT_EQ(200, res4->status);
  12401. // If-None-Match takes precedence over If-Modified-Since
  12402. // (send matching ETag with old If-Modified-Since -> should still be 304)
  12403. ASSERT_TRUE(res1->has_header("ETag"));
  12404. std::string etag = res1->get_header_value("ETag");
  12405. Headers h5 = {{"If-None-Match", etag},
  12406. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12407. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  12408. ASSERT_TRUE(res5);
  12409. EXPECT_EQ(304, res5->status);
  12410. svr.stop();
  12411. t.join();
  12412. std::remove(fname);
  12413. }
  12414. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  12415. using namespace httplib;
  12416. Server svr;
  12417. // Endpoint that returns compressible content
  12418. svr.Get("/compressible", [](const Request &, Response &res) {
  12419. // Return a large enough body to trigger compression
  12420. std::string body(1000, 'a');
  12421. res.set_content(body, "text/plain");
  12422. });
  12423. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12424. svr.wait_until_ready();
  12425. Client cli(HOST, PORT);
  12426. // Request with gzip support: should get Vary header when compressed
  12427. cli.set_compress(true);
  12428. auto res1 = cli.Get("/compressible");
  12429. ASSERT_TRUE(res1);
  12430. EXPECT_EQ(200, res1->status);
  12431. // If Content-Encoding is set, Vary should also be set
  12432. if (res1->has_header("Content-Encoding")) {
  12433. EXPECT_TRUE(res1->has_header("Vary"));
  12434. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  12435. }
  12436. // Request without Accept-Encoding header: should not have compression
  12437. Headers h_no_compress;
  12438. auto res2 = cli.Get("/compressible", h_no_compress);
  12439. ASSERT_TRUE(res2);
  12440. EXPECT_EQ(200, res2->status);
  12441. // Verify Vary header is present when compression is applied
  12442. // (the exact behavior depends on server configuration)
  12443. svr.stop();
  12444. t.join();
  12445. }
  12446. TEST(ETagTest, IfRangeWithETag) {
  12447. using namespace httplib;
  12448. // Create a test file with known content
  12449. const char *fname = "if_range_testfile.txt";
  12450. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  12451. {
  12452. std::ofstream ofs(fname);
  12453. ofs << content;
  12454. ASSERT_TRUE(ofs.good());
  12455. }
  12456. Server svr;
  12457. svr.set_mount_point("/static", ".");
  12458. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12459. svr.wait_until_ready();
  12460. Client cli(HOST, PORT);
  12461. // First request: get ETag
  12462. auto res1 = cli.Get("/static/if_range_testfile.txt");
  12463. ASSERT_TRUE(res1);
  12464. ASSERT_EQ(200, res1->status);
  12465. ASSERT_TRUE(res1->has_header("ETag"));
  12466. std::string etag = res1->get_header_value("ETag");
  12467. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  12468. // Since our server generates weak ETags (W/"..."), If-Range with our
  12469. // ETag should NOT result in partial content - it should return full content.
  12470. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  12471. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  12472. ASSERT_TRUE(res2);
  12473. // Weak ETag in If-Range -> full content (200), not partial (206)
  12474. EXPECT_EQ(200, res2->status);
  12475. EXPECT_EQ(content, res2->body);
  12476. EXPECT_FALSE(res2->has_header("Content-Range"));
  12477. // Range request with non-matching If-Range (ETag): should get 200 (full
  12478. // content)
  12479. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  12480. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  12481. ASSERT_TRUE(res3);
  12482. EXPECT_EQ(200, res3->status);
  12483. EXPECT_EQ(content, res3->body);
  12484. EXPECT_FALSE(res3->has_header("Content-Range"));
  12485. // Range request with strong ETag (hypothetical - our server doesn't generate
  12486. // strong ETags, but if client sends a strong ETag that doesn't match, it
  12487. // should return full content)
  12488. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  12489. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  12490. ASSERT_TRUE(res4);
  12491. EXPECT_EQ(200, res4->status);
  12492. EXPECT_EQ(content, res4->body);
  12493. EXPECT_FALSE(res4->has_header("Content-Range"));
  12494. svr.stop();
  12495. t.join();
  12496. std::remove(fname);
  12497. }
  12498. TEST(ETagTest, IfRangeWithDate) {
  12499. using namespace httplib;
  12500. // Create a test file
  12501. const char *fname = "if_range_date_testfile.txt";
  12502. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  12503. {
  12504. std::ofstream ofs(fname);
  12505. ofs << content;
  12506. ASSERT_TRUE(ofs.good());
  12507. }
  12508. Server svr;
  12509. svr.set_mount_point("/static", ".");
  12510. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12511. svr.wait_until_ready();
  12512. Client cli(HOST, PORT);
  12513. // First request: get Last-Modified
  12514. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  12515. ASSERT_TRUE(res1);
  12516. ASSERT_EQ(200, res1->status);
  12517. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12518. std::string last_modified = res1->get_header_value("Last-Modified");
  12519. // Range request with matching If-Range (date): should get 206
  12520. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  12521. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  12522. ASSERT_TRUE(res2);
  12523. EXPECT_EQ(206, res2->status);
  12524. EXPECT_EQ("FGHIJ", res2->body);
  12525. // Range request with old If-Range date: should get 200 (full content)
  12526. Headers h3 = {{"Range", "bytes=5-9"},
  12527. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12528. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  12529. ASSERT_TRUE(res3);
  12530. EXPECT_EQ(200, res3->status);
  12531. EXPECT_EQ(content, res3->body);
  12532. // Range request with future If-Range date: should get 206
  12533. Headers h4 = {{"Range", "bytes=0-4"},
  12534. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12535. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  12536. ASSERT_TRUE(res4);
  12537. EXPECT_EQ(206, res4->status);
  12538. EXPECT_EQ("ABCDE", res4->body);
  12539. svr.stop();
  12540. t.join();
  12541. std::remove(fname);
  12542. }
  12543. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  12544. using namespace httplib;
  12545. const char *fname = "etag_malformed.txt";
  12546. const char *content = "malformed-etag";
  12547. {
  12548. std::ofstream ofs(fname);
  12549. ofs << content;
  12550. ASSERT_TRUE(ofs.good());
  12551. }
  12552. Server svr;
  12553. svr.set_mount_point("/static", ".");
  12554. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12555. svr.wait_until_ready();
  12556. Client cli(HOST, PORT);
  12557. // baseline: should get 200 and an ETag
  12558. auto res1 = cli.Get("/static/etag_malformed.txt");
  12559. ASSERT_TRUE(res1);
  12560. ASSERT_EQ(200, res1->status);
  12561. ASSERT_TRUE(res1->has_header("ETag"));
  12562. // Malformed ETag value (missing quotes) should be treated as non-matching
  12563. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  12564. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  12565. ASSERT_TRUE(res_bad);
  12566. EXPECT_EQ(200, res_bad->status);
  12567. // Whitespace-only header value should be considered invalid / non-matching
  12568. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  12569. "Host: localhost\r\n"
  12570. "If-None-Match: \r\n"
  12571. "Connection: close\r\n"
  12572. "\r\n";
  12573. std::string out;
  12574. ASSERT_TRUE(send_request(5, raw_req, &out));
  12575. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12576. svr.stop();
  12577. t.join();
  12578. std::remove(fname);
  12579. }
  12580. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  12581. using namespace httplib;
  12582. const char *fname = "ims_invalid_format.txt";
  12583. const char *content = "ims-bad-format";
  12584. {
  12585. std::ofstream ofs(fname);
  12586. ofs << content;
  12587. ASSERT_TRUE(ofs.good());
  12588. }
  12589. Server svr;
  12590. svr.set_mount_point("/static", ".");
  12591. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12592. svr.wait_until_ready();
  12593. Client cli(HOST, PORT);
  12594. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  12595. ASSERT_TRUE(res1);
  12596. ASSERT_EQ(200, res1->status);
  12597. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12598. // If-Modified-Since with invalid format should not result in 304
  12599. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  12600. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  12601. ASSERT_TRUE(res_bad);
  12602. EXPECT_EQ(200, res_bad->status);
  12603. // If-Range with invalid date format should be treated as mismatch -> full
  12604. // content (200)
  12605. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  12606. {"If-Range", "invalid-date"}};
  12607. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  12608. ASSERT_TRUE(res_ifrange);
  12609. EXPECT_EQ(200, res_ifrange->status);
  12610. svr.stop();
  12611. t.join();
  12612. std::remove(fname);
  12613. }
  12614. TEST(ETagTest, IfRangeWithMalformedETag) {
  12615. using namespace httplib;
  12616. const char *fname = "ifrange_malformed.txt";
  12617. const std::string content = "0123456789";
  12618. {
  12619. std::ofstream ofs(fname);
  12620. ofs << content;
  12621. ASSERT_TRUE(ofs.good());
  12622. }
  12623. Server svr;
  12624. svr.set_mount_point("/static", ".");
  12625. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12626. svr.wait_until_ready();
  12627. Client cli(HOST, PORT);
  12628. // First request: get ETag
  12629. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  12630. ASSERT_TRUE(res1);
  12631. ASSERT_EQ(200, res1->status);
  12632. ASSERT_TRUE(res1->has_header("ETag"));
  12633. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  12634. // full content (200)
  12635. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  12636. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  12637. ASSERT_TRUE(res2);
  12638. EXPECT_EQ(200, res2->status);
  12639. EXPECT_EQ(content, res2->body);
  12640. svr.stop();
  12641. t.join();
  12642. std::remove(fname);
  12643. }
  12644. TEST(ETagTest, ExtremeLargeDateValues) {
  12645. using namespace httplib;
  12646. const char *fname = "ims_extreme_date.txt";
  12647. const char *content = "ims-extreme-date";
  12648. {
  12649. std::ofstream ofs(fname);
  12650. ofs << content;
  12651. ASSERT_TRUE(ofs.good());
  12652. }
  12653. Server svr;
  12654. svr.set_mount_point("/static", ".");
  12655. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12656. svr.wait_until_ready();
  12657. Client cli(HOST, PORT);
  12658. auto res1 = cli.Get(std::string("/static/") + fname);
  12659. ASSERT_TRUE(res1);
  12660. ASSERT_EQ(200, res1->status);
  12661. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12662. // Extremely large year that may overflow date parsing routines.
  12663. Headers h_large_date = {
  12664. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12665. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  12666. ASSERT_TRUE(res_bad);
  12667. // Expect server to treat this as invalid/mismatch and return full content
  12668. EXPECT_EQ(200, res_bad->status);
  12669. // If-Range with extremely large date should be treated as mismatch -> full
  12670. // content (200)
  12671. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  12672. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12673. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  12674. ASSERT_TRUE(res_ifrange);
  12675. EXPECT_EQ(200, res_ifrange->status);
  12676. svr.stop();
  12677. t.join();
  12678. std::remove(fname);
  12679. }
  12680. TEST(ETagTest, NegativeFileModificationTime) {
  12681. using namespace httplib;
  12682. const char *fname = "ims_negative_mtime.txt";
  12683. const std::string content = "negative-mtime";
  12684. {
  12685. std::ofstream ofs(fname);
  12686. ofs << content;
  12687. ASSERT_TRUE(ofs.good());
  12688. }
  12689. // Try to set file mtime to a negative value. This may fail on some
  12690. // platforms/filesystems; if it fails, the test will still verify server
  12691. // behaves safely by performing a regular conditional request.
  12692. #if defined(__APPLE__) || defined(__linux__)
  12693. bool set_negative = false;
  12694. do {
  12695. struct timeval times[2];
  12696. // access time: now
  12697. times[0].tv_sec = time(nullptr);
  12698. times[0].tv_usec = 0;
  12699. // modification time: negative (e.g., -1)
  12700. times[1].tv_sec = -1;
  12701. times[1].tv_usec = 0;
  12702. if (utimes(fname, times) == 0) { set_negative = true; }
  12703. } while (0);
  12704. #else
  12705. bool set_negative = false;
  12706. #endif
  12707. Server svr;
  12708. svr.set_mount_point("/static", ".");
  12709. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12710. svr.wait_until_ready();
  12711. Client cli(HOST, PORT);
  12712. auto res1 = cli.Get(std::string("/static/") + fname);
  12713. ASSERT_TRUE(res1);
  12714. ASSERT_EQ(200, res1->status);
  12715. bool has_last_modified = res1->has_header("Last-Modified");
  12716. std::string last_modified;
  12717. if (has_last_modified) {
  12718. last_modified = res1->get_header_value("Last-Modified");
  12719. }
  12720. if (set_negative) {
  12721. // If we successfully set a negative mtime, ensure server returns a
  12722. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  12723. // with an old date and ensure server handles it without crash.
  12724. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  12725. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  12726. ASSERT_TRUE(res2);
  12727. // Behavior may vary; at minimum ensure server responds (200 or 304).
  12728. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  12729. } else {
  12730. // Could not set negative mtime on this platform; fall back to verifying
  12731. // that normal invalid/malformed dates are treated safely (non-304).
  12732. Headers h_bad_date = {
  12733. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12734. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  12735. ASSERT_TRUE(res_bad);
  12736. EXPECT_EQ(200, res_bad->status);
  12737. }
  12738. svr.stop();
  12739. t.join();
  12740. std::remove(fname);
  12741. }
  12742. //==============================================================================
  12743. // SSE Parsing Tests
  12744. //==============================================================================
  12745. class SSEParsingTest : public ::testing::Test {
  12746. protected:
  12747. // Test helper that mimics SSE parsing behavior
  12748. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  12749. int &retry_ms) {
  12750. // Blank line signals end of event
  12751. if (line.empty() || line == "\r") { return true; }
  12752. // Lines starting with ':' are comments (ignored)
  12753. if (!line.empty() && line[0] == ':') { return false; }
  12754. // Find the colon separator
  12755. auto colon_pos = line.find(':');
  12756. if (colon_pos == std::string::npos) {
  12757. // Line with no colon is treated as field name with empty value
  12758. return false;
  12759. }
  12760. std::string field = line.substr(0, colon_pos);
  12761. std::string value;
  12762. // Value starts after colon, skip optional single space
  12763. if (colon_pos + 1 < line.size()) {
  12764. size_t value_start = colon_pos + 1;
  12765. if (line[value_start] == ' ') { value_start++; }
  12766. value = line.substr(value_start);
  12767. // Remove trailing \r if present
  12768. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  12769. }
  12770. // Handle known fields
  12771. if (field == "event") {
  12772. msg.event = value;
  12773. } else if (field == "data") {
  12774. // Multiple data lines are concatenated with newlines
  12775. if (!msg.data.empty()) { msg.data += "\n"; }
  12776. msg.data += value;
  12777. } else if (field == "id") {
  12778. // Empty id is valid (clears the last event ID)
  12779. msg.id = value;
  12780. } else if (field == "retry") {
  12781. // Parse retry interval in milliseconds
  12782. {
  12783. int v = 0;
  12784. auto res =
  12785. detail::from_chars(value.data(), value.data() + value.size(), v);
  12786. if (res.ec == std::errc{}) { retry_ms = v; }
  12787. }
  12788. }
  12789. // Unknown fields are ignored per SSE spec
  12790. return false;
  12791. }
  12792. };
  12793. // Test: Single-line data
  12794. TEST_F(SSEParsingTest, SingleLineData) {
  12795. sse::SSEMessage msg;
  12796. int retry_ms = 3000;
  12797. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  12798. EXPECT_EQ(msg.data, "hello");
  12799. EXPECT_EQ(msg.event, "message");
  12800. // Blank line ends event
  12801. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12802. }
  12803. // Test: Multi-line data
  12804. TEST_F(SSEParsingTest, MultiLineData) {
  12805. sse::SSEMessage msg;
  12806. int retry_ms = 3000;
  12807. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  12808. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  12809. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  12810. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  12811. }
  12812. // Test: Custom event types
  12813. TEST_F(SSEParsingTest, CustomEventType) {
  12814. sse::SSEMessage msg;
  12815. int retry_ms = 3000;
  12816. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  12817. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  12818. EXPECT_EQ(msg.event, "update");
  12819. EXPECT_EQ(msg.data, "payload");
  12820. }
  12821. // Test: Event ID handling
  12822. TEST_F(SSEParsingTest, EventIdHandling) {
  12823. sse::SSEMessage msg;
  12824. int retry_ms = 3000;
  12825. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  12826. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  12827. EXPECT_EQ(msg.id, "12345");
  12828. }
  12829. // Test: Empty event ID (clears last event ID)
  12830. TEST_F(SSEParsingTest, EmptyEventId) {
  12831. sse::SSEMessage msg;
  12832. msg.id = "previous";
  12833. int retry_ms = 3000;
  12834. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  12835. EXPECT_EQ(msg.id, "");
  12836. }
  12837. // Test: Retry field parsing
  12838. TEST_F(SSEParsingTest, RetryFieldParsing) {
  12839. sse::SSEMessage msg;
  12840. int retry_ms = 3000;
  12841. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  12842. EXPECT_EQ(retry_ms, 5000);
  12843. }
  12844. // Test: Invalid retry value
  12845. TEST_F(SSEParsingTest, InvalidRetryValue) {
  12846. sse::SSEMessage msg;
  12847. int retry_ms = 3000;
  12848. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  12849. EXPECT_EQ(retry_ms, 3000); // Unchanged
  12850. }
  12851. // Test: Comments (lines starting with :)
  12852. TEST_F(SSEParsingTest, CommentsIgnored) {
  12853. sse::SSEMessage msg;
  12854. int retry_ms = 3000;
  12855. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  12856. EXPECT_EQ(msg.data, "");
  12857. EXPECT_EQ(msg.event, "message");
  12858. }
  12859. // Test: Colon in value
  12860. TEST_F(SSEParsingTest, ColonInValue) {
  12861. sse::SSEMessage msg;
  12862. int retry_ms = 3000;
  12863. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  12864. EXPECT_EQ(msg.data, "hello:world:test");
  12865. }
  12866. // Test: Line with no colon (field name only)
  12867. TEST_F(SSEParsingTest, FieldNameOnly) {
  12868. sse::SSEMessage msg;
  12869. int retry_ms = 3000;
  12870. // According to SSE spec, this is treated as field name with empty value
  12871. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  12872. // Since we don't recognize "data" without colon, data should be empty
  12873. EXPECT_EQ(msg.data, "");
  12874. }
  12875. // Test: Trailing \r handling
  12876. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  12877. sse::SSEMessage msg;
  12878. int retry_ms = 3000;
  12879. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  12880. EXPECT_EQ(msg.data, "hello");
  12881. }
  12882. // Test: Unknown fields ignored
  12883. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  12884. sse::SSEMessage msg;
  12885. int retry_ms = 3000;
  12886. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  12887. EXPECT_EQ(msg.data, "");
  12888. EXPECT_EQ(msg.event, "message");
  12889. }
  12890. // Test: Space after colon is optional
  12891. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  12892. sse::SSEMessage msg1, msg2;
  12893. int retry_ms = 3000;
  12894. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  12895. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  12896. EXPECT_EQ(msg1.data, "hello");
  12897. EXPECT_EQ(msg2.data, "hello");
  12898. }
  12899. // Test: SSEMessage clear
  12900. TEST_F(SSEParsingTest, MessageClear) {
  12901. sse::SSEMessage msg;
  12902. msg.event = "custom";
  12903. msg.data = "some data";
  12904. msg.id = "123";
  12905. msg.clear();
  12906. EXPECT_EQ(msg.event, "message");
  12907. EXPECT_EQ(msg.data, "");
  12908. EXPECT_EQ(msg.id, "");
  12909. }
  12910. // Test: Complete event parsing
  12911. TEST_F(SSEParsingTest, CompleteEventParsing) {
  12912. sse::SSEMessage msg;
  12913. int retry_ms = 3000;
  12914. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  12915. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  12916. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  12917. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  12918. // Blank line ends event
  12919. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12920. EXPECT_EQ(msg.event, "notification");
  12921. EXPECT_EQ(msg.id, "evt-42");
  12922. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  12923. EXPECT_EQ(retry_ms, 1000);
  12924. }
  12925. //==============================================================================
  12926. // Integration Tests with Server
  12927. //==============================================================================
  12928. class SSEIntegrationTest : public ::testing::Test {
  12929. protected:
  12930. void SetUp() override {
  12931. stop_server_.store(false);
  12932. events_.clear();
  12933. server_ = httplib::detail::make_unique<Server>();
  12934. setup_server();
  12935. start_server();
  12936. }
  12937. void TearDown() override {
  12938. stop_server_.store(true);
  12939. event_cv_.notify_all();
  12940. server_->stop();
  12941. if (server_thread_.joinable()) { server_thread_.join(); }
  12942. }
  12943. void setup_server() {
  12944. // Simple SSE endpoint
  12945. server_->Get("/events", [this](const Request &req, Response &res) {
  12946. auto last_id = req.get_header_value("Last-Event-ID");
  12947. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  12948. res.set_chunked_content_provider(
  12949. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  12950. std::unique_lock<std::mutex> lock(event_mutex_);
  12951. if (event_cv_.wait_for(
  12952. lock, std::chrono::milliseconds(200), [this] {
  12953. return !events_.empty() || stop_server_.load();
  12954. })) {
  12955. if (stop_server_.load()) { return false; }
  12956. if (!events_.empty()) {
  12957. std::string event = events_.front();
  12958. events_.erase(events_.begin());
  12959. sink.write(event.data(), event.size());
  12960. return true;
  12961. }
  12962. }
  12963. return !stop_server_.load();
  12964. });
  12965. });
  12966. // Endpoint that returns error
  12967. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  12968. res.status = 500;
  12969. res.set_content("Internal Server Error", "text/plain");
  12970. });
  12971. // Endpoint for custom event types
  12972. server_->Get("/custom-events", [](const Request &, Response &res) {
  12973. res.set_chunked_content_provider(
  12974. "text/event-stream", [](size_t offset, DataSink &sink) {
  12975. if (offset == 0) {
  12976. std::string event = "event: update\ndata: updated\n\n"
  12977. "event: delete\ndata: deleted\n\n";
  12978. sink.write(event.data(), event.size());
  12979. }
  12980. return false; // End stream after sending
  12981. });
  12982. });
  12983. }
  12984. void start_server() {
  12985. port_ = server_->bind_to_any_port(HOST);
  12986. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  12987. // Wait for server to start
  12988. while (!server_->is_running()) {
  12989. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12990. }
  12991. }
  12992. int get_port() const { return port_; }
  12993. void send_event(const std::string &event) {
  12994. std::lock_guard<std::mutex> lock(event_mutex_);
  12995. events_.push_back(event);
  12996. event_cv_.notify_all();
  12997. }
  12998. std::unique_ptr<Server> server_;
  12999. std::thread server_thread_;
  13000. std::mutex event_mutex_;
  13001. std::condition_variable event_cv_;
  13002. std::vector<std::string> events_;
  13003. std::atomic<bool> stop_server_{false};
  13004. std::string last_received_event_id_;
  13005. int port_ = 0;
  13006. };
  13007. // Test: Successful connection and on_open callback
  13008. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  13009. // Add a simple endpoint that sends one event and closes
  13010. server_->Get("/simple-event", [](const Request &, Response &res) {
  13011. res.set_chunked_content_provider(
  13012. "text/event-stream", [](size_t offset, DataSink &sink) {
  13013. if (offset == 0) {
  13014. std::string event = "data: hello\n\n";
  13015. sink.write(event.data(), event.size());
  13016. }
  13017. return false; // Close stream after sending
  13018. });
  13019. });
  13020. Client client("localhost", get_port());
  13021. sse::SSEClient sse(client, "/simple-event");
  13022. std::atomic<bool> open_called{false};
  13023. std::atomic<bool> message_received{false};
  13024. sse.on_open([&open_called]() { open_called.store(true); });
  13025. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  13026. if (msg.data == "hello") { message_received.store(true); }
  13027. });
  13028. sse.set_reconnect_interval(100);
  13029. sse.set_max_reconnect_attempts(1);
  13030. // Start async
  13031. sse.start_async();
  13032. // Wait for message to be processed
  13033. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13034. sse.stop();
  13035. EXPECT_TRUE(open_called.load());
  13036. EXPECT_TRUE(message_received.load());
  13037. }
  13038. // Test: on_message callback
  13039. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  13040. // Endpoint that sends multiple events then closes
  13041. server_->Get("/multi-event", [](const Request &, Response &res) {
  13042. res.set_chunked_content_provider(
  13043. "text/event-stream", [](size_t offset, DataSink &sink) {
  13044. if (offset == 0) {
  13045. std::string events = "data: message1\n\ndata: message2\n\n";
  13046. sink.write(events.data(), events.size());
  13047. }
  13048. return false;
  13049. });
  13050. });
  13051. Client client("localhost", get_port());
  13052. sse::SSEClient sse(client, "/multi-event");
  13053. std::vector<std::string> received_messages;
  13054. std::mutex messages_mutex;
  13055. sse.on_message([&](const sse::SSEMessage &msg) {
  13056. std::lock_guard<std::mutex> lock(messages_mutex);
  13057. received_messages.push_back(msg.data);
  13058. });
  13059. sse.set_reconnect_interval(100);
  13060. sse.set_max_reconnect_attempts(1);
  13061. sse.start_async();
  13062. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13063. sse.stop();
  13064. std::lock_guard<std::mutex> lock(messages_mutex);
  13065. EXPECT_GE(received_messages.size(), 2u);
  13066. if (received_messages.size() >= 2) {
  13067. EXPECT_EQ(received_messages[0], "message1");
  13068. EXPECT_EQ(received_messages[1], "message2");
  13069. }
  13070. }
  13071. // Test: on_event for specific types
  13072. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  13073. Client client("localhost", get_port());
  13074. sse::SSEClient sse(client, "/custom-events");
  13075. std::atomic<bool> update_received{false};
  13076. std::atomic<bool> delete_received{false};
  13077. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  13078. if (msg.data == "updated") { update_received.store(true); }
  13079. });
  13080. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  13081. if (msg.data == "deleted") { delete_received.store(true); }
  13082. });
  13083. sse.set_max_reconnect_attempts(1);
  13084. sse.start_async();
  13085. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  13086. sse.stop();
  13087. EXPECT_TRUE(update_received.load());
  13088. EXPECT_TRUE(delete_received.load());
  13089. }
  13090. // Test: on_error callback on connection failure
  13091. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  13092. // Connect to a non-existent port
  13093. Client client("localhost", 59999);
  13094. sse::SSEClient sse(client, "/events");
  13095. std::atomic<bool> error_called{false};
  13096. Error received_error = Error::Success;
  13097. sse.on_error([&](Error err) {
  13098. error_called.store(true);
  13099. received_error = err;
  13100. });
  13101. sse.set_reconnect_interval(50);
  13102. sse.set_max_reconnect_attempts(1);
  13103. sse.start_async();
  13104. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13105. sse.stop();
  13106. EXPECT_TRUE(error_called.load());
  13107. EXPECT_NE(received_error, Error::Success);
  13108. }
  13109. // Test: Last-Event-ID header sent on reconnect
  13110. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  13111. // Endpoint that sends event with ID
  13112. server_->Get("/event-with-id", [](const Request &, Response &res) {
  13113. res.set_chunked_content_provider(
  13114. "text/event-stream", [](size_t offset, DataSink &sink) {
  13115. if (offset == 0) {
  13116. std::string event = "id: evt-123\ndata: test\n\n";
  13117. sink.write(event.data(), event.size());
  13118. }
  13119. return false;
  13120. });
  13121. });
  13122. Client client("localhost", get_port());
  13123. sse::SSEClient sse(client, "/event-with-id");
  13124. std::atomic<bool> id_received{false};
  13125. sse.on_message([&](const sse::SSEMessage &msg) {
  13126. if (!msg.id.empty()) { id_received.store(true); }
  13127. });
  13128. sse.set_reconnect_interval(100);
  13129. sse.set_max_reconnect_attempts(1);
  13130. sse.start_async();
  13131. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13132. sse.stop();
  13133. EXPECT_TRUE(id_received.load());
  13134. EXPECT_EQ(sse.last_event_id(), "evt-123");
  13135. }
  13136. // Test: Manual stop
  13137. TEST_F(SSEIntegrationTest, ManualStop) {
  13138. // Endpoint that sends one event and stays open briefly
  13139. std::atomic<bool> handler_running{true};
  13140. server_->Get("/stay-open", [&handler_running](const Request &,
  13141. Response &res) {
  13142. res.set_chunked_content_provider(
  13143. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  13144. if (offset == 0) {
  13145. std::string event = "data: connected\n\n";
  13146. sink.write(event.data(), event.size());
  13147. }
  13148. // Keep connection open while handler_running is true
  13149. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  13150. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13151. }
  13152. return false;
  13153. });
  13154. });
  13155. Client client("localhost", get_port());
  13156. sse::SSEClient sse(client, "/stay-open");
  13157. std::atomic<bool> connected{false};
  13158. sse.on_open([&connected]() { connected.store(true); });
  13159. sse.set_reconnect_interval(100);
  13160. sse.set_max_reconnect_attempts(1);
  13161. sse.start_async();
  13162. // Wait for connection to establish
  13163. for (int i = 0; i < 20 && !connected.load(); ++i) {
  13164. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13165. }
  13166. EXPECT_TRUE(connected.load());
  13167. EXPECT_TRUE(sse.is_connected());
  13168. // Signal handler to stop
  13169. handler_running.store(false);
  13170. // Stop SSE client
  13171. sse.stop();
  13172. EXPECT_FALSE(sse.is_connected());
  13173. }
  13174. // Test: SSEClient with custom headers
  13175. TEST_F(SSEIntegrationTest, CustomHeaders) {
  13176. // Setup a server endpoint that checks for custom header
  13177. std::atomic<bool> header_received{false};
  13178. server_->Get("/header-check", [&](const Request &req, Response &res) {
  13179. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  13180. header_received.store(true);
  13181. }
  13182. res.set_chunked_content_provider("text/event-stream",
  13183. [](size_t, DataSink &) { return false; });
  13184. });
  13185. Client client("localhost", get_port());
  13186. Headers headers = {{"X-Custom-Header", "custom-value"}};
  13187. sse::SSEClient sse(client, "/header-check", headers);
  13188. sse.set_max_reconnect_attempts(1);
  13189. sse.start_async();
  13190. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13191. sse.stop();
  13192. EXPECT_TRUE(header_received.load());
  13193. }
  13194. // Test: Reconnect interval configuration
  13195. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  13196. Client client("localhost", get_port());
  13197. sse::SSEClient sse(client, "/events");
  13198. auto &result = sse.set_reconnect_interval(500);
  13199. // Builder pattern should return reference to self
  13200. EXPECT_EQ(&result, &sse);
  13201. }
  13202. // Test: Max reconnect attempts
  13203. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  13204. // Connect to non-existent port to force reconnects
  13205. Client client("localhost", 59998);
  13206. sse::SSEClient sse(client, "/events");
  13207. std::atomic<int> error_count{0};
  13208. sse.on_error([&](Error) { error_count.fetch_add(1); });
  13209. sse.set_reconnect_interval(50);
  13210. sse.set_max_reconnect_attempts(2);
  13211. auto start = std::chrono::steady_clock::now();
  13212. sse.start(); // Blocking call
  13213. auto end = std::chrono::steady_clock::now();
  13214. // Should have stopped after 2 failed attempts
  13215. EXPECT_GE(error_count.load(), 2);
  13216. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  13217. auto duration =
  13218. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  13219. #ifdef _WIN32
  13220. // Windows is much slower for socket connection failures
  13221. EXPECT_LT(duration.count(), 7000);
  13222. #else
  13223. EXPECT_LT(duration.count(), 1000);
  13224. #endif
  13225. }
  13226. // Test: Multi-line data in integration
  13227. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  13228. // Endpoint with multi-line data
  13229. server_->Get("/multiline-data", [](const Request &, Response &res) {
  13230. res.set_chunked_content_provider(
  13231. "text/event-stream", [](size_t offset, DataSink &sink) {
  13232. if (offset == 0) {
  13233. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  13234. sink.write(event.data(), event.size());
  13235. }
  13236. return false;
  13237. });
  13238. });
  13239. Client client("localhost", get_port());
  13240. sse::SSEClient sse(client, "/multiline-data");
  13241. std::string received_data;
  13242. std::mutex data_mutex;
  13243. sse.on_message([&](const sse::SSEMessage &msg) {
  13244. std::lock_guard<std::mutex> lock(data_mutex);
  13245. received_data = msg.data;
  13246. });
  13247. sse.set_reconnect_interval(100);
  13248. sse.set_max_reconnect_attempts(1);
  13249. sse.start_async();
  13250. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13251. sse.stop();
  13252. std::lock_guard<std::mutex> lock(data_mutex);
  13253. EXPECT_EQ(received_data, "line1\nline2\nline3");
  13254. }
  13255. // Test: Auto-reconnect after server disconnection
  13256. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  13257. std::atomic<int> connection_count{0};
  13258. std::atomic<int> message_count{0};
  13259. // Endpoint that sends one event and closes, forcing reconnect
  13260. server_->Get("/reconnect-test",
  13261. [&connection_count](const Request &, Response &res) {
  13262. connection_count.fetch_add(1);
  13263. res.set_chunked_content_provider(
  13264. "text/event-stream", [](size_t offset, DataSink &sink) {
  13265. if (offset == 0) {
  13266. std::string event = "data: hello\n\n";
  13267. sink.write(event.data(), event.size());
  13268. }
  13269. return false; // Close connection after sending
  13270. });
  13271. });
  13272. Client client("localhost", get_port());
  13273. sse::SSEClient sse(client, "/reconnect-test");
  13274. sse.on_message([&message_count](const sse::SSEMessage &) {
  13275. message_count.fetch_add(1);
  13276. });
  13277. sse.set_reconnect_interval(100);
  13278. sse.set_max_reconnect_attempts(3);
  13279. sse.start_async();
  13280. // Wait long enough for multiple reconnects
  13281. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13282. sse.stop();
  13283. // Should have connected multiple times (initial + reconnects)
  13284. EXPECT_GE(connection_count.load(), 2);
  13285. // Should have received messages from multiple connections
  13286. EXPECT_GE(message_count.load(), 2);
  13287. }
  13288. // Test: Last-Event-ID sent on reconnect
  13289. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  13290. std::atomic<int> connection_count{0};
  13291. std::vector<std::string> received_last_event_ids;
  13292. std::mutex id_mutex;
  13293. // Endpoint that checks Last-Event-ID header and sends event with ID
  13294. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  13295. int conn = connection_count.fetch_add(1);
  13296. // Capture the Last-Event-ID header from each connection
  13297. {
  13298. std::lock_guard<std::mutex> lock(id_mutex);
  13299. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  13300. }
  13301. res.set_chunked_content_provider(
  13302. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  13303. if (offset == 0) {
  13304. std::string event =
  13305. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  13306. sink.write(event.data(), event.size());
  13307. }
  13308. return false;
  13309. });
  13310. });
  13311. Client client("localhost", get_port());
  13312. sse::SSEClient sse(client, "/reconnect-with-id");
  13313. sse.set_reconnect_interval(100);
  13314. sse.set_max_reconnect_attempts(3);
  13315. sse.start_async();
  13316. // Wait for at least 2 connections
  13317. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13318. sse.stop();
  13319. // Verify behavior
  13320. std::lock_guard<std::mutex> lock(id_mutex);
  13321. EXPECT_GE(received_last_event_ids.size(), 2u);
  13322. // First connection should have no Last-Event-ID
  13323. if (!received_last_event_ids.empty()) {
  13324. EXPECT_EQ(received_last_event_ids[0], "");
  13325. }
  13326. // Second connection should have Last-Event-ID from first connection
  13327. if (received_last_event_ids.size() >= 2) {
  13328. EXPECT_EQ(received_last_event_ids[1], "event-0");
  13329. }
  13330. }
  13331. // Test: set_headers updates headers used on reconnect
  13332. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  13333. std::vector<std::string> received_tokens;
  13334. std::mutex token_mutex;
  13335. // Endpoint that captures Authorization header
  13336. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  13337. {
  13338. std::lock_guard<std::mutex> lock(token_mutex);
  13339. received_tokens.push_back(req.get_header_value("Authorization"));
  13340. }
  13341. res.set_chunked_content_provider(
  13342. "text/event-stream", [](size_t offset, DataSink &sink) {
  13343. if (offset == 0) {
  13344. std::string event = "data: hello\n\n";
  13345. sink.write(event.data(), event.size());
  13346. }
  13347. return false; // Close connection to trigger reconnect
  13348. });
  13349. });
  13350. Client client("localhost", get_port());
  13351. Headers headers = {{"Authorization", "Bearer old-token"}};
  13352. sse::SSEClient sse(client, "/auth-check", headers);
  13353. // Update headers on each successful connection
  13354. sse.on_open(
  13355. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  13356. sse.set_reconnect_interval(100);
  13357. sse.set_max_reconnect_attempts(3);
  13358. sse.start_async();
  13359. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13360. sse.stop();
  13361. std::lock_guard<std::mutex> lock(token_mutex);
  13362. ASSERT_GE(received_tokens.size(), 2u);
  13363. // First connection uses original header
  13364. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  13365. // Second connection uses updated header from set_headers
  13366. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  13367. }
  13368. // Test: 401 allows reconnection (so on_error can refresh headers)
  13369. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  13370. std::atomic<int> connection_count{0};
  13371. // Endpoint: returns 401 on first attempt, 200 on second
  13372. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  13373. int conn = connection_count.fetch_add(1);
  13374. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  13375. res.status = StatusCode::Unauthorized_401;
  13376. res.set_content("Unauthorized", "text/plain");
  13377. return;
  13378. }
  13379. res.set_chunked_content_provider(
  13380. "text/event-stream", [](size_t offset, DataSink &sink) {
  13381. if (offset == 0) {
  13382. std::string event = "data: authenticated\n\n";
  13383. sink.write(event.data(), event.size());
  13384. }
  13385. return false;
  13386. });
  13387. });
  13388. Client client("localhost", get_port());
  13389. Headers headers = {{"Authorization", "Bearer expired"}};
  13390. sse::SSEClient sse(client, "/auth-retry", headers);
  13391. std::atomic<bool> message_received{false};
  13392. // Refresh token on error
  13393. sse.on_error(
  13394. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  13395. sse.on_message([&](const sse::SSEMessage &msg) {
  13396. if (msg.data == "authenticated") { message_received.store(true); }
  13397. });
  13398. sse.set_reconnect_interval(100);
  13399. sse.set_max_reconnect_attempts(3);
  13400. sse.start_async();
  13401. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13402. sse.stop();
  13403. // Should have reconnected after 401 and succeeded with new token
  13404. EXPECT_GE(connection_count.load(), 2);
  13405. EXPECT_TRUE(message_received.load());
  13406. }
  13407. TEST(Issue2318Test, EmptyHostString) {
  13408. {
  13409. httplib::Client cli_empty("", PORT);
  13410. auto res = cli_empty.Get("/");
  13411. ASSERT_FALSE(res);
  13412. EXPECT_EQ(httplib::Error::Connection, res.error());
  13413. }
  13414. {
  13415. httplib::Client cli(" ", PORT);
  13416. auto res = cli.Get("/");
  13417. ASSERT_FALSE(res);
  13418. EXPECT_EQ(httplib::Error::Connection, res.error());
  13419. }
  13420. }
  13421. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13422. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  13423. Server svr;
  13424. // Set a small payload limit (1KB)
  13425. svr.set_payload_max_length(1024);
  13426. svr.Post("/test", [&](const Request &req, Response &res) {
  13427. res.set_content("Body size: " + std::to_string(req.body.size()),
  13428. "text/plain");
  13429. });
  13430. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13431. auto se = detail::scope_exit([&] {
  13432. svr.stop();
  13433. listen_thread.join();
  13434. });
  13435. svr.wait_until_ready();
  13436. // Create data that compresses well but exceeds limit when decompressed
  13437. // 8KB of repeated null bytes compresses to a very small size
  13438. std::string original_data(8 * 1024, '\0');
  13439. // Compress the data using gzip
  13440. std::string compressed_data;
  13441. detail::gzip_compressor compressor;
  13442. compressor.compress(original_data.data(), original_data.size(), true,
  13443. [&](const char *data, size_t size) {
  13444. compressed_data.append(data, size);
  13445. return true;
  13446. });
  13447. // Verify compression worked (compressed should be much smaller)
  13448. ASSERT_LT(compressed_data.size(), original_data.size());
  13449. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  13450. // Send compressed data with Content-Encoding: gzip
  13451. Client cli(HOST, PORT);
  13452. Headers headers = {{"Content-Encoding", "gzip"}};
  13453. auto res =
  13454. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  13455. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  13456. ASSERT_TRUE(res);
  13457. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13458. }
  13459. #endif
  13460. // ============================================================================
  13461. // OpenSSL-Specific Tests
  13462. // ============================================================================
  13463. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13464. X509 *readCertificate(const std::string &strFileName) {
  13465. std::ifstream inStream(strFileName);
  13466. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  13467. std::istreambuf_iterator<char>());
  13468. if (strCertPEM.empty()) return (nullptr);
  13469. BIO *pbCert = BIO_new(BIO_s_mem());
  13470. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  13471. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  13472. BIO_free(pbCert);
  13473. return (pCert);
  13474. }
  13475. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  13476. std::ifstream inStream(strFileName);
  13477. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  13478. std::istreambuf_iterator<char>());
  13479. if (strPrivateKeyPEM.empty()) return (nullptr);
  13480. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  13481. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  13482. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  13483. BIO_free(pbPrivKey);
  13484. return (pPrivateKey);
  13485. }
  13486. TEST(BindServerTest, UpdateCerts) {
  13487. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13488. int port = svr.bind_to_any_port("0.0.0.0");
  13489. ASSERT_TRUE(svr.is_valid());
  13490. ASSERT_TRUE(port > 0);
  13491. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13492. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13493. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13494. ASSERT_TRUE(cert != nullptr);
  13495. ASSERT_TRUE(ca_cert != nullptr);
  13496. ASSERT_TRUE(key != nullptr);
  13497. X509_STORE *cert_store = X509_STORE_new();
  13498. X509_STORE_add_cert(cert_store, ca_cert);
  13499. // svr.update_certs(cert, key, cert_store); // deprecated
  13500. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13501. CLIENT_CA_CERT_FILE);
  13502. ASSERT_TRUE(svr.is_valid());
  13503. svr.stop();
  13504. X509_STORE_free(cert_store);
  13505. X509_free(cert);
  13506. X509_free(ca_cert);
  13507. EVP_PKEY_free(key);
  13508. }
  13509. // Test that SSLServer(X509*, EVP_PKEY*, X509_STORE*) constructor sets
  13510. // client CA list correctly for TLS handshake
  13511. TEST(SSLClientServerTest, X509ConstructorSetsClientCAList) {
  13512. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13513. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13514. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13515. ASSERT_TRUE(cert != nullptr);
  13516. ASSERT_TRUE(ca_cert != nullptr);
  13517. ASSERT_TRUE(key != nullptr);
  13518. X509_STORE *cert_store = X509_STORE_new();
  13519. X509_STORE_add_cert(cert_store, ca_cert);
  13520. // Use X509-based constructor (deprecated but should still work correctly)
  13521. #pragma GCC diagnostic push
  13522. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  13523. SSLServer svr(cert, key, cert_store);
  13524. #pragma GCC diagnostic pop
  13525. ASSERT_TRUE(svr.is_valid());
  13526. // Verify that client CA list is set in SSL_CTX
  13527. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13528. ASSERT_TRUE(ssl_ctx != nullptr);
  13529. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13530. ASSERT_TRUE(ca_list != nullptr);
  13531. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13532. X509_free(cert);
  13533. X509_free(ca_cert);
  13534. EVP_PKEY_free(key);
  13535. }
  13536. // Test that update_certs() updates client CA list correctly
  13537. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  13538. // Start with file-based constructor
  13539. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13540. ASSERT_TRUE(svr.is_valid());
  13541. // Initially no client CA list should be set
  13542. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13543. ASSERT_TRUE(ssl_ctx != nullptr);
  13544. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  13545. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  13546. EXPECT_EQ(0, count_before);
  13547. // Now update with client CA (PEM string)
  13548. std::string cert_pem, key_pem, ca_pem;
  13549. read_file(SERVER_CERT_FILE, cert_pem);
  13550. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13551. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13552. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  13553. ASSERT_TRUE(svr.is_valid());
  13554. // Now client CA list should be set
  13555. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  13556. ASSERT_TRUE(ca_list_after != nullptr);
  13557. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  13558. }
  13559. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  13560. // Test that the file-path SSLServer constructor properly sets the client CA
  13561. // list that is sent to clients during the TLS handshake (CertificateRequest)
  13562. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13563. ASSERT_TRUE(svr.is_valid());
  13564. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13565. ASSERT_TRUE(ssl_ctx != nullptr);
  13566. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13567. ASSERT_TRUE(ca_list != nullptr);
  13568. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13569. }
  13570. #endif
  13571. // ============================================================================
  13572. // MbedTLS-Specific Tests
  13573. // ============================================================================
  13574. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  13575. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  13576. using namespace httplib::tls;
  13577. // Track if callback was invoked
  13578. bool callback_invoked = false;
  13579. // The callback receives void* ctx which is actually MbedTlsContext*
  13580. // We can access the mbedtls_ssl_config via the context
  13581. auto setup_callback = [&callback_invoked](void *ctx) {
  13582. callback_invoked = true;
  13583. // Cast to MbedTlsContext* to access the ssl config
  13584. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  13585. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  13586. // Use static variables to hold certificate data (simplified for test)
  13587. static mbedtls_x509_crt own_cert;
  13588. static mbedtls_pk_context own_key;
  13589. static mbedtls_x509_crt ca_chain;
  13590. static bool initialized = false;
  13591. if (!initialized) {
  13592. mbedtls_x509_crt_init(&own_cert);
  13593. mbedtls_pk_init(&own_key);
  13594. mbedtls_x509_crt_init(&ca_chain);
  13595. // Load server certificate
  13596. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  13597. return false;
  13598. }
  13599. // Load server private key
  13600. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  13601. #if MBEDTLS_VERSION_MAJOR >= 3
  13602. ,
  13603. mbedtls_ctr_drbg_random, nullptr
  13604. #endif
  13605. ) != 0) {
  13606. return false;
  13607. }
  13608. // Load CA chain for client verification
  13609. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  13610. return false;
  13611. }
  13612. initialized = true;
  13613. }
  13614. // Configure the SSL config
  13615. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  13616. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  13617. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  13618. // Set minimum TLS version using mbedTLS native API
  13619. #if MBEDTLS_VERSION_MAJOR >= 3
  13620. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  13621. #else
  13622. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  13623. MBEDTLS_SSL_MINOR_VERSION_3);
  13624. #endif
  13625. return true;
  13626. };
  13627. SSLServer svr(setup_callback);
  13628. ASSERT_TRUE(svr.is_valid());
  13629. ASSERT_TRUE(callback_invoked);
  13630. svr.Get("/test", [&](const Request &req, Response &res) {
  13631. res.set_content("test", "text/plain");
  13632. auto cert = req.peer_cert();
  13633. ASSERT_TRUE(static_cast<bool>(cert));
  13634. auto common_name = cert.subject_cn();
  13635. EXPECT_EQ("Common Name", common_name);
  13636. });
  13637. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13638. auto se = detail::scope_exit([&] {
  13639. svr.stop();
  13640. t.join();
  13641. ASSERT_FALSE(svr.is_running());
  13642. });
  13643. svr.wait_until_ready();
  13644. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13645. cli.enable_server_certificate_verification(false);
  13646. cli.set_connection_timeout(30);
  13647. auto res = cli.Get("/test");
  13648. ASSERT_TRUE(res);
  13649. ASSERT_EQ(StatusCode::OK_200, res->status);
  13650. }
  13651. #endif
  13652. // WebSocket Tests
  13653. TEST(WebSocketTest, RSVBitsMustBeZero) {
  13654. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  13655. // defining the meaning of these bits has been negotiated.
  13656. auto make_frame = [](uint8_t first_byte) {
  13657. std::string frame;
  13658. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  13659. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  13660. frame += "Hello";
  13661. return frame;
  13662. };
  13663. // RSV1 set (0x40)
  13664. {
  13665. detail::BufferStream strm;
  13666. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  13667. ws::Opcode opcode;
  13668. std::string payload;
  13669. bool fin;
  13670. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13671. false, 1024));
  13672. }
  13673. // RSV2 set (0x20)
  13674. {
  13675. detail::BufferStream strm;
  13676. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  13677. ws::Opcode opcode;
  13678. std::string payload;
  13679. bool fin;
  13680. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13681. false, 1024));
  13682. }
  13683. // RSV3 set (0x10)
  13684. {
  13685. detail::BufferStream strm;
  13686. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  13687. ws::Opcode opcode;
  13688. std::string payload;
  13689. bool fin;
  13690. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13691. false, 1024));
  13692. }
  13693. // No RSV bits set - should succeed
  13694. {
  13695. detail::BufferStream strm;
  13696. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  13697. ws::Opcode opcode;
  13698. std::string payload;
  13699. bool fin;
  13700. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13701. false, 1024));
  13702. EXPECT_EQ(ws::Opcode::Text, opcode);
  13703. EXPECT_EQ("Hello", payload);
  13704. EXPECT_TRUE(fin);
  13705. }
  13706. }
  13707. TEST(WebSocketTest, ControlFrameValidation) {
  13708. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  13709. // payload length <= 125.
  13710. // Ping with FIN=0 - must be rejected
  13711. {
  13712. detail::BufferStream strm;
  13713. std::string frame;
  13714. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  13715. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13716. strm.write(frame.data(), frame.size());
  13717. ws::Opcode opcode;
  13718. std::string payload;
  13719. bool fin;
  13720. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13721. false, 1024));
  13722. }
  13723. // Close with FIN=0 - must be rejected
  13724. {
  13725. detail::BufferStream strm;
  13726. std::string frame;
  13727. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  13728. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13729. strm.write(frame.data(), frame.size());
  13730. ws::Opcode opcode;
  13731. std::string payload;
  13732. bool fin;
  13733. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13734. false, 1024));
  13735. }
  13736. // Ping with payload_len=126 (extended length) - must be rejected
  13737. {
  13738. detail::BufferStream strm;
  13739. std::string frame;
  13740. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13741. frame += static_cast<char>(126); // payload_len=126 (>125)
  13742. frame += static_cast<char>(0x00); // extended length high byte
  13743. frame += static_cast<char>(126); // extended length low byte
  13744. frame += std::string(126, 'x');
  13745. strm.write(frame.data(), frame.size());
  13746. ws::Opcode opcode;
  13747. std::string payload;
  13748. bool fin;
  13749. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13750. false, 1024));
  13751. }
  13752. // Ping with FIN=1 and payload_len=125 - should succeed
  13753. {
  13754. detail::BufferStream strm;
  13755. std::string frame;
  13756. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13757. frame += static_cast<char>(125); // payload_len=125
  13758. frame += std::string(125, 'x');
  13759. strm.write(frame.data(), frame.size());
  13760. ws::Opcode opcode;
  13761. std::string payload;
  13762. bool fin;
  13763. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13764. false, 1024));
  13765. EXPECT_EQ(ws::Opcode::Ping, opcode);
  13766. EXPECT_EQ(125u, payload.size());
  13767. EXPECT_TRUE(fin);
  13768. }
  13769. }
  13770. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  13771. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  13772. // length MUST be 0.
  13773. // MSB set - must be rejected
  13774. {
  13775. detail::BufferStream strm;
  13776. std::string frame;
  13777. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13778. frame += static_cast<char>(127); // 64-bit extended length
  13779. frame += static_cast<char>(0x80); // MSB set (invalid)
  13780. frame += std::string(7, '\0'); // remaining 7 bytes of length
  13781. strm.write(frame.data(), frame.size());
  13782. ws::Opcode opcode;
  13783. std::string payload;
  13784. bool fin;
  13785. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13786. false, 1024));
  13787. }
  13788. // MSB clear - should pass length parsing (will be rejected by max_len,
  13789. // but that's a different check; use a small length to verify)
  13790. {
  13791. detail::BufferStream strm;
  13792. std::string frame;
  13793. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13794. frame += static_cast<char>(127); // 64-bit extended length
  13795. frame += std::string(7, '\0'); // high bytes = 0
  13796. frame += static_cast<char>(0x03); // length = 3
  13797. frame += "abc";
  13798. strm.write(frame.data(), frame.size());
  13799. ws::Opcode opcode;
  13800. std::string payload;
  13801. bool fin;
  13802. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13803. false, 1024));
  13804. EXPECT_EQ(ws::Opcode::Text, opcode);
  13805. EXPECT_EQ("abc", payload);
  13806. }
  13807. }
  13808. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  13809. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  13810. // Valid UTF-8
  13811. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  13812. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  13813. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  13814. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  13815. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  13816. // Invalid UTF-8
  13817. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  13818. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  13819. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  13820. EXPECT_FALSE(
  13821. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  13822. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  13823. }
  13824. TEST(WebSocketTest, ConnectAndDisconnect) {
  13825. Server svr;
  13826. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  13827. std::string msg;
  13828. while (ws.read(msg)) {}
  13829. });
  13830. auto port = svr.bind_to_any_port(HOST);
  13831. std::thread t([&]() { svr.listen_after_bind(); });
  13832. svr.wait_until_ready();
  13833. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  13834. ASSERT_TRUE(client.connect());
  13835. EXPECT_TRUE(client.is_open());
  13836. client.close();
  13837. EXPECT_FALSE(client.is_open());
  13838. svr.stop();
  13839. t.join();
  13840. }
  13841. TEST(WebSocketTest, ValidURL) {
  13842. ws::WebSocketClient ws1("ws://localhost:8080/path");
  13843. EXPECT_TRUE(ws1.is_valid());
  13844. ws::WebSocketClient ws2("ws://example.com/path");
  13845. EXPECT_TRUE(ws2.is_valid());
  13846. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  13847. EXPECT_TRUE(ws3.is_valid());
  13848. #ifdef CPPHTTPLIB_SSL_ENABLED
  13849. ws::WebSocketClient wss1("wss://example.com/path");
  13850. EXPECT_TRUE(wss1.is_valid());
  13851. ws::WebSocketClient wss2("wss://example.com:443/path");
  13852. EXPECT_TRUE(wss2.is_valid());
  13853. #endif
  13854. }
  13855. TEST(WebSocketTest, InvalidURL) {
  13856. // No scheme
  13857. ws::WebSocketClient ws1("localhost:8080/path");
  13858. EXPECT_FALSE(ws1.is_valid());
  13859. // No path
  13860. ws::WebSocketClient ws2("ws://localhost:8080");
  13861. EXPECT_FALSE(ws2.is_valid());
  13862. // Empty string
  13863. ws::WebSocketClient ws3("");
  13864. EXPECT_FALSE(ws3.is_valid());
  13865. // Missing host
  13866. ws::WebSocketClient ws4("ws://:8080/path");
  13867. EXPECT_FALSE(ws4.is_valid());
  13868. // Port number overflow — should not crash
  13869. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  13870. EXPECT_FALSE(ws5.is_valid());
  13871. // Port out of range
  13872. ws::WebSocketClient ws6("ws://localhost:99999/path");
  13873. EXPECT_FALSE(ws6.is_valid());
  13874. }
  13875. TEST(WebSocketTest, UnsupportedScheme) {
  13876. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13877. ws::WebSocketClient ws1("http://localhost:8080/path");
  13878. EXPECT_FALSE(ws1.is_valid());
  13879. ws::WebSocketClient ws2("https://localhost:8080/path");
  13880. EXPECT_FALSE(ws2.is_valid());
  13881. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  13882. EXPECT_FALSE(ws3.is_valid());
  13883. #else
  13884. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  13885. std::invalid_argument);
  13886. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  13887. std::invalid_argument);
  13888. #endif
  13889. }
  13890. TEST(WebSocketTest, ConnectWhenInvalid) {
  13891. ws::WebSocketClient ws("not a valid url");
  13892. EXPECT_FALSE(ws.is_valid());
  13893. EXPECT_FALSE(ws.connect());
  13894. }
  13895. TEST(WebSocketTest, DefaultPort) {
  13896. ws::WebSocketClient ws1("ws://example.com/path");
  13897. EXPECT_TRUE(ws1.is_valid());
  13898. // ws:// defaults to port 80 (verified by successful parse)
  13899. #ifdef CPPHTTPLIB_SSL_ENABLED
  13900. ws::WebSocketClient ws2("wss://example.com/path");
  13901. EXPECT_TRUE(ws2.is_valid());
  13902. // wss:// defaults to port 443 (verified by successful parse)
  13903. #endif
  13904. }
  13905. TEST(WebSocketTest, IPv6LiteralAddress) {
  13906. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  13907. EXPECT_TRUE(ws1.is_valid());
  13908. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  13909. EXPECT_TRUE(ws2.is_valid());
  13910. }
  13911. TEST(WebSocketTest, ComplexPath) {
  13912. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  13913. EXPECT_TRUE(ws1.is_valid());
  13914. ws::WebSocketClient ws2("ws://localhost:8080/");
  13915. EXPECT_TRUE(ws2.is_valid());
  13916. }
  13917. class WebSocketIntegrationTest : public ::testing::Test {
  13918. protected:
  13919. void SetUp() override {
  13920. server_ = httplib::detail::make_unique<Server>();
  13921. setup_server();
  13922. start_server();
  13923. }
  13924. void TearDown() override {
  13925. server_->stop();
  13926. if (server_thread_.joinable()) { server_thread_.join(); }
  13927. }
  13928. void setup_server() {
  13929. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  13930. std::string msg;
  13931. ws::ReadResult ret;
  13932. while ((ret = ws.read(msg))) {
  13933. if (ret == ws::Binary) {
  13934. ws.send(msg.data(), msg.size());
  13935. } else {
  13936. ws.send(msg);
  13937. }
  13938. }
  13939. });
  13940. server_->WebSocket("/ws-echo-string",
  13941. [](const Request &, ws::WebSocket &ws) {
  13942. std::string msg;
  13943. while (ws.read(msg)) {
  13944. ws.send("echo: " + msg);
  13945. }
  13946. });
  13947. server_->WebSocket(
  13948. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  13949. // Echo back request metadata
  13950. ws.send("path:" + req.path);
  13951. ws.send("header:" + req.get_header_value("X-Test-Header"));
  13952. std::string msg;
  13953. while (ws.read(msg)) {}
  13954. });
  13955. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  13956. std::string msg;
  13957. ws.read(msg); // wait for a message
  13958. ws.close();
  13959. });
  13960. server_->WebSocket("/ws-close-status",
  13961. [](const Request &, ws::WebSocket &ws) {
  13962. std::string msg;
  13963. ws.read(msg); // wait for a message
  13964. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  13965. });
  13966. server_->WebSocket(
  13967. "/ws-subprotocol",
  13968. [](const Request &, ws::WebSocket &ws) {
  13969. std::string msg;
  13970. while (ws.read(msg)) {
  13971. ws.send(msg);
  13972. }
  13973. },
  13974. [](const std::vector<std::string> &protocols) -> std::string {
  13975. for (const auto &p : protocols) {
  13976. if (p == "graphql-ws") { return p; }
  13977. }
  13978. return "";
  13979. });
  13980. }
  13981. void start_server() {
  13982. port_ = server_->bind_to_any_port(HOST);
  13983. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13984. server_->wait_until_ready();
  13985. }
  13986. std::unique_ptr<Server> server_;
  13987. std::thread server_thread_;
  13988. int port_ = 0;
  13989. };
  13990. TEST_F(WebSocketIntegrationTest, TextEcho) {
  13991. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13992. "/ws-echo");
  13993. ASSERT_TRUE(client.connect());
  13994. ASSERT_TRUE(client.is_open());
  13995. ASSERT_TRUE(client.send("Hello WebSocket"));
  13996. std::string msg;
  13997. EXPECT_EQ(ws::Text, client.read(msg));
  13998. EXPECT_EQ("Hello WebSocket", msg);
  13999. client.close();
  14000. }
  14001. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  14002. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14003. "/ws-echo");
  14004. ASSERT_TRUE(client.connect());
  14005. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  14006. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  14007. std::string msg;
  14008. EXPECT_EQ(ws::Binary, client.read(msg));
  14009. EXPECT_EQ(binary_data, msg);
  14010. client.close();
  14011. }
  14012. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  14013. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14014. "/ws-echo");
  14015. ASSERT_TRUE(client.connect());
  14016. for (int i = 0; i < 10; i++) {
  14017. auto text = "message " + std::to_string(i);
  14018. ASSERT_TRUE(client.send(text));
  14019. std::string msg;
  14020. ASSERT_TRUE(client.read(msg));
  14021. EXPECT_EQ(text, msg);
  14022. }
  14023. client.close();
  14024. }
  14025. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  14026. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14027. "/ws-close");
  14028. ASSERT_TRUE(client.connect());
  14029. // Send a message to trigger the server to close
  14030. ASSERT_TRUE(client.send("trigger close"));
  14031. // The server will close, so read should return false
  14032. std::string msg;
  14033. EXPECT_FALSE(client.read(msg));
  14034. EXPECT_FALSE(client.is_open());
  14035. }
  14036. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  14037. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14038. "/ws-echo");
  14039. ASSERT_TRUE(client.connect());
  14040. // 128KB message
  14041. std::string large_data(128 * 1024, 'X');
  14042. ASSERT_TRUE(client.send(large_data));
  14043. std::string msg;
  14044. ASSERT_TRUE(client.read(msg));
  14045. EXPECT_EQ(large_data, msg);
  14046. client.close();
  14047. }
  14048. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  14049. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14050. "/ws-echo");
  14051. ASSERT_TRUE(client.connect());
  14052. const int num_threads = 4;
  14053. std::vector<std::thread> threads;
  14054. std::atomic<int> send_count{0};
  14055. for (int t = 0; t < num_threads; t++) {
  14056. threads.emplace_back([&client, &send_count, t]() {
  14057. for (int i = 0; i < 5; i++) {
  14058. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  14059. if (client.send(text)) { send_count++; }
  14060. }
  14061. });
  14062. }
  14063. for (auto &th : threads) {
  14064. th.join();
  14065. }
  14066. int received = 0;
  14067. std::string msg;
  14068. while (received < send_count.load()) {
  14069. if (!client.read(msg)) { break; }
  14070. received++;
  14071. }
  14072. EXPECT_EQ(send_count.load(), received);
  14073. client.close();
  14074. }
  14075. TEST_F(WebSocketIntegrationTest, ReadString) {
  14076. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14077. "/ws-echo-string");
  14078. ASSERT_TRUE(client.connect());
  14079. ASSERT_TRUE(client.send("hello"));
  14080. std::string msg;
  14081. ASSERT_TRUE(client.read(msg));
  14082. EXPECT_EQ("echo: hello", msg);
  14083. ASSERT_TRUE(client.send("world"));
  14084. ASSERT_TRUE(client.read(msg));
  14085. EXPECT_EQ("echo: world", msg);
  14086. client.close();
  14087. }
  14088. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  14089. Headers headers = {{"X-Test-Header", "test-value"}};
  14090. ws::WebSocketClient client(
  14091. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  14092. ASSERT_TRUE(client.connect());
  14093. std::string msg;
  14094. ASSERT_TRUE(client.read(msg));
  14095. EXPECT_EQ("path:/ws-request-info", msg);
  14096. ASSERT_TRUE(client.read(msg));
  14097. EXPECT_EQ("header:test-value", msg);
  14098. client.close();
  14099. }
  14100. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  14101. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14102. "/ws-echo");
  14103. client.set_read_timeout(1, 0); // 1 second
  14104. ASSERT_TRUE(client.connect());
  14105. // Don't send anything — server echo handler waits for a message,
  14106. // so read() should time out and return false.
  14107. std::string msg;
  14108. EXPECT_FALSE(client.read(msg));
  14109. }
  14110. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  14111. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14112. "/ws-echo");
  14113. client.set_read_timeout(5, 0);
  14114. ASSERT_TRUE(client.connect());
  14115. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14116. // The server should reject it and close the connection.
  14117. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  14118. client.send(oversized);
  14119. // The server's read() should have failed due to payload limit,
  14120. // so our read() should return false (connection closed).
  14121. std::string msg;
  14122. EXPECT_FALSE(client.read(msg));
  14123. }
  14124. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  14125. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14126. "/ws-echo");
  14127. client.set_read_timeout(10, 0);
  14128. ASSERT_TRUE(client.connect());
  14129. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14130. // This should succeed.
  14131. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  14132. ASSERT_TRUE(client.send(at_limit));
  14133. std::string msg;
  14134. ASSERT_TRUE(client.read(msg));
  14135. EXPECT_EQ(at_limit.size(), msg.size());
  14136. client.close();
  14137. }
  14138. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  14139. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14140. "/nonexistent");
  14141. EXPECT_FALSE(client.connect());
  14142. EXPECT_FALSE(client.is_open());
  14143. }
  14144. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  14145. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14146. "/ws-echo");
  14147. ASSERT_TRUE(client.connect());
  14148. ASSERT_TRUE(client.send(""));
  14149. std::string msg;
  14150. EXPECT_EQ(ws::Text, client.read(msg));
  14151. EXPECT_EQ("", msg);
  14152. client.close();
  14153. }
  14154. TEST_F(WebSocketIntegrationTest, Reconnect) {
  14155. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14156. "/ws-echo");
  14157. // First connection
  14158. ASSERT_TRUE(client.connect());
  14159. ASSERT_TRUE(client.send("first"));
  14160. std::string msg;
  14161. ASSERT_TRUE(client.read(msg));
  14162. EXPECT_EQ("first", msg);
  14163. client.close();
  14164. EXPECT_FALSE(client.is_open());
  14165. // Reconnect using the same client object
  14166. ASSERT_TRUE(client.connect());
  14167. ASSERT_TRUE(client.is_open());
  14168. ASSERT_TRUE(client.send("second"));
  14169. ASSERT_TRUE(client.read(msg));
  14170. EXPECT_EQ("second", msg);
  14171. client.close();
  14172. }
  14173. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  14174. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14175. "/ws-close-status");
  14176. ASSERT_TRUE(client.connect());
  14177. // Trigger the server to close with GoingAway status
  14178. ASSERT_TRUE(client.send("trigger"));
  14179. // read() should return false after receiving the close frame
  14180. std::string msg;
  14181. EXPECT_FALSE(client.read(msg));
  14182. EXPECT_FALSE(client.is_open());
  14183. }
  14184. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  14185. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14186. "/ws-echo");
  14187. ASSERT_TRUE(client.connect());
  14188. client.close(ws::CloseStatus::GoingAway, "client leaving");
  14189. EXPECT_FALSE(client.is_open());
  14190. }
  14191. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  14192. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  14193. ws::WebSocketClient client(
  14194. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14195. ASSERT_TRUE(client.connect());
  14196. // Server should have selected graphql-ws
  14197. EXPECT_EQ("graphql-ws", client.subprotocol());
  14198. client.close();
  14199. }
  14200. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  14201. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  14202. ws::WebSocketClient client(
  14203. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14204. ASSERT_TRUE(client.connect());
  14205. // Server should not have selected any subprotocol
  14206. EXPECT_TRUE(client.subprotocol().empty());
  14207. client.close();
  14208. }
  14209. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  14210. // Connect without requesting any subprotocol
  14211. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14212. "/ws-subprotocol");
  14213. ASSERT_TRUE(client.connect());
  14214. EXPECT_TRUE(client.subprotocol().empty());
  14215. client.close();
  14216. }
  14217. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  14218. Server svr;
  14219. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  14220. if (!req.has_header("Authorization")) {
  14221. res.status = StatusCode::Unauthorized_401;
  14222. res.set_content("Unauthorized", "text/plain");
  14223. return Server::HandlerResponse::Handled;
  14224. }
  14225. return Server::HandlerResponse::Unhandled;
  14226. });
  14227. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14228. std::string msg;
  14229. while (ws.read(msg)) {
  14230. ws.send(msg);
  14231. }
  14232. });
  14233. auto port = svr.bind_to_any_port("localhost");
  14234. std::thread t([&]() { svr.listen_after_bind(); });
  14235. svr.wait_until_ready();
  14236. // Without Authorization header - should be rejected before upgrade
  14237. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  14238. EXPECT_FALSE(client1.connect());
  14239. // With Authorization header - should succeed
  14240. Headers headers = {{"Authorization", "Bearer token123"}};
  14241. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  14242. headers);
  14243. ASSERT_TRUE(client2.connect());
  14244. ASSERT_TRUE(client2.send("hello"));
  14245. std::string msg;
  14246. ASSERT_TRUE(client2.read(msg));
  14247. EXPECT_EQ("hello", msg);
  14248. client2.close();
  14249. svr.stop();
  14250. t.join();
  14251. }
  14252. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14253. class WebSocketSSLIntegrationTest : public ::testing::Test {
  14254. protected:
  14255. void SetUp() override {
  14256. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  14257. SERVER_PRIVATE_KEY_FILE);
  14258. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14259. std::string msg;
  14260. ws::ReadResult ret;
  14261. while ((ret = ws.read(msg))) {
  14262. if (ret == ws::Binary) {
  14263. ws.send(msg.data(), msg.size());
  14264. } else {
  14265. ws.send(msg);
  14266. }
  14267. }
  14268. });
  14269. port_ = server_->bind_to_any_port(HOST);
  14270. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14271. server_->wait_until_ready();
  14272. }
  14273. void TearDown() override {
  14274. server_->stop();
  14275. if (server_thread_.joinable()) { server_thread_.join(); }
  14276. }
  14277. std::unique_ptr<SSLServer> server_;
  14278. std::thread server_thread_;
  14279. int port_ = 0;
  14280. };
  14281. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  14282. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  14283. "/ws-echo");
  14284. client.enable_server_certificate_verification(false);
  14285. ASSERT_TRUE(client.connect());
  14286. ASSERT_TRUE(client.is_open());
  14287. ASSERT_TRUE(client.send("Hello WSS"));
  14288. std::string msg;
  14289. EXPECT_EQ(ws::Text, client.read(msg));
  14290. EXPECT_EQ("Hello WSS", msg);
  14291. client.close();
  14292. }
  14293. #endif
  14294. #if !defined(_WIN32)
  14295. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  14296. auto secret_dir = std::string("./symlink_test_secret");
  14297. auto served_dir = std::string("./symlink_test_served");
  14298. auto secret_file = secret_dir + "/secret.txt";
  14299. auto symlink_path = served_dir + "/escape";
  14300. // Setup: create directories and files
  14301. mkdir(secret_dir.c_str(), 0755);
  14302. mkdir(served_dir.c_str(), 0755);
  14303. {
  14304. std::ofstream ofs(secret_file);
  14305. ofs << "SECRET_DATA";
  14306. }
  14307. // Create symlink using absolute path so it resolves correctly
  14308. char abs_secret[PATH_MAX];
  14309. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  14310. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  14311. auto se = detail::scope_exit([&] {
  14312. unlink(symlink_path.c_str());
  14313. unlink(secret_file.c_str());
  14314. rmdir(served_dir.c_str());
  14315. rmdir(secret_dir.c_str());
  14316. });
  14317. Server svr;
  14318. svr.set_mount_point("/", served_dir);
  14319. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  14320. auto se2 = detail::scope_exit([&] {
  14321. svr.stop();
  14322. listen_thread.join();
  14323. });
  14324. svr.wait_until_ready();
  14325. Client cli("localhost", PORT);
  14326. // Symlink pointing outside base dir should be blocked
  14327. auto res = cli.Get("/escape/secret.txt");
  14328. ASSERT_TRUE(res);
  14329. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  14330. }
  14331. #endif