test.cc 525 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #if __cplusplus >= 202002L
  28. inline std::string u8_to_string(const char8_t *s) {
  29. return std::string(reinterpret_cast<const char *>(s));
  30. }
  31. #define U8(x) u8_to_string(u8##x)
  32. #else
  33. #define U8(x) u8##x
  34. #endif
  35. #define SERVER_CERT_FILE "./cert.pem"
  36. #define SERVER_CERT2_FILE "./cert2.pem"
  37. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  38. #define CA_CERT_FILE "./ca-bundle.crt"
  39. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  40. #define CLIENT_CA_CERT_DIR "."
  41. #define CLIENT_CERT_FILE "./client.cert.pem"
  42. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  43. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  44. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  45. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  46. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  47. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  48. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  49. using namespace std;
  50. using namespace httplib;
  51. const char *HOST = "localhost";
  52. static int get_base_port() {
  53. const char *shard = getenv("GTEST_SHARD_INDEX");
  54. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  55. }
  56. const int PORT = get_base_port();
  57. const string LONG_QUERY_VALUE = string(25000, '@');
  58. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  59. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  60. const string TOO_LONG_QUERY_URL =
  61. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  62. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  63. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  64. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  65. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  66. return file.name == key;
  67. });
  68. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  69. return *it;
  70. #else
  71. if (it != items.end()) { return *it; }
  72. throw std::runtime_error("invalid multipart form data name error");
  73. #endif
  74. }
  75. static void read_file(const std::string &path, std::string &out) {
  76. std::ifstream fs(path, std::ios_base::binary);
  77. if (!fs) {
  78. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  79. return;
  80. #else
  81. throw std::runtime_error("File not found: " + path);
  82. #endif
  83. }
  84. fs.seekg(0, std::ios_base::end);
  85. auto size = fs.tellg();
  86. fs.seekg(0);
  87. out.resize(static_cast<size_t>(size));
  88. fs.read(&out[0], static_cast<std::streamsize>(size));
  89. }
  90. void performance_test(const char *host) {
  91. Server svr;
  92. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  93. res.set_content("Benchmark Response", "text/plain");
  94. });
  95. auto listen_thread = std::thread([&]() { svr.listen(host, PORT); });
  96. auto se = detail::scope_exit([&] {
  97. svr.stop();
  98. listen_thread.join();
  99. ASSERT_FALSE(svr.is_running());
  100. });
  101. svr.wait_until_ready();
  102. Client cli(host, PORT);
  103. // Warm-up request to establish connection and resolve DNS
  104. auto warmup_res = cli.Get("/benchmark");
  105. ASSERT_TRUE(warmup_res); // Ensure server is responding correctly
  106. // Run multiple trials and collect timings
  107. const int num_trials = 20;
  108. std::vector<int64_t> timings;
  109. timings.reserve(num_trials);
  110. for (int i = 0; i < num_trials; i++) {
  111. auto start = std::chrono::high_resolution_clock::now();
  112. auto res = cli.Get("/benchmark");
  113. auto end = std::chrono::high_resolution_clock::now();
  114. auto elapsed =
  115. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  116. .count();
  117. // Assertions after timing measurement to avoid overhead
  118. ASSERT_TRUE(res);
  119. EXPECT_EQ(StatusCode::OK_200, res->status);
  120. timings.push_back(elapsed);
  121. }
  122. // Calculate 25th percentile (lower quartile)
  123. std::sort(timings.begin(), timings.end());
  124. auto p25 = timings[num_trials / 4];
  125. // Format timings for output
  126. std::ostringstream timings_str;
  127. timings_str << "[";
  128. for (size_t i = 0; i < timings.size(); i++) {
  129. if (i > 0) timings_str << ", ";
  130. timings_str << timings[i];
  131. }
  132. timings_str << "]";
  133. // Localhost HTTP GET should be fast even in CI environments
  134. EXPECT_LE(p25, 5) << "25th percentile performance is too slow: " << p25
  135. << "ms (Issue #1777). Timings: " << timings_str.str();
  136. }
  137. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  138. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  139. class UnixSocketTest : public ::testing::Test {
  140. protected:
  141. void TearDown() override { std::remove(pathname_.c_str()); }
  142. void client_GET(const std::string &addr) {
  143. httplib::Client cli{addr};
  144. cli.set_address_family(AF_UNIX);
  145. ASSERT_TRUE(cli.is_valid());
  146. const auto &result = cli.Get(pattern_);
  147. ASSERT_TRUE(result) << "error: " << result.error();
  148. const auto &resp = result.value();
  149. EXPECT_EQ(resp.status, StatusCode::OK_200);
  150. EXPECT_EQ(resp.body, content_);
  151. }
  152. static std::string make_sock_path() {
  153. const char *shard = getenv("GTEST_SHARD_INDEX");
  154. return shard ? std::string("./httplib-server-") + shard + ".sock"
  155. : "./httplib-server.sock";
  156. }
  157. const std::string pathname_{make_sock_path()};
  158. const std::string pattern_{"/hi"};
  159. const std::string content_{"Hello World!"};
  160. };
  161. TEST_F(UnixSocketTest, pathname) {
  162. httplib::Server svr;
  163. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  164. res.set_content(content_, "text/plain");
  165. });
  166. std::thread t{[&] {
  167. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  168. }};
  169. auto se = detail::scope_exit([&] {
  170. svr.stop();
  171. t.join();
  172. ASSERT_FALSE(svr.is_running());
  173. });
  174. svr.wait_until_ready();
  175. ASSERT_TRUE(svr.is_running());
  176. client_GET(pathname_);
  177. }
  178. #if defined(__linux__) || \
  179. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  180. TEST_F(UnixSocketTest, PeerPid) {
  181. httplib::Server svr;
  182. std::string remote_port_val;
  183. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  184. res.set_content(content_, "text/plain");
  185. remote_port_val = std::to_string(req.remote_port);
  186. });
  187. std::thread t{[&] {
  188. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  189. }};
  190. auto se = detail::scope_exit([&] {
  191. svr.stop();
  192. t.join();
  193. ASSERT_FALSE(svr.is_running());
  194. });
  195. svr.wait_until_ready();
  196. ASSERT_TRUE(svr.is_running());
  197. client_GET(pathname_);
  198. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  199. }
  200. #endif
  201. #ifdef __linux__
  202. TEST_F(UnixSocketTest, abstract) {
  203. constexpr char svr_path[]{"\x00httplib-server.sock"};
  204. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  205. httplib::Server svr;
  206. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  207. res.set_content(content_, "text/plain");
  208. });
  209. std::thread t{[&] {
  210. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  211. }};
  212. auto se = detail::scope_exit([&] {
  213. svr.stop();
  214. t.join();
  215. ASSERT_FALSE(svr.is_running());
  216. });
  217. svr.wait_until_ready();
  218. ASSERT_TRUE(svr.is_running());
  219. client_GET(abstract_addr);
  220. }
  221. #endif
  222. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  223. httplib::Server svr;
  224. std::string received_host_header;
  225. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  226. // Capture the Host header sent by the client
  227. auto host_iter = req.headers.find("Host");
  228. if (host_iter != req.headers.end()) {
  229. received_host_header = host_iter->second;
  230. }
  231. res.set_content(content_, "text/plain");
  232. });
  233. std::thread t{[&] {
  234. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  235. }};
  236. auto se = detail::scope_exit([&] {
  237. svr.stop();
  238. t.join();
  239. ASSERT_FALSE(svr.is_running());
  240. });
  241. svr.wait_until_ready();
  242. ASSERT_TRUE(svr.is_running());
  243. // Test that Host header is automatically set to "localhost" for Unix socket
  244. // connections
  245. httplib::Client cli{pathname_};
  246. cli.set_address_family(AF_UNIX);
  247. ASSERT_TRUE(cli.is_valid());
  248. const auto &result = cli.Get(pattern_);
  249. ASSERT_TRUE(result) << "error: " << result.error();
  250. const auto &resp = result.value();
  251. EXPECT_EQ(resp.status, StatusCode::OK_200);
  252. EXPECT_EQ(resp.body, content_);
  253. // Verify that Host header was automatically set to "localhost"
  254. EXPECT_EQ(received_host_header, "localhost");
  255. }
  256. #ifndef _WIN32
  257. TEST(SocketStream, wait_writable_UNIX) {
  258. int fds[2];
  259. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  260. const auto asSocketStream = [&](socket_t fd,
  261. std::function<bool(Stream &)> func) {
  262. return detail::process_client_socket(
  263. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  264. };
  265. asSocketStream(fds[0], [&](Stream &s0) {
  266. EXPECT_EQ(s0.socket(), fds[0]);
  267. EXPECT_TRUE(s0.wait_writable());
  268. EXPECT_TRUE(s0.is_peer_alive());
  269. EXPECT_EQ(0, close(fds[1]));
  270. EXPECT_FALSE(s0.is_peer_alive());
  271. return true;
  272. });
  273. EXPECT_EQ(0, close(fds[0]));
  274. }
  275. TEST(SocketStream, wait_writable_INET) {
  276. sockaddr_in addr;
  277. memset(&addr, 0, sizeof(addr));
  278. addr.sin_family = AF_INET;
  279. addr.sin_port = htons(PORT + 1);
  280. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  281. int disconnected_svr_sock = -1;
  282. std::thread svr{[&] {
  283. const int s = socket(AF_INET, SOCK_STREAM, 0);
  284. ASSERT_LE(0, s);
  285. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  286. ASSERT_EQ(0, listen(s, 1));
  287. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  288. ASSERT_EQ(0, close(s));
  289. }};
  290. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  291. std::thread cli{[&] {
  292. const int s = socket(AF_INET, SOCK_STREAM, 0);
  293. ASSERT_LE(0, s);
  294. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  295. ASSERT_EQ(0, close(s));
  296. }};
  297. cli.join();
  298. svr.join();
  299. ASSERT_NE(disconnected_svr_sock, -1);
  300. const auto asSocketStream = [&](socket_t fd,
  301. std::function<bool(Stream &)> func) {
  302. return detail::process_client_socket(
  303. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  304. };
  305. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  306. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  307. // wait_writable() returns true because select_write() only checks if the
  308. // send buffer has space. Peer disconnection is detected later by send().
  309. EXPECT_TRUE(ss.wait_writable());
  310. return true;
  311. });
  312. ASSERT_EQ(0, close(disconnected_svr_sock));
  313. }
  314. #endif // #ifndef _WIN32
  315. TEST(ClientTest, MoveConstructible) {
  316. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  317. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  318. }
  319. TEST(ClientTest, MoveAssignable) {
  320. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  321. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  322. }
  323. #ifdef _WIN32
  324. TEST(StartupTest, WSAStartup) {
  325. WSADATA wsaData;
  326. int ret = WSAStartup(0x0002, &wsaData);
  327. ASSERT_EQ(0, ret);
  328. }
  329. #endif
  330. TEST(DecodePathTest, PercentCharacter) {
  331. EXPECT_EQ(
  332. decode_path_component(
  333. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  334. U8("descrip=Gastos áéíóúñÑ 6"));
  335. }
  336. TEST(DecodePathTest, PercentCharacterNUL) {
  337. string expected;
  338. expected.push_back('x');
  339. expected.push_back('\0');
  340. expected.push_back('x');
  341. EXPECT_EQ(decode_path_component("x%00x"), expected);
  342. }
  343. TEST(DecodePathTest, UnicodeEncoding) {
  344. // %u0041 = 'A' (1-byte UTF-8)
  345. EXPECT_EQ("A", decode_path_component("%u0041"));
  346. // %u00E9 = 'é' (2-byte UTF-8)
  347. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  348. // %u3042 = 'あ' (3-byte UTF-8)
  349. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  350. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  351. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  352. // %uD800 = surrogate (invalid, silently dropped)
  353. EXPECT_EQ("", decode_path_component("%uD800"));
  354. }
  355. TEST(SanitizeFilenameTest, VariousPatterns) {
  356. // Path traversal
  357. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  358. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  359. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  360. // Normal and edge cases
  361. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  362. EXPECT_EQ("filename.txt",
  363. httplib::sanitize_filename("/path/to/filename.txt"));
  364. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  365. EXPECT_EQ("", httplib::sanitize_filename(".."));
  366. EXPECT_EQ("", httplib::sanitize_filename(""));
  367. // Null bytes stripped
  368. EXPECT_EQ("safe.txt",
  369. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  370. // Whitespace-only rejected
  371. EXPECT_EQ("", httplib::sanitize_filename(" "));
  372. }
  373. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  374. string unescapedCharacters = "-_.!~*'()";
  375. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  376. }
  377. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  378. string reservedCharacters = ";,/?:@&=+$";
  379. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  380. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  381. }
  382. TEST(ClientQueryOrder, PreserveOrder) {
  383. // This test reproduces Issue #2259: client may reorder query parameters
  384. // when sending a GET request. The expected behavior is that the client
  385. // preserves the original query string order when the caller supplied it
  386. // as part of the path.
  387. Server svr;
  388. svr.Get("/", [&](const Request &req, Response &res) {
  389. // Echo back the raw target so the test can assert ordering
  390. res.set_content(req.target, "text/plain");
  391. });
  392. std::thread t{[&] { svr.listen(HOST, PORT); }};
  393. auto se = detail::scope_exit([&] {
  394. svr.stop();
  395. t.join();
  396. ASSERT_FALSE(svr.is_running());
  397. });
  398. svr.wait_until_ready();
  399. Client cli(HOST, PORT);
  400. ASSERT_TRUE(cli.is_valid());
  401. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  402. auto res = cli.Get(original);
  403. ASSERT_TRUE(res);
  404. // Expect the echoed target to exactly match the original path (order
  405. // preserved)
  406. EXPECT_EQ(res->body, original);
  407. }
  408. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  409. string chineseCharacters = U8("中国語");
  410. string russianCharacters = U8("дом");
  411. string brazilianCharacters = U8("óculos");
  412. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  413. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  414. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  415. "%D0%B4%D0%BE%D0%BC");
  416. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  417. }
  418. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  419. string unescapedCharacters = "-_.!~*'()";
  420. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  421. }
  422. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  423. string reservedCharacters = ";,/?:@&=+$";
  424. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  425. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  426. }
  427. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  428. string chineseCharacters = U8("中国語");
  429. string russianCharacters = U8("дом");
  430. string brazilianCharacters = U8("óculos");
  431. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  432. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  433. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  434. "%D0%B4%D0%BE%D0%BC");
  435. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  436. }
  437. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  438. // Issue #2082 use case: encoding path component with ampersand
  439. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  440. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  441. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  442. }
  443. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  444. string unescapedCharacters = "-_.!~*'()";
  445. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  446. }
  447. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  448. string reservedCharacters = ";,/?:@&=+$#";
  449. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  450. }
  451. TEST(EncodeUriTest, TestUTF8Characters) {
  452. string chineseCharacters = U8("中国語");
  453. string russianCharacters = U8("дом");
  454. string brazilianCharacters = U8("óculos");
  455. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  456. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  457. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  458. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  459. }
  460. TEST(EncodeUriTest, TestCompleteUri) {
  461. string uri =
  462. "https://example.com/path/to/resource?query=value&param=test#fragment";
  463. EXPECT_EQ(
  464. httplib::encode_uri(uri),
  465. "https://example.com/path/to/resource?query=value&param=test#fragment");
  466. }
  467. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  468. string uri =
  469. "https://example.com/path with spaces/file name.html?q=hello world";
  470. EXPECT_EQ(httplib::encode_uri(uri),
  471. "https://example.com/path%20with%20spaces/"
  472. "file%20name.html?q=hello%20world");
  473. }
  474. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  475. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  476. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  477. }
  478. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  479. string unescapedCharacters = "-_.!~*'()";
  480. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  481. }
  482. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  483. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  484. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  485. string encodedBrazilian = "%C3%B3culos";
  486. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  487. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  488. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  489. }
  490. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  491. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  492. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  493. "Piri Tommy Villiers - on & on");
  494. }
  495. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  496. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  497. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  498. }
  499. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  500. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  501. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  502. }
  503. TEST(DecodeUriTest, TestUTF8Characters) {
  504. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  505. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  506. string encodedBrazilian = "%C3%B3culos";
  507. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  508. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  509. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  510. }
  511. TEST(DecodeUriTest, TestCompleteUri) {
  512. string encodedUri = "https://example.com/path%20with%20spaces/"
  513. "file%20name.html?q=hello%20world";
  514. EXPECT_EQ(
  515. httplib::decode_uri(encodedUri),
  516. "https://example.com/path with spaces/file name.html?q=hello world");
  517. }
  518. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  519. string original =
  520. "https://example.com/path with spaces/file name.html?q=hello world";
  521. string encoded = httplib::encode_uri(original);
  522. string decoded = httplib::decode_uri(encoded);
  523. EXPECT_EQ(decoded, original);
  524. }
  525. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  526. string original = "Piri Tommy Villiers - on & on";
  527. string encoded = httplib::encode_uri_component(original);
  528. string decoded = httplib::decode_uri_component(encoded);
  529. EXPECT_EQ(decoded, original);
  530. }
  531. TEST(TrimTests, TrimStringTests) {
  532. EXPECT_EQ("abc", detail::trim_copy("abc"));
  533. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  534. EXPECT_TRUE(detail::trim_copy("").empty());
  535. }
  536. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  537. // Simple case without quality values
  538. std::vector<std::string> result1;
  539. EXPECT_TRUE(detail::parse_accept_header(
  540. "text/html,application/json,text/plain", result1));
  541. EXPECT_EQ(result1.size(), 3U);
  542. EXPECT_EQ(result1[0], "text/html");
  543. EXPECT_EQ(result1[1], "application/json");
  544. EXPECT_EQ(result1[2], "text/plain");
  545. // With quality values
  546. std::vector<std::string> result2;
  547. EXPECT_TRUE(detail::parse_accept_header(
  548. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  549. EXPECT_EQ(result2.size(), 3U);
  550. EXPECT_EQ(result2[0], "application/json"); // highest q value
  551. EXPECT_EQ(result2[1], "text/html");
  552. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  553. }
  554. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  555. // Mixed with and without quality values
  556. std::vector<std::string> result;
  557. EXPECT_TRUE(detail::parse_accept_header(
  558. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  559. EXPECT_EQ(result.size(), 3U);
  560. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  561. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  562. EXPECT_EQ(result[2], "application/json"); // q=0.5
  563. }
  564. TEST(ParseAcceptHeaderTest, EdgeCases) {
  565. // Empty header
  566. std::vector<std::string> empty_result;
  567. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  568. EXPECT_TRUE(empty_result.empty());
  569. // Single type
  570. std::vector<std::string> single_result;
  571. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  572. EXPECT_EQ(single_result.size(), 1U);
  573. EXPECT_EQ(single_result[0], "application/json");
  574. // Wildcard types
  575. std::vector<std::string> wildcard_result;
  576. EXPECT_TRUE(detail::parse_accept_header(
  577. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  578. EXPECT_EQ(wildcard_result.size(), 3U);
  579. EXPECT_EQ(wildcard_result[0], "application/json");
  580. EXPECT_EQ(wildcard_result[1], "text/*");
  581. EXPECT_EQ(wildcard_result[2], "*/*");
  582. }
  583. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  584. // Common browser Accept header
  585. std::vector<std::string> browser_result;
  586. EXPECT_TRUE(
  587. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  588. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  589. browser_result));
  590. EXPECT_EQ(browser_result.size(), 6U);
  591. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  592. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  593. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  594. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  595. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  596. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  597. // API client header
  598. std::vector<std::string> api_result;
  599. EXPECT_TRUE(detail::parse_accept_header(
  600. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  601. api_result));
  602. EXPECT_EQ(api_result.size(), 3U);
  603. EXPECT_EQ(api_result[0], "application/json");
  604. EXPECT_EQ(api_result[1], "application/xml");
  605. EXPECT_EQ(api_result[2], "text/plain");
  606. }
  607. TEST(ParseAcceptHeaderTest, SpecialCases) {
  608. // Quality value with 3 decimal places
  609. std::vector<std::string> decimal_result;
  610. EXPECT_TRUE(detail::parse_accept_header(
  611. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  612. EXPECT_EQ(decimal_result.size(), 2U);
  613. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  614. EXPECT_EQ(decimal_result[1], "text/html");
  615. // Zero quality (should still be included but with lowest priority)
  616. std::vector<std::string> zero_q_result;
  617. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  618. zero_q_result));
  619. EXPECT_EQ(zero_q_result.size(), 2U);
  620. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  621. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  622. // No spaces around commas
  623. std::vector<std::string> no_space_result;
  624. EXPECT_TRUE(detail::parse_accept_header(
  625. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  626. no_space_result));
  627. EXPECT_EQ(no_space_result.size(), 3U);
  628. EXPECT_EQ(no_space_result[0], "text/html");
  629. EXPECT_EQ(no_space_result[1], "application/json");
  630. EXPECT_EQ(no_space_result[2], "text/plain");
  631. }
  632. TEST(ParseAcceptHeaderTest, InvalidCases) {
  633. std::vector<std::string> result;
  634. // Invalid quality value (> 1.0)
  635. EXPECT_FALSE(
  636. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  637. // Invalid quality value (< 0.0)
  638. EXPECT_FALSE(
  639. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  640. // Invalid quality value (not a number)
  641. EXPECT_FALSE(detail::parse_accept_header(
  642. "text/html;q=invalid,application/json", result));
  643. // Empty quality value
  644. EXPECT_FALSE(
  645. detail::parse_accept_header("text/html;q=,application/json", result));
  646. // Invalid media type format (no slash and not wildcard)
  647. EXPECT_FALSE(
  648. detail::parse_accept_header("invalidtype,application/json", result));
  649. // Empty media type
  650. result.clear();
  651. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  652. // Only commas
  653. result.clear();
  654. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  655. // Valid cases should still work
  656. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  657. EXPECT_EQ(result.size(), 1U);
  658. EXPECT_EQ(result[0], "*/*");
  659. EXPECT_TRUE(detail::parse_accept_header("*", result));
  660. EXPECT_EQ(result.size(), 1U);
  661. EXPECT_EQ(result[0], "*");
  662. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  663. EXPECT_EQ(result.size(), 1U);
  664. EXPECT_EQ(result[0], "text/*");
  665. }
  666. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  667. Server svr;
  668. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  669. EXPECT_EQ(req.accept_content_types.size(), 3U);
  670. EXPECT_EQ(req.accept_content_types[0], "application/json");
  671. EXPECT_EQ(req.accept_content_types[1], "text/html");
  672. EXPECT_EQ(req.accept_content_types[2], "*/*");
  673. res.set_content("ok", "text/plain");
  674. });
  675. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  676. EXPECT_TRUE(false);
  677. res.set_content("bad request", "text/plain");
  678. });
  679. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  680. auto se = detail::scope_exit([&] {
  681. svr.stop();
  682. listen_thread.join();
  683. ASSERT_FALSE(svr.is_running());
  684. });
  685. svr.wait_until_ready();
  686. Client cli("localhost", PORT);
  687. {
  688. auto res =
  689. cli.Get("/accept_ok",
  690. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  691. ASSERT_TRUE(res);
  692. EXPECT_EQ(StatusCode::OK_200, res->status);
  693. }
  694. {
  695. auto res = cli.Get("/accept_bad_request",
  696. {{"Accept", "text/html;q=abc,application/json"}});
  697. ASSERT_TRUE(res);
  698. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  699. }
  700. }
  701. TEST(DivideTest, DivideStringTests) {
  702. auto divide = [](const std::string &str, char d) {
  703. std::string lhs;
  704. std::string rhs;
  705. detail::divide(str, d,
  706. [&](const char *lhs_data, std::size_t lhs_size,
  707. const char *rhs_data, std::size_t rhs_size) {
  708. lhs.assign(lhs_data, lhs_size);
  709. rhs.assign(rhs_data, rhs_size);
  710. });
  711. return std::make_pair(std::move(lhs), std::move(rhs));
  712. };
  713. {
  714. const auto res = divide("", '=');
  715. EXPECT_EQ(res.first, "");
  716. EXPECT_EQ(res.second, "");
  717. }
  718. {
  719. const auto res = divide("=", '=');
  720. EXPECT_EQ(res.first, "");
  721. EXPECT_EQ(res.second, "");
  722. }
  723. {
  724. const auto res = divide(" ", '=');
  725. EXPECT_EQ(res.first, " ");
  726. EXPECT_EQ(res.second, "");
  727. }
  728. {
  729. const auto res = divide("a", '=');
  730. EXPECT_EQ(res.first, "a");
  731. EXPECT_EQ(res.second, "");
  732. }
  733. {
  734. const auto res = divide("a=", '=');
  735. EXPECT_EQ(res.first, "a");
  736. EXPECT_EQ(res.second, "");
  737. }
  738. {
  739. const auto res = divide("=b", '=');
  740. EXPECT_EQ(res.first, "");
  741. EXPECT_EQ(res.second, "b");
  742. }
  743. {
  744. const auto res = divide("a=b", '=');
  745. EXPECT_EQ(res.first, "a");
  746. EXPECT_EQ(res.second, "b");
  747. }
  748. {
  749. const auto res = divide("a=b=", '=');
  750. EXPECT_EQ(res.first, "a");
  751. EXPECT_EQ(res.second, "b=");
  752. }
  753. {
  754. const auto res = divide("a=b=c", '=');
  755. EXPECT_EQ(res.first, "a");
  756. EXPECT_EQ(res.second, "b=c");
  757. }
  758. }
  759. TEST(SplitTest, ParseQueryString) {
  760. string s = "key1=val1&key2=val2&key3=val3";
  761. Params dic;
  762. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  763. [&](const char *b, const char *e) {
  764. string key, val;
  765. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  766. if (key.empty()) {
  767. key.assign(b2, e2);
  768. } else {
  769. val.assign(b2, e2);
  770. }
  771. });
  772. dic.emplace(key, val);
  773. });
  774. EXPECT_EQ("val1", dic.find("key1")->second);
  775. EXPECT_EQ("val2", dic.find("key2")->second);
  776. EXPECT_EQ("val3", dic.find("key3")->second);
  777. }
  778. TEST(SplitTest, ParseInvalidQueryTests) {
  779. {
  780. string s = " ";
  781. Params dict;
  782. detail::parse_query_text(s, dict);
  783. EXPECT_TRUE(dict.empty());
  784. }
  785. {
  786. string s = " = =";
  787. Params dict;
  788. detail::parse_query_text(s, dict);
  789. EXPECT_TRUE(dict.empty());
  790. }
  791. }
  792. TEST(ParseQueryTest, ParseQueryString) {
  793. {
  794. std::string s = "key1=val1&key2=val2&key3=val3";
  795. Params dic;
  796. detail::parse_query_text(s, dic);
  797. EXPECT_EQ("val1", dic.find("key1")->second);
  798. EXPECT_EQ("val2", dic.find("key2")->second);
  799. EXPECT_EQ("val3", dic.find("key3")->second);
  800. }
  801. {
  802. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  803. Params dic;
  804. detail::parse_query_text(s, dic);
  805. EXPECT_EQ("", dic.find("key1")->second);
  806. EXPECT_EQ("val1", dic.find("key2")->second);
  807. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  808. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  809. }
  810. }
  811. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  812. Params dic;
  813. EXPECT_EQ(detail::params_to_query_str(dic), "");
  814. dic.emplace("key1", "val1");
  815. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  816. dic.emplace("key2", "val2");
  817. dic.emplace("key3", "val3");
  818. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  819. }
  820. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  821. string content_type = "multipart/form-data; boundary=something";
  822. string boundary;
  823. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  824. EXPECT_TRUE(ret);
  825. EXPECT_EQ(boundary, "something");
  826. }
  827. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  828. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  829. string boundary;
  830. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  831. EXPECT_TRUE(ret);
  832. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  833. }
  834. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  835. string content_type =
  836. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  837. string boundary;
  838. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  839. EXPECT_TRUE(ret);
  840. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  841. }
  842. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  843. string content_type =
  844. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  845. string boundary;
  846. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  847. EXPECT_TRUE(ret);
  848. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  849. }
  850. TEST(GetHeaderValueTest, DefaultValue) {
  851. Headers headers = {{"Dummy", "Dummy"}};
  852. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  853. EXPECT_STREQ("text/plain", val);
  854. }
  855. TEST(GetHeaderValueTest, DefaultValueInt) {
  856. Headers headers = {{"Dummy", "Dummy"}};
  857. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  858. EXPECT_EQ(100ull, val);
  859. }
  860. TEST(GetHeaderValueTest, RegularValue) {
  861. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  862. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  863. EXPECT_STREQ("text/html", val);
  864. }
  865. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  866. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  867. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  868. EXPECT_STREQ("text/html", val);
  869. }
  870. TEST(GetHeaderValueTest, SetContent) {
  871. Response res;
  872. res.set_content("html", "text/html");
  873. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  874. res.set_content("text", "text/plain");
  875. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  876. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  877. }
  878. TEST(GetHeaderValueTest, RegularValueInt) {
  879. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  880. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  881. EXPECT_EQ(100ull, val);
  882. }
  883. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  884. Headers headers = {{"Content-Length", "x"}};
  885. auto is_invalid_value = false;
  886. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  887. is_invalid_value);
  888. EXPECT_EQ(0ull, val);
  889. EXPECT_TRUE(is_invalid_value);
  890. }
  891. TEST(GetHeaderValueTest, Range) {
  892. {
  893. Headers headers = {make_range_header({{1, -1}})};
  894. auto val = detail::get_header_value(headers, "Range", 0, 0);
  895. EXPECT_STREQ("bytes=1-", val);
  896. }
  897. {
  898. Headers headers = {make_range_header({{-1, 1}})};
  899. auto val = detail::get_header_value(headers, "Range", 0, 0);
  900. EXPECT_STREQ("bytes=-1", val);
  901. }
  902. {
  903. Headers headers = {make_range_header({{1, 10}})};
  904. auto val = detail::get_header_value(headers, "Range", 0, 0);
  905. EXPECT_STREQ("bytes=1-10", val);
  906. }
  907. {
  908. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  909. auto val = detail::get_header_value(headers, "Range", 0, 0);
  910. EXPECT_STREQ("bytes=1-10, 100-", val);
  911. }
  912. {
  913. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  914. auto val = detail::get_header_value(headers, "Range", 0, 0);
  915. EXPECT_STREQ("bytes=1-10, 100-200", val);
  916. }
  917. {
  918. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  919. auto val = detail::get_header_value(headers, "Range", 0, 0);
  920. EXPECT_STREQ("bytes=0-0, -1", val);
  921. }
  922. }
  923. TEST(ParseHeaderValueTest, Range) {
  924. {
  925. Ranges ranges;
  926. auto ret = detail::parse_range_header("bytes=1-", ranges);
  927. EXPECT_TRUE(ret);
  928. EXPECT_EQ(1u, ranges.size());
  929. EXPECT_EQ(1u, ranges[0].first);
  930. EXPECT_EQ(-1, ranges[0].second);
  931. }
  932. {
  933. Ranges ranges;
  934. auto ret = detail::parse_range_header("bytes=-1", ranges);
  935. EXPECT_TRUE(ret);
  936. EXPECT_EQ(1u, ranges.size());
  937. EXPECT_EQ(-1, ranges[0].first);
  938. EXPECT_EQ(1u, ranges[0].second);
  939. }
  940. {
  941. Ranges ranges;
  942. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  943. EXPECT_TRUE(ret);
  944. EXPECT_EQ(1u, ranges.size());
  945. EXPECT_EQ(1u, ranges[0].first);
  946. EXPECT_EQ(10u, ranges[0].second);
  947. }
  948. {
  949. Ranges ranges;
  950. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  951. EXPECT_FALSE(ret);
  952. }
  953. {
  954. Ranges ranges;
  955. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  956. EXPECT_TRUE(ret);
  957. EXPECT_EQ(2u, ranges.size());
  958. EXPECT_EQ(1u, ranges[0].first);
  959. EXPECT_EQ(10u, ranges[0].second);
  960. EXPECT_EQ(100u, ranges[1].first);
  961. EXPECT_EQ(-1, ranges[1].second);
  962. }
  963. {
  964. Ranges ranges;
  965. auto ret =
  966. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  967. EXPECT_TRUE(ret);
  968. EXPECT_EQ(3u, ranges.size());
  969. EXPECT_EQ(1u, ranges[0].first);
  970. EXPECT_EQ(10u, ranges[0].second);
  971. EXPECT_EQ(100u, ranges[1].first);
  972. EXPECT_EQ(200u, ranges[1].second);
  973. EXPECT_EQ(300u, ranges[2].first);
  974. EXPECT_EQ(400u, ranges[2].second);
  975. }
  976. {
  977. Ranges ranges;
  978. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  979. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  980. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  981. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  982. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  983. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  984. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  985. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  986. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  987. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  988. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  989. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  990. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  991. EXPECT_TRUE(ranges.empty());
  992. }
  993. }
  994. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  995. Request req;
  996. req.set_header("Accept-Encoding", "gzip");
  997. Response res;
  998. res.set_header("Content-Type", "text/plain");
  999. auto ret = detail::encoding_type(req, res);
  1000. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1001. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1002. #else
  1003. EXPECT_TRUE(ret == detail::EncodingType::None);
  1004. #endif
  1005. }
  1006. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1007. Request req;
  1008. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1009. Response res;
  1010. res.set_header("Content-Type", "text/plain");
  1011. auto ret = detail::encoding_type(req, res);
  1012. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1013. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1014. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1015. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1016. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1017. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1018. #else
  1019. EXPECT_TRUE(ret == detail::EncodingType::None);
  1020. #endif
  1021. }
  1022. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1023. Request req;
  1024. req.set_header("Accept-Encoding",
  1025. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1026. Response res;
  1027. res.set_header("Content-Type", "text/plain");
  1028. auto ret = detail::encoding_type(req, res);
  1029. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1030. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1031. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1032. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1033. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1034. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1035. #else
  1036. EXPECT_TRUE(ret == detail::EncodingType::None);
  1037. #endif
  1038. }
  1039. TEST(BufferStreamTest, read) {
  1040. detail::BufferStream strm1;
  1041. Stream &strm = strm1;
  1042. EXPECT_EQ(5, strm.write("hello"));
  1043. char buf[512];
  1044. EXPECT_EQ(2, strm.read(buf, 2));
  1045. EXPECT_EQ('h', buf[0]);
  1046. EXPECT_EQ('e', buf[1]);
  1047. EXPECT_EQ(2, strm.read(buf, 2));
  1048. EXPECT_EQ('l', buf[0]);
  1049. EXPECT_EQ('l', buf[1]);
  1050. EXPECT_EQ(1, strm.read(buf, 1));
  1051. EXPECT_EQ('o', buf[0]);
  1052. EXPECT_EQ(0, strm.read(buf, 1));
  1053. }
  1054. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1055. auto host = "www.httpwatch.com";
  1056. auto ip = hosted_at(host);
  1057. EXPECT_EQ("23.96.13.243", ip);
  1058. std::vector<std::string> addrs;
  1059. hosted_at(host, addrs);
  1060. EXPECT_EQ(1u, addrs.size());
  1061. }
  1062. #if 0 // It depends on each test environment...
  1063. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1064. auto host = "www.youtube.com";
  1065. std::vector<std::string> addrs;
  1066. hosted_at(host, addrs);
  1067. EXPECT_EQ(20u, addrs.size());
  1068. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1069. EXPECT_TRUE(it != addrs.end());
  1070. }
  1071. #endif
  1072. class ChunkedEncodingTest : public ::testing::Test {
  1073. protected:
  1074. ChunkedEncodingTest()
  1075. : cli_(HOST, PORT)
  1076. #ifdef CPPHTTPLIB_SSL_ENABLED
  1077. ,
  1078. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1079. #endif
  1080. {
  1081. cli_.set_connection_timeout(2);
  1082. #ifdef CPPHTTPLIB_SSL_ENABLED
  1083. cli_.enable_server_certificate_verification(false);
  1084. #endif
  1085. }
  1086. virtual void SetUp() {
  1087. read_file("./image.jpg", image_data_);
  1088. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1089. res.set_content("Hello World!", "text/plain");
  1090. });
  1091. svr_.Get(
  1092. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1093. res.set_chunked_content_provider(
  1094. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1095. size_t remaining = image_data_.size() - offset;
  1096. if (remaining == 0) {
  1097. sink.done();
  1098. } else {
  1099. constexpr size_t CHUNK_SIZE = 1024;
  1100. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1101. sink.write(&image_data_[offset], send_size);
  1102. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1103. }
  1104. return true;
  1105. });
  1106. });
  1107. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1108. svr_.wait_until_ready();
  1109. }
  1110. virtual void TearDown() {
  1111. svr_.stop();
  1112. if (!request_threads_.empty()) {
  1113. std::this_thread::sleep_for(std::chrono::seconds(1));
  1114. for (auto &t : request_threads_) {
  1115. t.join();
  1116. }
  1117. }
  1118. t_.join();
  1119. }
  1120. #ifdef CPPHTTPLIB_SSL_ENABLED
  1121. SSLClient cli_;
  1122. SSLServer svr_;
  1123. #else
  1124. Client cli_;
  1125. Server svr_;
  1126. #endif
  1127. thread t_;
  1128. std::vector<thread> request_threads_;
  1129. std::string image_data_;
  1130. };
  1131. TEST_F(ChunkedEncodingTest, NormalGet) {
  1132. auto res = cli_.Get("/chunked");
  1133. ASSERT_TRUE(res);
  1134. std::string out;
  1135. read_file("./image.jpg", out);
  1136. EXPECT_EQ(StatusCode::OK_200, res->status);
  1137. EXPECT_EQ(out, res->body);
  1138. }
  1139. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1140. std::string body;
  1141. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1142. body.append(data, data_length);
  1143. return true;
  1144. });
  1145. ASSERT_TRUE(res);
  1146. std::string out;
  1147. read_file("./image.jpg", out);
  1148. EXPECT_EQ(StatusCode::OK_200, res->status);
  1149. EXPECT_EQ(out, body);
  1150. }
  1151. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1152. std::string body;
  1153. auto res = cli_.Get(
  1154. "/chunked",
  1155. [&](const Response &response) {
  1156. EXPECT_EQ(StatusCode::OK_200, response.status);
  1157. return true;
  1158. },
  1159. [&](const char *data, size_t data_length) {
  1160. body.append(data, data_length);
  1161. return true;
  1162. });
  1163. ASSERT_TRUE(res);
  1164. std::string out;
  1165. read_file("./image.jpg", out);
  1166. EXPECT_EQ(StatusCode::OK_200, res->status);
  1167. EXPECT_EQ(out, body);
  1168. }
  1169. TEST(RangeTest, FromHTTPBin_Online) {
  1170. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1171. auto host = "httpcan.org";
  1172. auto path = std::string{"/range/32"};
  1173. #else
  1174. auto host = "nghttp2.org";
  1175. auto path = std::string{"/httpbin/range/32"};
  1176. #endif
  1177. #ifdef CPPHTTPLIB_SSL_ENABLED
  1178. auto port = 443;
  1179. SSLClient cli(host, port);
  1180. #else
  1181. auto port = 80;
  1182. Client cli(host, port);
  1183. #endif
  1184. cli.set_connection_timeout(5);
  1185. {
  1186. auto res = cli.Get(path);
  1187. ASSERT_TRUE(res);
  1188. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1189. EXPECT_EQ(StatusCode::OK_200, res->status);
  1190. }
  1191. {
  1192. Headers headers = {make_range_header({{1, -1}})};
  1193. auto res = cli.Get(path, headers);
  1194. ASSERT_TRUE(res);
  1195. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1196. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1197. }
  1198. {
  1199. Headers headers = {make_range_header({{1, 10}})};
  1200. auto res = cli.Get(path, headers);
  1201. ASSERT_TRUE(res);
  1202. EXPECT_EQ("bcdefghijk", res->body);
  1203. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1204. }
  1205. {
  1206. Headers headers = {make_range_header({{0, 31}})};
  1207. auto res = cli.Get(path, headers);
  1208. ASSERT_TRUE(res);
  1209. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1210. EXPECT_EQ(StatusCode::OK_200, res->status);
  1211. }
  1212. {
  1213. Headers headers = {make_range_header({{0, -1}})};
  1214. auto res = cli.Get(path, headers);
  1215. ASSERT_TRUE(res);
  1216. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1217. EXPECT_EQ(StatusCode::OK_200, res->status);
  1218. }
  1219. {
  1220. Headers headers = {make_range_header({{0, 32}})};
  1221. auto res = cli.Get(path, headers);
  1222. ASSERT_TRUE(res);
  1223. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1224. }
  1225. }
  1226. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1227. auto host = "unresolvableaddress.local";
  1228. auto path = std::string{"/"};
  1229. #ifdef CPPHTTPLIB_SSL_ENABLED
  1230. auto port = 443;
  1231. SSLClient cli(host, port);
  1232. #else
  1233. auto port = 80;
  1234. Client cli(host, port);
  1235. #endif
  1236. cli.set_connection_timeout(1);
  1237. {
  1238. auto res = cli.Get(path);
  1239. ASSERT_FALSE(res);
  1240. }
  1241. std::this_thread::sleep_for(std::chrono::seconds(8));
  1242. }
  1243. TEST(ConnectionErrorTest, InvalidHost) {
  1244. auto host = "-abcde.com";
  1245. #ifdef CPPHTTPLIB_SSL_ENABLED
  1246. auto port = 443;
  1247. SSLClient cli(host, port);
  1248. #else
  1249. auto port = 80;
  1250. Client cli(host, port);
  1251. #endif
  1252. cli.set_connection_timeout(std::chrono::seconds(2));
  1253. auto res = cli.Get("/");
  1254. ASSERT_TRUE(!res);
  1255. EXPECT_EQ(Error::Connection, res.error());
  1256. }
  1257. TEST(ConnectionErrorTest, InvalidHost2) {
  1258. auto host = "httpcan.org/";
  1259. #ifdef CPPHTTPLIB_SSL_ENABLED
  1260. SSLClient cli(host);
  1261. #else
  1262. Client cli(host);
  1263. #endif
  1264. cli.set_connection_timeout(std::chrono::seconds(2));
  1265. auto res = cli.Get("/");
  1266. ASSERT_TRUE(!res);
  1267. EXPECT_EQ(Error::Connection, res.error());
  1268. }
  1269. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1270. auto host = "httpcan.org/";
  1271. #ifdef CPPHTTPLIB_SSL_ENABLED
  1272. SSLClient cli(host);
  1273. #else
  1274. Client cli(host);
  1275. #endif
  1276. cli.set_connection_timeout(std::chrono::seconds(2));
  1277. auto res = cli.Get("/");
  1278. ASSERT_TRUE(!res);
  1279. stringstream s;
  1280. s << "error code: " << res.error();
  1281. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1282. }
  1283. TEST(ConnectionErrorTest, InvalidPort) {
  1284. auto host = "localhost";
  1285. auto port = 44380;
  1286. #ifdef CPPHTTPLIB_SSL_ENABLED
  1287. SSLClient cli(host, port);
  1288. #else
  1289. Client cli(host, port);
  1290. #endif
  1291. cli.set_connection_timeout(std::chrono::seconds(2));
  1292. auto res = cli.Get("/");
  1293. ASSERT_TRUE(!res);
  1294. EXPECT_TRUE(Error::Connection == res.error() ||
  1295. Error::ConnectionTimeout == res.error());
  1296. }
  1297. TEST(ConnectionErrorTest, Timeout_Online) {
  1298. auto host = "google.com";
  1299. #ifdef CPPHTTPLIB_SSL_ENABLED
  1300. auto port = 44380;
  1301. SSLClient cli(host, port);
  1302. #else
  1303. auto port = 8080;
  1304. Client cli(host, port);
  1305. #endif
  1306. cli.set_connection_timeout(std::chrono::seconds(2));
  1307. // only probe one address type so that the error reason
  1308. // correlates to the timed-out IPv4, not the unsupported
  1309. // IPv6 connection attempt
  1310. cli.set_address_family(AF_INET);
  1311. auto res = cli.Get("/");
  1312. ASSERT_TRUE(!res);
  1313. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1314. }
  1315. TEST(CancelTest, NoCancel_Online) {
  1316. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1317. auto host = "httpcan.org";
  1318. auto path = std::string{"/range/32"};
  1319. #else
  1320. auto host = "nghttp2.org";
  1321. auto path = std::string{"/httpbin/range/32"};
  1322. #endif
  1323. #ifdef CPPHTTPLIB_SSL_ENABLED
  1324. auto port = 443;
  1325. SSLClient cli(host, port);
  1326. #else
  1327. auto port = 80;
  1328. Client cli(host, port);
  1329. #endif
  1330. cli.set_connection_timeout(std::chrono::seconds(5));
  1331. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1332. ASSERT_TRUE(res);
  1333. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1334. EXPECT_EQ(StatusCode::OK_200, res->status);
  1335. }
  1336. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1337. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1338. auto host = "httpcan.org";
  1339. auto path = std::string{"/range/32"};
  1340. #else
  1341. auto host = "nghttp2.org";
  1342. auto path = std::string{"/httpbin/range/32"};
  1343. #endif
  1344. #ifdef CPPHTTPLIB_SSL_ENABLED
  1345. auto port = 443;
  1346. SSLClient cli(host, port);
  1347. #else
  1348. auto port = 80;
  1349. Client cli(host, port);
  1350. #endif
  1351. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1352. cli.set_connection_timeout(std::chrono::seconds(5));
  1353. ASSERT_TRUE(!res);
  1354. EXPECT_EQ(Error::Canceled, res.error());
  1355. }
  1356. TEST(CancelTest, WithCancelLargePayload_Online) {
  1357. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1358. auto host = "httpcan.org";
  1359. auto path = std::string{"/range/65536"};
  1360. #else
  1361. auto host = "nghttp2.org";
  1362. auto path = std::string{"/httpbin/range/65536"};
  1363. #endif
  1364. #ifdef CPPHTTPLIB_SSL_ENABLED
  1365. auto port = 443;
  1366. SSLClient cli(host, port);
  1367. #else
  1368. auto port = 80;
  1369. Client cli(host, port);
  1370. #endif
  1371. cli.set_connection_timeout(std::chrono::seconds(5));
  1372. uint32_t count = 0;
  1373. auto res =
  1374. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1375. ASSERT_TRUE(!res);
  1376. EXPECT_EQ(Error::Canceled, res.error());
  1377. }
  1378. TEST(CancelTest, NoCancelPost) {
  1379. Server svr;
  1380. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1381. res.set_content("Hello World!", "text/plain");
  1382. });
  1383. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1384. auto se = detail::scope_exit([&] {
  1385. svr.stop();
  1386. thread.join();
  1387. ASSERT_FALSE(svr.is_running());
  1388. });
  1389. svr.wait_until_ready();
  1390. Client cli(HOST, PORT);
  1391. cli.set_connection_timeout(std::chrono::seconds(5));
  1392. auto res =
  1393. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1394. "application/json", [](uint64_t, uint64_t) { return true; });
  1395. ASSERT_TRUE(res);
  1396. EXPECT_EQ("Hello World!", res->body);
  1397. EXPECT_EQ(StatusCode::OK_200, res->status);
  1398. }
  1399. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1400. Server svr;
  1401. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1402. res.set_content("Hello World!", "text/plain");
  1403. });
  1404. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1405. auto se = detail::scope_exit([&] {
  1406. svr.stop();
  1407. thread.join();
  1408. ASSERT_FALSE(svr.is_running());
  1409. });
  1410. svr.wait_until_ready();
  1411. Client cli(HOST, PORT);
  1412. cli.set_connection_timeout(std::chrono::seconds(5));
  1413. auto res =
  1414. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1415. "application/json", [](uint64_t, uint64_t) { return false; });
  1416. ASSERT_TRUE(!res);
  1417. EXPECT_EQ(Error::Canceled, res.error());
  1418. }
  1419. TEST(CancelTest, WithCancelLargePayloadPost) {
  1420. Server svr;
  1421. svr.set_payload_max_length(200 * 1024 * 1024);
  1422. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1423. res.set_content(LARGE_DATA, "text/plain");
  1424. });
  1425. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1426. auto se = detail::scope_exit([&] {
  1427. svr.stop();
  1428. thread.join();
  1429. ASSERT_FALSE(svr.is_running());
  1430. });
  1431. svr.wait_until_ready();
  1432. Client cli(HOST, PORT);
  1433. cli.set_payload_max_length(200 * 1024 * 1024);
  1434. cli.set_connection_timeout(std::chrono::seconds(5));
  1435. auto res =
  1436. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1437. "application/json", [](uint64_t, uint64_t) { return false; });
  1438. ASSERT_TRUE(!res);
  1439. EXPECT_EQ(Error::Canceled, res.error());
  1440. }
  1441. TEST(CancelTest, NoCancelPut) {
  1442. Server svr;
  1443. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1444. res.set_content("Hello World!", "text/plain");
  1445. });
  1446. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1447. auto se = detail::scope_exit([&] {
  1448. svr.stop();
  1449. thread.join();
  1450. ASSERT_FALSE(svr.is_running());
  1451. });
  1452. svr.wait_until_ready();
  1453. Client cli(HOST, PORT);
  1454. cli.set_connection_timeout(std::chrono::seconds(5));
  1455. auto res =
  1456. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1457. "application/json", [](uint64_t, uint64_t) { return true; });
  1458. ASSERT_TRUE(res);
  1459. EXPECT_EQ("Hello World!", res->body);
  1460. EXPECT_EQ(StatusCode::OK_200, res->status);
  1461. }
  1462. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1463. Server svr;
  1464. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1465. res.set_content("Hello World!", "text/plain");
  1466. });
  1467. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1468. auto se = detail::scope_exit([&] {
  1469. svr.stop();
  1470. thread.join();
  1471. ASSERT_FALSE(svr.is_running());
  1472. });
  1473. svr.wait_until_ready();
  1474. Client cli(HOST, PORT);
  1475. cli.set_connection_timeout(std::chrono::seconds(5));
  1476. auto res =
  1477. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1478. "application/json", [](uint64_t, uint64_t) { return false; });
  1479. ASSERT_TRUE(!res);
  1480. EXPECT_EQ(Error::Canceled, res.error());
  1481. }
  1482. TEST(CancelTest, WithCancelLargePayloadPut) {
  1483. Server svr;
  1484. svr.set_payload_max_length(200 * 1024 * 1024);
  1485. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1486. res.set_content(LARGE_DATA, "text/plain");
  1487. });
  1488. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1489. auto se = detail::scope_exit([&] {
  1490. svr.stop();
  1491. thread.join();
  1492. ASSERT_FALSE(svr.is_running());
  1493. });
  1494. svr.wait_until_ready();
  1495. Client cli(HOST, PORT);
  1496. cli.set_payload_max_length(200 * 1024 * 1024);
  1497. cli.set_connection_timeout(std::chrono::seconds(5));
  1498. auto res =
  1499. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1500. "application/json", [](uint64_t, uint64_t) { return false; });
  1501. ASSERT_TRUE(!res);
  1502. EXPECT_EQ(Error::Canceled, res.error());
  1503. }
  1504. TEST(CancelTest, NoCancelPatch) {
  1505. Server svr;
  1506. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1507. res.set_content("Hello World!", "text/plain");
  1508. });
  1509. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1510. auto se = detail::scope_exit([&] {
  1511. svr.stop();
  1512. thread.join();
  1513. ASSERT_FALSE(svr.is_running());
  1514. });
  1515. svr.wait_until_ready();
  1516. Client cli(HOST, PORT);
  1517. cli.set_connection_timeout(std::chrono::seconds(5));
  1518. auto res =
  1519. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1520. "application/json", [](uint64_t, uint64_t) { return true; });
  1521. ASSERT_TRUE(res);
  1522. EXPECT_EQ("Hello World!", res->body);
  1523. EXPECT_EQ(StatusCode::OK_200, res->status);
  1524. }
  1525. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1526. Server svr;
  1527. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1528. res.set_content("Hello World!", "text/plain");
  1529. });
  1530. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1531. auto se = detail::scope_exit([&] {
  1532. svr.stop();
  1533. thread.join();
  1534. ASSERT_FALSE(svr.is_running());
  1535. });
  1536. svr.wait_until_ready();
  1537. Client cli(HOST, PORT);
  1538. cli.set_connection_timeout(std::chrono::seconds(5));
  1539. auto res =
  1540. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1541. "application/json", [](uint64_t, uint64_t) { return false; });
  1542. ASSERT_TRUE(!res);
  1543. EXPECT_EQ(Error::Canceled, res.error());
  1544. }
  1545. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1546. Server svr;
  1547. svr.set_payload_max_length(200 * 1024 * 1024);
  1548. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1549. res.set_content(LARGE_DATA, "text/plain");
  1550. });
  1551. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1552. auto se = detail::scope_exit([&] {
  1553. svr.stop();
  1554. thread.join();
  1555. ASSERT_FALSE(svr.is_running());
  1556. });
  1557. svr.wait_until_ready();
  1558. Client cli(HOST, PORT);
  1559. cli.set_payload_max_length(200 * 1024 * 1024);
  1560. cli.set_connection_timeout(std::chrono::seconds(5));
  1561. auto res =
  1562. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1563. "application/json", [](uint64_t, uint64_t) { return false; });
  1564. ASSERT_TRUE(!res);
  1565. EXPECT_EQ(Error::Canceled, res.error());
  1566. }
  1567. TEST(CancelTest, NoCancelDelete) {
  1568. Server svr;
  1569. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1570. res.set_content("Hello World!", "text/plain");
  1571. });
  1572. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1573. auto se = detail::scope_exit([&] {
  1574. svr.stop();
  1575. thread.join();
  1576. ASSERT_FALSE(svr.is_running());
  1577. });
  1578. svr.wait_until_ready();
  1579. Client cli(HOST, PORT);
  1580. cli.set_connection_timeout(std::chrono::seconds(5));
  1581. auto res =
  1582. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1583. "application/json", [](uint64_t, uint64_t) { return true; });
  1584. ASSERT_TRUE(res);
  1585. EXPECT_EQ("Hello World!", res->body);
  1586. EXPECT_EQ(StatusCode::OK_200, res->status);
  1587. }
  1588. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1589. Server svr;
  1590. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1591. res.set_content("Hello World!", "text/plain");
  1592. });
  1593. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1594. auto se = detail::scope_exit([&] {
  1595. svr.stop();
  1596. thread.join();
  1597. ASSERT_FALSE(svr.is_running());
  1598. });
  1599. svr.wait_until_ready();
  1600. Client cli(HOST, PORT);
  1601. cli.set_connection_timeout(std::chrono::seconds(5));
  1602. auto res =
  1603. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1604. "application/json", [](uint64_t, uint64_t) { return false; });
  1605. ASSERT_TRUE(!res);
  1606. EXPECT_EQ(Error::Canceled, res.error());
  1607. }
  1608. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1609. Server svr;
  1610. svr.set_payload_max_length(200 * 1024 * 1024);
  1611. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1612. res.set_content(LARGE_DATA, "text/plain");
  1613. });
  1614. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1615. auto se = detail::scope_exit([&] {
  1616. svr.stop();
  1617. thread.join();
  1618. ASSERT_FALSE(svr.is_running());
  1619. });
  1620. svr.wait_until_ready();
  1621. Client cli(HOST, PORT);
  1622. cli.set_payload_max_length(200 * 1024 * 1024);
  1623. cli.set_connection_timeout(std::chrono::seconds(5));
  1624. auto res =
  1625. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1626. "application/json", [](uint64_t, uint64_t) { return false; });
  1627. ASSERT_TRUE(!res);
  1628. EXPECT_EQ(Error::Canceled, res.error());
  1629. }
  1630. static std::string remove_whitespace(const std::string &input) {
  1631. std::string output;
  1632. output.reserve(input.size());
  1633. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1634. [](unsigned char c) { return !std::isspace(c); });
  1635. return output;
  1636. }
  1637. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1638. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1639. auto host = "httpcan.org";
  1640. auto path = std::string{"/basic-auth/hello/world"};
  1641. #else
  1642. auto host = "nghttp2.org";
  1643. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1644. #endif
  1645. #ifdef CPPHTTPLIB_SSL_ENABLED
  1646. auto port = 443;
  1647. SSLClient cli(host, port);
  1648. #else
  1649. auto port = 80;
  1650. Client cli(host, port);
  1651. #endif
  1652. {
  1653. auto res = cli.Get(path);
  1654. ASSERT_TRUE(res);
  1655. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1656. }
  1657. {
  1658. auto res =
  1659. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1660. ASSERT_TRUE(res);
  1661. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1662. remove_whitespace(res->body));
  1663. EXPECT_EQ(StatusCode::OK_200, res->status);
  1664. }
  1665. {
  1666. cli.set_basic_auth("hello", "world");
  1667. auto res = cli.Get(path);
  1668. ASSERT_TRUE(res);
  1669. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1670. remove_whitespace(res->body));
  1671. EXPECT_EQ(StatusCode::OK_200, res->status);
  1672. }
  1673. {
  1674. cli.set_basic_auth("hello", "bad");
  1675. auto res = cli.Get(path);
  1676. ASSERT_TRUE(res);
  1677. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1678. }
  1679. {
  1680. cli.set_basic_auth("bad", "world");
  1681. auto res = cli.Get(path);
  1682. ASSERT_TRUE(res);
  1683. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1684. }
  1685. }
  1686. #ifdef CPPHTTPLIB_SSL_ENABLED
  1687. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1688. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1689. auto host = "httpcan.org";
  1690. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1691. auto paths = std::vector<std::string>{
  1692. "/digest-auth/auth/hello/world/MD5",
  1693. "/digest-auth/auth/hello/world/SHA-256",
  1694. "/digest-auth/auth/hello/world/SHA-512",
  1695. };
  1696. #else
  1697. auto host = "nghttp2.org";
  1698. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1699. auto paths = std::vector<std::string>{
  1700. "/httpbin/digest-auth/auth/hello/world/MD5",
  1701. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1702. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1703. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1704. };
  1705. #endif
  1706. auto port = 443;
  1707. SSLClient cli(host, port);
  1708. {
  1709. auto res = cli.Get(unauth_path);
  1710. ASSERT_TRUE(res);
  1711. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1712. }
  1713. {
  1714. cli.set_digest_auth("hello", "world");
  1715. for (const auto &path : paths) {
  1716. auto res = cli.Get(path.c_str());
  1717. ASSERT_TRUE(res);
  1718. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1719. std::string algo(path.substr(path.rfind('/') + 1));
  1720. EXPECT_EQ(
  1721. remove_whitespace("{\"algorithm\":\"" + algo +
  1722. "\",\"authenticated\":true,\"user\":\"hello\"}\n"),
  1723. remove_whitespace(res->body));
  1724. #else
  1725. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1726. remove_whitespace(res->body));
  1727. #endif
  1728. EXPECT_EQ(StatusCode::OK_200, res->status);
  1729. }
  1730. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1731. cli.set_digest_auth("hello", "bad");
  1732. for (const auto &path : paths) {
  1733. auto res = cli.Get(path.c_str());
  1734. ASSERT_TRUE(res);
  1735. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1736. }
  1737. #endif
  1738. }
  1739. }
  1740. #endif
  1741. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1742. auto host = "google.com";
  1743. auto another_host = "example.com";
  1744. auto wrong_ip = "0.0.0.0";
  1745. #ifdef CPPHTTPLIB_SSL_ENABLED
  1746. SSLClient cli(host);
  1747. #else
  1748. Client cli(host);
  1749. #endif
  1750. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1751. auto res = cli.Get("/");
  1752. ASSERT_TRUE(res);
  1753. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1754. }
  1755. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1756. auto host = "google.com";
  1757. auto wrong_ip = "0.0.0.0";
  1758. #ifdef CPPHTTPLIB_SSL_ENABLED
  1759. SSLClient cli(host);
  1760. #else
  1761. Client cli(host);
  1762. #endif
  1763. cli.set_hostname_addr_map({{host, wrong_ip}});
  1764. auto res = cli.Get("/");
  1765. ASSERT_TRUE(!res);
  1766. EXPECT_EQ(Error::Connection, res.error());
  1767. }
  1768. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1769. auto host = "nghttp2.org";
  1770. #ifdef CPPHTTPLIB_SSL_ENABLED
  1771. SSLClient cli(host);
  1772. #else
  1773. Client cli(host);
  1774. #endif
  1775. cli.set_follow_location(true);
  1776. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1777. ASSERT_TRUE(res);
  1778. EXPECT_EQ(StatusCode::OK_200, res->status);
  1779. }
  1780. TEST(RedirectTest, Redirect_Online) {
  1781. auto host = "nghttp2.org";
  1782. #ifdef CPPHTTPLIB_SSL_ENABLED
  1783. SSLClient cli(host);
  1784. #else
  1785. Client cli(host);
  1786. #endif
  1787. cli.set_follow_location(true);
  1788. auto res = cli.Get("/httpbin/redirect/3");
  1789. ASSERT_TRUE(res);
  1790. EXPECT_EQ(StatusCode::OK_200, res->status);
  1791. }
  1792. TEST(RelativeRedirectTest, Redirect_Online) {
  1793. auto host = "nghttp2.org";
  1794. #ifdef CPPHTTPLIB_SSL_ENABLED
  1795. SSLClient cli(host);
  1796. #else
  1797. Client cli(host);
  1798. #endif
  1799. cli.set_follow_location(true);
  1800. auto res = cli.Get("/httpbin/relative-redirect/3");
  1801. ASSERT_TRUE(res);
  1802. EXPECT_EQ(StatusCode::OK_200, res->status);
  1803. }
  1804. TEST(TooManyRedirectTest, Redirect_Online) {
  1805. auto host = "nghttp2.org";
  1806. #ifdef CPPHTTPLIB_SSL_ENABLED
  1807. SSLClient cli(host);
  1808. #else
  1809. Client cli(host);
  1810. #endif
  1811. cli.set_follow_location(true);
  1812. auto res = cli.Get("/httpbin/redirect/21");
  1813. ASSERT_TRUE(!res);
  1814. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1815. }
  1816. #ifdef CPPHTTPLIB_SSL_ENABLED
  1817. TEST(YahooRedirectTest, Redirect_Online) {
  1818. Client cli("yahoo.com");
  1819. auto res = cli.Get("/");
  1820. ASSERT_TRUE(res);
  1821. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1822. cli.set_follow_location(true);
  1823. res = cli.Get("/");
  1824. ASSERT_TRUE(res);
  1825. EXPECT_EQ(StatusCode::OK_200, res->status);
  1826. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1827. }
  1828. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1829. #define REDIR_HOST "httpbingo.org"
  1830. #define REDIR_PATH "/redirect-to"
  1831. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1832. SSLClient cli(REDIR_HOST);
  1833. cli.set_follow_location(true);
  1834. auto res =
  1835. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1836. ASSERT_TRUE(res);
  1837. EXPECT_EQ(StatusCode::OK_200, res->status);
  1838. }
  1839. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1840. SSLClient cli(REDIR_HOST);
  1841. cli.set_follow_location(true);
  1842. Params params;
  1843. params.emplace("url", "http://example.com");
  1844. params.emplace("status_code", "302");
  1845. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1846. ASSERT_TRUE(res);
  1847. EXPECT_EQ(StatusCode::OK_200, res->status);
  1848. }
  1849. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1850. SSLClient cli(REDIR_HOST);
  1851. cli.set_follow_location(true);
  1852. Params params;
  1853. params.emplace("url", "http://example.com");
  1854. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1855. ASSERT_TRUE(res);
  1856. EXPECT_EQ(StatusCode::OK_200, res->status);
  1857. }
  1858. TEST(UrlWithSpace, Redirect_Online) {
  1859. SSLClient cli("edge.forgecdn.net");
  1860. cli.set_follow_location(true);
  1861. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1862. ASSERT_TRUE(res);
  1863. EXPECT_EQ(StatusCode::OK_200, res->status);
  1864. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1865. }
  1866. #endif
  1867. #if !defined(_WIN32) && !defined(_WIN64)
  1868. TEST(ReceiveSignals, Signal) {
  1869. auto setupSignalHandlers = []() {
  1870. struct sigaction act;
  1871. sigemptyset(&act.sa_mask);
  1872. act.sa_flags = SA_SIGINFO;
  1873. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1874. switch (sig) {
  1875. case SIGINT:
  1876. default: break;
  1877. }
  1878. };
  1879. ::sigaction(SIGINT, &act, nullptr);
  1880. };
  1881. Server svr;
  1882. int port = 0;
  1883. auto thread = std::thread([&]() {
  1884. setupSignalHandlers();
  1885. port = svr.bind_to_any_port(HOST);
  1886. svr.listen_after_bind();
  1887. });
  1888. auto se = detail::scope_exit([&] {
  1889. svr.stop();
  1890. thread.join();
  1891. ASSERT_FALSE(svr.is_running());
  1892. });
  1893. svr.wait_until_ready();
  1894. ASSERT_TRUE(svr.is_running());
  1895. pthread_kill(thread.native_handle(), SIGINT);
  1896. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1897. ASSERT_TRUE(svr.is_running());
  1898. }
  1899. #endif
  1900. TEST(RedirectToDifferentPort, Redirect) {
  1901. Server svr1;
  1902. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1903. res.set_content("Hello World!", "text/plain");
  1904. });
  1905. int svr1_port = 0;
  1906. auto thread1 = std::thread([&]() {
  1907. svr1_port = svr1.bind_to_any_port(HOST);
  1908. svr1.listen_after_bind();
  1909. });
  1910. Server svr2;
  1911. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1912. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1913. });
  1914. int svr2_port = 0;
  1915. auto thread2 = std::thread([&]() {
  1916. svr2_port = svr2.bind_to_any_port(HOST);
  1917. svr2.listen_after_bind();
  1918. });
  1919. auto se = detail::scope_exit([&] {
  1920. svr2.stop();
  1921. thread2.join();
  1922. svr1.stop();
  1923. thread1.join();
  1924. ASSERT_FALSE(svr2.is_running());
  1925. ASSERT_FALSE(svr1.is_running());
  1926. });
  1927. svr1.wait_until_ready();
  1928. svr2.wait_until_ready();
  1929. Client cli("localhost", svr2_port);
  1930. cli.set_follow_location(true);
  1931. auto res = cli.Get("/2");
  1932. ASSERT_TRUE(res);
  1933. EXPECT_EQ(StatusCode::OK_200, res->status);
  1934. EXPECT_EQ("Hello World!", res->body);
  1935. }
  1936. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  1937. Server svr;
  1938. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  1939. // Port number that overflows int — should not crash
  1940. res.set_redirect("http://localhost:99999999999999999999/target");
  1941. });
  1942. auto port = svr.bind_to_any_port(HOST);
  1943. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  1944. auto se = detail::scope_exit([&] {
  1945. svr.stop();
  1946. thread.join();
  1947. ASSERT_FALSE(svr.is_running());
  1948. });
  1949. svr.wait_until_ready();
  1950. Client cli(HOST, port);
  1951. cli.set_follow_location(true);
  1952. auto res = cli.Get("/redir");
  1953. // Should fail gracefully, not crash (no valid response due to bad port)
  1954. EXPECT_FALSE(res);
  1955. }
  1956. TEST(RedirectFromPageWithContent, Redirect) {
  1957. Server svr;
  1958. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1959. res.set_content("___", "text/plain");
  1960. res.set_redirect("/2");
  1961. });
  1962. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1963. res.set_content("Hello World!", "text/plain");
  1964. });
  1965. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1966. auto se = detail::scope_exit([&] {
  1967. svr.stop();
  1968. th.join();
  1969. ASSERT_FALSE(svr.is_running());
  1970. });
  1971. svr.wait_until_ready();
  1972. {
  1973. Client cli("localhost", PORT);
  1974. cli.set_follow_location(true);
  1975. std::string body;
  1976. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1977. body.append(data, data_length);
  1978. return true;
  1979. });
  1980. ASSERT_TRUE(res);
  1981. EXPECT_EQ(StatusCode::OK_200, res->status);
  1982. EXPECT_EQ("Hello World!", body);
  1983. }
  1984. {
  1985. Client cli("localhost", PORT);
  1986. std::string body;
  1987. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1988. body.append(data, data_length);
  1989. return true;
  1990. });
  1991. ASSERT_TRUE(res);
  1992. EXPECT_EQ(StatusCode::Found_302, res->status);
  1993. EXPECT_EQ("___", body);
  1994. }
  1995. }
  1996. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1997. Server svr;
  1998. auto port_str = std::to_string(PORT);
  1999. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2000. auto expected_host = "[::1]:" + port_str;
  2001. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2002. res.set_content("___", "text/plain");
  2003. // res.set_redirect("/2");
  2004. res.set_redirect(redirect_url);
  2005. });
  2006. svr.Get("/2", [&](const Request &req, Response &res) {
  2007. auto host_header = req.headers.find("Host");
  2008. ASSERT_TRUE(host_header != req.headers.end());
  2009. EXPECT_EQ(expected_host, host_header->second);
  2010. res.set_content("Hello World!", "text/plain");
  2011. });
  2012. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2013. auto se = detail::scope_exit([&] {
  2014. svr.stop();
  2015. th.join();
  2016. ASSERT_FALSE(svr.is_running());
  2017. });
  2018. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2019. // actually starts anything, so the condition !svr.is_running() will
  2020. // always remain true, and the loop never stops.
  2021. // This basically counts how many milliseconds have passed since the
  2022. // call to svr.listen(), and if after 5 seconds nothing started yet
  2023. // aborts the test.
  2024. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2025. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2026. ASSERT_LT(milliseconds, 5000U);
  2027. }
  2028. {
  2029. Client cli("::1", PORT);
  2030. cli.set_follow_location(true);
  2031. std::string body;
  2032. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2033. body.append(data, data_length);
  2034. return true;
  2035. });
  2036. ASSERT_TRUE(res);
  2037. EXPECT_EQ(StatusCode::OK_200, res->status);
  2038. EXPECT_EQ("Hello World!", body);
  2039. }
  2040. {
  2041. Client cli("::1", PORT);
  2042. std::string body;
  2043. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2044. body.append(data, data_length);
  2045. return true;
  2046. });
  2047. ASSERT_TRUE(res);
  2048. EXPECT_EQ(StatusCode::Found_302, res->status);
  2049. EXPECT_EQ("___", body);
  2050. }
  2051. }
  2052. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2053. Server svr;
  2054. svr.Get("/foo", [](const Request &req, Response &res) {
  2055. auto a = req.params.find("a");
  2056. if (a != req.params.end()) {
  2057. res.set_content((*a).second, "text/plain");
  2058. res.status = StatusCode::OK_200;
  2059. } else {
  2060. res.status = StatusCode::BadRequest_400;
  2061. }
  2062. });
  2063. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2064. auto se = detail::scope_exit([&] {
  2065. svr.stop();
  2066. thread.join();
  2067. ASSERT_FALSE(svr.is_running());
  2068. });
  2069. svr.wait_until_ready();
  2070. {
  2071. Client cli(HOST, PORT);
  2072. cli.set_path_encode(false);
  2073. auto res = cli.Get("/foo?a=explicitly+encoded");
  2074. ASSERT_TRUE(res);
  2075. EXPECT_EQ(StatusCode::OK_200, res->status);
  2076. // This expects it back with a space, as the `+` won't have been
  2077. // url-encoded, and server-side the params get decoded turning `+`
  2078. // into spaces.
  2079. EXPECT_EQ("explicitly encoded", res->body);
  2080. }
  2081. }
  2082. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2083. Server svr;
  2084. svr.Get("/", [](const Request &req, Response &) {
  2085. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2086. });
  2087. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2088. auto se = detail::scope_exit([&] {
  2089. svr.stop();
  2090. thread.join();
  2091. ASSERT_FALSE(svr.is_running());
  2092. });
  2093. svr.wait_until_ready();
  2094. {
  2095. Client cli(HOST, PORT);
  2096. cli.set_path_encode(false);
  2097. auto res = cli.Get("/?something=%0A");
  2098. ASSERT_TRUE(res);
  2099. EXPECT_EQ(StatusCode::OK_200, res->status);
  2100. }
  2101. }
  2102. TEST(BindServerTest, DISABLED_BindDualStack) {
  2103. Server svr;
  2104. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2105. res.set_content("Hello World!", "text/plain");
  2106. });
  2107. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2108. auto se = detail::scope_exit([&] {
  2109. svr.stop();
  2110. thread.join();
  2111. ASSERT_FALSE(svr.is_running());
  2112. });
  2113. svr.wait_until_ready();
  2114. {
  2115. Client cli("127.0.0.1", PORT);
  2116. auto res = cli.Get("/1");
  2117. ASSERT_TRUE(res);
  2118. EXPECT_EQ(StatusCode::OK_200, res->status);
  2119. EXPECT_EQ("Hello World!", res->body);
  2120. }
  2121. {
  2122. Client cli("::1", PORT);
  2123. auto res = cli.Get("/1");
  2124. ASSERT_TRUE(res);
  2125. EXPECT_EQ(StatusCode::OK_200, res->status);
  2126. EXPECT_EQ("Hello World!", res->body);
  2127. }
  2128. }
  2129. TEST(BindServerTest, BindAndListenSeparately) {
  2130. Server svr;
  2131. int port = svr.bind_to_any_port("0.0.0.0");
  2132. ASSERT_TRUE(svr.is_valid());
  2133. ASSERT_TRUE(port > 0);
  2134. svr.stop();
  2135. }
  2136. #ifdef CPPHTTPLIB_SSL_ENABLED
  2137. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2138. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2139. CLIENT_CA_CERT_DIR);
  2140. int port = svr.bind_to_any_port("0.0.0.0");
  2141. ASSERT_TRUE(svr.is_valid());
  2142. ASSERT_TRUE(port > 0);
  2143. svr.stop();
  2144. }
  2145. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2146. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2147. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2148. int port = svr.bind_to_any_port("0.0.0.0");
  2149. ASSERT_TRUE(svr.is_valid());
  2150. ASSERT_TRUE(port > 0);
  2151. svr.stop();
  2152. }
  2153. TEST(BindServerTest, UpdateCertsPem) {
  2154. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2155. int port = svr.bind_to_any_port("0.0.0.0");
  2156. ASSERT_TRUE(svr.is_valid());
  2157. ASSERT_TRUE(port > 0);
  2158. // Read PEM files
  2159. std::string cert_pem, key_pem, ca_pem;
  2160. read_file(SERVER_CERT_FILE, cert_pem);
  2161. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2162. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2163. // Update server certificates using PEM API
  2164. ASSERT_TRUE(
  2165. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2166. ASSERT_TRUE(svr.is_valid());
  2167. svr.stop();
  2168. }
  2169. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2170. // Start server with client CA (enables client auth)
  2171. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2172. ASSERT_TRUE(svr.is_valid());
  2173. bool handler_called = false;
  2174. svr.Get("/test", [&](const Request &req, Response &res) {
  2175. handler_called = true;
  2176. // Verify client certificate is present
  2177. auto cert = req.peer_cert();
  2178. EXPECT_TRUE(static_cast<bool>(cert));
  2179. res.set_content("ok", "text/plain");
  2180. });
  2181. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2182. auto se = detail::scope_exit([&] {
  2183. svr.stop();
  2184. t.join();
  2185. ASSERT_FALSE(svr.is_running());
  2186. });
  2187. svr.wait_until_ready();
  2188. // Read PEM files
  2189. std::string cert_pem, key_pem, ca_pem;
  2190. read_file(SERVER_CERT_FILE, cert_pem);
  2191. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2192. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2193. // Update server certificates and client CA using PEM API while server running
  2194. ASSERT_TRUE(
  2195. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2196. // Connect with client certificate
  2197. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2198. cli.enable_server_certificate_verification(false);
  2199. cli.set_connection_timeout(30);
  2200. auto res = cli.Get("/test");
  2201. ASSERT_TRUE(res);
  2202. ASSERT_EQ(StatusCode::OK_200, res->status);
  2203. ASSERT_TRUE(handler_called);
  2204. EXPECT_EQ("ok", res->body);
  2205. }
  2206. #endif
  2207. TEST(ErrorHandlerTest, ContentLength) {
  2208. Server svr;
  2209. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2210. res.status = StatusCode::OK_200;
  2211. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2212. "text/html"); // <= Content-Length still 13
  2213. });
  2214. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2215. res.set_content("Hello World!\n", "text/plain");
  2216. res.status = 524;
  2217. });
  2218. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2219. auto se = detail::scope_exit([&] {
  2220. svr.stop();
  2221. thread.join();
  2222. ASSERT_FALSE(svr.is_running());
  2223. });
  2224. svr.wait_until_ready();
  2225. {
  2226. Client cli(HOST, PORT);
  2227. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2228. ASSERT_TRUE(res);
  2229. EXPECT_EQ(StatusCode::OK_200, res->status);
  2230. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2231. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2232. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2233. }
  2234. }
  2235. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2236. TEST(ExceptionTest, WithoutExceptionHandler) {
  2237. Server svr;
  2238. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2239. throw std::runtime_error("exception...");
  2240. });
  2241. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2242. throw std::runtime_error("exception\r\n...");
  2243. });
  2244. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2245. auto se = detail::scope_exit([&] {
  2246. svr.stop();
  2247. listen_thread.join();
  2248. ASSERT_FALSE(svr.is_running());
  2249. });
  2250. svr.wait_until_ready();
  2251. Client cli("localhost", PORT);
  2252. {
  2253. auto res = cli.Get("/exception");
  2254. ASSERT_TRUE(res);
  2255. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2256. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2257. }
  2258. {
  2259. auto res = cli.Get("/unknown");
  2260. ASSERT_TRUE(res);
  2261. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2262. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2263. }
  2264. }
  2265. TEST(ExceptionTest, WithExceptionHandler) {
  2266. Server svr;
  2267. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2268. std::exception_ptr ep) {
  2269. EXPECT_FALSE(ep == nullptr);
  2270. try {
  2271. std::rethrow_exception(ep);
  2272. } catch (std::exception &e) {
  2273. EXPECT_EQ("abc", std::string(e.what()));
  2274. } catch (...) {}
  2275. res.status = StatusCode::InternalServerError_500;
  2276. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2277. "text/html"); // <= Content-Length still 13 at this point
  2278. });
  2279. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2280. res.set_content("Hello World!\n", "text/plain");
  2281. throw std::runtime_error("abc");
  2282. });
  2283. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2284. auto se = detail::scope_exit([&] {
  2285. svr.stop();
  2286. thread.join();
  2287. ASSERT_FALSE(svr.is_running());
  2288. });
  2289. svr.wait_until_ready();
  2290. for (size_t i = 0; i < 10; i++) {
  2291. Client cli(HOST, PORT);
  2292. for (size_t j = 0; j < 100; j++) {
  2293. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2294. ASSERT_TRUE(res);
  2295. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2296. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2297. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2298. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2299. }
  2300. cli.set_keep_alive(true);
  2301. for (size_t j = 0; j < 100; j++) {
  2302. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2303. ASSERT_TRUE(res);
  2304. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2305. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2306. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2307. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2308. }
  2309. }
  2310. }
  2311. TEST(ExceptionTest, AndErrorHandler) {
  2312. Server svr;
  2313. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2314. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2315. });
  2316. svr.set_exception_handler(
  2317. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2318. EXPECT_FALSE(ep == nullptr);
  2319. try {
  2320. std::rethrow_exception(ep);
  2321. } catch (std::exception &e) {
  2322. res.set_content(e.what(), "text/html");
  2323. } catch (...) {}
  2324. res.status = StatusCode::InternalServerError_500;
  2325. });
  2326. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2327. throw std::runtime_error("EXCEPTION");
  2328. });
  2329. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2330. res.set_content("ERROR", "text/html");
  2331. res.status = StatusCode::InternalServerError_500;
  2332. });
  2333. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2334. auto se = detail::scope_exit([&] {
  2335. svr.stop();
  2336. thread.join();
  2337. ASSERT_FALSE(svr.is_running());
  2338. });
  2339. svr.wait_until_ready();
  2340. Client cli(HOST, PORT);
  2341. {
  2342. auto res = cli.Get("/exception");
  2343. ASSERT_TRUE(res);
  2344. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2345. EXPECT_EQ("EXCEPTION", res->body);
  2346. }
  2347. {
  2348. auto res = cli.Get("/error");
  2349. ASSERT_TRUE(res);
  2350. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2351. EXPECT_EQ("ERROR", res->body);
  2352. }
  2353. {
  2354. auto res = cli.Get("/invalid");
  2355. ASSERT_TRUE(res);
  2356. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2357. EXPECT_EQ("NOT_FOUND", res->body);
  2358. }
  2359. }
  2360. #endif
  2361. TEST(NoContentTest, ContentLength) {
  2362. Server svr;
  2363. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2364. res.status = StatusCode::NoContent_204;
  2365. });
  2366. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2367. auto se = detail::scope_exit([&] {
  2368. svr.stop();
  2369. thread.join();
  2370. ASSERT_FALSE(svr.is_running());
  2371. });
  2372. svr.wait_until_ready();
  2373. {
  2374. Client cli(HOST, PORT);
  2375. auto res = cli.Get("/hi");
  2376. ASSERT_TRUE(res);
  2377. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2378. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2379. }
  2380. }
  2381. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2382. #ifdef CPPHTTPLIB_SSL_ENABLED
  2383. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2384. ASSERT_TRUE(svr.is_valid());
  2385. #else
  2386. Server svr;
  2387. #endif
  2388. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2389. if (req.path == "/routing_handler") {
  2390. res.set_header("PRE_ROUTING", "on");
  2391. res.set_content("Routing Handler", "text/plain");
  2392. return httplib::Server::HandlerResponse::Handled;
  2393. }
  2394. return httplib::Server::HandlerResponse::Unhandled;
  2395. });
  2396. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2397. res.set_content("Error", "text/html");
  2398. });
  2399. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2400. if (req.path == "/routing_handler") {
  2401. res.set_header("POST_ROUTING", "on");
  2402. }
  2403. });
  2404. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2405. res.set_content("Hello World!\n", "text/plain");
  2406. });
  2407. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2408. auto se = detail::scope_exit([&] {
  2409. svr.stop();
  2410. thread.join();
  2411. ASSERT_FALSE(svr.is_running());
  2412. });
  2413. svr.wait_until_ready();
  2414. {
  2415. #ifdef CPPHTTPLIB_SSL_ENABLED
  2416. SSLClient cli(HOST, PORT);
  2417. cli.enable_server_certificate_verification(false);
  2418. #else
  2419. Client cli(HOST, PORT);
  2420. #endif
  2421. auto res = cli.Get("/routing_handler");
  2422. ASSERT_TRUE(res);
  2423. EXPECT_EQ(StatusCode::OK_200, res->status);
  2424. EXPECT_EQ("Routing Handler", res->body);
  2425. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2426. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2427. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2428. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2429. }
  2430. {
  2431. #ifdef CPPHTTPLIB_SSL_ENABLED
  2432. SSLClient cli(HOST, PORT);
  2433. cli.enable_server_certificate_verification(false);
  2434. #else
  2435. Client cli(HOST, PORT);
  2436. #endif
  2437. auto res = cli.Get("/hi");
  2438. ASSERT_TRUE(res);
  2439. EXPECT_EQ(StatusCode::OK_200, res->status);
  2440. EXPECT_EQ("Hello World!\n", res->body);
  2441. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2442. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2443. }
  2444. {
  2445. #ifdef CPPHTTPLIB_SSL_ENABLED
  2446. SSLClient cli(HOST, PORT);
  2447. cli.enable_server_certificate_verification(false);
  2448. #else
  2449. Client cli(HOST, PORT);
  2450. #endif
  2451. auto res = cli.Get("/aaa");
  2452. ASSERT_TRUE(res);
  2453. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2454. EXPECT_EQ("Error", res->body);
  2455. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2456. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2457. }
  2458. }
  2459. TEST(RequestHandlerTest, PreRequestHandler) {
  2460. auto route_path = "/user/:user";
  2461. Server svr;
  2462. svr.Get("/hi", [](const Request &, Response &res) {
  2463. res.set_content("hi", "text/plain");
  2464. });
  2465. svr.Get(route_path, [](const Request &req, Response &res) {
  2466. res.set_content(req.path_params.at("user"), "text/plain");
  2467. });
  2468. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2469. if (req.matched_route == route_path) {
  2470. auto user = req.path_params.at("user");
  2471. if (user != "john") {
  2472. res.status = StatusCode::Forbidden_403;
  2473. res.set_content("error", "text/html");
  2474. return Server::HandlerResponse::Handled;
  2475. }
  2476. }
  2477. return Server::HandlerResponse::Unhandled;
  2478. });
  2479. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2480. auto se = detail::scope_exit([&] {
  2481. svr.stop();
  2482. thread.join();
  2483. ASSERT_FALSE(svr.is_running());
  2484. });
  2485. svr.wait_until_ready();
  2486. Client cli(HOST, PORT);
  2487. {
  2488. auto res = cli.Get("/hi");
  2489. ASSERT_TRUE(res);
  2490. EXPECT_EQ(StatusCode::OK_200, res->status);
  2491. EXPECT_EQ("hi", res->body);
  2492. }
  2493. {
  2494. auto res = cli.Get("/user/john");
  2495. ASSERT_TRUE(res);
  2496. EXPECT_EQ(StatusCode::OK_200, res->status);
  2497. EXPECT_EQ("john", res->body);
  2498. }
  2499. {
  2500. auto res = cli.Get("/user/invalid-user");
  2501. ASSERT_TRUE(res);
  2502. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2503. EXPECT_EQ("error", res->body);
  2504. }
  2505. }
  2506. TEST(AnyTest, BasicOperations) {
  2507. // Default construction
  2508. httplib::any a;
  2509. EXPECT_FALSE(a.has_value());
  2510. // Value construction and any_cast (pointer form, noexcept)
  2511. httplib::any b(42);
  2512. EXPECT_TRUE(b.has_value());
  2513. auto *p = httplib::any_cast<int>(&b);
  2514. ASSERT_NE(nullptr, p);
  2515. EXPECT_EQ(42, *p);
  2516. // Type mismatch → nullptr
  2517. auto *q = httplib::any_cast<std::string>(&b);
  2518. EXPECT_EQ(nullptr, q);
  2519. // any_cast (value form) succeeds
  2520. EXPECT_EQ(42, httplib::any_cast<int>(b));
  2521. // any_cast (value form) throws on type mismatch
  2522. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2523. EXPECT_THROW(httplib::any_cast<std::string>(b), httplib::bad_any_cast);
  2524. #endif
  2525. // Copy
  2526. httplib::any c = b;
  2527. EXPECT_EQ(42, httplib::any_cast<int>(c));
  2528. // Move
  2529. httplib::any d = std::move(c);
  2530. EXPECT_EQ(42, httplib::any_cast<int>(d));
  2531. // Assignment with different type
  2532. b = std::string("hello");
  2533. EXPECT_EQ("hello", httplib::any_cast<std::string>(b));
  2534. // Reset
  2535. b.reset();
  2536. EXPECT_FALSE(b.has_value());
  2537. }
  2538. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2539. struct AuthCtx {
  2540. std::string user_id;
  2541. };
  2542. Server svr;
  2543. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2544. res.user_data["auth"] = AuthCtx{"alice"};
  2545. return Server::HandlerResponse::Unhandled;
  2546. });
  2547. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2548. auto *ctx = httplib::any_cast<AuthCtx>(&res.user_data["auth"]);
  2549. ASSERT_NE(nullptr, ctx);
  2550. res.set_content("Hello " + ctx->user_id, "text/plain");
  2551. });
  2552. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2553. auto se = detail::scope_exit([&] {
  2554. svr.stop();
  2555. thread.join();
  2556. ASSERT_FALSE(svr.is_running());
  2557. });
  2558. svr.wait_until_ready();
  2559. Client cli(HOST, PORT);
  2560. auto res = cli.Get("/me");
  2561. ASSERT_TRUE(res);
  2562. EXPECT_EQ(StatusCode::OK_200, res->status);
  2563. EXPECT_EQ("Hello alice", res->body);
  2564. }
  2565. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2566. struct RoleCtx {
  2567. std::string role;
  2568. };
  2569. Server svr;
  2570. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2571. res.user_data["role"] = RoleCtx{"admin"};
  2572. return Server::HandlerResponse::Unhandled;
  2573. });
  2574. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2575. auto *ctx = httplib::any_cast<RoleCtx>(&res.user_data["role"]);
  2576. ASSERT_NE(nullptr, ctx);
  2577. res.set_content(ctx->role, "text/plain");
  2578. });
  2579. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2580. auto se = detail::scope_exit([&] {
  2581. svr.stop();
  2582. thread.join();
  2583. ASSERT_FALSE(svr.is_running());
  2584. });
  2585. svr.wait_until_ready();
  2586. Client cli(HOST, PORT);
  2587. auto res = cli.Get("/role");
  2588. ASSERT_TRUE(res);
  2589. EXPECT_EQ(StatusCode::OK_200, res->status);
  2590. EXPECT_EQ("admin", res->body);
  2591. }
  2592. TEST(InvalidFormatTest, StatusCode) {
  2593. Server svr;
  2594. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2595. res.set_content("Hello World!\n", "text/plain");
  2596. res.status = 9999; // Status should be a three-digit code...
  2597. });
  2598. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2599. auto se = detail::scope_exit([&] {
  2600. svr.stop();
  2601. thread.join();
  2602. ASSERT_FALSE(svr.is_running());
  2603. });
  2604. svr.wait_until_ready();
  2605. {
  2606. Client cli(HOST, PORT);
  2607. auto res = cli.Get("/hi");
  2608. ASSERT_FALSE(res);
  2609. }
  2610. }
  2611. TEST(URLFragmentTest, WithFragment) {
  2612. Server svr;
  2613. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2614. EXPECT_TRUE(req.target == "/hi");
  2615. });
  2616. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2617. auto se = detail::scope_exit([&] {
  2618. svr.stop();
  2619. thread.join();
  2620. ASSERT_FALSE(svr.is_running());
  2621. });
  2622. svr.wait_until_ready();
  2623. {
  2624. Client cli(HOST, PORT);
  2625. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2626. EXPECT_TRUE(res);
  2627. EXPECT_EQ(StatusCode::OK_200, res->status);
  2628. res = cli.Get("/hi%23key1=val1=key2=val2");
  2629. EXPECT_TRUE(res);
  2630. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2631. }
  2632. }
  2633. TEST(HeaderWriter, SetHeaderWriter) {
  2634. Server svr;
  2635. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2636. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2637. return detail::write_headers(strm, hdrs);
  2638. });
  2639. svr.Get("/hi", [](const Request &req, Response &res) {
  2640. auto it = req.headers.find("CustomClientHeader");
  2641. EXPECT_TRUE(it != req.headers.end());
  2642. EXPECT_EQ(it->second, "CustomClientValue");
  2643. res.set_content("Hello World!\n", "text/plain");
  2644. });
  2645. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2646. auto se = detail::scope_exit([&] {
  2647. svr.stop();
  2648. thread.join();
  2649. ASSERT_FALSE(svr.is_running());
  2650. });
  2651. svr.wait_until_ready();
  2652. {
  2653. Client cli(HOST, PORT);
  2654. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2655. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2656. return detail::write_headers(strm, hdrs);
  2657. });
  2658. auto res = cli.Get("/hi");
  2659. EXPECT_TRUE(res);
  2660. EXPECT_EQ(StatusCode::OK_200, res->status);
  2661. auto it = res->headers.find("CustomServerHeader");
  2662. EXPECT_TRUE(it != res->headers.end());
  2663. EXPECT_EQ(it->second, "CustomServerValue");
  2664. }
  2665. }
  2666. class ServerTest : public ::testing::Test {
  2667. protected:
  2668. ServerTest()
  2669. : cli_(HOST, PORT)
  2670. #ifdef CPPHTTPLIB_SSL_ENABLED
  2671. ,
  2672. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2673. #endif
  2674. {
  2675. #ifdef CPPHTTPLIB_SSL_ENABLED
  2676. cli_.enable_server_certificate_verification(false);
  2677. #endif
  2678. // Allow LARGE_DATA (100MB) responses
  2679. cli_.set_payload_max_length(200 * 1024 * 1024);
  2680. }
  2681. virtual void SetUp() {
  2682. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2683. svr_.set_payload_max_length(200 * 1024 * 1024);
  2684. svr_.set_mount_point("/", "./www");
  2685. svr_.set_mount_point("/mount", "./www2");
  2686. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2687. svr_.Get("/hi",
  2688. [&](const Request & /*req*/, Response &res) {
  2689. res.set_content("Hello World!", "text/plain");
  2690. })
  2691. .Get("/file_content",
  2692. [&](const Request & /*req*/, Response &res) {
  2693. res.set_file_content("./www/dir/test.html");
  2694. })
  2695. .Get("/file_content_with_content_type",
  2696. [&](const Request & /*req*/, Response &res) {
  2697. res.set_file_content("./www/file", "text/plain");
  2698. })
  2699. .Get("/invalid_file_content",
  2700. [&](const Request & /*req*/, Response &res) {
  2701. res.set_file_content("./www/dir/invalid_file_path");
  2702. })
  2703. .Get("/http_response_splitting",
  2704. [&](const Request & /*req*/, Response &res) {
  2705. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2706. EXPECT_EQ(0U, res.headers.size());
  2707. EXPECT_FALSE(res.has_header("a"));
  2708. res.set_header("a", "1\nSet-Cookie: a=1");
  2709. EXPECT_EQ(0U, res.headers.size());
  2710. EXPECT_FALSE(res.has_header("a"));
  2711. res.set_header("a", "1\rSet-Cookie: a=1");
  2712. EXPECT_EQ(0U, res.headers.size());
  2713. EXPECT_FALSE(res.has_header("a"));
  2714. res.set_header("a\r\nb", "0");
  2715. EXPECT_EQ(0U, res.headers.size());
  2716. EXPECT_FALSE(res.has_header("a"));
  2717. res.set_header("a\rb", "0");
  2718. EXPECT_EQ(0U, res.headers.size());
  2719. EXPECT_FALSE(res.has_header("a"));
  2720. res.set_header("a\nb", "0");
  2721. EXPECT_EQ(0U, res.headers.size());
  2722. EXPECT_FALSE(res.has_header("a"));
  2723. res.set_redirect("1\r\nSet-Cookie: a=1");
  2724. EXPECT_EQ(0U, res.headers.size());
  2725. EXPECT_FALSE(res.has_header("Location"));
  2726. })
  2727. .Get("/slow",
  2728. [&](const Request & /*req*/, Response &res) {
  2729. std::this_thread::sleep_for(std::chrono::seconds(2));
  2730. res.set_content("slow", "text/plain");
  2731. })
  2732. #if 0
  2733. .Post("/slowpost",
  2734. [&](const Request & /*req*/, Response &res) {
  2735. std::this_thread::sleep_for(std::chrono::seconds(2));
  2736. res.set_content("slow", "text/plain");
  2737. })
  2738. #endif
  2739. .Get("/remote_addr",
  2740. [&](const Request &req, Response &res) {
  2741. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2742. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2743. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2744. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2745. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2746. #endif
  2747. res.set_content(req.remote_addr, "text/plain");
  2748. })
  2749. .Get("/local_addr",
  2750. [&](const Request &req, Response &res) {
  2751. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2752. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2753. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2754. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2755. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2756. #endif
  2757. auto local_addr = req.local_addr;
  2758. auto local_port = std::to_string(req.local_port);
  2759. res.set_content(local_addr.append(":").append(local_port),
  2760. "text/plain");
  2761. })
  2762. .Get("/endwith%",
  2763. [&](const Request & /*req*/, Response &res) {
  2764. res.set_content("Hello World!", "text/plain");
  2765. })
  2766. .Get("/a\\+\\+b",
  2767. [&](const Request &req, Response &res) {
  2768. ASSERT_TRUE(req.has_param("a +b"));
  2769. auto val = req.get_param_value("a +b");
  2770. res.set_content(val, "text/plain");
  2771. })
  2772. .Get("/", [&](const Request & /*req*/,
  2773. Response &res) { res.set_redirect("/hi"); })
  2774. .Post("/1",
  2775. [](const Request & /*req*/, Response &res) {
  2776. res.set_redirect("/2", StatusCode::SeeOther_303);
  2777. })
  2778. .Get("/2",
  2779. [](const Request & /*req*/, Response &res) {
  2780. res.set_content("redirected.", "text/plain");
  2781. res.status = StatusCode::OK_200;
  2782. })
  2783. .Post("/person",
  2784. [&](const Request &req, Response &res) {
  2785. if (req.has_param("name") && req.has_param("note")) {
  2786. persons_[req.get_param_value("name")] =
  2787. req.get_param_value("note");
  2788. } else {
  2789. res.status = StatusCode::BadRequest_400;
  2790. }
  2791. })
  2792. .Put("/person",
  2793. [&](const Request &req, Response &res) {
  2794. if (req.has_param("name") && req.has_param("note")) {
  2795. persons_[req.get_param_value("name")] =
  2796. req.get_param_value("note");
  2797. } else {
  2798. res.status = StatusCode::BadRequest_400;
  2799. }
  2800. })
  2801. .Get("/person/(.*)",
  2802. [&](const Request &req, Response &res) {
  2803. string name = req.matches[1];
  2804. if (persons_.find(name) != persons_.end()) {
  2805. auto note = persons_[name];
  2806. res.set_content(note, "text/plain");
  2807. } else {
  2808. res.status = StatusCode::NotFound_404;
  2809. }
  2810. })
  2811. .Delete("/person",
  2812. [&](const Request &req, Response &res) {
  2813. if (req.has_param("name")) {
  2814. string name = req.get_param_value("name");
  2815. if (persons_.find(name) != persons_.end()) {
  2816. persons_.erase(name);
  2817. res.set_content("DELETED", "text/plain");
  2818. } else {
  2819. res.status = StatusCode::NotFound_404;
  2820. }
  2821. } else {
  2822. res.status = StatusCode::BadRequest_400;
  2823. }
  2824. })
  2825. .Post("/x-www-form-urlencoded-json",
  2826. [&](const Request &req, Response &res) {
  2827. auto json = req.get_param_value("json");
  2828. ASSERT_EQ(JSON_DATA, json);
  2829. res.set_content(json, "appliation/json");
  2830. res.status = StatusCode::OK_200;
  2831. })
  2832. .Get("/streamed-chunked",
  2833. [&](const Request & /*req*/, Response &res) {
  2834. res.set_chunked_content_provider(
  2835. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2836. sink.os << "123";
  2837. sink.os << "456";
  2838. sink.os << "789";
  2839. sink.done();
  2840. return true;
  2841. });
  2842. })
  2843. .Get("/streamed-chunked-with-prohibited-trailer",
  2844. [&](const Request & /*req*/, Response &res) {
  2845. auto i = new int(0);
  2846. // Declare both a prohibited trailer (Content-Length) and an
  2847. // allowed one
  2848. res.set_header("Trailer", "Content-Length, X-Allowed");
  2849. res.set_chunked_content_provider(
  2850. "text/plain",
  2851. [i](size_t /*offset*/, DataSink &sink) {
  2852. switch (*i) {
  2853. case 0: sink.os << "123"; break;
  2854. case 1: sink.os << "456"; break;
  2855. case 2: sink.os << "789"; break;
  2856. case 3: {
  2857. sink.done_with_trailer(
  2858. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2859. } break;
  2860. }
  2861. (*i)++;
  2862. return true;
  2863. },
  2864. [i](bool success) {
  2865. EXPECT_TRUE(success);
  2866. delete i;
  2867. });
  2868. })
  2869. .Get("/streamed-chunked2",
  2870. [&](const Request & /*req*/, Response &res) {
  2871. auto i = new int(0);
  2872. res.set_chunked_content_provider(
  2873. "text/plain",
  2874. [i](size_t /*offset*/, DataSink &sink) {
  2875. switch (*i) {
  2876. case 0: sink.os << "123"; break;
  2877. case 1: sink.os << "456"; break;
  2878. case 2: sink.os << "789"; break;
  2879. case 3: sink.done(); break;
  2880. }
  2881. (*i)++;
  2882. return true;
  2883. },
  2884. [i](bool success) {
  2885. EXPECT_TRUE(success);
  2886. delete i;
  2887. });
  2888. })
  2889. .Get("/streamed-chunked-with-trailer",
  2890. [&](const Request & /*req*/, Response &res) {
  2891. auto i = new int(0);
  2892. res.set_header("Trailer", "Dummy1, Dummy2");
  2893. res.set_chunked_content_provider(
  2894. "text/plain",
  2895. [i](size_t /*offset*/, DataSink &sink) {
  2896. switch (*i) {
  2897. case 0: sink.os << "123"; break;
  2898. case 1: sink.os << "456"; break;
  2899. case 2: sink.os << "789"; break;
  2900. case 3: {
  2901. sink.done_with_trailer(
  2902. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2903. } break;
  2904. }
  2905. (*i)++;
  2906. return true;
  2907. },
  2908. [i](bool success) {
  2909. EXPECT_TRUE(success);
  2910. delete i;
  2911. });
  2912. })
  2913. .Get("/streamed",
  2914. [&](const Request & /*req*/, Response &res) {
  2915. res.set_content_provider(
  2916. 6, "text/plain",
  2917. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2918. sink.os << (offset < 3 ? "a" : "b");
  2919. return true;
  2920. });
  2921. })
  2922. .Get("/streamed-with-range",
  2923. [&](const Request &req, Response &res) {
  2924. auto data = new std::string("abcdefg");
  2925. res.set_content_provider(
  2926. data->size(), "text/plain",
  2927. [data](size_t offset, size_t length, DataSink &sink) {
  2928. size_t DATA_CHUNK_SIZE = 4;
  2929. const auto &d = *data;
  2930. auto out_len =
  2931. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2932. auto ret =
  2933. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2934. EXPECT_TRUE(ret);
  2935. return true;
  2936. },
  2937. [data, &req](bool success) {
  2938. EXPECT_EQ(success, !req.has_param("error"));
  2939. delete data;
  2940. });
  2941. })
  2942. .Get("/streamed-cancel",
  2943. [&](const Request & /*req*/, Response &res) {
  2944. res.set_content_provider(
  2945. size_t(-1), "text/plain",
  2946. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2947. sink.os << "data_chunk";
  2948. return true;
  2949. });
  2950. })
  2951. .Get("/regex-with-delimiter",
  2952. [&](const Request &req, Response & /*res*/) {
  2953. ASSERT_TRUE(req.has_param("key"));
  2954. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2955. })
  2956. .Get("/with-range",
  2957. [&](const Request & /*req*/, Response &res) {
  2958. res.set_content("abcdefg", "text/plain");
  2959. })
  2960. .Get("/test-start-time",
  2961. [&](const Request &req, Response & /*res*/) {
  2962. EXPECT_NE(req.start_time_,
  2963. std::chrono::steady_clock::time_point::min());
  2964. })
  2965. .Get("/with-range-customized-response",
  2966. [&](const Request & /*req*/, Response &res) {
  2967. res.status = StatusCode::BadRequest_400;
  2968. res.set_content(JSON_DATA, "application/json");
  2969. })
  2970. .Post("/chunked",
  2971. [&](const Request &req, Response & /*res*/) {
  2972. EXPECT_EQ(req.body, "dechunked post body");
  2973. })
  2974. .Post("/large-chunked",
  2975. [&](const Request &req, Response & /*res*/) {
  2976. std::string expected(6 * 30 * 1024u, 'a');
  2977. EXPECT_EQ(req.body, expected);
  2978. })
  2979. .Post("/multipart",
  2980. [&](const Request &req, Response & /*res*/) {
  2981. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2982. req.form.get_field_count("text2") +
  2983. req.form.get_field_count("file3") +
  2984. req.form.get_field_count("file4"));
  2985. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2986. req.form.get_file_count("file2"));
  2987. ASSERT_TRUE(!req.form.has_file("???"));
  2988. ASSERT_TRUE(!req.form.has_field("???"));
  2989. ASSERT_TRUE(req.body.empty());
  2990. {
  2991. const auto &text = req.form.get_field("text1");
  2992. EXPECT_EQ("text default", text);
  2993. }
  2994. {
  2995. const auto &text = req.form.get_field("text2");
  2996. EXPECT_EQ("aωb", text);
  2997. }
  2998. {
  2999. const auto &file = req.form.get_file("file1");
  3000. EXPECT_EQ("hello.txt", file.filename);
  3001. EXPECT_EQ("text/plain", file.content_type);
  3002. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3003. }
  3004. {
  3005. const auto &file = req.form.get_file("file2");
  3006. EXPECT_EQ("world.json", file.filename);
  3007. EXPECT_EQ("application/json", file.content_type);
  3008. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3009. }
  3010. {
  3011. const auto &text = req.form.get_field("file3");
  3012. EXPECT_EQ(0u, text.size());
  3013. }
  3014. {
  3015. const auto &text = req.form.get_field("file4");
  3016. EXPECT_EQ(0u, text.size());
  3017. }
  3018. })
  3019. .Post("/multipart/multi_file_values",
  3020. [&](const Request &req, Response & /*res*/) {
  3021. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3022. req.form.get_field_count("multi_text1"));
  3023. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3024. ASSERT_TRUE(!req.form.has_file("???"));
  3025. ASSERT_TRUE(!req.form.has_field("???"));
  3026. ASSERT_TRUE(req.body.empty());
  3027. {
  3028. const auto &text = req.form.get_field("text");
  3029. EXPECT_EQ("default text", text);
  3030. }
  3031. {
  3032. const auto &text1_values = req.form.get_fields("multi_text1");
  3033. EXPECT_EQ(2u, text1_values.size());
  3034. EXPECT_EQ("aaaaa", text1_values[0]);
  3035. EXPECT_EQ("bbbbb", text1_values[1]);
  3036. }
  3037. {
  3038. const auto &file1_values = req.form.get_files("multi_file1");
  3039. EXPECT_EQ(2u, file1_values.size());
  3040. auto file1 = file1_values[0];
  3041. EXPECT_EQ(file1.filename, "hello.txt");
  3042. EXPECT_EQ(file1.content_type, "text/plain");
  3043. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3044. auto file2 = file1_values[1];
  3045. EXPECT_EQ(file2.filename, "world.json");
  3046. EXPECT_EQ(file2.content_type, "application/json");
  3047. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3048. }
  3049. })
  3050. .Post("/empty",
  3051. [&](const Request &req, Response &res) {
  3052. EXPECT_EQ(req.body, "");
  3053. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3054. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3055. res.set_content("empty", "text/plain");
  3056. })
  3057. .Post("/empty-no-content-type",
  3058. [&](const Request &req, Response &res) {
  3059. EXPECT_EQ(req.body, "");
  3060. EXPECT_FALSE(req.has_header("Content-Type"));
  3061. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3062. res.set_content("empty-no-content-type", "text/plain");
  3063. })
  3064. .Post("/path-only",
  3065. [&](const Request &req, Response &res) {
  3066. EXPECT_EQ(req.body, "");
  3067. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3068. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3069. res.set_content("path-only", "text/plain");
  3070. })
  3071. .Post("/path-headers-only",
  3072. [&](const Request &req, Response &res) {
  3073. EXPECT_EQ(req.body, "");
  3074. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3075. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3076. EXPECT_EQ("world", req.get_header_value("hello"));
  3077. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3078. res.set_content("path-headers-only", "text/plain");
  3079. })
  3080. .Post("/post-large",
  3081. [&](const Request &req, Response &res) {
  3082. EXPECT_EQ(req.body, LARGE_DATA);
  3083. res.set_content(req.body, "text/plain");
  3084. })
  3085. .Post("/post-loopback",
  3086. [&](const Request &, Response &res,
  3087. ContentReader const &content_reader) {
  3088. std::string body;
  3089. content_reader([&](const char *data, size_t data_length) {
  3090. body.append(data, data_length);
  3091. return true;
  3092. });
  3093. res.set_content(body, "text/plain");
  3094. })
  3095. .Put("/put-loopback",
  3096. [&](const Request &, Response &res,
  3097. ContentReader const &content_reader) {
  3098. std::string body;
  3099. content_reader([&](const char *data, size_t data_length) {
  3100. body.append(data, data_length);
  3101. return true;
  3102. });
  3103. res.set_content(body, "text/plain");
  3104. })
  3105. .Patch("/patch-loopback",
  3106. [&](const Request &, Response &res,
  3107. ContentReader const &content_reader) {
  3108. std::string body;
  3109. content_reader([&](const char *data, size_t data_length) {
  3110. body.append(data, data_length);
  3111. return true;
  3112. });
  3113. res.set_content(body, "text/plain");
  3114. })
  3115. .Put("/empty-no-content-type",
  3116. [&](const Request &req, Response &res) {
  3117. EXPECT_EQ(req.body, "");
  3118. EXPECT_FALSE(req.has_header("Content-Type"));
  3119. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3120. res.set_content("empty-no-content-type", "text/plain");
  3121. })
  3122. .Put("/put",
  3123. [&](const Request &req, Response &res) {
  3124. EXPECT_EQ(req.body, "PUT");
  3125. res.set_content(req.body, "text/plain");
  3126. })
  3127. .Put("/put-large",
  3128. [&](const Request &req, Response &res) {
  3129. EXPECT_EQ(req.body, LARGE_DATA);
  3130. res.set_content(req.body, "text/plain");
  3131. })
  3132. .Patch("/patch",
  3133. [&](const Request &req, Response &res) {
  3134. EXPECT_EQ(req.body, "PATCH");
  3135. res.set_content(req.body, "text/plain");
  3136. })
  3137. .Delete("/delete",
  3138. [&](const Request & /*req*/, Response &res) {
  3139. res.set_content("DELETE", "text/plain");
  3140. })
  3141. .Delete("/delete-body",
  3142. [&](const Request &req, Response &res) {
  3143. EXPECT_EQ(req.body, "content");
  3144. res.set_content(req.body, "text/plain");
  3145. })
  3146. .Options(R"(\*)",
  3147. [&](const Request & /*req*/, Response &res) {
  3148. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3149. })
  3150. .Get("/request-target",
  3151. [&](const Request &req, Response & /*res*/) {
  3152. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3153. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3154. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3155. })
  3156. .Get("/long-query-value",
  3157. [&](const Request &req, Response & /*res*/) {
  3158. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3159. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3160. })
  3161. .Get("/too-long-query-value",
  3162. [&](const Request &req, Response & /*res*/) {
  3163. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3164. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3165. })
  3166. .Get("/array-param",
  3167. [&](const Request &req, Response & /*res*/) {
  3168. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3169. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3170. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3171. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3172. })
  3173. .Post("/validate-no-multiple-headers",
  3174. [&](const Request &req, Response & /*res*/) {
  3175. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3176. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3177. })
  3178. .Post("/content_receiver",
  3179. [&](const Request &req, Response &res,
  3180. const ContentReader &content_reader) {
  3181. if (req.is_multipart_form_data()) {
  3182. std::vector<FormData> items;
  3183. content_reader(
  3184. [&](const FormData &file) {
  3185. items.push_back(file);
  3186. return true;
  3187. },
  3188. [&](const char *data, size_t data_length) {
  3189. items.back().content.append(data, data_length);
  3190. return true;
  3191. });
  3192. EXPECT_EQ(5u, items.size());
  3193. {
  3194. const auto &file = get_file_value(items, "text1");
  3195. EXPECT_TRUE(file.filename.empty());
  3196. EXPECT_EQ("text default", file.content);
  3197. }
  3198. {
  3199. const auto &file = get_file_value(items, "text2");
  3200. EXPECT_TRUE(file.filename.empty());
  3201. EXPECT_EQ("aωb", file.content);
  3202. }
  3203. {
  3204. const auto &file = get_file_value(items, "file1");
  3205. EXPECT_EQ("hello.txt", file.filename);
  3206. EXPECT_EQ("text/plain", file.content_type);
  3207. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3208. }
  3209. {
  3210. const auto &file = get_file_value(items, "file2");
  3211. EXPECT_EQ("world.json", file.filename);
  3212. EXPECT_EQ("application/json", file.content_type);
  3213. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3214. }
  3215. {
  3216. const auto &file = get_file_value(items, "file3");
  3217. EXPECT_TRUE(file.filename.empty());
  3218. EXPECT_EQ("application/octet-stream", file.content_type);
  3219. EXPECT_EQ(0u, file.content.size());
  3220. }
  3221. } else {
  3222. std::string body;
  3223. content_reader([&](const char *data, size_t data_length) {
  3224. EXPECT_EQ(7U, data_length);
  3225. body.append(data, data_length);
  3226. return true;
  3227. });
  3228. EXPECT_EQ(body, "content");
  3229. res.set_content(body, "text/plain");
  3230. }
  3231. })
  3232. .Put("/content_receiver",
  3233. [&](const Request & /*req*/, Response &res,
  3234. const ContentReader &content_reader) {
  3235. std::string body;
  3236. content_reader([&](const char *data, size_t data_length) {
  3237. body.append(data, data_length);
  3238. return true;
  3239. });
  3240. EXPECT_EQ(body, "content");
  3241. res.set_content(body, "text/plain");
  3242. })
  3243. .Patch("/content_receiver",
  3244. [&](const Request & /*req*/, Response &res,
  3245. const ContentReader &content_reader) {
  3246. std::string body;
  3247. content_reader([&](const char *data, size_t data_length) {
  3248. body.append(data, data_length);
  3249. return true;
  3250. });
  3251. EXPECT_EQ(body, "content");
  3252. res.set_content(body, "text/plain");
  3253. })
  3254. .Post("/query-string-and-body",
  3255. [&](const Request &req, Response & /*res*/) {
  3256. ASSERT_TRUE(req.has_param("key"));
  3257. EXPECT_EQ(req.get_param_value("key"), "value");
  3258. EXPECT_EQ(req.body, "content");
  3259. })
  3260. .Get("/last-request",
  3261. [&](const Request &req, Response & /*res*/) {
  3262. EXPECT_EQ("close", req.get_header_value("Connection"));
  3263. })
  3264. .Get(R"(/redirect/(\d+))",
  3265. [&](const Request &req, Response &res) {
  3266. auto num = std::stoi(req.matches[1]) + 1;
  3267. std::string url = "/redirect/" + std::to_string(num);
  3268. res.set_redirect(url);
  3269. })
  3270. .Post("/binary",
  3271. [&](const Request &req, Response &res) {
  3272. EXPECT_EQ(4U, req.body.size());
  3273. EXPECT_EQ("application/octet-stream",
  3274. req.get_header_value("Content-Type"));
  3275. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3276. res.set_content(req.body, "application/octet-stream");
  3277. })
  3278. .Put("/binary",
  3279. [&](const Request &req, Response &res) {
  3280. EXPECT_EQ(4U, req.body.size());
  3281. EXPECT_EQ("application/octet-stream",
  3282. req.get_header_value("Content-Type"));
  3283. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3284. res.set_content(req.body, "application/octet-stream");
  3285. })
  3286. .Patch("/binary",
  3287. [&](const Request &req, Response &res) {
  3288. EXPECT_EQ(4U, req.body.size());
  3289. EXPECT_EQ("application/octet-stream",
  3290. req.get_header_value("Content-Type"));
  3291. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3292. res.set_content(req.body, "application/octet-stream");
  3293. })
  3294. .Delete("/binary",
  3295. [&](const Request &req, Response &res) {
  3296. EXPECT_EQ(4U, req.body.size());
  3297. EXPECT_EQ("application/octet-stream",
  3298. req.get_header_value("Content-Type"));
  3299. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3300. res.set_content(req.body, "application/octet-stream");
  3301. })
  3302. .Get("/issue1772",
  3303. [&](const Request & /*req*/, Response &res) {
  3304. res.status = 401;
  3305. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3306. })
  3307. .Delete("/issue609",
  3308. [](const httplib::Request &, httplib::Response &res,
  3309. const httplib::ContentReader &) {
  3310. res.set_content("ok", "text/plain");
  3311. })
  3312. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3313. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3314. .Get("/compress",
  3315. [&](const Request & /*req*/, Response &res) {
  3316. res.set_content(
  3317. "12345678901234567890123456789012345678901234567890123456789"
  3318. "01234567890123456789012345678901234567890",
  3319. "text/plain");
  3320. })
  3321. .Get("/compress-with-charset",
  3322. [&](const Request & /*req*/, Response &res) {
  3323. res.set_content(
  3324. "12345678901234567890123456789012345678901234567890123456789"
  3325. "01234567890123456789012345678901234567890",
  3326. "application/json; charset=utf-8");
  3327. })
  3328. .Get("/nocompress",
  3329. [&](const Request & /*req*/, Response &res) {
  3330. res.set_content(
  3331. "12345678901234567890123456789012345678901234567890123456789"
  3332. "01234567890123456789012345678901234567890",
  3333. "application/octet-stream");
  3334. })
  3335. .Post("/compress-multipart",
  3336. [&](const Request &req, Response & /*res*/) {
  3337. EXPECT_EQ(2u, req.form.fields.size());
  3338. ASSERT_TRUE(!req.form.has_field("???"));
  3339. {
  3340. const auto &text = req.form.get_field("key1");
  3341. EXPECT_EQ("test", text);
  3342. }
  3343. {
  3344. const auto &text = req.form.get_field("key2");
  3345. EXPECT_EQ("--abcdefg123", text);
  3346. }
  3347. })
  3348. #endif
  3349. ;
  3350. persons_["john"] = "programmer";
  3351. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3352. svr_.wait_until_ready();
  3353. }
  3354. virtual void TearDown() {
  3355. svr_.stop();
  3356. if (!request_threads_.empty()) {
  3357. std::this_thread::sleep_for(std::chrono::seconds(1));
  3358. for (auto &t : request_threads_) {
  3359. t.join();
  3360. }
  3361. }
  3362. t_.join();
  3363. }
  3364. map<string, string> persons_;
  3365. #ifdef CPPHTTPLIB_SSL_ENABLED
  3366. SSLClient cli_;
  3367. SSLServer svr_;
  3368. #else
  3369. Client cli_;
  3370. Server svr_;
  3371. #endif
  3372. thread t_;
  3373. std::vector<thread> request_threads_;
  3374. };
  3375. TEST_F(ServerTest, GetMethod200) {
  3376. auto res = cli_.Get("/hi");
  3377. ASSERT_TRUE(res);
  3378. EXPECT_EQ("HTTP/1.1", res->version);
  3379. EXPECT_EQ(StatusCode::OK_200, res->status);
  3380. EXPECT_EQ("OK", res->reason);
  3381. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3382. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3383. EXPECT_EQ("Hello World!", res->body);
  3384. }
  3385. TEST_F(ServerTest, GetEmptyFile) {
  3386. auto res = cli_.Get("/empty_file");
  3387. ASSERT_TRUE(res);
  3388. EXPECT_EQ(StatusCode::OK_200, res->status);
  3389. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3390. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3391. EXPECT_EQ("", res->body);
  3392. }
  3393. TEST_F(ServerTest, GetFileContent) {
  3394. auto res = cli_.Get("/file_content");
  3395. ASSERT_TRUE(res);
  3396. EXPECT_EQ(StatusCode::OK_200, res->status);
  3397. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3398. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3399. EXPECT_EQ("test.html", res->body);
  3400. }
  3401. TEST_F(ServerTest, GetFileContentWithRange) {
  3402. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3403. ASSERT_TRUE(res);
  3404. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3405. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3406. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3407. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3408. EXPECT_EQ("est", res->body);
  3409. }
  3410. TEST_F(ServerTest, GetFileContentWithContentType) {
  3411. auto res = cli_.Get("/file_content_with_content_type");
  3412. ASSERT_TRUE(res);
  3413. EXPECT_EQ(StatusCode::OK_200, res->status);
  3414. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3415. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3416. EXPECT_EQ("file\n", res->body);
  3417. }
  3418. TEST_F(ServerTest, GetInvalidFileContent) {
  3419. auto res = cli_.Get("/invalid_file_content");
  3420. ASSERT_TRUE(res);
  3421. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3422. }
  3423. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3424. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3425. ASSERT_TRUE(res);
  3426. EXPECT_EQ("HTTP/1.1", res->version);
  3427. EXPECT_EQ(StatusCode::OK_200, res->status);
  3428. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3429. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3430. EXPECT_EQ("Hello World!", res->body);
  3431. }
  3432. TEST_F(ServerTest, GetMethod302) {
  3433. auto res = cli_.Get("/");
  3434. ASSERT_TRUE(res);
  3435. EXPECT_EQ(StatusCode::Found_302, res->status);
  3436. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3437. }
  3438. TEST_F(ServerTest, GetMethod302Redirect) {
  3439. cli_.set_follow_location(true);
  3440. auto res = cli_.Get("/");
  3441. ASSERT_TRUE(res);
  3442. EXPECT_EQ(StatusCode::OK_200, res->status);
  3443. EXPECT_EQ("Hello World!", res->body);
  3444. EXPECT_EQ("/hi", res->location);
  3445. }
  3446. TEST_F(ServerTest, GetMethod404) {
  3447. auto res = cli_.Get("/invalid");
  3448. ASSERT_TRUE(res);
  3449. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3450. }
  3451. TEST_F(ServerTest, HeadMethod200) {
  3452. auto res = cli_.Head("/hi");
  3453. ASSERT_TRUE(res);
  3454. EXPECT_EQ(StatusCode::OK_200, res->status);
  3455. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3456. EXPECT_TRUE(res->body.empty());
  3457. }
  3458. TEST_F(ServerTest, HeadMethod200Static) {
  3459. auto res = cli_.Head("/mount/dir/index.html");
  3460. ASSERT_TRUE(res);
  3461. EXPECT_EQ(StatusCode::OK_200, res->status);
  3462. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3463. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3464. EXPECT_TRUE(res->body.empty());
  3465. }
  3466. TEST_F(ServerTest, HeadMethod404) {
  3467. auto res = cli_.Head("/invalid");
  3468. ASSERT_TRUE(res);
  3469. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3470. EXPECT_TRUE(res->body.empty());
  3471. }
  3472. TEST_F(ServerTest, GetMethodPersonJohn) {
  3473. auto res = cli_.Get("/person/john");
  3474. ASSERT_TRUE(res);
  3475. EXPECT_EQ(StatusCode::OK_200, res->status);
  3476. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3477. EXPECT_EQ("programmer", res->body);
  3478. }
  3479. TEST_F(ServerTest, PostMethod1) {
  3480. auto res = cli_.Get("/person/john1");
  3481. ASSERT_TRUE(res);
  3482. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3483. res = cli_.Post("/person", "name=john1&note=coder",
  3484. "application/x-www-form-urlencoded");
  3485. ASSERT_TRUE(res);
  3486. ASSERT_EQ(StatusCode::OK_200, res->status);
  3487. res = cli_.Get("/person/john1");
  3488. ASSERT_TRUE(res);
  3489. ASSERT_EQ(StatusCode::OK_200, res->status);
  3490. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3491. ASSERT_EQ("coder", res->body);
  3492. }
  3493. TEST_F(ServerTest, PostMethod2) {
  3494. auto res = cli_.Get("/person/john2");
  3495. ASSERT_TRUE(res);
  3496. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3497. Params params;
  3498. params.emplace("name", "john2");
  3499. params.emplace("note", "coder");
  3500. res = cli_.Post("/person", params);
  3501. ASSERT_TRUE(res);
  3502. ASSERT_EQ(StatusCode::OK_200, res->status);
  3503. res = cli_.Get("/person/john2");
  3504. ASSERT_TRUE(res);
  3505. ASSERT_EQ(StatusCode::OK_200, res->status);
  3506. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3507. ASSERT_EQ("coder", res->body);
  3508. }
  3509. TEST_F(ServerTest, PutMethod3) {
  3510. auto res = cli_.Get("/person/john3");
  3511. ASSERT_TRUE(res);
  3512. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3513. Params params;
  3514. params.emplace("name", "john3");
  3515. params.emplace("note", "coder");
  3516. res = cli_.Put("/person", params);
  3517. ASSERT_TRUE(res);
  3518. ASSERT_EQ(StatusCode::OK_200, res->status);
  3519. res = cli_.Get("/person/john3");
  3520. ASSERT_TRUE(res);
  3521. ASSERT_EQ(StatusCode::OK_200, res->status);
  3522. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3523. ASSERT_EQ("coder", res->body);
  3524. }
  3525. TEST_F(ServerTest, DeleteMethod1) {
  3526. auto res = cli_.Get("/person/john4");
  3527. ASSERT_TRUE(res);
  3528. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3529. Params params;
  3530. params.emplace("name", "john4");
  3531. params.emplace("note", "coder");
  3532. res = cli_.Post("/person", params);
  3533. ASSERT_TRUE(res);
  3534. ASSERT_EQ(StatusCode::OK_200, res->status);
  3535. res = cli_.Get("/person/john4");
  3536. ASSERT_TRUE(res);
  3537. ASSERT_EQ(StatusCode::OK_200, res->status);
  3538. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3539. ASSERT_EQ("coder", res->body);
  3540. Params delete_params;
  3541. delete_params.emplace("name", "john4");
  3542. res = cli_.Delete("/person", delete_params);
  3543. ASSERT_TRUE(res);
  3544. ASSERT_EQ(StatusCode::OK_200, res->status);
  3545. ASSERT_EQ("DELETED", res->body);
  3546. res = cli_.Get("/person/john4");
  3547. ASSERT_TRUE(res);
  3548. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3549. }
  3550. TEST_F(ServerTest, DeleteMethod2) {
  3551. auto res = cli_.Get("/person/john5");
  3552. ASSERT_TRUE(res);
  3553. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3554. Params params;
  3555. params.emplace("name", "john5");
  3556. params.emplace("note", "developer");
  3557. res = cli_.Post("/person", params);
  3558. ASSERT_TRUE(res);
  3559. ASSERT_EQ(StatusCode::OK_200, res->status);
  3560. res = cli_.Get("/person/john5");
  3561. ASSERT_TRUE(res);
  3562. ASSERT_EQ(StatusCode::OK_200, res->status);
  3563. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3564. ASSERT_EQ("developer", res->body);
  3565. Params delete_params;
  3566. delete_params.emplace("name", "john5");
  3567. Headers headers;
  3568. headers.emplace("Custom-Header", "test-value");
  3569. res = cli_.Delete("/person", headers, delete_params);
  3570. ASSERT_TRUE(res);
  3571. ASSERT_EQ(StatusCode::OK_200, res->status);
  3572. ASSERT_EQ("DELETED", res->body);
  3573. res = cli_.Get("/person/john5");
  3574. ASSERT_TRUE(res);
  3575. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3576. }
  3577. TEST_F(ServerTest, DeleteMethod3) {
  3578. auto res = cli_.Get("/person/john6");
  3579. ASSERT_TRUE(res);
  3580. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3581. Params params;
  3582. params.emplace("name", "john6");
  3583. params.emplace("note", "tester");
  3584. res = cli_.Post("/person", params);
  3585. ASSERT_TRUE(res);
  3586. ASSERT_EQ(StatusCode::OK_200, res->status);
  3587. res = cli_.Get("/person/john6");
  3588. ASSERT_TRUE(res);
  3589. ASSERT_EQ(StatusCode::OK_200, res->status);
  3590. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3591. ASSERT_EQ("tester", res->body);
  3592. Params delete_params;
  3593. delete_params.emplace("name", "john6");
  3594. Headers headers;
  3595. headers.emplace("Custom-Header", "test-value");
  3596. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3597. ASSERT_TRUE(res);
  3598. ASSERT_EQ(StatusCode::OK_200, res->status);
  3599. ASSERT_EQ("DELETED", res->body);
  3600. res = cli_.Get("/person/john6");
  3601. ASSERT_TRUE(res);
  3602. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3603. }
  3604. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3605. Params params;
  3606. params.emplace("json", JSON_DATA);
  3607. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3608. ASSERT_TRUE(res);
  3609. ASSERT_EQ(StatusCode::OK_200, res->status);
  3610. ASSERT_EQ(JSON_DATA, res->body);
  3611. }
  3612. TEST_F(ServerTest, PostEmptyContent) {
  3613. auto res = cli_.Post("/empty", "", "text/plain");
  3614. ASSERT_TRUE(res);
  3615. ASSERT_EQ(StatusCode::OK_200, res->status);
  3616. ASSERT_EQ("empty", res->body);
  3617. }
  3618. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3619. auto res = cli_.Post("/empty-no-content-type");
  3620. ASSERT_TRUE(res);
  3621. ASSERT_EQ(StatusCode::OK_200, res->status);
  3622. ASSERT_EQ("empty-no-content-type", res->body);
  3623. }
  3624. TEST_F(ServerTest, PostPathOnly) {
  3625. auto res = cli_.Post("/path-only");
  3626. ASSERT_TRUE(res);
  3627. ASSERT_EQ(StatusCode::OK_200, res->status);
  3628. ASSERT_EQ("path-only", res->body);
  3629. }
  3630. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3631. auto res = cli_.Post("/path-headers-only",
  3632. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3633. ASSERT_TRUE(res);
  3634. ASSERT_EQ(StatusCode::OK_200, res->status);
  3635. ASSERT_EQ("path-headers-only", res->body);
  3636. }
  3637. TEST_F(ServerTest, PostLarge) {
  3638. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3639. ASSERT_TRUE(res);
  3640. ASSERT_EQ(StatusCode::OK_200, res->status);
  3641. EXPECT_EQ(LARGE_DATA, res->body);
  3642. }
  3643. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3644. auto res = cli_.Put("/empty-no-content-type");
  3645. ASSERT_TRUE(res);
  3646. ASSERT_EQ(StatusCode::OK_200, res->status);
  3647. ASSERT_EQ("empty-no-content-type", res->body);
  3648. }
  3649. TEST_F(ServerTest, GetMethodDir) {
  3650. auto res = cli_.Get("/dir/");
  3651. ASSERT_TRUE(res);
  3652. EXPECT_EQ(StatusCode::OK_200, res->status);
  3653. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3654. auto body = R"(<html>
  3655. <head>
  3656. </head>
  3657. <body>
  3658. <a href="/dir/test.html">Test</a>
  3659. <a href="/hi">hi</a>
  3660. </body>
  3661. </html>
  3662. )";
  3663. EXPECT_EQ(body, res->body);
  3664. }
  3665. TEST_F(ServerTest, GetMethodDirTest) {
  3666. auto res = cli_.Get("/dir/test.html");
  3667. ASSERT_TRUE(res);
  3668. EXPECT_EQ(StatusCode::OK_200, res->status);
  3669. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3670. EXPECT_EQ("test.html", res->body);
  3671. }
  3672. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3673. auto res = cli_.Get("/dir/../dir/test.html");
  3674. ASSERT_TRUE(res);
  3675. EXPECT_EQ(StatusCode::OK_200, res->status);
  3676. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3677. EXPECT_EQ("test.html", res->body);
  3678. }
  3679. TEST_F(ServerTest, GetMethodInvalidPath) {
  3680. auto res = cli_.Get("/dir/../test.html");
  3681. ASSERT_TRUE(res);
  3682. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3683. }
  3684. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3685. auto res = cli_.Get("/../www/dir/test.html");
  3686. ASSERT_TRUE(res);
  3687. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3688. }
  3689. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3690. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3691. ASSERT_TRUE(res);
  3692. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3693. }
  3694. TEST_F(ServerTest, GetMethodDirMountTest) {
  3695. auto res = cli_.Get("/mount/dir/test.html");
  3696. ASSERT_TRUE(res);
  3697. EXPECT_EQ(StatusCode::OK_200, res->status);
  3698. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3699. EXPECT_EQ("test.html", res->body);
  3700. }
  3701. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3702. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3703. ASSERT_TRUE(res);
  3704. EXPECT_EQ(StatusCode::OK_200, res->status);
  3705. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3706. EXPECT_EQ("test.html", res->body);
  3707. }
  3708. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3709. auto res = cli_.Get("/mount/dir/../test.html");
  3710. ASSERT_TRUE(res);
  3711. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3712. }
  3713. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3714. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3715. ASSERT_TRUE(res);
  3716. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3717. }
  3718. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3719. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3720. ASSERT_TRUE(res);
  3721. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3722. }
  3723. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3724. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3725. ASSERT_TRUE(res);
  3726. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3727. }
  3728. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3729. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3730. ASSERT_TRUE(res);
  3731. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3732. }
  3733. TEST_F(ServerTest, PostMethod303) {
  3734. auto res = cli_.Post("/1", "body", "text/plain");
  3735. ASSERT_TRUE(res);
  3736. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3737. EXPECT_EQ("/2", res->get_header_value("Location"));
  3738. }
  3739. TEST_F(ServerTest, PostMethod303Redirect) {
  3740. cli_.set_follow_location(true);
  3741. auto res = cli_.Post("/1", "body", "text/plain");
  3742. ASSERT_TRUE(res);
  3743. EXPECT_EQ(StatusCode::OK_200, res->status);
  3744. EXPECT_EQ("redirected.", res->body);
  3745. EXPECT_EQ("/2", res->location);
  3746. }
  3747. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3748. auto res = cli_.Get("/dir/test.abcde");
  3749. ASSERT_TRUE(res);
  3750. EXPECT_EQ(StatusCode::OK_200, res->status);
  3751. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3752. EXPECT_EQ("abcde", res->body);
  3753. }
  3754. TEST_F(ServerTest, StaticFileRange) {
  3755. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3756. ASSERT_TRUE(res);
  3757. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3758. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3759. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3760. EXPECT_EQ(true, res->has_header("Content-Range"));
  3761. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3762. EXPECT_EQ(std::string("cd"), res->body);
  3763. }
  3764. TEST_F(ServerTest, StaticFileRanges) {
  3765. auto res =
  3766. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3767. ASSERT_TRUE(res);
  3768. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3769. EXPECT_TRUE(
  3770. res->get_header_value("Content-Type")
  3771. .find(
  3772. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3773. 0);
  3774. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3775. }
  3776. TEST_F(ServerTest, StaticFileRangeHead) {
  3777. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3778. ASSERT_TRUE(res);
  3779. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3780. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3781. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3782. EXPECT_EQ(true, res->has_header("Content-Range"));
  3783. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3784. }
  3785. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3786. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3787. ASSERT_TRUE(res);
  3788. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3789. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3790. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3791. EXPECT_EQ(true, res->has_header("Content-Range"));
  3792. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3793. res->get_header_value("Content-Range"));
  3794. EXPECT_EQ("LAST\n", res->body);
  3795. }
  3796. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3797. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3798. ASSERT_TRUE(res);
  3799. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3800. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3801. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3802. EXPECT_EQ(true, res->has_header("Content-Range"));
  3803. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3804. }
  3805. TEST_F(ServerTest, StaticFileBigFile) {
  3806. auto res = cli_.Get("/dir/1MB.txt");
  3807. ASSERT_TRUE(res);
  3808. EXPECT_EQ(StatusCode::OK_200, res->status);
  3809. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3810. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3811. }
  3812. TEST_F(ServerTest, InvalidBaseDirMount) {
  3813. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3814. }
  3815. TEST_F(ServerTest, Binary) {
  3816. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3817. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3818. "application/octet-stream");
  3819. ASSERT_TRUE(res);
  3820. ASSERT_EQ(StatusCode::OK_200, res->status);
  3821. ASSERT_EQ(4U, res->body.size());
  3822. res = cli_.Put("/binary", binary.data(), binary.size(),
  3823. "application/octet-stream");
  3824. ASSERT_TRUE(res);
  3825. ASSERT_EQ(StatusCode::OK_200, res->status);
  3826. ASSERT_EQ(4U, res->body.size());
  3827. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3828. "application/octet-stream");
  3829. ASSERT_TRUE(res);
  3830. ASSERT_EQ(StatusCode::OK_200, res->status);
  3831. ASSERT_EQ(4U, res->body.size());
  3832. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3833. "application/octet-stream");
  3834. ASSERT_TRUE(res);
  3835. ASSERT_EQ(StatusCode::OK_200, res->status);
  3836. ASSERT_EQ(4U, res->body.size());
  3837. }
  3838. TEST_F(ServerTest, BinaryString) {
  3839. auto binary = std::string("\x00\x01\x02\x03", 4);
  3840. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3841. ASSERT_TRUE(res);
  3842. ASSERT_EQ(StatusCode::OK_200, res->status);
  3843. ASSERT_EQ(4U, res->body.size());
  3844. res = cli_.Put("/binary", binary, "application/octet-stream");
  3845. ASSERT_TRUE(res);
  3846. ASSERT_EQ(StatusCode::OK_200, res->status);
  3847. ASSERT_EQ(4U, res->body.size());
  3848. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3849. ASSERT_TRUE(res);
  3850. ASSERT_EQ(StatusCode::OK_200, res->status);
  3851. ASSERT_EQ(4U, res->body.size());
  3852. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3853. ASSERT_TRUE(res);
  3854. ASSERT_EQ(StatusCode::OK_200, res->status);
  3855. ASSERT_EQ(4U, res->body.size());
  3856. }
  3857. TEST_F(ServerTest, EmptyRequest) {
  3858. auto res = cli_.Get("");
  3859. ASSERT_TRUE(!res);
  3860. EXPECT_EQ(Error::Connection, res.error());
  3861. }
  3862. TEST_F(ServerTest, LongRequest) {
  3863. std::string request;
  3864. for (size_t i = 0; i < 545; i++) {
  3865. request += "/TooLongRequest";
  3866. }
  3867. request += "OK";
  3868. auto res = cli_.Get(request.c_str());
  3869. ASSERT_TRUE(res);
  3870. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3871. }
  3872. TEST_F(ServerTest, TooLongRequest) {
  3873. std::string request;
  3874. for (size_t i = 0; i < 546; i++) {
  3875. request += "/TooLongRequest";
  3876. }
  3877. request += "_NG";
  3878. auto start = std::chrono::high_resolution_clock::now();
  3879. cli_.set_keep_alive(true);
  3880. auto res = cli_.Get(request.c_str());
  3881. auto end = std::chrono::high_resolution_clock::now();
  3882. auto elapsed =
  3883. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3884. .count();
  3885. ASSERT_TRUE(res);
  3886. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3887. EXPECT_LE(elapsed, 1000);
  3888. EXPECT_EQ("close", res->get_header_value("Connection"));
  3889. EXPECT_FALSE(cli_.is_socket_open());
  3890. }
  3891. TEST_F(ServerTest, AlmostTooLongRequest) {
  3892. // test for #2046 - URI length check shouldn't include other content on req
  3893. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3894. // leading /, space, HTTP/1.1)
  3895. std::string request =
  3896. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3897. auto res = cli_.Get(request.c_str());
  3898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3899. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3900. }
  3901. TEST_F(ServerTest, LongHeader) {
  3902. Request req;
  3903. req.method = "GET";
  3904. req.path = "/hi";
  3905. std::string host_and_port;
  3906. host_and_port += HOST;
  3907. host_and_port += ":";
  3908. host_and_port += std::to_string(PORT);
  3909. req.headers.emplace("Host", host_and_port.c_str());
  3910. req.headers.emplace("Accept", "*/*");
  3911. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3912. req.headers.emplace(
  3913. "Header-Name",
  3914. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3915. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3916. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3917. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3918. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3919. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3920. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3921. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3922. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3923. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3924. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3925. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3926. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3927. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3928. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3929. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3930. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3931. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3932. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3933. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3934. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3935. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3936. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3937. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3938. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3939. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3940. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3941. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3942. "@@@@@@@@@@@@@@@@");
  3943. auto res = std::make_shared<Response>();
  3944. auto error = Error::Success;
  3945. auto ret = cli_.send(req, *res, error);
  3946. ASSERT_TRUE(ret);
  3947. EXPECT_EQ(StatusCode::OK_200, res->status);
  3948. }
  3949. TEST_F(ServerTest, LongQueryValue) {
  3950. auto start = std::chrono::high_resolution_clock::now();
  3951. cli_.set_keep_alive(true);
  3952. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3953. auto end = std::chrono::high_resolution_clock::now();
  3954. auto elapsed =
  3955. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3956. .count();
  3957. ASSERT_TRUE(res);
  3958. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3959. EXPECT_LE(elapsed, 1000);
  3960. EXPECT_EQ("close", res->get_header_value("Connection"));
  3961. EXPECT_FALSE(cli_.is_socket_open());
  3962. }
  3963. TEST_F(ServerTest, TooLongQueryValue) {
  3964. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3965. ASSERT_FALSE(res);
  3966. EXPECT_EQ(Error::Read, res.error());
  3967. }
  3968. TEST_F(ServerTest, TooLongHeader) {
  3969. Request req;
  3970. req.method = "GET";
  3971. req.path = "/hi";
  3972. std::string host_and_port;
  3973. host_and_port += HOST;
  3974. host_and_port += ":";
  3975. host_and_port += std::to_string(PORT);
  3976. req.headers.emplace("Host", host_and_port.c_str());
  3977. req.headers.emplace("Accept", "*/*");
  3978. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3979. req.headers.emplace(
  3980. "Header-Name",
  3981. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3982. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3983. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3984. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3985. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3986. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3987. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3988. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3989. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3990. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3991. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3992. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3993. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3994. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3995. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3996. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3997. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3998. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3999. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4000. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4001. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4002. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4003. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4004. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4005. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4006. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4007. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4008. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4009. "@@@@@@@@@@@@@@@@@");
  4010. auto res = std::make_shared<Response>();
  4011. auto error = Error::Success;
  4012. auto ret = cli_.send(req, *res, error);
  4013. ASSERT_TRUE(ret);
  4014. EXPECT_EQ(StatusCode::OK_200, res->status);
  4015. }
  4016. TEST_F(ServerTest, HeaderCountAtLimit) {
  4017. // Test with headers just under the 100 limit
  4018. httplib::Headers headers;
  4019. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4020. // This should keep us just under the 100 header limit
  4021. for (int i = 0; i < 95; i++) {
  4022. std::string name = "X-Test-Header-" + std::to_string(i);
  4023. std::string value = "value" + std::to_string(i);
  4024. headers.emplace(name, value);
  4025. }
  4026. // This should work fine as we're under the limit
  4027. auto res = cli_.Get("/hi", headers);
  4028. EXPECT_TRUE(res);
  4029. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4030. }
  4031. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4032. // Test with many headers to exceed the 100 limit
  4033. httplib::Headers headers;
  4034. // Add 150 headers to definitely exceed the 100 limit
  4035. for (int i = 0; i < 150; i++) {
  4036. std::string name = "X-Test-Header-" + std::to_string(i);
  4037. std::string value = "value" + std::to_string(i);
  4038. headers.emplace(name, value);
  4039. }
  4040. // This should fail due to exceeding header count limit
  4041. cli_.set_keep_alive(true);
  4042. auto res = cli_.Get("/hi", headers);
  4043. // The server should respond with 400 Bad Request
  4044. ASSERT_TRUE(res);
  4045. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4046. EXPECT_EQ("close", res->get_header_value("Connection"));
  4047. EXPECT_FALSE(cli_.is_socket_open());
  4048. }
  4049. TEST_F(ServerTest, PercentEncoding) {
  4050. auto res = cli_.Get("/e%6edwith%");
  4051. ASSERT_TRUE(res);
  4052. EXPECT_EQ(StatusCode::OK_200, res->status);
  4053. }
  4054. TEST_F(ServerTest, PercentEncodingUnicode) {
  4055. auto res = cli_.Get("/e%u006edwith%");
  4056. ASSERT_TRUE(res);
  4057. EXPECT_EQ(StatusCode::OK_200, res->status);
  4058. }
  4059. TEST_F(ServerTest, InvalidPercentEncoding) {
  4060. auto res = cli_.Get("/%endwith%");
  4061. ASSERT_TRUE(res);
  4062. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4063. }
  4064. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4065. auto res = cli_.Get("/%uendwith%");
  4066. ASSERT_TRUE(res);
  4067. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4068. }
  4069. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4070. auto res = cli_.Get("/hello?aaa=bbb%");
  4071. ASSERT_TRUE(res);
  4072. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4073. }
  4074. TEST_F(ServerTest, PlusSignEncoding) {
  4075. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4076. ASSERT_TRUE(res);
  4077. EXPECT_EQ(StatusCode::OK_200, res->status);
  4078. EXPECT_EQ("a +b", res->body);
  4079. }
  4080. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4081. // This test simulates a potential DoS attack using many headers
  4082. // to verify our security fix prevents memory exhaustion
  4083. httplib::Headers attack_headers;
  4084. // Attempt to add many headers like an attacker would (200 headers to far
  4085. // exceed limit)
  4086. for (int i = 0; i < 200; i++) {
  4087. std::string name = "X-Attack-Header-" + std::to_string(i);
  4088. std::string value = "attack_payload_" + std::to_string(i);
  4089. attack_headers.emplace(name, value);
  4090. }
  4091. // Try to POST with excessive headers
  4092. cli_.set_keep_alive(true);
  4093. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4094. // Should either fail or return 400 Bad Request due to security limit
  4095. if (res) {
  4096. // If we get a response, it should be 400 Bad Request
  4097. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4098. EXPECT_EQ("close", res->get_header_value("Connection"));
  4099. }
  4100. EXPECT_FALSE(cli_.is_socket_open());
  4101. }
  4102. TEST_F(ServerTest, MultipartFormData) {
  4103. UploadFormDataItems items = {
  4104. {"text1", "text default", "", ""},
  4105. {"text2", "aωb", "", ""},
  4106. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4107. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4108. {"file3", "", "", "application/octet-stream"},
  4109. {"file4", "", "", " application/json tmp-string "}};
  4110. auto res = cli_.Post("/multipart", items);
  4111. ASSERT_TRUE(res);
  4112. EXPECT_EQ(StatusCode::OK_200, res->status);
  4113. }
  4114. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4115. UploadFormDataItems items = {
  4116. {"text", "default text", "", ""},
  4117. {"multi_text1", "aaaaa", "", ""},
  4118. {"multi_text1", "bbbbb", "", ""},
  4119. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4120. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4121. "application/json"},
  4122. };
  4123. auto res = cli_.Post("/multipart/multi_file_values", items);
  4124. ASSERT_TRUE(res);
  4125. EXPECT_EQ(StatusCode::OK_200, res->status);
  4126. }
  4127. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4128. auto res = cli_.Get("/hi");
  4129. ASSERT_TRUE(res);
  4130. EXPECT_EQ(StatusCode::OK_200, res->status);
  4131. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4132. EXPECT_EQ("Hello World!", res->body);
  4133. }
  4134. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4135. Request req;
  4136. req.method = "POST";
  4137. req.path = "/chunked";
  4138. std::string host_and_port;
  4139. host_and_port += HOST;
  4140. host_and_port += ":";
  4141. host_and_port += std::to_string(PORT);
  4142. req.headers.emplace("Host", host_and_port.c_str());
  4143. req.headers.emplace("Accept", "*/*");
  4144. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4145. req.headers.emplace("Content-Type", "text/plain");
  4146. req.headers.emplace("Content-Length", "0");
  4147. req.headers.emplace(
  4148. "Transfer-Encoding",
  4149. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4150. // Client does not chunk, so make a chunked body manually.
  4151. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4152. auto res = std::make_shared<Response>();
  4153. auto error = Error::Success;
  4154. auto ret = cli_.send(req, *res, error);
  4155. ASSERT_TRUE(ret);
  4156. EXPECT_EQ(StatusCode::OK_200, res->status);
  4157. }
  4158. TEST_F(ServerTest, GetStreamed2) {
  4159. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4160. ASSERT_TRUE(res);
  4161. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4162. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4163. EXPECT_EQ(true, res->has_header("Content-Range"));
  4164. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4165. EXPECT_EQ(std::string("ab"), res->body);
  4166. }
  4167. TEST_F(ServerTest, GetStreamed) {
  4168. auto res = cli_.Get("/streamed");
  4169. ASSERT_TRUE(res);
  4170. EXPECT_EQ(StatusCode::OK_200, res->status);
  4171. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4172. EXPECT_EQ(std::string("aaabbb"), res->body);
  4173. }
  4174. TEST_F(ServerTest, GetStreamedWithRange1) {
  4175. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4176. ASSERT_TRUE(res);
  4177. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4178. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4179. EXPECT_EQ(true, res->has_header("Content-Range"));
  4180. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4181. EXPECT_EQ(std::string("def"), res->body);
  4182. }
  4183. TEST_F(ServerTest, GetStreamedWithRange2) {
  4184. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4185. ASSERT_TRUE(res);
  4186. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4187. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4188. EXPECT_EQ(true, res->has_header("Content-Range"));
  4189. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4190. EXPECT_EQ(std::string("bcdefg"), res->body);
  4191. }
  4192. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4193. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4194. ASSERT_TRUE(res);
  4195. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4196. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4197. EXPECT_EQ(true, res->has_header("Content-Range"));
  4198. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4199. EXPECT_EQ(std::string("efg"), res->body);
  4200. }
  4201. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4202. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4203. ASSERT_TRUE(res);
  4204. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4205. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4206. EXPECT_EQ(false, res->has_header("Content-Range"));
  4207. EXPECT_EQ(0U, res->body.size());
  4208. }
  4209. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4210. auto res = cli_.Get("/streamed-with-range",
  4211. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4212. "92233720368547758079223372036854775807"}});
  4213. ASSERT_TRUE(res);
  4214. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4215. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4216. EXPECT_EQ(false, res->has_header("Content-Range"));
  4217. EXPECT_EQ(0U, res->body.size());
  4218. }
  4219. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4220. auto res = cli_.Get(
  4221. "/with-range",
  4222. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4223. {"Accept-Encoding", ""}});
  4224. ASSERT_TRUE(res);
  4225. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4226. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4227. EXPECT_EQ(true, res->has_header("Content-Range"));
  4228. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4229. EXPECT_EQ(std::string("abcdefg"), res->body);
  4230. }
  4231. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4232. auto res = cli_.Get("/with-range", {
  4233. {"Range", "bytes=0-"},
  4234. {"Accept-Encoding", ""},
  4235. });
  4236. ASSERT_TRUE(res);
  4237. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4238. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4239. EXPECT_EQ(true, res->has_header("Content-Range"));
  4240. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4241. EXPECT_EQ(std::string("abcdefg"), res->body);
  4242. }
  4243. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4244. auto res =
  4245. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4246. ASSERT_TRUE(res);
  4247. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4248. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4249. EXPECT_EQ(false, res->has_header("Content-Range"));
  4250. EXPECT_EQ(267U, res->body.size());
  4251. // Check that both range contents are present
  4252. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4253. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4254. // Check that Content-Range headers are present for both ranges
  4255. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4256. std::string::npos);
  4257. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4258. std::string::npos);
  4259. }
  4260. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4261. Ranges ranges;
  4262. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4263. ranges.emplace_back(0, -1);
  4264. }
  4265. auto res =
  4266. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4267. ASSERT_TRUE(res);
  4268. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4269. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4270. EXPECT_EQ(false, res->has_header("Content-Range"));
  4271. EXPECT_EQ(0U, res->body.size());
  4272. }
  4273. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4274. auto res =
  4275. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4276. ASSERT_TRUE(res);
  4277. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4278. EXPECT_EQ(5U, res->body.size());
  4279. // Check that overlapping ranges are coalesced into a single range
  4280. EXPECT_EQ("bcdef", res->body);
  4281. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4282. // Should be single range, not multipart
  4283. EXPECT_TRUE(res->has_header("Content-Range"));
  4284. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4285. }
  4286. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4287. auto res =
  4288. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4289. ASSERT_TRUE(res);
  4290. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4291. EXPECT_EQ(268U, res->body.size());
  4292. // Check that both range contents are present
  4293. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4294. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4295. // Check that Content-Range headers are present for both ranges
  4296. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4297. std::string::npos);
  4298. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4299. std::string::npos);
  4300. }
  4301. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4302. auto res =
  4303. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4304. ASSERT_TRUE(res);
  4305. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4306. EXPECT_EQ(269U, res->body.size());
  4307. // Check that both duplicate range contents are present
  4308. size_t first_abc = res->body.find("abc\r\n");
  4309. EXPECT_TRUE(first_abc != std::string::npos);
  4310. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4311. EXPECT_TRUE(second_abc != std::string::npos);
  4312. // Check that Content-Range headers are present for both ranges
  4313. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4314. EXPECT_TRUE(first_range != std::string::npos);
  4315. size_t second_range =
  4316. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4317. EXPECT_TRUE(second_range != std::string::npos);
  4318. }
  4319. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4320. auto res = cli_.Get("/streamed-with-range?error",
  4321. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4322. ASSERT_TRUE(res);
  4323. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4324. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4325. EXPECT_EQ(false, res->has_header("Content-Range"));
  4326. EXPECT_EQ(0U, res->body.size());
  4327. }
  4328. TEST_F(ServerTest, GetStreamedEndless) {
  4329. uint64_t offset = 0;
  4330. auto res = cli_.Get("/streamed-cancel",
  4331. [&](const char * /*data*/, uint64_t data_length) {
  4332. if (offset < 100) {
  4333. offset += data_length;
  4334. return true;
  4335. }
  4336. return false;
  4337. });
  4338. ASSERT_TRUE(!res);
  4339. EXPECT_EQ(Error::Canceled, res.error());
  4340. }
  4341. TEST_F(ServerTest, ClientStop) {
  4342. std::atomic_size_t count{4};
  4343. std::vector<std::thread> threads;
  4344. for (auto i = count.load(); i != 0; --i) {
  4345. threads.emplace_back([&]() {
  4346. auto res = cli_.Get("/streamed-cancel",
  4347. [&](const char *, uint64_t) { return true; });
  4348. --count;
  4349. ASSERT_TRUE(!res);
  4350. EXPECT_TRUE(res.error() == Error::Canceled ||
  4351. res.error() == Error::Read || res.error() == Error::Write);
  4352. });
  4353. }
  4354. std::this_thread::sleep_for(std::chrono::seconds(2));
  4355. while (count != 0) {
  4356. cli_.stop();
  4357. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4358. }
  4359. for (auto &t : threads) {
  4360. t.join();
  4361. }
  4362. }
  4363. TEST_F(ServerTest, GetWithRange1) {
  4364. auto res = cli_.Get("/with-range", {
  4365. make_range_header({{3, 5}}),
  4366. {"Accept-Encoding", ""},
  4367. });
  4368. ASSERT_TRUE(res);
  4369. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4370. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4371. EXPECT_EQ(true, res->has_header("Content-Range"));
  4372. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4373. EXPECT_EQ(std::string("def"), res->body);
  4374. }
  4375. TEST_F(ServerTest, GetWithRange2) {
  4376. auto res = cli_.Get("/with-range", {
  4377. make_range_header({{1, -1}}),
  4378. {"Accept-Encoding", ""},
  4379. });
  4380. ASSERT_TRUE(res);
  4381. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4382. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4383. EXPECT_EQ(true, res->has_header("Content-Range"));
  4384. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4385. EXPECT_EQ(std::string("bcdefg"), res->body);
  4386. }
  4387. TEST_F(ServerTest, GetWithRange3) {
  4388. auto res = cli_.Get("/with-range", {
  4389. make_range_header({{0, 0}}),
  4390. {"Accept-Encoding", ""},
  4391. });
  4392. ASSERT_TRUE(res);
  4393. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4394. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4395. EXPECT_EQ(true, res->has_header("Content-Range"));
  4396. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4397. EXPECT_EQ(std::string("a"), res->body);
  4398. }
  4399. TEST_F(ServerTest, GetWithRange4) {
  4400. auto res = cli_.Get("/with-range", {
  4401. make_range_header({{-1, 2}}),
  4402. {"Accept-Encoding", ""},
  4403. });
  4404. ASSERT_TRUE(res);
  4405. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4406. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4407. EXPECT_EQ(true, res->has_header("Content-Range"));
  4408. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4409. EXPECT_EQ(std::string("fg"), res->body);
  4410. }
  4411. TEST_F(ServerTest, GetWithRange5) {
  4412. auto res = cli_.Get("/with-range", {
  4413. make_range_header({{0, 5}}),
  4414. {"Accept-Encoding", ""},
  4415. });
  4416. ASSERT_TRUE(res);
  4417. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4418. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4419. EXPECT_EQ(true, res->has_header("Content-Range"));
  4420. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4421. EXPECT_EQ(std::string("abcdef"), res->body);
  4422. }
  4423. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4424. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4425. ASSERT_TRUE(res);
  4426. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4427. }
  4428. TEST_F(ServerTest, GetWithRangeMultipart) {
  4429. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4430. ASSERT_TRUE(res);
  4431. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4432. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4433. EXPECT_EQ(false, res->has_header("Content-Range"));
  4434. EXPECT_EQ(267U, res->body.size());
  4435. }
  4436. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4437. auto res =
  4438. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4439. ASSERT_TRUE(res);
  4440. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4441. }
  4442. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4443. auto res = cli_.Get("/with-range-customized-response",
  4444. {{make_range_header({{1, 2}})}});
  4445. ASSERT_TRUE(res);
  4446. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4447. EXPECT_EQ(true, res->has_header("Content-Length"));
  4448. EXPECT_EQ(false, res->has_header("Content-Range"));
  4449. EXPECT_EQ(JSON_DATA, res->body);
  4450. }
  4451. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4452. auto res = cli_.Get("/with-range-customized-response",
  4453. {{make_range_header({{1, 2}, {4, 5}})}});
  4454. ASSERT_TRUE(res);
  4455. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4456. EXPECT_EQ(true, res->has_header("Content-Length"));
  4457. EXPECT_EQ(false, res->has_header("Content-Range"));
  4458. EXPECT_EQ(JSON_DATA, res->body);
  4459. }
  4460. TEST_F(ServerTest, Issue1772) {
  4461. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4462. ASSERT_TRUE(res);
  4463. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4464. }
  4465. TEST_F(ServerTest, Issue609) {
  4466. auto res = cli_.Delete("/issue609");
  4467. ASSERT_TRUE(res);
  4468. EXPECT_EQ(StatusCode::OK_200, res->status);
  4469. EXPECT_EQ(std::string("ok"), res->body);
  4470. }
  4471. TEST_F(ServerTest, GetStreamedChunked) {
  4472. auto res = cli_.Get("/streamed-chunked");
  4473. ASSERT_TRUE(res);
  4474. EXPECT_EQ(StatusCode::OK_200, res->status);
  4475. EXPECT_EQ(std::string("123456789"), res->body);
  4476. }
  4477. TEST_F(ServerTest, GetStreamedChunked2) {
  4478. auto res = cli_.Get("/streamed-chunked2");
  4479. ASSERT_TRUE(res);
  4480. EXPECT_EQ(StatusCode::OK_200, res->status);
  4481. EXPECT_EQ(std::string("123456789"), res->body);
  4482. }
  4483. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4484. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4485. ASSERT_TRUE(res);
  4486. EXPECT_EQ(StatusCode::OK_200, res->status);
  4487. EXPECT_EQ(std::string("123456789"), res->body);
  4488. EXPECT_TRUE(res->has_header("Trailer"));
  4489. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4490. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4491. // Trailers are now stored separately from headers (security fix)
  4492. EXPECT_EQ(2U, res->trailers.size());
  4493. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4494. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4495. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4496. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4497. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4498. // Verify trailers are NOT in headers (security verification)
  4499. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4500. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4501. }
  4502. TEST_F(ServerTest, LargeChunkedPost) {
  4503. Request req;
  4504. req.method = "POST";
  4505. req.path = "/large-chunked";
  4506. std::string host_and_port;
  4507. host_and_port += HOST;
  4508. host_and_port += ":";
  4509. host_and_port += std::to_string(PORT);
  4510. req.headers.emplace("Host", host_and_port.c_str());
  4511. req.headers.emplace("Accept", "*/*");
  4512. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4513. req.headers.emplace("Content-Type", "text/plain");
  4514. req.headers.emplace("Content-Length", "0");
  4515. req.headers.emplace("Transfer-Encoding", "chunked");
  4516. std::string long_string(30 * 1024u, 'a');
  4517. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4518. // Attempt to make a large enough post to exceed OS buffers, to test that
  4519. // the server handles short reads if the full chunk data isn't available.
  4520. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4521. auto res = std::make_shared<Response>();
  4522. auto error = Error::Success;
  4523. auto ret = cli_.send(req, *res, error);
  4524. ASSERT_TRUE(ret);
  4525. EXPECT_EQ(StatusCode::OK_200, res->status);
  4526. }
  4527. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4528. auto res = cli_.Get("/remote_addr");
  4529. ASSERT_TRUE(res);
  4530. EXPECT_EQ(StatusCode::OK_200, res->status);
  4531. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4532. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4533. }
  4534. TEST_F(ServerTest, GetMethodLocalAddr) {
  4535. auto res = cli_.Get("/local_addr");
  4536. ASSERT_TRUE(res);
  4537. EXPECT_EQ(StatusCode::OK_200, res->status);
  4538. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4539. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4540. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4541. }
  4542. TEST_F(ServerTest, HTTPResponseSplitting) {
  4543. auto res = cli_.Get("/http_response_splitting");
  4544. ASSERT_TRUE(res);
  4545. EXPECT_EQ(StatusCode::OK_200, res->status);
  4546. }
  4547. TEST_F(ServerTest, SlowRequest) {
  4548. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4549. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4550. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4551. }
  4552. #if 0
  4553. TEST_F(ServerTest, SlowPost) {
  4554. char buffer[64 * 1024];
  4555. memset(buffer, 0x42, sizeof(buffer));
  4556. auto res = cli_.Post(
  4557. "/slowpost", 64 * 1024 * 1024,
  4558. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4559. auto ret = sink.write(buffer, sizeof(buffer));
  4560. EXPECT_TRUE(ret);
  4561. return true;
  4562. },
  4563. "text/plain");
  4564. ASSERT_TRUE(res);
  4565. EXPECT_EQ(StatusCode::OK_200, res->status);
  4566. }
  4567. TEST_F(ServerTest, SlowPostFail) {
  4568. char buffer[64 * 1024];
  4569. memset(buffer, 0x42, sizeof(buffer));
  4570. cli_.set_write_timeout(std::chrono::seconds(0));
  4571. auto res = cli_.Post(
  4572. "/slowpost", 64 * 1024 * 1024,
  4573. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4574. sink.write(buffer, sizeof(buffer));
  4575. return true;
  4576. },
  4577. "text/plain");
  4578. ASSERT_TRUE(!res);
  4579. EXPECT_EQ(Error::Write, res.error());
  4580. }
  4581. #endif
  4582. TEST_F(ServerTest, Put) {
  4583. auto res = cli_.Put("/put", "PUT", "text/plain");
  4584. ASSERT_TRUE(res);
  4585. EXPECT_EQ(StatusCode::OK_200, res->status);
  4586. EXPECT_EQ("PUT", res->body);
  4587. }
  4588. TEST_F(ServerTest, PutWithContentProvider) {
  4589. auto res = cli_.Put(
  4590. "/put", 3,
  4591. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4592. sink.os << "PUT";
  4593. return true;
  4594. },
  4595. "text/plain");
  4596. ASSERT_TRUE(res);
  4597. EXPECT_EQ(StatusCode::OK_200, res->status);
  4598. EXPECT_EQ("PUT", res->body);
  4599. }
  4600. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4601. auto res = cli_.Post(
  4602. "/post", 42,
  4603. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4604. return false;
  4605. },
  4606. "text/plain");
  4607. ASSERT_TRUE(!res);
  4608. EXPECT_EQ(Error::Canceled, res.error());
  4609. }
  4610. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4611. auto res = cli_.Put(
  4612. "/put",
  4613. [](size_t /*offset*/, DataSink &sink) {
  4614. sink.os << "PUT";
  4615. sink.done();
  4616. return true;
  4617. },
  4618. "text/plain");
  4619. ASSERT_TRUE(res);
  4620. EXPECT_EQ(StatusCode::OK_200, res->status);
  4621. EXPECT_EQ("PUT", res->body);
  4622. }
  4623. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4624. auto res = cli_.Post(
  4625. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4626. "text/plain");
  4627. ASSERT_TRUE(!res);
  4628. EXPECT_EQ(Error::Canceled, res.error());
  4629. }
  4630. TEST_F(ServerTest, PostLoopBack) {
  4631. std::string body;
  4632. auto res = cli_.Post(
  4633. "/post-loopback", 9,
  4634. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4635. EXPECT_EQ(9u, length);
  4636. sink.write("123", 3);
  4637. sink.write("456", 3);
  4638. sink.write("789", 3);
  4639. return true;
  4640. },
  4641. "text/plain",
  4642. [&body](const char *data, size_t data_length) {
  4643. body.append(data, data_length);
  4644. return true;
  4645. });
  4646. ASSERT_TRUE(res);
  4647. EXPECT_EQ(StatusCode::OK_200, res->status);
  4648. EXPECT_EQ("123456789", body);
  4649. }
  4650. TEST_F(ServerTest, PutLoopBack) {
  4651. std::string body;
  4652. auto res = cli_.Put(
  4653. "/put-loopback", 9,
  4654. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4655. EXPECT_EQ(9u, length);
  4656. sink.write("123", 3);
  4657. sink.write("456", 3);
  4658. sink.write("789", 3);
  4659. return true;
  4660. },
  4661. "text/plain",
  4662. [&body](const char *data, size_t data_length) {
  4663. body.append(data, data_length);
  4664. return true;
  4665. });
  4666. ASSERT_TRUE(res);
  4667. EXPECT_EQ(StatusCode::OK_200, res->status);
  4668. EXPECT_EQ("123456789", body);
  4669. }
  4670. TEST_F(ServerTest, PatchLoopBack) {
  4671. std::string body;
  4672. auto res = cli_.Patch(
  4673. "/patch-loopback", 9,
  4674. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4675. EXPECT_EQ(9u, length);
  4676. sink.write("123", 3);
  4677. sink.write("456", 3);
  4678. sink.write("789", 3);
  4679. return true;
  4680. },
  4681. "text/plain",
  4682. [&body](const char *data, size_t data_length) {
  4683. body.append(data, data_length);
  4684. return true;
  4685. });
  4686. ASSERT_TRUE(res);
  4687. EXPECT_EQ(StatusCode::OK_200, res->status);
  4688. EXPECT_EQ("123456789", body);
  4689. }
  4690. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4691. std::string body;
  4692. auto res = cli_.Post(
  4693. "/post-loopback",
  4694. [](size_t /*offset*/, DataSink &sink) {
  4695. sink.write("123", 3);
  4696. sink.write("456", 3);
  4697. sink.write("789", 3);
  4698. sink.done();
  4699. return true;
  4700. },
  4701. "text/plain",
  4702. [&body](const char *data, size_t data_length) {
  4703. body.append(data, data_length);
  4704. return true;
  4705. });
  4706. ASSERT_TRUE(res);
  4707. EXPECT_EQ(StatusCode::OK_200, res->status);
  4708. EXPECT_EQ("123456789", body);
  4709. }
  4710. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4711. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4712. cli_.set_compress(true);
  4713. auto res = cli_.Put(
  4714. "/put", 3,
  4715. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4716. sink.os << "PUT";
  4717. return true;
  4718. },
  4719. "text/plain");
  4720. ASSERT_TRUE(res);
  4721. EXPECT_EQ(StatusCode::OK_200, res->status);
  4722. EXPECT_EQ("PUT", res->body);
  4723. }
  4724. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4725. cli_.set_compress(true);
  4726. auto res = cli_.Post(
  4727. "/post", 42,
  4728. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4729. return false;
  4730. },
  4731. "text/plain");
  4732. ASSERT_TRUE(!res);
  4733. EXPECT_EQ(Error::Canceled, res.error());
  4734. }
  4735. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4736. cli_.set_compress(true);
  4737. auto res = cli_.Put(
  4738. "/put",
  4739. [](size_t /*offset*/, DataSink &sink) {
  4740. sink.os << "PUT";
  4741. sink.done();
  4742. return true;
  4743. },
  4744. "text/plain");
  4745. ASSERT_TRUE(res);
  4746. EXPECT_EQ(StatusCode::OK_200, res->status);
  4747. EXPECT_EQ("PUT", res->body);
  4748. }
  4749. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4750. cli_.set_compress(true);
  4751. auto res = cli_.Post(
  4752. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4753. "text/plain");
  4754. ASSERT_TRUE(!res);
  4755. EXPECT_EQ(Error::Canceled, res.error());
  4756. }
  4757. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4758. cli_.set_compress(true);
  4759. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4760. ASSERT_TRUE(res);
  4761. EXPECT_EQ(StatusCode::OK_200, res->status);
  4762. EXPECT_EQ(LARGE_DATA, res->body);
  4763. }
  4764. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4765. #ifdef CPPHTTPLIB_SSL_ENABLED
  4766. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4767. Client cli(s.c_str());
  4768. cli.enable_server_certificate_verification(false);
  4769. #else
  4770. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4771. Client cli(s.c_str());
  4772. #endif
  4773. cli.set_compress(true);
  4774. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4775. ASSERT_TRUE(res);
  4776. EXPECT_EQ(StatusCode::OK_200, res->status);
  4777. EXPECT_EQ(LARGE_DATA, res->body);
  4778. // The compressed size should be less than a 10th of the original. May vary
  4779. // depending on the zlib library.
  4780. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4781. static_cast<uint64_t>(10 * 1024 * 1024));
  4782. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4783. }
  4784. TEST_F(ServerTest, PutContentWithDeflate) {
  4785. cli_.set_compress(false);
  4786. Headers headers;
  4787. headers.emplace("Content-Encoding", "deflate");
  4788. // PUT in deflate format:
  4789. auto res = cli_.Put("/put", headers,
  4790. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4791. ASSERT_TRUE(res);
  4792. EXPECT_EQ(StatusCode::OK_200, res->status);
  4793. EXPECT_EQ("PUT", res->body);
  4794. }
  4795. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4796. Headers headers;
  4797. headers.emplace("Accept-Encoding", "gzip, deflate");
  4798. auto res = cli_.Get("/streamed-chunked", headers);
  4799. ASSERT_TRUE(res);
  4800. EXPECT_EQ(StatusCode::OK_200, res->status);
  4801. EXPECT_EQ(std::string("123456789"), res->body);
  4802. }
  4803. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4804. Headers headers;
  4805. headers.emplace("Accept-Encoding", "gzip, deflate");
  4806. auto res = cli_.Get("/streamed-chunked2", headers);
  4807. ASSERT_TRUE(res);
  4808. EXPECT_EQ(StatusCode::OK_200, res->status);
  4809. EXPECT_EQ(std::string("123456789"), res->body);
  4810. }
  4811. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4812. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4813. ASSERT_TRUE(res);
  4814. EXPECT_EQ(StatusCode::OK_200, res->status);
  4815. }
  4816. TEST(GzipDecompressor, ChunkedDecompression) {
  4817. std::string data;
  4818. for (size_t i = 0; i < 32 * 1024; ++i) {
  4819. data.push_back(static_cast<char>('a' + i % 26));
  4820. }
  4821. std::string compressed_data;
  4822. {
  4823. httplib::detail::gzip_compressor compressor;
  4824. bool result = compressor.compress(
  4825. data.data(), data.size(),
  4826. /*last=*/true,
  4827. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4828. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4829. compressed_data_size);
  4830. return true;
  4831. });
  4832. ASSERT_TRUE(result);
  4833. }
  4834. std::string decompressed_data;
  4835. {
  4836. httplib::detail::gzip_decompressor decompressor;
  4837. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4838. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4839. size_t chunk_size = 130;
  4840. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4841. chunk_begin += chunk_size) {
  4842. size_t current_chunk_size =
  4843. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4844. bool result = decompressor.decompress(
  4845. compressed_data.data() + chunk_begin, current_chunk_size,
  4846. [&](const char *decompressed_data_chunk,
  4847. size_t decompressed_data_chunk_size) {
  4848. decompressed_data.insert(decompressed_data.size(),
  4849. decompressed_data_chunk,
  4850. decompressed_data_chunk_size);
  4851. return true;
  4852. });
  4853. ASSERT_TRUE(result);
  4854. }
  4855. }
  4856. ASSERT_EQ(data, decompressed_data);
  4857. }
  4858. TEST(GzipDecompressor, DeflateDecompression) {
  4859. std::string original_text = "Raw deflate without gzip";
  4860. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4861. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4862. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4863. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4864. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4865. std::string decompressed_data;
  4866. {
  4867. httplib::detail::gzip_decompressor decompressor;
  4868. bool result = decompressor.decompress(
  4869. compressed_data.data(), compressed_data.size(),
  4870. [&](const char *decompressed_data_chunk,
  4871. size_t decompressed_data_chunk_size) {
  4872. decompressed_data.insert(decompressed_data.size(),
  4873. decompressed_data_chunk,
  4874. decompressed_data_chunk_size);
  4875. return true;
  4876. });
  4877. ASSERT_TRUE(result);
  4878. }
  4879. ASSERT_EQ(original_text, decompressed_data);
  4880. }
  4881. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4882. std::string original_text = "Raw deflate without gzip";
  4883. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4884. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4885. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4886. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4887. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4888. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4889. std::string decompressed_data;
  4890. {
  4891. httplib::detail::gzip_decompressor decompressor;
  4892. bool result = decompressor.decompress(
  4893. compressed_data.data(), compressed_data.size(),
  4894. [&](const char *decompressed_data_chunk,
  4895. size_t decompressed_data_chunk_size) {
  4896. decompressed_data.insert(decompressed_data.size(),
  4897. decompressed_data_chunk,
  4898. decompressed_data_chunk_size);
  4899. return true;
  4900. });
  4901. ASSERT_TRUE(result);
  4902. }
  4903. ASSERT_EQ(original_text, decompressed_data);
  4904. }
  4905. #ifdef _WIN32
  4906. TEST(GzipDecompressor, LargeRandomData) {
  4907. // prepare large random data that is difficult to be compressed and is
  4908. // expected to have large size even when compressed
  4909. std::random_device seed_gen;
  4910. std::mt19937 random(seed_gen());
  4911. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4912. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4913. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4914. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4915. // compress data over 4GiB
  4916. std::string compressed_data;
  4917. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4918. httplib::detail::gzip_compressor compressor;
  4919. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4920. data.size() * sizeof(std::uint32_t), true,
  4921. [&](const char *data, size_t size) {
  4922. compressed_data.insert(
  4923. compressed_data.size(), data, size);
  4924. return true;
  4925. });
  4926. ASSERT_TRUE(result);
  4927. // FIXME: compressed data size is expected to be greater than 4GiB,
  4928. // but there is no guarantee
  4929. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4930. // decompress data over 4GiB
  4931. std::string decompressed_data;
  4932. decompressed_data.reserve(data_size);
  4933. httplib::detail::gzip_decompressor decompressor;
  4934. result = decompressor.decompress(
  4935. compressed_data.data(), compressed_data.size(),
  4936. [&](const char *data, size_t size) {
  4937. decompressed_data.insert(decompressed_data.size(), data, size);
  4938. return true;
  4939. });
  4940. ASSERT_TRUE(result);
  4941. // compare
  4942. ASSERT_EQ(data_size, decompressed_data.size());
  4943. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4944. 0);
  4945. }
  4946. #endif
  4947. #endif
  4948. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4949. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4950. Headers headers;
  4951. headers.emplace("Accept-Encoding", "br");
  4952. auto res = cli_.Get("/streamed-chunked", headers);
  4953. ASSERT_TRUE(res);
  4954. EXPECT_EQ(StatusCode::OK_200, res->status);
  4955. EXPECT_EQ(std::string("123456789"), res->body);
  4956. }
  4957. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4958. Headers headers;
  4959. headers.emplace("Accept-Encoding", "br");
  4960. auto res = cli_.Get("/streamed-chunked2", headers);
  4961. ASSERT_TRUE(res);
  4962. EXPECT_EQ(StatusCode::OK_200, res->status);
  4963. EXPECT_EQ(std::string("123456789"), res->body);
  4964. }
  4965. #endif
  4966. TEST_F(ServerTest, Patch) {
  4967. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4968. ASSERT_TRUE(res);
  4969. EXPECT_EQ(StatusCode::OK_200, res->status);
  4970. EXPECT_EQ("PATCH", res->body);
  4971. }
  4972. TEST_F(ServerTest, Delete) {
  4973. auto res = cli_.Delete("/delete");
  4974. ASSERT_TRUE(res);
  4975. EXPECT_EQ(StatusCode::OK_200, res->status);
  4976. EXPECT_EQ("DELETE", res->body);
  4977. }
  4978. TEST_F(ServerTest, DeleteContentReceiver) {
  4979. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4980. ASSERT_TRUE(res);
  4981. EXPECT_EQ(StatusCode::OK_200, res->status);
  4982. EXPECT_EQ("content", res->body);
  4983. }
  4984. TEST_F(ServerTest, Options) {
  4985. auto res = cli_.Options("*");
  4986. ASSERT_TRUE(res);
  4987. EXPECT_EQ(StatusCode::OK_200, res->status);
  4988. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4989. EXPECT_TRUE(res->body.empty());
  4990. }
  4991. TEST_F(ServerTest, URL) {
  4992. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4993. ASSERT_TRUE(res);
  4994. EXPECT_EQ(StatusCode::OK_200, res->status);
  4995. }
  4996. TEST_F(ServerTest, ArrayParam) {
  4997. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4998. ASSERT_TRUE(res);
  4999. EXPECT_EQ(StatusCode::OK_200, res->status);
  5000. }
  5001. TEST_F(ServerTest, NoMultipleHeaders) {
  5002. Headers headers = {{"Content-Length", "5"}};
  5003. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5004. "text/plain");
  5005. ASSERT_TRUE(res);
  5006. EXPECT_EQ(StatusCode::OK_200, res->status);
  5007. }
  5008. TEST_F(ServerTest, PostContentReceiver) {
  5009. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5010. ASSERT_TRUE(res);
  5011. ASSERT_EQ(StatusCode::OK_200, res->status);
  5012. ASSERT_EQ("content", res->body);
  5013. }
  5014. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5015. UploadFormDataItems items = {
  5016. {"text1", "text default", "", ""},
  5017. {"text2", "aωb", "", ""},
  5018. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5019. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5020. {"file3", "", "", "application/octet-stream"},
  5021. };
  5022. auto res = cli_.Post("/content_receiver", items);
  5023. ASSERT_TRUE(res);
  5024. EXPECT_EQ(StatusCode::OK_200, res->status);
  5025. }
  5026. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5027. UploadFormDataItems items = {
  5028. {"text1", "text default", "", ""},
  5029. {"text2", "aωb", "", ""},
  5030. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5031. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5032. {"file3", "", "", "application/octet-stream"},
  5033. };
  5034. auto boundary = std::string("+++++");
  5035. std::string body;
  5036. for (const auto &item : items) {
  5037. body += "--" + boundary + "\r\n";
  5038. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5039. if (!item.filename.empty()) {
  5040. body += "; filename=\"" + item.filename + "\"";
  5041. }
  5042. body += "\r\n";
  5043. if (!item.content_type.empty()) {
  5044. body += "Content-Type: " + item.content_type + "\r\n";
  5045. }
  5046. body += "\r\n";
  5047. body += item.content + "\r\n";
  5048. }
  5049. body += "--" + boundary + "--\r\n";
  5050. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5051. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5052. ASSERT_TRUE(res);
  5053. EXPECT_EQ(StatusCode::OK_200, res->status);
  5054. }
  5055. TEST_F(ServerTest, PostContentReceiverGzip) {
  5056. cli_.set_compress(true);
  5057. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5058. ASSERT_TRUE(res);
  5059. ASSERT_EQ(StatusCode::OK_200, res->status);
  5060. ASSERT_EQ("content", res->body);
  5061. }
  5062. TEST_F(ServerTest, PutContentReceiver) {
  5063. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5064. ASSERT_TRUE(res);
  5065. ASSERT_EQ(StatusCode::OK_200, res->status);
  5066. ASSERT_EQ("content", res->body);
  5067. }
  5068. TEST_F(ServerTest, PatchContentReceiver) {
  5069. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5070. ASSERT_TRUE(res);
  5071. ASSERT_EQ(StatusCode::OK_200, res->status);
  5072. ASSERT_EQ("content", res->body);
  5073. }
  5074. template <typename ClientType>
  5075. void TestWithHeadersAndContentReceiver(
  5076. ClientType &cli,
  5077. std::function<Result(ClientType &, const std::string &, const Headers &,
  5078. const std::string &, const std::string &,
  5079. ContentReceiver, DownloadProgress)>
  5080. request_func) {
  5081. Headers headers;
  5082. headers.emplace("X-Custom-Header", "test-value");
  5083. std::string received_body;
  5084. auto res = request_func(
  5085. cli, "/content_receiver", headers, "content", "application/json",
  5086. [&](const char *data, size_t data_length) {
  5087. received_body.append(data, data_length);
  5088. return true;
  5089. },
  5090. nullptr);
  5091. ASSERT_TRUE(res);
  5092. EXPECT_EQ(StatusCode::OK_200, res->status);
  5093. EXPECT_EQ("content", received_body);
  5094. }
  5095. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5096. #ifdef CPPHTTPLIB_SSL_ENABLED
  5097. using ClientT = SSLClient;
  5098. #else
  5099. using ClientT = Client;
  5100. #endif
  5101. TestWithHeadersAndContentReceiver<ClientT>(
  5102. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5103. const std::string &body, const std::string &content_type,
  5104. ContentReceiver receiver, DownloadProgress progress) {
  5105. return cli.Post(path, headers, body, content_type, receiver, progress);
  5106. });
  5107. }
  5108. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5109. #ifdef CPPHTTPLIB_SSL_ENABLED
  5110. using ClientT = SSLClient;
  5111. #else
  5112. using ClientT = Client;
  5113. #endif
  5114. TestWithHeadersAndContentReceiver<ClientT>(
  5115. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5116. const std::string &body, const std::string &content_type,
  5117. ContentReceiver receiver, DownloadProgress progress) {
  5118. return cli.Put(path, headers, body, content_type, receiver, progress);
  5119. });
  5120. }
  5121. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5122. #ifdef CPPHTTPLIB_SSL_ENABLED
  5123. using ClientT = SSLClient;
  5124. #else
  5125. using ClientT = Client;
  5126. #endif
  5127. TestWithHeadersAndContentReceiver<ClientT>(
  5128. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5129. const std::string &body, const std::string &content_type,
  5130. ContentReceiver receiver, DownloadProgress progress) {
  5131. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5132. });
  5133. }
  5134. template <typename ClientType>
  5135. void TestWithHeadersAndContentReceiverWithProgress(
  5136. ClientType &cli,
  5137. std::function<Result(ClientType &, const std::string &, const Headers &,
  5138. const std::string &, const std::string &,
  5139. ContentReceiver, DownloadProgress)>
  5140. request_func) {
  5141. Headers headers;
  5142. headers.emplace("X-Test-Header", "progress-test");
  5143. std::string received_body;
  5144. auto progress_called = false;
  5145. auto res = request_func(
  5146. cli, "/content_receiver", headers, "content", "text/plain",
  5147. [&](const char *data, size_t data_length) {
  5148. received_body.append(data, data_length);
  5149. return true;
  5150. },
  5151. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5152. progress_called = true;
  5153. return true;
  5154. });
  5155. ASSERT_TRUE(res);
  5156. EXPECT_EQ(StatusCode::OK_200, res->status);
  5157. EXPECT_EQ("content", received_body);
  5158. EXPECT_TRUE(progress_called);
  5159. }
  5160. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5161. #ifdef CPPHTTPLIB_SSL_ENABLED
  5162. using ClientT = SSLClient;
  5163. #else
  5164. using ClientT = Client;
  5165. #endif
  5166. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5167. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5168. const std::string &body, const std::string &content_type,
  5169. ContentReceiver receiver, DownloadProgress progress) {
  5170. return cli.Post(path, headers, body, content_type, receiver, progress);
  5171. });
  5172. }
  5173. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5174. #ifdef CPPHTTPLIB_SSL_ENABLED
  5175. using ClientT = SSLClient;
  5176. #else
  5177. using ClientT = Client;
  5178. #endif
  5179. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5180. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5181. const std::string &body, const std::string &content_type,
  5182. ContentReceiver receiver, DownloadProgress progress) {
  5183. return cli.Put(path, headers, body, content_type, receiver, progress);
  5184. });
  5185. }
  5186. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5187. #ifdef CPPHTTPLIB_SSL_ENABLED
  5188. using ClientT = SSLClient;
  5189. #else
  5190. using ClientT = Client;
  5191. #endif
  5192. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5193. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5194. const std::string &body, const std::string &content_type,
  5195. ContentReceiver receiver, DownloadProgress progress) {
  5196. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5197. });
  5198. }
  5199. template <typename ClientType>
  5200. void TestWithHeadersAndContentReceiverError(
  5201. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5202. const Headers &, const std::string &,
  5203. const std::string &, ContentReceiver)>
  5204. request_func) {
  5205. Headers headers;
  5206. headers.emplace("X-Error-Test", "true");
  5207. std::string received_body;
  5208. auto receiver_failed = false;
  5209. auto res =
  5210. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5211. [&](const char *data, size_t data_length) {
  5212. received_body.append(data, data_length);
  5213. receiver_failed = true;
  5214. return false;
  5215. });
  5216. ASSERT_FALSE(res);
  5217. EXPECT_TRUE(receiver_failed);
  5218. }
  5219. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5220. #ifdef CPPHTTPLIB_SSL_ENABLED
  5221. using ClientT = SSLClient;
  5222. #else
  5223. using ClientT = Client;
  5224. #endif
  5225. TestWithHeadersAndContentReceiverError<ClientT>(
  5226. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5227. const std::string &body, const std::string &content_type,
  5228. ContentReceiver receiver) {
  5229. return cli.Post(path, headers, body, content_type, receiver);
  5230. });
  5231. }
  5232. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5233. #ifdef CPPHTTPLIB_SSL_ENABLED
  5234. using ClientT = SSLClient;
  5235. #else
  5236. using ClientT = Client;
  5237. #endif
  5238. TestWithHeadersAndContentReceiverError<ClientT>(
  5239. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5240. const std::string &body, const std::string &content_type,
  5241. ContentReceiver receiver) {
  5242. return cli.Put(path, headers, body, content_type, receiver);
  5243. });
  5244. }
  5245. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5246. #ifdef CPPHTTPLIB_SSL_ENABLED
  5247. using ClientT = SSLClient;
  5248. #else
  5249. using ClientT = Client;
  5250. #endif
  5251. TestWithHeadersAndContentReceiverError<ClientT>(
  5252. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5253. const std::string &body, const std::string &content_type,
  5254. ContentReceiver receiver) {
  5255. return cli.Patch(path, headers, body, content_type, receiver);
  5256. });
  5257. }
  5258. TEST_F(ServerTest, PostQueryStringAndBody) {
  5259. auto res =
  5260. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5261. ASSERT_TRUE(res);
  5262. ASSERT_EQ(StatusCode::OK_200, res->status);
  5263. }
  5264. TEST_F(ServerTest, HTTP2Magic) {
  5265. Request req;
  5266. req.method = "PRI";
  5267. req.path = "*";
  5268. req.body = "SM";
  5269. auto res = std::make_shared<Response>();
  5270. auto error = Error::Success;
  5271. auto ret = cli_.send(req, *res, error);
  5272. ASSERT_TRUE(ret);
  5273. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5274. }
  5275. TEST_F(ServerTest, KeepAlive) {
  5276. auto res = cli_.Get("/hi");
  5277. ASSERT_TRUE(res);
  5278. EXPECT_EQ(StatusCode::OK_200, res->status);
  5279. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5280. EXPECT_EQ("Hello World!", res->body);
  5281. res = cli_.Get("/hi");
  5282. ASSERT_TRUE(res);
  5283. EXPECT_EQ(StatusCode::OK_200, res->status);
  5284. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5285. EXPECT_EQ("Hello World!", res->body);
  5286. res = cli_.Get("/hi");
  5287. ASSERT_TRUE(res);
  5288. EXPECT_EQ(StatusCode::OK_200, res->status);
  5289. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5290. EXPECT_EQ("Hello World!", res->body);
  5291. res = cli_.Get("/not-exist");
  5292. ASSERT_TRUE(res);
  5293. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5294. res = cli_.Post("/empty", "", "text/plain");
  5295. ASSERT_TRUE(res);
  5296. EXPECT_EQ(StatusCode::OK_200, res->status);
  5297. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5298. EXPECT_EQ("empty", res->body);
  5299. EXPECT_EQ("close", res->get_header_value("Connection"));
  5300. res = cli_.Post(
  5301. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5302. "text/plain");
  5303. ASSERT_TRUE(res);
  5304. EXPECT_EQ(StatusCode::OK_200, res->status);
  5305. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5306. EXPECT_EQ("empty", res->body);
  5307. cli_.set_keep_alive(false);
  5308. res = cli_.Get("/last-request");
  5309. ASSERT_TRUE(res);
  5310. EXPECT_EQ(StatusCode::OK_200, res->status);
  5311. EXPECT_EQ("close", res->get_header_value("Connection"));
  5312. }
  5313. TEST_F(ServerTest, TooManyRedirect) {
  5314. cli_.set_follow_location(true);
  5315. auto res = cli_.Get("/redirect/0");
  5316. ASSERT_TRUE(!res);
  5317. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5318. }
  5319. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5320. Request req;
  5321. req.method = "FOOBAR";
  5322. req.path = "/hi";
  5323. cli_.set_keep_alive(true);
  5324. auto res = cli_.send(req);
  5325. ASSERT_TRUE(res);
  5326. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5327. EXPECT_EQ("close", res->get_header_value("Connection"));
  5328. EXPECT_FALSE(cli_.is_socket_open());
  5329. }
  5330. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5331. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5332. TEST_F(ServerTest, Gzip) {
  5333. Headers headers;
  5334. headers.emplace("Accept-Encoding", "gzip, deflate");
  5335. auto res = cli_.Get("/compress", headers);
  5336. ASSERT_TRUE(res);
  5337. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5338. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5339. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5340. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5341. "7890123456789012345678901234567890",
  5342. res->body);
  5343. EXPECT_EQ(StatusCode::OK_200, res->status);
  5344. }
  5345. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5346. Headers headers;
  5347. headers.emplace("Accept-Encoding", "gzip, deflate");
  5348. auto res = cli_.Get("/compress-with-charset", headers);
  5349. ASSERT_TRUE(res);
  5350. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5351. EXPECT_EQ("application/json; charset=utf-8",
  5352. res->get_header_value("Content-Type"));
  5353. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5354. "7890123456789012345678901234567890",
  5355. res->body);
  5356. EXPECT_EQ(StatusCode::OK_200, res->status);
  5357. }
  5358. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5359. Headers headers;
  5360. headers.emplace("Accept-Encoding", "");
  5361. auto res = cli_.Get("/compress", headers);
  5362. ASSERT_TRUE(res);
  5363. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5364. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5365. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5366. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5367. "7890123456789012345678901234567890",
  5368. res->body);
  5369. EXPECT_EQ(StatusCode::OK_200, res->status);
  5370. }
  5371. TEST_F(ServerTest, GzipWithContentReceiver) {
  5372. Headers headers;
  5373. headers.emplace("Accept-Encoding", "gzip, deflate");
  5374. std::string body;
  5375. auto res = cli_.Get("/compress", headers,
  5376. [&](const char *data, uint64_t data_length) {
  5377. EXPECT_EQ(100U, data_length);
  5378. body.append(data, data_length);
  5379. return true;
  5380. });
  5381. ASSERT_TRUE(res);
  5382. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5383. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5384. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5385. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5386. "7890123456789012345678901234567890",
  5387. body);
  5388. EXPECT_EQ(StatusCode::OK_200, res->status);
  5389. }
  5390. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5391. Headers headers;
  5392. headers.emplace("Accept-Encoding", "gzip, deflate");
  5393. cli_.set_decompress(false);
  5394. auto res = cli_.Get("/compress", headers);
  5395. ASSERT_TRUE(res);
  5396. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5397. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5398. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5399. EXPECT_EQ(33U, res->body.size());
  5400. EXPECT_EQ(StatusCode::OK_200, res->status);
  5401. }
  5402. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5403. Headers headers;
  5404. headers.emplace("Accept-Encoding", "");
  5405. std::string body;
  5406. auto res = cli_.Get("/compress", headers,
  5407. [&](const char *data, uint64_t data_length) {
  5408. EXPECT_EQ(100U, data_length);
  5409. body.append(data, data_length);
  5410. return true;
  5411. });
  5412. ASSERT_TRUE(res);
  5413. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5414. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5415. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5416. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5417. "7890123456789012345678901234567890",
  5418. body);
  5419. EXPECT_EQ(StatusCode::OK_200, res->status);
  5420. }
  5421. TEST_F(ServerTest, NoGzip) {
  5422. Headers headers;
  5423. headers.emplace("Accept-Encoding", "gzip, deflate");
  5424. auto res = cli_.Get("/nocompress", headers);
  5425. ASSERT_TRUE(res);
  5426. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5427. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5428. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5429. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5430. "7890123456789012345678901234567890",
  5431. res->body);
  5432. EXPECT_EQ(StatusCode::OK_200, res->status);
  5433. }
  5434. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5435. Headers headers;
  5436. headers.emplace("Accept-Encoding", "gzip, deflate");
  5437. std::string body;
  5438. auto res = cli_.Get("/nocompress", headers,
  5439. [&](const char *data, uint64_t data_length) {
  5440. EXPECT_EQ(100U, data_length);
  5441. body.append(data, data_length);
  5442. return true;
  5443. });
  5444. ASSERT_TRUE(res);
  5445. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5446. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5447. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5448. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5449. "7890123456789012345678901234567890",
  5450. body);
  5451. EXPECT_EQ(StatusCode::OK_200, res->status);
  5452. }
  5453. TEST_F(ServerTest, MultipartFormDataGzip) {
  5454. UploadFormDataItems items = {
  5455. {"key1", "test", "", ""},
  5456. {"key2", "--abcdefg123", "", ""},
  5457. };
  5458. cli_.set_compress(true);
  5459. auto res = cli_.Post("/compress-multipart", items);
  5460. ASSERT_TRUE(res);
  5461. EXPECT_EQ(StatusCode::OK_200, res->status);
  5462. }
  5463. #endif
  5464. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5465. TEST_F(ServerTest, Brotli) {
  5466. Headers headers;
  5467. headers.emplace("Accept-Encoding", "br");
  5468. auto res = cli_.Get("/compress", headers);
  5469. ASSERT_TRUE(res);
  5470. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5471. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5472. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5473. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5474. "7890123456789012345678901234567890",
  5475. res->body);
  5476. EXPECT_EQ(StatusCode::OK_200, res->status);
  5477. }
  5478. #endif
  5479. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5480. TEST_F(ServerTest, Zstd) {
  5481. Headers headers;
  5482. headers.emplace("Accept-Encoding", "zstd");
  5483. auto res = cli_.Get("/compress", headers);
  5484. ASSERT_TRUE(res);
  5485. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5486. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5487. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5488. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5489. "7890123456789012345678901234567890",
  5490. res->body);
  5491. EXPECT_EQ(StatusCode::OK_200, res->status);
  5492. }
  5493. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5494. Headers headers;
  5495. headers.emplace("Accept-Encoding", "");
  5496. auto res = cli_.Get("/compress", headers);
  5497. ASSERT_TRUE(res);
  5498. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5499. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5500. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5501. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5502. "7890123456789012345678901234567890",
  5503. res->body);
  5504. EXPECT_EQ(StatusCode::OK_200, res->status);
  5505. }
  5506. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5507. Headers headers;
  5508. headers.emplace("Accept-Encoding", "zstd");
  5509. std::string body;
  5510. auto res = cli_.Get("/compress", headers,
  5511. [&](const char *data, uint64_t data_length) {
  5512. EXPECT_EQ(100U, data_length);
  5513. body.append(data, data_length);
  5514. return true;
  5515. });
  5516. ASSERT_TRUE(res);
  5517. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5518. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5519. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5520. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5521. "7890123456789012345678901234567890",
  5522. body);
  5523. EXPECT_EQ(StatusCode::OK_200, res->status);
  5524. }
  5525. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5526. Headers headers;
  5527. headers.emplace("Accept-Encoding", "zstd");
  5528. cli_.set_decompress(false);
  5529. auto res = cli_.Get("/compress", headers);
  5530. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5531. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5532. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5533. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5534. ASSERT_TRUE(res);
  5535. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5536. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5537. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5538. EXPECT_EQ(StatusCode::OK_200, res->status);
  5539. ASSERT_EQ(26U, res->body.size());
  5540. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5541. 0);
  5542. }
  5543. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5544. Headers headers;
  5545. headers.emplace("Accept-Encoding", "");
  5546. std::string body;
  5547. auto res = cli_.Get("/compress", headers,
  5548. [&](const char *data, uint64_t data_length) {
  5549. EXPECT_EQ(100U, data_length);
  5550. body.append(data, data_length);
  5551. return true;
  5552. });
  5553. ASSERT_TRUE(res);
  5554. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5555. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5556. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5557. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5558. "7890123456789012345678901234567890",
  5559. body);
  5560. EXPECT_EQ(StatusCode::OK_200, res->status);
  5561. }
  5562. TEST_F(ServerTest, NoZstd) {
  5563. Headers headers;
  5564. headers.emplace("Accept-Encoding", "zstd");
  5565. auto res = cli_.Get("/nocompress", headers);
  5566. ASSERT_TRUE(res);
  5567. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5568. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5569. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5570. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5571. "7890123456789012345678901234567890",
  5572. res->body);
  5573. EXPECT_EQ(StatusCode::OK_200, res->status);
  5574. }
  5575. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5576. Headers headers;
  5577. headers.emplace("Accept-Encoding", "zstd");
  5578. std::string body;
  5579. auto res = cli_.Get("/nocompress", headers,
  5580. [&](const char *data, uint64_t data_length) {
  5581. EXPECT_EQ(100U, data_length);
  5582. body.append(data, data_length);
  5583. return true;
  5584. });
  5585. ASSERT_TRUE(res);
  5586. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5587. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5588. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5589. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5590. "7890123456789012345678901234567890",
  5591. body);
  5592. EXPECT_EQ(StatusCode::OK_200, res->status);
  5593. }
  5594. // TODO: How to enable zstd ??
  5595. TEST_F(ServerTest, MultipartFormDataZstd) {
  5596. UploadFormDataItems items = {
  5597. {"key1", "test", "", ""},
  5598. {"key2", "--abcdefg123", "", ""},
  5599. };
  5600. Headers headers;
  5601. headers.emplace("Accept-Encoding", "zstd");
  5602. cli_.set_compress(true);
  5603. auto res = cli_.Post("/compress-multipart", headers, items);
  5604. ASSERT_TRUE(res);
  5605. EXPECT_EQ(StatusCode::OK_200, res->status);
  5606. }
  5607. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5608. Headers headers;
  5609. headers.emplace("Accept-Encoding", "zstd");
  5610. cli_.set_compress(true);
  5611. auto res = cli_.Put(
  5612. "/put", headers, 3,
  5613. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5614. sink.os << "PUT";
  5615. return true;
  5616. },
  5617. "text/plain");
  5618. ASSERT_TRUE(res);
  5619. EXPECT_EQ(StatusCode::OK_200, res->status);
  5620. EXPECT_EQ("PUT", res->body);
  5621. }
  5622. // Pre-compression logging tests
  5623. TEST_F(ServerTest, PreCompressionLogging) {
  5624. // Test data for compression (matches the actual /compress endpoint content)
  5625. const std::string test_content =
  5626. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5627. "3456789012345678901234567890";
  5628. // Variables to capture logging data
  5629. std::string pre_compression_body;
  5630. std::string pre_compression_content_type;
  5631. std::string pre_compression_content_encoding;
  5632. std::string post_compression_body;
  5633. std::string post_compression_content_type;
  5634. std::string post_compression_content_encoding;
  5635. // Set up pre-compression logger
  5636. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5637. const Response &res) {
  5638. pre_compression_body = res.body;
  5639. pre_compression_content_type = res.get_header_value("Content-Type");
  5640. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5641. });
  5642. // Set up post-compression logger
  5643. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5644. post_compression_body = res.body;
  5645. post_compression_content_type = res.get_header_value("Content-Type");
  5646. post_compression_content_encoding =
  5647. res.get_header_value("Content-Encoding");
  5648. });
  5649. // Test with gzip compression
  5650. Headers headers;
  5651. headers.emplace("Accept-Encoding", "gzip");
  5652. auto res = cli_.Get("/compress", headers);
  5653. // Verify response was compressed
  5654. ASSERT_TRUE(res);
  5655. EXPECT_EQ(StatusCode::OK_200, res->status);
  5656. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5657. // Verify pre-compression logger captured uncompressed content
  5658. EXPECT_EQ(test_content, pre_compression_body);
  5659. EXPECT_EQ("text/plain", pre_compression_content_type);
  5660. EXPECT_TRUE(pre_compression_content_encoding
  5661. .empty()); // No encoding header before compression
  5662. // Verify post-compression logger captured compressed content
  5663. EXPECT_NE(test_content,
  5664. post_compression_body); // Should be different after compression
  5665. EXPECT_EQ("text/plain", post_compression_content_type);
  5666. EXPECT_EQ("gzip", post_compression_content_encoding);
  5667. // Verify compressed content is smaller
  5668. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5669. }
  5670. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5671. const std::string test_content =
  5672. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5673. "3456789012345678901234567890";
  5674. std::string pre_compression_body;
  5675. std::string post_compression_body;
  5676. svr_.set_pre_compression_logger(
  5677. [&](const Request & /*req*/, const Response &res) {
  5678. pre_compression_body = res.body;
  5679. });
  5680. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5681. post_compression_body = res.body;
  5682. });
  5683. Headers headers;
  5684. headers.emplace("Accept-Encoding", "br");
  5685. auto res = cli_.Get("/compress", headers);
  5686. ASSERT_TRUE(res);
  5687. EXPECT_EQ(StatusCode::OK_200, res->status);
  5688. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5689. // Verify pre-compression content is uncompressed
  5690. EXPECT_EQ(test_content, pre_compression_body);
  5691. // Verify post-compression content is compressed
  5692. EXPECT_NE(test_content, post_compression_body);
  5693. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5694. }
  5695. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5696. const std::string test_content =
  5697. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5698. "3456789012345678901234567890";
  5699. std::string pre_compression_body;
  5700. std::string post_compression_body;
  5701. svr_.set_pre_compression_logger(
  5702. [&](const Request & /*req*/, const Response &res) {
  5703. pre_compression_body = res.body;
  5704. });
  5705. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5706. post_compression_body = res.body;
  5707. });
  5708. // Request without compression (use /nocompress endpoint)
  5709. Headers headers;
  5710. auto res = cli_.Get("/nocompress", headers);
  5711. ASSERT_TRUE(res);
  5712. EXPECT_EQ(StatusCode::OK_200, res->status);
  5713. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5714. // Pre-compression logger should not be called when no compression is applied
  5715. EXPECT_TRUE(
  5716. pre_compression_body.empty()); // Pre-compression logger not called
  5717. EXPECT_EQ(
  5718. test_content,
  5719. post_compression_body); // Post-compression logger captures final content
  5720. }
  5721. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5722. const std::string test_content =
  5723. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5724. "3456789012345678901234567890";
  5725. std::string pre_compression_body;
  5726. bool pre_logger_called = false;
  5727. // Set only pre-compression logger
  5728. svr_.set_pre_compression_logger(
  5729. [&](const Request & /*req*/, const Response &res) {
  5730. pre_compression_body = res.body;
  5731. pre_logger_called = true;
  5732. });
  5733. Headers headers;
  5734. headers.emplace("Accept-Encoding", "gzip");
  5735. auto res = cli_.Get("/compress", headers);
  5736. ASSERT_TRUE(res);
  5737. EXPECT_EQ(StatusCode::OK_200, res->status);
  5738. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5739. // Verify pre-compression logger was called
  5740. EXPECT_TRUE(pre_logger_called);
  5741. EXPECT_EQ(test_content, pre_compression_body);
  5742. }
  5743. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5744. {
  5745. // Test with Expect: 100-continue header - success case
  5746. // Server returns 100 Continue, client sends body, server returns 200 OK
  5747. Request req;
  5748. req.method = "POST";
  5749. req.path = "/post-large";
  5750. req.set_header("Expect", "100-continue");
  5751. req.body = LARGE_DATA;
  5752. Response res;
  5753. auto error = Error::Success;
  5754. cli_.set_keep_alive(true);
  5755. auto ret = cli_.send(req, res, error);
  5756. EXPECT_TRUE(ret);
  5757. EXPECT_EQ(StatusCode::OK_200, res.status);
  5758. EXPECT_EQ(LARGE_DATA, res.body);
  5759. }
  5760. {
  5761. // Test with Expect: 100-continue header - error case
  5762. // Client should not send the body when server returns an error
  5763. Request req;
  5764. req.method = "POST";
  5765. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5766. req.set_header("Expect", "100-continue");
  5767. req.body = LARGE_DATA;
  5768. Response res;
  5769. auto error = Error::Success;
  5770. auto start = std::chrono::high_resolution_clock::now();
  5771. cli_.set_keep_alive(true);
  5772. auto ret = cli_.send(req, res, error);
  5773. auto end = std::chrono::high_resolution_clock::now();
  5774. auto elapsed =
  5775. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5776. .count();
  5777. // With Expect: 100-continue, request completes successfully but with error
  5778. EXPECT_TRUE(ret);
  5779. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5780. EXPECT_EQ("close", res.get_header_value("Connection"));
  5781. EXPECT_FALSE(cli_.is_socket_open());
  5782. EXPECT_LE(elapsed, 200);
  5783. }
  5784. {
  5785. // Send an extra GET request to ensure error recovery without hanging
  5786. Request req;
  5787. req.method = "GET";
  5788. req.path = "/hi";
  5789. auto start = std::chrono::high_resolution_clock::now();
  5790. auto res = cli_.send(req);
  5791. auto end = std::chrono::high_resolution_clock::now();
  5792. auto elapsed =
  5793. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5794. .count();
  5795. ASSERT_TRUE(res);
  5796. EXPECT_EQ(StatusCode::OK_200, res->status);
  5797. EXPECT_EQ("Hello World!", res->body);
  5798. EXPECT_LE(elapsed, 500);
  5799. }
  5800. }
  5801. TEST(ZstdDecompressor, ChunkedDecompression) {
  5802. std::string data;
  5803. for (size_t i = 0; i < 32 * 1024; ++i) {
  5804. data.push_back(static_cast<char>('a' + i % 26));
  5805. }
  5806. std::string compressed_data;
  5807. {
  5808. httplib::detail::zstd_compressor compressor;
  5809. bool result = compressor.compress(
  5810. data.data(), data.size(),
  5811. /*last=*/true,
  5812. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5813. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5814. compressed_data_size);
  5815. return true;
  5816. });
  5817. ASSERT_TRUE(result);
  5818. }
  5819. std::string decompressed_data;
  5820. {
  5821. httplib::detail::zstd_decompressor decompressor;
  5822. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5823. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5824. size_t chunk_size = 130;
  5825. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5826. chunk_begin += chunk_size) {
  5827. size_t current_chunk_size =
  5828. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5829. bool result = decompressor.decompress(
  5830. compressed_data.data() + chunk_begin, current_chunk_size,
  5831. [&](const char *decompressed_data_chunk,
  5832. size_t decompressed_data_chunk_size) {
  5833. decompressed_data.insert(decompressed_data.size(),
  5834. decompressed_data_chunk,
  5835. decompressed_data_chunk_size);
  5836. return true;
  5837. });
  5838. ASSERT_TRUE(result);
  5839. }
  5840. }
  5841. ASSERT_EQ(data, decompressed_data);
  5842. }
  5843. TEST(ZstdDecompressor, Decompress) {
  5844. std::string original_text = "Compressed with ZSTD";
  5845. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5846. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5847. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5848. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5849. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5850. std::string decompressed_data;
  5851. {
  5852. httplib::detail::zstd_decompressor decompressor;
  5853. bool result = decompressor.decompress(
  5854. compressed_data.data(), compressed_data.size(),
  5855. [&](const char *decompressed_data_chunk,
  5856. size_t decompressed_data_chunk_size) {
  5857. decompressed_data.insert(decompressed_data.size(),
  5858. decompressed_data_chunk,
  5859. decompressed_data_chunk_size);
  5860. return true;
  5861. });
  5862. ASSERT_TRUE(result);
  5863. }
  5864. ASSERT_EQ(original_text, decompressed_data);
  5865. }
  5866. #endif
  5867. // Sends a raw request to a server listening at HOST:PORT.
  5868. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5869. std::string *resp = nullptr) {
  5870. auto error = Error::Success;
  5871. auto client_sock = detail::create_client_socket(
  5872. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5873. /*connection_timeout_sec=*/5, 0,
  5874. /*read_timeout_sec=*/5, 0,
  5875. /*write_timeout_sec=*/5, 0, std::string(), error);
  5876. if (client_sock == INVALID_SOCKET) { return false; }
  5877. auto ret = detail::process_client_socket(
  5878. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5879. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5880. if (req.size() !=
  5881. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5882. return false;
  5883. }
  5884. char buf[512];
  5885. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5886. while (line_reader.getline()) {
  5887. if (resp) { *resp += line_reader.ptr(); }
  5888. }
  5889. return true;
  5890. });
  5891. detail::close_socket(client_sock);
  5892. return ret;
  5893. }
  5894. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5895. Server svr;
  5896. std::string header_value;
  5897. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5898. header_value = req.get_header_value("foo");
  5899. res.set_content("ok", "text/plain");
  5900. });
  5901. thread t = thread([&] { svr.listen(HOST, PORT); });
  5902. auto se = detail::scope_exit([&] {
  5903. svr.stop();
  5904. t.join();
  5905. ASSERT_FALSE(svr.is_running());
  5906. });
  5907. svr.wait_until_ready();
  5908. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5909. // like characters are not treated the same - use vertical tab and escape.
  5910. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5911. "foo: \t \v bar \x1B\t \r\n"
  5912. "Connection: close\r\n"
  5913. "\r\n";
  5914. std::string res;
  5915. ASSERT_TRUE(send_request(5, req, &res));
  5916. EXPECT_EQ(header_value, "");
  5917. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5918. }
  5919. // Sends a raw request and verifies that there isn't a crash or exception.
  5920. static void test_raw_request(const std::string &req,
  5921. std::string *out = nullptr) {
  5922. Server svr;
  5923. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5924. res.set_content("ok", "text/plain");
  5925. });
  5926. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5927. res.set_content("ok", "text/plain");
  5928. });
  5929. svr.Get("/header_field_value_check",
  5930. [&](const Request & /*req*/, Response &res) {
  5931. res.set_content("ok", "text/plain");
  5932. });
  5933. // Server read timeout must be longer than the client read timeout for the
  5934. // bug to reproduce, probably to force the server to process a request
  5935. // without a trailing blank line.
  5936. const time_t client_read_timeout_sec = 1;
  5937. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5938. bool listen_thread_ok = false;
  5939. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5940. auto se = detail::scope_exit([&] {
  5941. svr.stop();
  5942. t.join();
  5943. ASSERT_FALSE(svr.is_running());
  5944. EXPECT_TRUE(listen_thread_ok);
  5945. });
  5946. svr.wait_until_ready();
  5947. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5948. }
  5949. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5950. // A certain header line causes an exception if the header property is parsed
  5951. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5952. test_raw_request(
  5953. "GET /hi HTTP/1.1\r\n"
  5954. " : "
  5955. " "
  5956. " ");
  5957. }
  5958. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5959. // A certain header line causes an exception if the header property *name* is
  5960. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5961. // greedy matcher and requires backtracking when there are a lot of ":"
  5962. // characters.
  5963. // This occurs with libc++ but not libstdc++.
  5964. test_raw_request(
  5965. "GET /hi HTTP/1.1\r\n"
  5966. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5967. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5968. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5969. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5970. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5971. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5972. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5973. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5974. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5975. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5976. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5977. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5978. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5979. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5980. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5981. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5982. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5983. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5984. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5985. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5986. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5987. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5988. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5989. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5990. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5991. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5992. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5993. "&&&%%%");
  5994. }
  5995. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5996. // Make sure this doesn't crash the server.
  5997. // In a previous version of the header line regex, the "\r" rendered the line
  5998. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5999. // a new position where the leading white space ended and the field value
  6000. // began.
  6001. // The crash occurs with libc++ but not libstdc++.
  6002. test_raw_request("GET /hi HTTP/1.1\r\n"
  6003. "a:" +
  6004. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6005. "\r\n"
  6006. "\r\n");
  6007. }
  6008. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6009. std::string out;
  6010. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6011. "Content-Type: text/plain\r\n"
  6012. "Transfer-Encoding: chunked\r\n"
  6013. "\r\n"
  6014. "nothex\r\n",
  6015. &out);
  6016. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6017. }
  6018. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6019. std::string out;
  6020. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6021. "Content-Type: text/plain\r\n"
  6022. "Transfer-Encoding: chunked\r\n"
  6023. "\r\n"
  6024. "3\r\n"
  6025. "xyz\r\n"
  6026. "NaN\r\n",
  6027. &out);
  6028. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6029. }
  6030. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6031. std::string out;
  6032. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6033. "Content-Type: text/plain\r\n"
  6034. "Transfer-Encoding: chunked\r\n"
  6035. "\r\n"
  6036. // Length is too large for 64 bits.
  6037. "1ffffffffffffffff\r\n"
  6038. "xyz\r\n",
  6039. &out);
  6040. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6041. }
  6042. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6043. test_raw_request("GET /hi HTTP/1.1\r\n"
  6044. "Content-Type: text/plain\r\n\r");
  6045. }
  6046. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6047. std::string out;
  6048. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6049. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6050. }
  6051. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6052. Server svr;
  6053. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6054. EXPECT_TRUE(!req.remote_addr.empty());
  6055. });
  6056. thread t = thread([&] { svr.listen(HOST, PORT); });
  6057. auto se = detail::scope_exit([&] {
  6058. svr.stop();
  6059. t.join();
  6060. ASSERT_FALSE(svr.is_running());
  6061. });
  6062. svr.wait_until_ready();
  6063. // Send an invalid request line to trigger Bad Request
  6064. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6065. std::string out;
  6066. ASSERT_TRUE(send_request(5, bad_req, &out));
  6067. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6068. }
  6069. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6070. std::string out;
  6071. std::string request(
  6072. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6073. test_raw_request(request, &out);
  6074. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6075. }
  6076. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6077. std::string out;
  6078. std::string request(
  6079. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6080. test_raw_request(request, &out);
  6081. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6082. }
  6083. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6084. std::string out;
  6085. std::string request(
  6086. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6087. test_raw_request(request, &out);
  6088. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6089. }
  6090. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6091. std::string out;
  6092. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6093. "Test: \r\n\r\n",
  6094. &out);
  6095. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6096. }
  6097. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6098. Server svr;
  6099. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6100. res.set_header("Cache-Control", "no-cache");
  6101. res.set_chunked_content_provider(
  6102. "text/event-stream", [](size_t offset, DataSink &sink) {
  6103. std::string s = "data:";
  6104. s += std::to_string(offset);
  6105. s += "\n\n";
  6106. auto ret = sink.write(s.data(), s.size());
  6107. EXPECT_TRUE(ret);
  6108. std::this_thread::sleep_for(std::chrono::seconds(1));
  6109. return true;
  6110. });
  6111. });
  6112. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6113. svr.wait_until_ready();
  6114. Client client(HOST, PORT);
  6115. const Headers headers = {{"Accept", "text/event-stream"}};
  6116. auto get_thread = std::thread([&client, &headers]() {
  6117. auto res = client.Get(
  6118. "/events", headers,
  6119. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6120. });
  6121. auto se = detail::scope_exit([&] {
  6122. svr.stop();
  6123. get_thread.join();
  6124. listen_thread.join();
  6125. ASSERT_FALSE(svr.is_running());
  6126. });
  6127. // Give GET time to get a few messages.
  6128. std::this_thread::sleep_for(std::chrono::seconds(2));
  6129. }
  6130. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6131. httplib::Server svr;
  6132. svr.Post("/hi",
  6133. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6134. res.status = StatusCode::OK_200;
  6135. });
  6136. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6137. svr.wait_until_ready();
  6138. Client cli(HOST, PORT);
  6139. auto res = cli.Post("/hi", "data", "text/plain");
  6140. ASSERT_TRUE(res);
  6141. EXPECT_EQ(StatusCode::OK_200, res->status);
  6142. svr.stop();
  6143. thread.join();
  6144. ASSERT_FALSE(svr.is_running());
  6145. res = cli.Post("/hi", "data", "text/plain");
  6146. ASSERT_FALSE(res);
  6147. }
  6148. TEST(ServerStopTest, ListenFailure) {
  6149. Server svr;
  6150. auto t = thread([&]() {
  6151. auto ret = svr.listen("????", PORT);
  6152. EXPECT_FALSE(ret);
  6153. });
  6154. svr.wait_until_ready();
  6155. svr.stop();
  6156. t.join();
  6157. }
  6158. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6159. TEST(ServerStopTest, Decommision) {
  6160. Server svr;
  6161. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6162. for (int i = 0; i < 4; i++) {
  6163. auto is_even = !(i % 2);
  6164. std::thread t{[&] {
  6165. try {
  6166. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6167. if (is_even) {
  6168. throw std::runtime_error("Some thing that happens to go wrong.");
  6169. }
  6170. svr.listen(HOST, PORT);
  6171. } catch (...) { svr.decommission(); }
  6172. }};
  6173. svr.wait_until_ready();
  6174. // Server is up
  6175. {
  6176. Client cli(HOST, PORT);
  6177. auto res = cli.Get("/hi");
  6178. if (is_even) {
  6179. EXPECT_FALSE(res);
  6180. } else {
  6181. EXPECT_TRUE(res);
  6182. EXPECT_EQ("hi...", res->body);
  6183. }
  6184. }
  6185. svr.stop();
  6186. t.join();
  6187. // Server is down...
  6188. {
  6189. Client cli(HOST, PORT);
  6190. auto res = cli.Get("/hi");
  6191. EXPECT_FALSE(res);
  6192. }
  6193. }
  6194. }
  6195. #endif
  6196. // Helper function for string body upload progress tests
  6197. template <typename SetupHandler, typename ClientCall>
  6198. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6199. ClientCall &&client_call,
  6200. const string &body) {
  6201. Server svr;
  6202. setup_handler(svr);
  6203. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6204. auto se = detail::scope_exit([&] {
  6205. svr.stop();
  6206. t.join();
  6207. });
  6208. svr.wait_until_ready();
  6209. Client cli(HOST, PORT);
  6210. vector<uint64_t> progress_values;
  6211. bool progress_called = false;
  6212. auto res =
  6213. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6214. progress_values.push_back(current);
  6215. progress_called = true;
  6216. return true;
  6217. });
  6218. ASSERT_TRUE(res);
  6219. EXPECT_EQ(200, res->status);
  6220. EXPECT_TRUE(progress_called);
  6221. }
  6222. TEST(UploadProgressTest, PostStringBodyBasic) {
  6223. TestStringBodyUploadProgress(
  6224. [](Server &svr) {
  6225. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6226. res.set_content("received", "text/plain");
  6227. });
  6228. },
  6229. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6230. return cli.Post("/test", body, "text/plain", progress_callback);
  6231. },
  6232. "test data for upload progress");
  6233. }
  6234. TEST(UploadProgressTest, PutStringBodyBasic) {
  6235. TestStringBodyUploadProgress(
  6236. [](Server &svr) {
  6237. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6238. res.set_content("put received", "text/plain");
  6239. });
  6240. },
  6241. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6242. return cli.Put("/test", body, "text/plain", progress_callback);
  6243. },
  6244. "put test data for upload progress");
  6245. }
  6246. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6247. TestStringBodyUploadProgress(
  6248. [](Server &svr) {
  6249. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6250. res.set_content("patch received", "text/plain");
  6251. });
  6252. },
  6253. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6254. return cli.Patch("/test", body, "text/plain", progress_callback);
  6255. },
  6256. "patch test data for upload progress");
  6257. }
  6258. // Helper function for content provider upload progress tests
  6259. template <typename SetupHandler, typename ClientCall>
  6260. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6261. ClientCall &&client_call) {
  6262. Server svr;
  6263. setup_handler(svr);
  6264. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6265. auto se = detail::scope_exit([&] {
  6266. svr.stop();
  6267. t.join();
  6268. });
  6269. svr.wait_until_ready();
  6270. Client cli(HOST, PORT);
  6271. vector<uint64_t> progress_values;
  6272. auto res =
  6273. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6274. progress_values.push_back(current);
  6275. return true;
  6276. });
  6277. ASSERT_TRUE(res);
  6278. EXPECT_EQ(200, res->status);
  6279. EXPECT_FALSE(progress_values.empty());
  6280. }
  6281. TEST(UploadProgressTest, PostContentProviderProgress) {
  6282. TestContentProviderUploadProgress(
  6283. [](Server &svr) {
  6284. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6285. res.set_content("provider received", "text/plain");
  6286. });
  6287. },
  6288. [](Client &cli, UploadProgress progress_callback) {
  6289. return cli.Post(
  6290. "/test", 10,
  6291. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6292. sink.os << "test data";
  6293. return true;
  6294. },
  6295. "text/plain", progress_callback);
  6296. });
  6297. }
  6298. // Helper function for multipart upload progress tests
  6299. template <typename SetupHandler, typename ClientCall>
  6300. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6301. ClientCall &&client_call,
  6302. const string &endpoint) {
  6303. Server svr;
  6304. setup_handler(svr);
  6305. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6306. auto se = detail::scope_exit([&] {
  6307. svr.stop();
  6308. t.join();
  6309. });
  6310. svr.wait_until_ready();
  6311. Client cli(HOST, PORT);
  6312. vector<uint64_t> progress_values;
  6313. UploadFormDataItems items = {
  6314. {"field1", "value1", "", ""},
  6315. {"field2", "longer value for progress tracking test", "", ""},
  6316. {"file1", "file content data for upload progress", "test.txt",
  6317. "text/plain"}};
  6318. auto res = client_call(cli, endpoint, items,
  6319. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6320. progress_values.push_back(current);
  6321. return true;
  6322. });
  6323. ASSERT_TRUE(res);
  6324. EXPECT_EQ(200, res->status);
  6325. EXPECT_FALSE(progress_values.empty());
  6326. }
  6327. TEST(UploadProgressTest, PostMultipartProgress) {
  6328. TestMultipartUploadProgress(
  6329. [](Server &svr) {
  6330. svr.Post("/multipart", [](const Request &req, Response &res) {
  6331. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6332. res.set_content("multipart received", "text/plain");
  6333. });
  6334. },
  6335. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6336. UploadProgress progress_callback) {
  6337. return cli.Post(endpoint, items, progress_callback);
  6338. },
  6339. "/multipart");
  6340. }
  6341. // Helper function for basic download progress tests
  6342. template <typename SetupHandler, typename ClientCall>
  6343. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6344. ClientCall &&client_call, const string &endpoint,
  6345. size_t expected_content_size) {
  6346. Server svr;
  6347. setup_handler(svr);
  6348. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6349. auto se = detail::scope_exit([&] {
  6350. svr.stop();
  6351. t.join();
  6352. });
  6353. svr.wait_until_ready();
  6354. Client cli(HOST, PORT);
  6355. vector<uint64_t> progress_values;
  6356. auto res = client_call(cli, endpoint,
  6357. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6358. progress_values.push_back(current);
  6359. return true;
  6360. });
  6361. ASSERT_TRUE(res);
  6362. EXPECT_EQ(200, res->status);
  6363. EXPECT_FALSE(progress_values.empty());
  6364. EXPECT_EQ(expected_content_size, res->body.size());
  6365. }
  6366. TEST(DownloadProgressTest, GetBasic) {
  6367. TestBasicDownloadProgress(
  6368. [](Server &svr) {
  6369. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6370. string content(1000, 'D');
  6371. res.set_content(content, "text/plain");
  6372. });
  6373. },
  6374. [](Client &cli, const string &endpoint,
  6375. DownloadProgress progress_callback) {
  6376. return cli.Get(endpoint, progress_callback);
  6377. },
  6378. "/download", 1000u);
  6379. }
  6380. // Helper function for content receiver download progress tests
  6381. template <typename SetupHandler, typename ClientCall>
  6382. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6383. ClientCall &&client_call,
  6384. const string &endpoint,
  6385. size_t expected_content_size) {
  6386. Server svr;
  6387. setup_handler(svr);
  6388. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6389. auto se = detail::scope_exit([&] {
  6390. svr.stop();
  6391. t.join();
  6392. });
  6393. svr.wait_until_ready();
  6394. Client cli(HOST, PORT);
  6395. vector<uint64_t> progress_values;
  6396. string received_body;
  6397. auto res = client_call(
  6398. cli, endpoint,
  6399. [&](const char *data, size_t data_length) -> bool {
  6400. received_body.append(data, data_length);
  6401. return true;
  6402. },
  6403. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6404. progress_values.push_back(current);
  6405. return true;
  6406. });
  6407. ASSERT_TRUE(res);
  6408. EXPECT_EQ(200, res->status);
  6409. EXPECT_FALSE(progress_values.empty());
  6410. EXPECT_EQ(expected_content_size, received_body.size());
  6411. EXPECT_TRUE(res->body.empty());
  6412. }
  6413. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6414. TestContentReceiverDownloadProgress(
  6415. [](Server &svr) {
  6416. svr.Get("/download-receiver",
  6417. [](const Request & /*req*/, Response &res) {
  6418. string content(2000, 'R');
  6419. res.set_content(content, "text/plain");
  6420. });
  6421. },
  6422. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6423. DownloadProgress progress_callback) {
  6424. return cli.Get(endpoint, content_receiver, progress_callback);
  6425. },
  6426. "/download-receiver", 2000u);
  6427. }
  6428. TEST(StreamingTest, NoContentLengthStreaming) {
  6429. Server svr;
  6430. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6431. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6432. if (offset < 6) {
  6433. sink.os << (offset < 3 ? "a" : "b");
  6434. } else {
  6435. sink.done();
  6436. }
  6437. return true;
  6438. });
  6439. });
  6440. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6441. auto listen_se = detail::scope_exit([&] {
  6442. svr.stop();
  6443. listen_thread.join();
  6444. ASSERT_FALSE(svr.is_running());
  6445. });
  6446. svr.wait_until_ready();
  6447. Client client(HOST, PORT);
  6448. auto get_thread = std::thread([&client]() {
  6449. std::string s;
  6450. auto res =
  6451. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6452. s += std::string(data, len);
  6453. return true;
  6454. });
  6455. ASSERT_TRUE(res);
  6456. EXPECT_EQ(StatusCode::OK_200, res->status);
  6457. EXPECT_EQ("aaabbb", s);
  6458. });
  6459. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6460. // Give GET time to get a few messages.
  6461. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6462. }
  6463. TEST(MountTest, Unmount) {
  6464. Server svr;
  6465. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6466. auto se = detail::scope_exit([&] {
  6467. svr.stop();
  6468. listen_thread.join();
  6469. ASSERT_FALSE(svr.is_running());
  6470. });
  6471. svr.wait_until_ready();
  6472. Client cli("localhost", PORT);
  6473. svr.set_mount_point("/mount2", "./www2");
  6474. auto res = cli.Get("/");
  6475. ASSERT_TRUE(res);
  6476. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6477. res = cli.Get("/mount2/dir/test.html");
  6478. ASSERT_TRUE(res);
  6479. EXPECT_EQ(StatusCode::OK_200, res->status);
  6480. svr.set_mount_point("/", "./www");
  6481. res = cli.Get("/dir/");
  6482. ASSERT_TRUE(res);
  6483. EXPECT_EQ(StatusCode::OK_200, res->status);
  6484. svr.remove_mount_point("/");
  6485. res = cli.Get("/dir/");
  6486. ASSERT_TRUE(res);
  6487. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6488. svr.remove_mount_point("/mount2");
  6489. res = cli.Get("/mount2/dir/test.html");
  6490. ASSERT_TRUE(res);
  6491. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6492. }
  6493. TEST(MountTest, Redicect) {
  6494. Server svr;
  6495. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6496. auto se = detail::scope_exit([&] {
  6497. svr.stop();
  6498. listen_thread.join();
  6499. ASSERT_FALSE(svr.is_running());
  6500. });
  6501. svr.set_mount_point("/", "./www");
  6502. svr.wait_until_ready();
  6503. Client cli("localhost", PORT);
  6504. auto res = cli.Get("/dir/");
  6505. ASSERT_TRUE(res);
  6506. EXPECT_EQ(StatusCode::OK_200, res->status);
  6507. res = cli.Get("/dir");
  6508. ASSERT_TRUE(res);
  6509. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6510. res = cli.Get("/file");
  6511. ASSERT_TRUE(res);
  6512. EXPECT_EQ(StatusCode::OK_200, res->status);
  6513. res = cli.Get("/file/");
  6514. ASSERT_TRUE(res);
  6515. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6516. cli.set_follow_location(true);
  6517. res = cli.Get("/dir");
  6518. ASSERT_TRUE(res);
  6519. EXPECT_EQ(StatusCode::OK_200, res->status);
  6520. }
  6521. TEST(MountTest, MultibytesPathName) {
  6522. Server svr;
  6523. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6524. auto se = detail::scope_exit([&] {
  6525. svr.stop();
  6526. listen_thread.join();
  6527. ASSERT_FALSE(svr.is_running());
  6528. });
  6529. svr.set_mount_point("/", "./www");
  6530. svr.wait_until_ready();
  6531. Client cli("localhost", PORT);
  6532. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6533. ASSERT_TRUE(res);
  6534. EXPECT_EQ(StatusCode::OK_200, res->status);
  6535. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6536. }
  6537. TEST(KeepAliveTest, ReadTimeout) {
  6538. Server svr;
  6539. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6540. std::this_thread::sleep_for(std::chrono::seconds(2));
  6541. res.set_content("a", "text/plain");
  6542. });
  6543. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6544. res.set_content("b", "text/plain");
  6545. });
  6546. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6547. auto se = detail::scope_exit([&] {
  6548. svr.stop();
  6549. listen_thread.join();
  6550. ASSERT_FALSE(svr.is_running());
  6551. });
  6552. svr.wait_until_ready();
  6553. Client cli("localhost", PORT);
  6554. cli.set_keep_alive(true);
  6555. cli.set_read_timeout(std::chrono::seconds(1));
  6556. auto resa = cli.Get("/a");
  6557. ASSERT_FALSE(resa);
  6558. EXPECT_EQ(Error::Read, resa.error());
  6559. auto resb = cli.Get("/b");
  6560. ASSERT_TRUE(resb);
  6561. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6562. EXPECT_EQ("b", resb->body);
  6563. }
  6564. TEST(KeepAliveTest, MaxCount) {
  6565. size_t keep_alive_max_count = 3;
  6566. Server svr;
  6567. svr.set_keep_alive_max_count(keep_alive_max_count);
  6568. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6569. res.set_content("Hello World!", "text/plain");
  6570. });
  6571. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6572. auto se = detail::scope_exit([&] {
  6573. svr.stop();
  6574. listen_thread.join();
  6575. ASSERT_FALSE(svr.is_running());
  6576. });
  6577. svr.wait_until_ready();
  6578. Client cli(HOST, PORT);
  6579. cli.set_keep_alive(true);
  6580. for (size_t i = 0; i < 5; i++) {
  6581. auto result = cli.Get("/hi");
  6582. ASSERT_TRUE(result);
  6583. EXPECT_EQ(StatusCode::OK_200, result->status);
  6584. if (i == keep_alive_max_count - 1) {
  6585. EXPECT_EQ("close", result->get_header_value("Connection"));
  6586. } else {
  6587. EXPECT_FALSE(result->has_header("Connection"));
  6588. }
  6589. }
  6590. }
  6591. TEST(KeepAliveTest, Issue1041) {
  6592. Server svr;
  6593. svr.set_keep_alive_timeout(3);
  6594. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6595. res.set_content("Hello World!", "text/plain");
  6596. });
  6597. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6598. auto se = detail::scope_exit([&] {
  6599. svr.stop();
  6600. listen_thread.join();
  6601. ASSERT_FALSE(svr.is_running());
  6602. });
  6603. svr.wait_until_ready();
  6604. Client cli(HOST, PORT);
  6605. cli.set_keep_alive(true);
  6606. auto result = cli.Get("/hi");
  6607. ASSERT_TRUE(result);
  6608. EXPECT_EQ(StatusCode::OK_200, result->status);
  6609. std::this_thread::sleep_for(std::chrono::seconds(5));
  6610. result = cli.Get("/hi");
  6611. ASSERT_TRUE(result);
  6612. EXPECT_EQ(StatusCode::OK_200, result->status);
  6613. }
  6614. TEST(KeepAliveTest, Issue1959) {
  6615. Server svr;
  6616. svr.set_keep_alive_timeout(5);
  6617. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6618. res.set_content("a", "text/plain");
  6619. });
  6620. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6621. auto se = detail::scope_exit([&] {
  6622. if (!svr.is_running()) return;
  6623. svr.stop();
  6624. listen_thread.join();
  6625. ASSERT_FALSE(svr.is_running());
  6626. });
  6627. svr.wait_until_ready();
  6628. Client cli("localhost", PORT);
  6629. cli.set_keep_alive(true);
  6630. using namespace std::chrono;
  6631. auto start = steady_clock::now();
  6632. cli.Get("/a");
  6633. svr.stop();
  6634. listen_thread.join();
  6635. auto end = steady_clock::now();
  6636. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6637. EXPECT_LT(elapsed, 5000);
  6638. }
  6639. #ifdef CPPHTTPLIB_SSL_ENABLED
  6640. TEST(KeepAliveTest, SSLClientReconnection) {
  6641. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6642. ASSERT_TRUE(svr.is_valid());
  6643. svr.set_keep_alive_timeout(1);
  6644. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6645. res.set_content("Hello World!", "text/plain");
  6646. });
  6647. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6648. auto se = detail::scope_exit([&] {
  6649. svr.stop();
  6650. listen_thread.join();
  6651. ASSERT_FALSE(svr.is_running());
  6652. });
  6653. svr.wait_until_ready();
  6654. SSLClient cli(HOST, PORT);
  6655. cli.enable_server_certificate_verification(false);
  6656. cli.set_keep_alive(true);
  6657. auto result = cli.Get("/hi");
  6658. ASSERT_TRUE(result);
  6659. EXPECT_EQ(StatusCode::OK_200, result->status);
  6660. result = cli.Get("/hi");
  6661. ASSERT_TRUE(result);
  6662. EXPECT_EQ(StatusCode::OK_200, result->status);
  6663. std::this_thread::sleep_for(std::chrono::seconds(2));
  6664. // Recoonect
  6665. result = cli.Get("/hi");
  6666. ASSERT_TRUE(result);
  6667. EXPECT_EQ(StatusCode::OK_200, result->status);
  6668. result = cli.Get("/hi");
  6669. ASSERT_TRUE(result);
  6670. EXPECT_EQ(StatusCode::OK_200, result->status);
  6671. }
  6672. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6673. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6674. ASSERT_TRUE(svr.is_valid());
  6675. svr.set_keep_alive_timeout(1);
  6676. std::string content = "reconnect";
  6677. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6678. res.set_content("Hello World!", "text/plain");
  6679. });
  6680. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6681. auto se = detail::scope_exit([&] {
  6682. svr.stop();
  6683. listen_thread.join();
  6684. ASSERT_FALSE(svr.is_running());
  6685. });
  6686. svr.wait_until_ready();
  6687. SSLClient cli(HOST, PORT);
  6688. cli.enable_server_certificate_verification(false);
  6689. cli.set_keep_alive(true);
  6690. auto result = cli.Post(
  6691. "/hi", content.size(),
  6692. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6693. sink.write(content.c_str(), content.size());
  6694. return true;
  6695. },
  6696. "text/plain");
  6697. ASSERT_TRUE(result);
  6698. EXPECT_EQ(200, result->status);
  6699. std::this_thread::sleep_for(std::chrono::seconds(2));
  6700. // Recoonect
  6701. result = cli.Post(
  6702. "/hi", content.size(),
  6703. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6704. sink.write(content.c_str(), content.size());
  6705. return true;
  6706. },
  6707. "text/plain");
  6708. ASSERT_TRUE(result);
  6709. EXPECT_EQ(200, result->status);
  6710. result = cli.Post(
  6711. "/hi", content.size(),
  6712. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6713. sink.write(content.c_str(), content.size());
  6714. return true;
  6715. },
  6716. "text/plain");
  6717. ASSERT_TRUE(result);
  6718. EXPECT_EQ(200, result->status);
  6719. }
  6720. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6721. using namespace httplib::tls;
  6722. {
  6723. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6724. ASSERT_TRUE(svr.is_valid());
  6725. svr.Get("/sni", [&](const Request &req, Response &res) {
  6726. std::string expected = req.sni();
  6727. EXPECT_EQ(expected, req.get_param_value("expected"));
  6728. res.set_content("ok", "text/plain");
  6729. });
  6730. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6731. auto se = detail::scope_exit([&] {
  6732. svr.stop();
  6733. listen_thread.join();
  6734. ASSERT_FALSE(svr.is_running());
  6735. });
  6736. svr.wait_until_ready();
  6737. {
  6738. SSLClient cli("localhost", PORT);
  6739. cli.enable_server_certificate_verification(false);
  6740. auto res = cli.Get("/sni?expected=localhost");
  6741. ASSERT_TRUE(res);
  6742. }
  6743. {
  6744. SSLClient cli("::1", PORT);
  6745. cli.enable_server_certificate_verification(false);
  6746. auto res = cli.Get("/sni?expected=");
  6747. // NOTE: This may fail if the server is listening on IPv4 only
  6748. // (e.g., when localhost resolves to 127.0.0.1 only)
  6749. if (res) {
  6750. EXPECT_EQ(StatusCode::OK_200, res->status);
  6751. } else {
  6752. EXPECT_EQ(Error::Connection, res.error());
  6753. }
  6754. }
  6755. }
  6756. }
  6757. #endif
  6758. TEST(ClientProblemDetectionTest, ContentProvider) {
  6759. Server svr;
  6760. size_t content_length = 1024 * 1024;
  6761. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6762. res.set_content_provider(
  6763. content_length, "text/plain",
  6764. [&](size_t offset, size_t length, DataSink &sink) {
  6765. auto out_len = std::min(length, static_cast<size_t>(1024));
  6766. std::string out(out_len, '@');
  6767. sink.write(out.data(), out_len);
  6768. return offset < 4096;
  6769. },
  6770. [](bool success) { ASSERT_FALSE(success); });
  6771. });
  6772. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6773. res.set_content_provider(
  6774. 0, "text/plain",
  6775. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6776. EXPECT_TRUE(false);
  6777. return true;
  6778. },
  6779. [](bool success) { ASSERT_FALSE(success); });
  6780. });
  6781. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6782. auto se = detail::scope_exit([&] {
  6783. svr.stop();
  6784. listen_thread.join();
  6785. ASSERT_FALSE(svr.is_running());
  6786. });
  6787. svr.wait_until_ready();
  6788. Client cli("localhost", PORT);
  6789. {
  6790. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6791. size_t /*data_length*/) { return false; });
  6792. ASSERT_FALSE(res);
  6793. }
  6794. {
  6795. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6796. size_t /*data_length*/) { return false; });
  6797. ASSERT_TRUE(res);
  6798. }
  6799. }
  6800. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6801. Server svr;
  6802. svr.set_error_handler([](Request const &, Response &res) -> void {
  6803. res.set_chunked_content_provider(
  6804. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6805. sink.os << "hello";
  6806. sink.os << "world";
  6807. sink.done();
  6808. return true;
  6809. });
  6810. });
  6811. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6812. auto se = detail::scope_exit([&] {
  6813. svr.stop();
  6814. listen_thread.join();
  6815. ASSERT_FALSE(svr.is_running());
  6816. });
  6817. svr.wait_until_ready();
  6818. Client cli("localhost", PORT);
  6819. auto res = cli.Get("/");
  6820. ASSERT_TRUE(res);
  6821. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6822. EXPECT_EQ("helloworld", res->body);
  6823. }
  6824. TEST(LongPollingTest, ClientCloseDetection) {
  6825. Server svr;
  6826. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6827. res.set_chunked_content_provider(
  6828. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6829. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6830. sink.os << "hello";
  6831. auto count = 10;
  6832. while (count > 0 && sink.is_writable()) {
  6833. this_thread::sleep_for(chrono::milliseconds(10));
  6834. count--;
  6835. }
  6836. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6837. return true;
  6838. });
  6839. });
  6840. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6841. auto se = detail::scope_exit([&] {
  6842. svr.stop();
  6843. listen_thread.join();
  6844. ASSERT_FALSE(svr.is_running());
  6845. });
  6846. svr.wait_until_ready();
  6847. Client cli("localhost", PORT);
  6848. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6849. EXPECT_EQ("hello", string(data, data_length));
  6850. return false; // close the socket immediately.
  6851. });
  6852. ASSERT_FALSE(res);
  6853. }
  6854. TEST(GetWithParametersTest, GetWithParameters) {
  6855. Server svr;
  6856. svr.Get("/", [&](const Request &req, Response &) {
  6857. EXPECT_EQ("world", req.get_param_value("hello"));
  6858. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6859. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6860. });
  6861. svr.Get("/params", [&](const Request &req, Response &) {
  6862. EXPECT_EQ("world", req.get_param_value("hello"));
  6863. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6864. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6865. });
  6866. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6867. EXPECT_EQ("resource-id", req.matches[1]);
  6868. EXPECT_EQ("foo", req.get_param_value("param1"));
  6869. EXPECT_EQ("bar", req.get_param_value("param2"));
  6870. });
  6871. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6872. EXPECT_EQ("user-id", req.path_params.at("id"));
  6873. EXPECT_EQ("foo", req.get_param_value("param1"));
  6874. EXPECT_EQ("bar", req.get_param_value("param2"));
  6875. });
  6876. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6877. auto se = detail::scope_exit([&] {
  6878. svr.stop();
  6879. listen_thread.join();
  6880. ASSERT_FALSE(svr.is_running());
  6881. });
  6882. svr.wait_until_ready();
  6883. {
  6884. Client cli(HOST, PORT);
  6885. Params params;
  6886. params.emplace("hello", "world");
  6887. params.emplace("hello2", "world2");
  6888. params.emplace("hello3", "world3");
  6889. auto res = cli.Get("/", params, Headers{});
  6890. ASSERT_TRUE(res);
  6891. EXPECT_EQ(StatusCode::OK_200, res->status);
  6892. }
  6893. {
  6894. Client cli(HOST, PORT);
  6895. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6896. ASSERT_TRUE(res);
  6897. EXPECT_EQ(StatusCode::OK_200, res->status);
  6898. }
  6899. {
  6900. Client cli(HOST, PORT);
  6901. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6902. ASSERT_TRUE(res);
  6903. EXPECT_EQ(StatusCode::OK_200, res->status);
  6904. }
  6905. {
  6906. Client cli(HOST, PORT);
  6907. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6908. ASSERT_TRUE(res);
  6909. EXPECT_EQ(StatusCode::OK_200, res->status);
  6910. }
  6911. }
  6912. TEST(GetWithParametersTest, GetWithParameters2) {
  6913. Server svr;
  6914. svr.Get("/", [&](const Request &req, Response &res) {
  6915. auto text = req.get_param_value("hello");
  6916. res.set_content(text, "text/plain");
  6917. });
  6918. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6919. auto se = detail::scope_exit([&] {
  6920. svr.stop();
  6921. listen_thread.join();
  6922. ASSERT_FALSE(svr.is_running());
  6923. });
  6924. svr.wait_until_ready();
  6925. Client cli("localhost", PORT);
  6926. Params params;
  6927. params.emplace("hello", "world");
  6928. std::string body;
  6929. auto res = cli.Get("/", params, Headers{},
  6930. [&](const char *data, size_t data_length) {
  6931. body.append(data, data_length);
  6932. return true;
  6933. });
  6934. ASSERT_TRUE(res);
  6935. EXPECT_EQ(StatusCode::OK_200, res->status);
  6936. EXPECT_EQ("world", body);
  6937. }
  6938. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6939. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6940. auto host = "httpcan.org";
  6941. auto path = std::string{"/range/32"};
  6942. #else
  6943. auto host = "nghttp2.org";
  6944. auto path = std::string{"/httpbin/range/32"};
  6945. #endif
  6946. #ifdef CPPHTTPLIB_SSL_ENABLED
  6947. SSLClient cli(host);
  6948. #else
  6949. Client cli(host);
  6950. #endif
  6951. cli.set_default_headers({make_range_header({{1, 10}})});
  6952. cli.set_connection_timeout(5);
  6953. {
  6954. auto res = cli.Get(path);
  6955. ASSERT_TRUE(res);
  6956. EXPECT_EQ("bcdefghijk", res->body);
  6957. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6958. }
  6959. {
  6960. auto res = cli.Get(path);
  6961. ASSERT_TRUE(res);
  6962. EXPECT_EQ("bcdefghijk", res->body);
  6963. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6964. }
  6965. }
  6966. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6967. Server svr;
  6968. svr.set_default_headers({{"Hello", "World"}});
  6969. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6970. res.set_content("ok", "text/plain");
  6971. });
  6972. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6973. auto se = detail::scope_exit([&] {
  6974. svr.stop();
  6975. listen_thread.join();
  6976. ASSERT_FALSE(svr.is_running());
  6977. });
  6978. svr.wait_until_ready();
  6979. Client cli("localhost", PORT);
  6980. auto res = cli.Get("/");
  6981. ASSERT_TRUE(res);
  6982. EXPECT_EQ(StatusCode::OK_200, res->status);
  6983. EXPECT_EQ("ok", res->body);
  6984. EXPECT_EQ("World", res->get_header_value("Hello"));
  6985. }
  6986. #ifdef CPPHTTPLIB_SSL_ENABLED
  6987. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6988. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6989. ASSERT_TRUE(svr.is_valid());
  6990. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6991. std::this_thread::sleep_for(std::chrono::seconds(2));
  6992. res.set_content("a", "text/plain");
  6993. });
  6994. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6995. res.set_content("b", "text/plain");
  6996. });
  6997. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6998. auto se = detail::scope_exit([&] {
  6999. svr.stop();
  7000. listen_thread.join();
  7001. ASSERT_FALSE(svr.is_running());
  7002. });
  7003. svr.wait_until_ready();
  7004. SSLClient cli("localhost", PORT);
  7005. cli.enable_server_certificate_verification(false);
  7006. cli.set_keep_alive(true);
  7007. cli.set_read_timeout(std::chrono::seconds(1));
  7008. auto resa = cli.Get("/a");
  7009. ASSERT_TRUE(!resa);
  7010. EXPECT_EQ(Error::Read, resa.error());
  7011. auto resb = cli.Get("/b");
  7012. ASSERT_TRUE(resb);
  7013. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7014. EXPECT_EQ("b", resb->body);
  7015. }
  7016. #endif
  7017. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7018. protected:
  7019. ServerTestWithAI_PASSIVE()
  7020. : cli_(HOST, PORT)
  7021. #ifdef CPPHTTPLIB_SSL_ENABLED
  7022. ,
  7023. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7024. #endif
  7025. {
  7026. #ifdef CPPHTTPLIB_SSL_ENABLED
  7027. cli_.enable_server_certificate_verification(false);
  7028. #endif
  7029. }
  7030. virtual void SetUp() {
  7031. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7032. res.set_content("Hello World!", "text/plain");
  7033. });
  7034. t_ = thread(
  7035. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7036. svr_.wait_until_ready();
  7037. }
  7038. virtual void TearDown() {
  7039. svr_.stop();
  7040. t_.join();
  7041. }
  7042. #ifdef CPPHTTPLIB_SSL_ENABLED
  7043. SSLClient cli_;
  7044. SSLServer svr_;
  7045. #else
  7046. Client cli_;
  7047. Server svr_;
  7048. #endif
  7049. thread t_;
  7050. };
  7051. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7052. auto res = cli_.Get("/hi");
  7053. ASSERT_TRUE(res);
  7054. EXPECT_EQ(StatusCode::OK_200, res->status);
  7055. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7056. EXPECT_EQ("Hello World!", res->body);
  7057. }
  7058. class ServerUpDownTest : public ::testing::Test {
  7059. protected:
  7060. ServerUpDownTest() : cli_(HOST, PORT) {}
  7061. virtual void SetUp() {
  7062. t_ = thread([&]() {
  7063. svr_.bind_to_any_port(HOST);
  7064. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7065. ASSERT_TRUE(svr_.listen_after_bind());
  7066. });
  7067. svr_.wait_until_ready();
  7068. }
  7069. virtual void TearDown() {
  7070. svr_.stop();
  7071. t_.join();
  7072. }
  7073. Client cli_;
  7074. Server svr_;
  7075. thread t_;
  7076. };
  7077. TEST_F(ServerUpDownTest, QuickStartStop) {
  7078. // Should not crash, especially when run with
  7079. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7080. }
  7081. class PayloadMaxLengthTest : public ::testing::Test {
  7082. protected:
  7083. PayloadMaxLengthTest()
  7084. : cli_(HOST, PORT)
  7085. #ifdef CPPHTTPLIB_SSL_ENABLED
  7086. ,
  7087. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7088. #endif
  7089. {
  7090. #ifdef CPPHTTPLIB_SSL_ENABLED
  7091. cli_.enable_server_certificate_verification(false);
  7092. #endif
  7093. }
  7094. virtual void SetUp() {
  7095. svr_.set_payload_max_length(8);
  7096. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7097. res.set_content("test", "text/plain");
  7098. });
  7099. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7100. svr_.wait_until_ready();
  7101. }
  7102. virtual void TearDown() {
  7103. svr_.stop();
  7104. t_.join();
  7105. }
  7106. #ifdef CPPHTTPLIB_SSL_ENABLED
  7107. SSLClient cli_;
  7108. SSLServer svr_;
  7109. #else
  7110. Client cli_;
  7111. Server svr_;
  7112. #endif
  7113. thread t_;
  7114. };
  7115. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7116. auto res = cli_.Post("/test", "123456789", "text/plain");
  7117. ASSERT_TRUE(res);
  7118. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7119. res = cli_.Post("/test", "12345678", "text/plain");
  7120. ASSERT_TRUE(res);
  7121. EXPECT_EQ(StatusCode::OK_200, res->status);
  7122. }
  7123. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7124. // Test chunked encoding with payload exceeding the 8-byte limit
  7125. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7126. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7127. ASSERT_TRUE(res);
  7128. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7129. }
  7130. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7131. // Test chunked encoding with payload within the 8-byte limit
  7132. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7133. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7134. ASSERT_TRUE(res);
  7135. EXPECT_EQ(StatusCode::OK_200, res->status);
  7136. }
  7137. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7138. // Test using send_request to send chunked data exceeding payload limit
  7139. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7140. "Host: " +
  7141. std::string(HOST) + ":" + std::to_string(PORT) +
  7142. "\r\n"
  7143. "Transfer-Encoding: chunked\r\n"
  7144. "Connection: close\r\n"
  7145. "\r\n"
  7146. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7147. "0123456789\r\n"
  7148. "0\r\n" // End chunk
  7149. "\r\n";
  7150. std::string response;
  7151. bool result = send_request(1, chunked_request, &response);
  7152. if (!result) {
  7153. // If send_request fails, it might be because the server closed the
  7154. // connection due to payload limit enforcement, which is acceptable
  7155. SUCCEED()
  7156. << "Server rejected oversized chunked request (connection closed)";
  7157. } else {
  7158. // If we got a response, check if it's an error response or connection was
  7159. // closed early Short response length indicates connection was closed due to
  7160. // payload limit
  7161. if (response.length() <= 10) {
  7162. SUCCEED() << "Server closed connection for oversized chunked request";
  7163. } else {
  7164. // Check for error status codes
  7165. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7166. response.find("Payload Too Large") != std::string::npos ||
  7167. response.find("400") != std::string::npos);
  7168. }
  7169. }
  7170. }
  7171. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7172. // Test request without Content-Length header exceeding payload limit
  7173. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7174. "Host: " +
  7175. std::string(HOST) + ":" +
  7176. std::to_string(PORT) +
  7177. "\r\n"
  7178. "Connection: close\r\n"
  7179. "\r\n";
  7180. // Add payload exceeding the 8-byte limit
  7181. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7182. request_without_content_length += large_payload;
  7183. std::string response;
  7184. bool result = send_request(1, request_without_content_length, &response);
  7185. if (!result) {
  7186. // If send_request fails, server likely closed connection due to payload
  7187. // limit
  7188. SUCCEED() << "Server rejected oversized request without Content-Length "
  7189. "(connection closed)";
  7190. } else {
  7191. // Check if server responded with error or closed connection early
  7192. if (response.length() <= 10) {
  7193. SUCCEED() << "Server closed connection for oversized request without "
  7194. "Content-Length";
  7195. } else {
  7196. // Check for error status codes
  7197. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7198. response.find("Payload Too Large") != std::string::npos ||
  7199. response.find("400") != std::string::npos);
  7200. }
  7201. }
  7202. }
  7203. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7204. // Test request without Content-Length header within payload limit
  7205. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7206. "Host: " +
  7207. std::string(HOST) + ":" +
  7208. std::to_string(PORT) +
  7209. "\r\n"
  7210. "Connection: close\r\n"
  7211. "\r\n";
  7212. // Add payload within the 8-byte limit
  7213. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7214. request_without_content_length += small_payload;
  7215. std::string response;
  7216. bool result = send_request(1, request_without_content_length, &response);
  7217. // For requests without Content-Length, the server may have different behavior
  7218. // The key is that it should not reject due to payload limit for small
  7219. // payloads
  7220. if (result) {
  7221. // Check for any HTTP response (success or error, but not connection closed)
  7222. if (response.length() > 10) {
  7223. SUCCEED()
  7224. << "Server processed request without Content-Length within limit";
  7225. } else {
  7226. // Short response might indicate connection closed, which is acceptable
  7227. SUCCEED() << "Server closed connection for request without "
  7228. "Content-Length (acceptable behavior)";
  7229. }
  7230. } else {
  7231. // Connection failure might be due to protocol requirements
  7232. SUCCEED() << "Connection issue with request without Content-Length "
  7233. "(environment-specific)";
  7234. }
  7235. }
  7236. class LargePayloadMaxLengthTest : public ::testing::Test {
  7237. protected:
  7238. LargePayloadMaxLengthTest()
  7239. : cli_(HOST, PORT)
  7240. #ifdef CPPHTTPLIB_SSL_ENABLED
  7241. ,
  7242. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7243. #endif
  7244. {
  7245. #ifdef CPPHTTPLIB_SSL_ENABLED
  7246. cli_.enable_server_certificate_verification(false);
  7247. #endif
  7248. }
  7249. virtual void SetUp() {
  7250. // Set 10MB payload limit
  7251. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7252. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7253. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7254. res.set_content("Large payload test", "text/plain");
  7255. });
  7256. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7257. svr_.wait_until_ready();
  7258. }
  7259. virtual void TearDown() {
  7260. svr_.stop();
  7261. t_.join();
  7262. }
  7263. #ifdef CPPHTTPLIB_SSL_ENABLED
  7264. SSLClient cli_;
  7265. SSLServer svr_;
  7266. #else
  7267. Client cli_;
  7268. Server svr_;
  7269. #endif
  7270. thread t_;
  7271. };
  7272. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7273. // Test chunked encoding with payload within 10MB limit
  7274. std::string medium_payload(5 * 1024 * 1024,
  7275. 'A'); // 5MB payload, within 10MB limit
  7276. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7277. ASSERT_TRUE(res);
  7278. EXPECT_EQ(StatusCode::OK_200, res->status);
  7279. }
  7280. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7281. // Test chunked encoding with payload exceeding 10MB limit
  7282. std::string large_payload(12 * 1024 * 1024,
  7283. 'B'); // 12MB payload, exceeds 10MB limit
  7284. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7285. // Server may either return 413 or close the connection
  7286. if (res) {
  7287. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7288. } else {
  7289. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7290. }
  7291. }
  7292. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7293. // Test request without Content-Length header within 10MB limit
  7294. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7295. "Host: " +
  7296. std::string(HOST) + ":" +
  7297. std::to_string(PORT) +
  7298. "\r\n"
  7299. "Connection: close\r\n"
  7300. "\r\n";
  7301. // Add 1MB payload (within 10MB limit)
  7302. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7303. request_without_content_length += medium_payload;
  7304. std::string response;
  7305. bool result = send_request(5, request_without_content_length, &response);
  7306. if (result) {
  7307. // Should get a proper HTTP response for payloads within limit
  7308. if (response.length() > 10) {
  7309. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7310. "10MB limit";
  7311. } else {
  7312. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7313. "Content-Length)";
  7314. }
  7315. } else {
  7316. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7317. }
  7318. }
  7319. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7320. // Test request without Content-Length header exceeding 10MB limit
  7321. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7322. "Host: " +
  7323. std::string(HOST) + ":" +
  7324. std::to_string(PORT) +
  7325. "\r\n"
  7326. "Connection: close\r\n"
  7327. "\r\n";
  7328. // Add 12MB payload (exceeds 10MB limit)
  7329. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7330. request_without_content_length += large_payload;
  7331. std::string response;
  7332. bool result = send_request(10, request_without_content_length, &response);
  7333. if (!result) {
  7334. // Server should close connection due to payload limit
  7335. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7336. "(connection closed)";
  7337. } else {
  7338. // Check for error response
  7339. if (response.length() <= 10) {
  7340. SUCCEED()
  7341. << "Server closed connection for 12MB request exceeding 10MB limit";
  7342. } else {
  7343. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7344. response.find("Payload Too Large") != std::string::npos ||
  7345. response.find("400") != std::string::npos);
  7346. }
  7347. }
  7348. }
  7349. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7350. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7351. // path.
  7352. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7353. Server svr;
  7354. const size_t LIMIT = 64 * 1024; // 64KB
  7355. svr.set_payload_max_length(LIMIT);
  7356. size_t total = 0;
  7357. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7358. const ContentReader &content_reader) {
  7359. content_reader([&](const char * /*data*/, size_t len) {
  7360. total += len;
  7361. return true;
  7362. });
  7363. res.status = 200;
  7364. res.set_content("stream_ok", "text/plain");
  7365. });
  7366. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7367. auto se = detail::scope_exit([&] {
  7368. svr.stop();
  7369. thread.join();
  7370. ASSERT_FALSE(svr.is_running());
  7371. });
  7372. svr.wait_until_ready();
  7373. // Prepare 256KB raw data and gzip-compress it
  7374. std::string raw(256 * 1024, 'A');
  7375. std::string gz;
  7376. {
  7377. z_stream zs{};
  7378. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7379. Z_DEFAULT_STRATEGY);
  7380. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7381. zs.avail_in = static_cast<uInt>(raw.size());
  7382. char outbuf[4096];
  7383. int ret;
  7384. do {
  7385. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7386. zs.avail_out = sizeof(outbuf);
  7387. ret = deflate(&zs, Z_FINISH);
  7388. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7389. } while (ret != Z_STREAM_END);
  7390. deflateEnd(&zs);
  7391. }
  7392. Client cli(HOST, PORT);
  7393. cli.set_connection_timeout(std::chrono::seconds(5));
  7394. Headers headers = {{"Content-Encoding", "gzip"}};
  7395. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7396. "application/octet-stream");
  7397. ASSERT_TRUE(res);
  7398. // Server must reject oversized decompressed payloads with 413.
  7399. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7400. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7401. EXPECT_LE(total, LIMIT);
  7402. }
  7403. #endif
  7404. // Regression test for DoS vulnerability: a malicious server sending a response
  7405. // without Content-Length header must not cause unbounded memory consumption on
  7406. // the client side. The client should stop reading after a reasonable limit,
  7407. // similar to the server-side set_payload_max_length protection.
  7408. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7409. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7410. #ifndef _WIN32
  7411. signal(SIGPIPE, SIG_IGN);
  7412. #endif
  7413. auto server_thread = std::thread([] {
  7414. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7415. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7416. default_socket_options(srv);
  7417. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7418. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7419. sockaddr_in addr{};
  7420. addr.sin_family = AF_INET;
  7421. addr.sin_port = htons(PORT + 2);
  7422. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7423. int opt = 1;
  7424. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7425. #ifdef _WIN32
  7426. reinterpret_cast<const char *>(&opt),
  7427. #else
  7428. &opt,
  7429. #endif
  7430. sizeof(opt));
  7431. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7432. ::listen(srv, 1);
  7433. sockaddr_in cli_addr{};
  7434. socklen_t cli_len = sizeof(cli_addr);
  7435. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7436. if (cli != INVALID_SOCKET) {
  7437. char buf[4096];
  7438. ::recv(cli, buf, sizeof(buf), 0);
  7439. // Malicious response: no Content-Length, no chunked encoding
  7440. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7441. "Connection: close\r\n"
  7442. "\r\n";
  7443. ::send(cli,
  7444. #ifdef _WIN32
  7445. static_cast<const char *>(response_header.c_str()),
  7446. static_cast<int>(response_header.size()),
  7447. #else
  7448. response_header.c_str(), response_header.size(),
  7449. #endif
  7450. 0);
  7451. // Send 10MB of data
  7452. std::string chunk(64 * 1024, 'A');
  7453. size_t total_sent = 0;
  7454. while (total_sent < MALICIOUS_DATA_SIZE) {
  7455. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7456. auto sent = ::send(cli,
  7457. #ifdef _WIN32
  7458. static_cast<const char *>(chunk.c_str()),
  7459. static_cast<int>(to_send),
  7460. #else
  7461. chunk.c_str(), to_send,
  7462. #endif
  7463. 0);
  7464. if (sent <= 0) break;
  7465. total_sent += static_cast<size_t>(sent);
  7466. }
  7467. detail::close_socket(cli);
  7468. }
  7469. detail::close_socket(srv);
  7470. });
  7471. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7472. size_t total_read = 0;
  7473. {
  7474. Client cli("127.0.0.1", PORT + 2);
  7475. cli.set_read_timeout(5, 0);
  7476. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7477. auto stream = cli.open_stream("GET", "/malicious");
  7478. ASSERT_TRUE(stream.is_valid());
  7479. char buffer[64 * 1024];
  7480. ssize_t n;
  7481. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7482. total_read += static_cast<size_t>(n);
  7483. }
  7484. } // StreamHandle and Client destroyed here, closing the socket
  7485. server_thread.join();
  7486. // With set_payload_max_length, the client must stop reading before consuming
  7487. // all 10MB. The read loop should be cut off at or near the configured limit.
  7488. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7489. << "Client read " << total_read << " bytes, exceeding the configured "
  7490. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7491. }
  7492. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7493. // the entire response body without truncation.
  7494. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7495. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7496. #ifndef _WIN32
  7497. signal(SIGPIPE, SIG_IGN);
  7498. #endif
  7499. auto server_thread = std::thread([] {
  7500. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7501. default_socket_options(srv);
  7502. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7503. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7504. sockaddr_in addr{};
  7505. addr.sin_family = AF_INET;
  7506. addr.sin_port = htons(PORT + 2);
  7507. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7508. int opt = 1;
  7509. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7510. #ifdef _WIN32
  7511. reinterpret_cast<const char *>(&opt),
  7512. #else
  7513. &opt,
  7514. #endif
  7515. sizeof(opt));
  7516. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7517. ::listen(srv, 1);
  7518. sockaddr_in cli_addr{};
  7519. socklen_t cli_len = sizeof(cli_addr);
  7520. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7521. if (cli != INVALID_SOCKET) {
  7522. char buf[4096];
  7523. ::recv(cli, buf, sizeof(buf), 0);
  7524. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7525. "Connection: close\r\n"
  7526. "\r\n";
  7527. ::send(cli,
  7528. #ifdef _WIN32
  7529. static_cast<const char *>(response_header.c_str()),
  7530. static_cast<int>(response_header.size()),
  7531. #else
  7532. response_header.c_str(), response_header.size(),
  7533. #endif
  7534. 0);
  7535. std::string chunk(64 * 1024, 'A');
  7536. size_t total_sent = 0;
  7537. while (total_sent < DATA_SIZE) {
  7538. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7539. auto sent = ::send(cli,
  7540. #ifdef _WIN32
  7541. static_cast<const char *>(chunk.c_str()),
  7542. static_cast<int>(to_send),
  7543. #else
  7544. chunk.c_str(), to_send,
  7545. #endif
  7546. 0);
  7547. if (sent <= 0) break;
  7548. total_sent += static_cast<size_t>(sent);
  7549. }
  7550. #ifdef _WIN32
  7551. ::shutdown(cli, SD_SEND);
  7552. #else
  7553. ::shutdown(cli, SHUT_WR);
  7554. #endif
  7555. // Drain until the client closes its end, ensuring all data is delivered
  7556. char drain[1024];
  7557. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7558. detail::close_socket(cli);
  7559. }
  7560. detail::close_socket(srv);
  7561. });
  7562. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7563. size_t total_read = 0;
  7564. {
  7565. Client cli("127.0.0.1", PORT + 2);
  7566. cli.set_read_timeout(5, 0);
  7567. cli.set_payload_max_length(0); // 0 means no limit
  7568. auto stream = cli.open_stream("GET", "/data");
  7569. ASSERT_TRUE(stream.is_valid());
  7570. char buffer[64 * 1024];
  7571. ssize_t n;
  7572. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7573. total_read += static_cast<size_t>(n);
  7574. }
  7575. }
  7576. server_thread.join();
  7577. EXPECT_EQ(total_read, DATA_SIZE)
  7578. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7579. << " bytes without truncation, but only read " << total_read << " bytes.";
  7580. }
  7581. // Verify that content_receiver bypasses the default payload_max_length,
  7582. // allowing streaming downloads larger than 100MB without requiring an explicit
  7583. // set_payload_max_length call.
  7584. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  7585. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7586. #ifndef _WIN32
  7587. signal(SIGPIPE, SIG_IGN);
  7588. #endif
  7589. auto server_thread = std::thread([] {
  7590. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7591. default_socket_options(srv);
  7592. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7593. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7594. sockaddr_in addr{};
  7595. addr.sin_family = AF_INET;
  7596. addr.sin_port = htons(PORT + 2);
  7597. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7598. int opt = 1;
  7599. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7600. #ifdef _WIN32
  7601. reinterpret_cast<const char *>(&opt),
  7602. #else
  7603. &opt,
  7604. #endif
  7605. sizeof(opt));
  7606. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7607. ::listen(srv, 1);
  7608. sockaddr_in cli_addr{};
  7609. socklen_t cli_len = sizeof(cli_addr);
  7610. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7611. if (cli != INVALID_SOCKET) {
  7612. char buf[4096];
  7613. ::recv(cli, buf, sizeof(buf), 0);
  7614. // Response with Content-Length larger than default 100MB limit
  7615. auto content_length = std::to_string(DATA_SIZE);
  7616. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7617. "Content-Length: " +
  7618. content_length +
  7619. "\r\n"
  7620. "Connection: close\r\n"
  7621. "\r\n";
  7622. ::send(cli,
  7623. #ifdef _WIN32
  7624. static_cast<const char *>(response_header.c_str()),
  7625. static_cast<int>(response_header.size()),
  7626. #else
  7627. response_header.c_str(), response_header.size(),
  7628. #endif
  7629. 0);
  7630. std::string chunk(64 * 1024, 'A');
  7631. size_t total_sent = 0;
  7632. while (total_sent < DATA_SIZE) {
  7633. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7634. auto sent = ::send(cli,
  7635. #ifdef _WIN32
  7636. static_cast<const char *>(chunk.c_str()),
  7637. static_cast<int>(to_send),
  7638. #else
  7639. chunk.c_str(), to_send,
  7640. #endif
  7641. 0);
  7642. if (sent <= 0) break;
  7643. total_sent += static_cast<size_t>(sent);
  7644. }
  7645. detail::close_socket(cli);
  7646. }
  7647. detail::close_socket(srv);
  7648. });
  7649. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7650. size_t total_received = 0;
  7651. {
  7652. Client cli("127.0.0.1", PORT + 2);
  7653. cli.set_read_timeout(10, 0);
  7654. // Do NOT call set_payload_max_length — use the default 100MB limit
  7655. auto res =
  7656. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7657. total_received += data_length;
  7658. return true;
  7659. });
  7660. ASSERT_TRUE(res);
  7661. EXPECT_EQ(StatusCode::OK_200, res->status);
  7662. }
  7663. server_thread.join();
  7664. EXPECT_EQ(total_received, DATA_SIZE)
  7665. << "With content_receiver, the client should read all " << DATA_SIZE
  7666. << " bytes despite the default 100MB payload_max_length, but only read "
  7667. << total_received << " bytes.";
  7668. }
  7669. // Verify that an explicit set_payload_max_length smaller than the response is
  7670. // enforced even when a content_receiver is used.
  7671. TEST(ClientVulnerabilityTest,
  7672. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  7673. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7674. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  7675. #ifndef _WIN32
  7676. signal(SIGPIPE, SIG_IGN);
  7677. #endif
  7678. auto server_thread = std::thread([] {
  7679. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7680. default_socket_options(srv);
  7681. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7682. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7683. sockaddr_in addr{};
  7684. addr.sin_family = AF_INET;
  7685. addr.sin_port = htons(PORT + 2);
  7686. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7687. int opt = 1;
  7688. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7689. #ifdef _WIN32
  7690. reinterpret_cast<const char *>(&opt),
  7691. #else
  7692. &opt,
  7693. #endif
  7694. sizeof(opt));
  7695. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7696. ::listen(srv, 1);
  7697. sockaddr_in cli_addr{};
  7698. socklen_t cli_len = sizeof(cli_addr);
  7699. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7700. if (cli != INVALID_SOCKET) {
  7701. char buf[4096];
  7702. ::recv(cli, buf, sizeof(buf), 0);
  7703. auto content_length = std::to_string(DATA_SIZE);
  7704. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7705. "Content-Length: " +
  7706. content_length +
  7707. "\r\n"
  7708. "Connection: close\r\n"
  7709. "\r\n";
  7710. ::send(cli,
  7711. #ifdef _WIN32
  7712. static_cast<const char *>(response_header.c_str()),
  7713. static_cast<int>(response_header.size()),
  7714. #else
  7715. response_header.c_str(), response_header.size(),
  7716. #endif
  7717. 0);
  7718. std::string chunk(64 * 1024, 'A');
  7719. size_t total_sent = 0;
  7720. while (total_sent < DATA_SIZE) {
  7721. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7722. auto sent = ::send(cli,
  7723. #ifdef _WIN32
  7724. static_cast<const char *>(chunk.c_str()),
  7725. static_cast<int>(to_send),
  7726. #else
  7727. chunk.c_str(), to_send,
  7728. #endif
  7729. 0);
  7730. if (sent <= 0) break;
  7731. total_sent += static_cast<size_t>(sent);
  7732. }
  7733. detail::close_socket(cli);
  7734. }
  7735. detail::close_socket(srv);
  7736. });
  7737. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7738. size_t total_received = 0;
  7739. {
  7740. Client cli("127.0.0.1", PORT + 2);
  7741. cli.set_read_timeout(10, 0);
  7742. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  7743. auto res =
  7744. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7745. total_received += data_length;
  7746. return true;
  7747. });
  7748. // Should fail because 200MB exceeds the explicit 150MB limit
  7749. EXPECT_FALSE(res);
  7750. }
  7751. server_thread.join();
  7752. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  7753. << "Client with content_receiver should respect the explicit "
  7754. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  7755. << total_received << " bytes.";
  7756. }
  7757. // Verify that an explicit set_payload_max_length larger than the response
  7758. // allows the content_receiver to read all data successfully.
  7759. TEST(ClientVulnerabilityTest,
  7760. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  7761. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7762. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  7763. #ifndef _WIN32
  7764. signal(SIGPIPE, SIG_IGN);
  7765. #endif
  7766. auto server_thread = std::thread([] {
  7767. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7768. default_socket_options(srv);
  7769. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7770. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7771. sockaddr_in addr{};
  7772. addr.sin_family = AF_INET;
  7773. addr.sin_port = htons(PORT + 2);
  7774. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7775. int opt = 1;
  7776. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7777. #ifdef _WIN32
  7778. reinterpret_cast<const char *>(&opt),
  7779. #else
  7780. &opt,
  7781. #endif
  7782. sizeof(opt));
  7783. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7784. ::listen(srv, 1);
  7785. sockaddr_in cli_addr{};
  7786. socklen_t cli_len = sizeof(cli_addr);
  7787. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7788. if (cli != INVALID_SOCKET) {
  7789. char buf[4096];
  7790. ::recv(cli, buf, sizeof(buf), 0);
  7791. auto content_length = std::to_string(DATA_SIZE);
  7792. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7793. "Content-Length: " +
  7794. content_length +
  7795. "\r\n"
  7796. "Connection: close\r\n"
  7797. "\r\n";
  7798. ::send(cli,
  7799. #ifdef _WIN32
  7800. static_cast<const char *>(response_header.c_str()),
  7801. static_cast<int>(response_header.size()),
  7802. #else
  7803. response_header.c_str(), response_header.size(),
  7804. #endif
  7805. 0);
  7806. std::string chunk(64 * 1024, 'A');
  7807. size_t total_sent = 0;
  7808. while (total_sent < DATA_SIZE) {
  7809. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7810. auto sent = ::send(cli,
  7811. #ifdef _WIN32
  7812. static_cast<const char *>(chunk.c_str()),
  7813. static_cast<int>(to_send),
  7814. #else
  7815. chunk.c_str(), to_send,
  7816. #endif
  7817. 0);
  7818. if (sent <= 0) break;
  7819. total_sent += static_cast<size_t>(sent);
  7820. }
  7821. #ifdef _WIN32
  7822. ::shutdown(cli, SD_SEND);
  7823. #else
  7824. ::shutdown(cli, SHUT_WR);
  7825. #endif
  7826. char drain[1024];
  7827. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7828. detail::close_socket(cli);
  7829. }
  7830. detail::close_socket(srv);
  7831. });
  7832. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7833. size_t total_received = 0;
  7834. {
  7835. Client cli("127.0.0.1", PORT + 2);
  7836. cli.set_read_timeout(10, 0);
  7837. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  7838. auto res =
  7839. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7840. total_received += data_length;
  7841. return true;
  7842. });
  7843. ASSERT_TRUE(res);
  7844. EXPECT_EQ(StatusCode::OK_200, res->status);
  7845. }
  7846. server_thread.join();
  7847. EXPECT_EQ(total_received, DATA_SIZE)
  7848. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  7849. << " bytes (larger than " << DATA_SIZE
  7850. << " bytes response), content_receiver should read all data, but only "
  7851. "read "
  7852. << total_received << " bytes.";
  7853. }
  7854. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  7855. // Regression test for "zip bomb" attack on the client side: a malicious server
  7856. // sends a small gzip-compressed response that decompresses to a huge payload.
  7857. // The client must enforce payload_max_length on the decompressed size.
  7858. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  7859. constexpr size_t DECOMPRESSED_SIZE =
  7860. 10 * 1024 * 1024; // 10MB after decompression
  7861. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7862. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  7863. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  7864. std::string compressed;
  7865. {
  7866. httplib::detail::gzip_compressor compressor;
  7867. bool ok =
  7868. compressor.compress(uncompressed.data(), uncompressed.size(),
  7869. /*last=*/true, [&](const char *buf, size_t len) {
  7870. compressed.append(buf, len);
  7871. return true;
  7872. });
  7873. ASSERT_TRUE(ok);
  7874. }
  7875. // Sanity: compressed data should be much smaller than the decompressed size
  7876. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  7877. #ifndef _WIN32
  7878. signal(SIGPIPE, SIG_IGN);
  7879. #endif
  7880. // Set up the listening socket in the main thread so the server is guaranteed
  7881. // to be ready before the client connects (eliminates race condition).
  7882. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7883. default_socket_options(srv);
  7884. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7885. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7886. sockaddr_in addr{};
  7887. addr.sin_family = AF_INET;
  7888. addr.sin_port = htons(PORT + 3);
  7889. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7890. int opt = 1;
  7891. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7892. #ifdef _WIN32
  7893. reinterpret_cast<const char *>(&opt),
  7894. #else
  7895. &opt,
  7896. #endif
  7897. sizeof(opt));
  7898. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  7899. ASSERT_EQ(0, ::listen(srv, 1));
  7900. auto server_thread = std::thread([&compressed, srv] {
  7901. sockaddr_in cli_addr{};
  7902. socklen_t cli_len = sizeof(cli_addr);
  7903. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7904. if (cli != INVALID_SOCKET) {
  7905. // Read the full HTTP request (until \r\n\r\n)
  7906. char buf[4096];
  7907. size_t total = 0;
  7908. while (total < sizeof(buf)) {
  7909. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  7910. if (n <= 0) break;
  7911. total += static_cast<size_t>(n);
  7912. // Check for end of headers
  7913. if (total >= 4) {
  7914. std::string req(buf, total);
  7915. if (req.find("\r\n\r\n") != std::string::npos) break;
  7916. }
  7917. }
  7918. // Malicious response: gzip-compressed body, no Content-Length
  7919. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7920. "Content-Encoding: gzip\r\n"
  7921. "Connection: close\r\n"
  7922. "\r\n";
  7923. ::send(cli,
  7924. #ifdef _WIN32
  7925. static_cast<const char *>(response_header.c_str()),
  7926. static_cast<int>(response_header.size()),
  7927. #else
  7928. response_header.c_str(), response_header.size(),
  7929. #endif
  7930. 0);
  7931. // Send the compressed payload (small on the wire, huge when decompressed)
  7932. size_t total_sent = 0;
  7933. while (total_sent < compressed.size()) {
  7934. auto to_send = std::min(compressed.size() - total_sent,
  7935. static_cast<size_t>(64 * 1024));
  7936. auto sent =
  7937. ::send(cli,
  7938. #ifdef _WIN32
  7939. static_cast<const char *>(compressed.c_str() + total_sent),
  7940. static_cast<int>(to_send),
  7941. #else
  7942. compressed.c_str() + total_sent, to_send,
  7943. #endif
  7944. 0);
  7945. if (sent <= 0) break;
  7946. total_sent += static_cast<size_t>(sent);
  7947. }
  7948. detail::close_socket(cli);
  7949. }
  7950. });
  7951. auto se = detail::scope_exit([&] {
  7952. detail::close_socket(srv);
  7953. server_thread.join();
  7954. });
  7955. size_t total_decompressed = 0;
  7956. {
  7957. Client cli("127.0.0.1", PORT + 3);
  7958. cli.set_read_timeout(5, 0);
  7959. cli.set_decompress(true);
  7960. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7961. auto stream = cli.open_stream("GET", "/zipbomb");
  7962. ASSERT_TRUE(stream.is_valid());
  7963. char buffer[64 * 1024];
  7964. ssize_t n;
  7965. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7966. total_decompressed += static_cast<size_t>(n);
  7967. }
  7968. }
  7969. // The decompressed size must be capped by payload_max_length. Without
  7970. // protection, the client would decompress the full 10MB from a tiny
  7971. // compressed payload, enabling a zip bomb DoS attack.
  7972. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  7973. << "Client decompressed " << total_decompressed
  7974. << " bytes from a gzip response. The decompressed size should be "
  7975. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  7976. }
  7977. #endif
  7978. TEST(HostAndPortPropertiesTest, NoSSL) {
  7979. httplib::Client cli("www.google.com", 1234);
  7980. ASSERT_EQ("www.google.com", cli.host());
  7981. ASSERT_EQ(1234, cli.port());
  7982. }
  7983. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7984. httplib::Client cli("www.google.com:1234");
  7985. ASSERT_EQ("www.google.com", cli.host());
  7986. ASSERT_EQ(1234, cli.port());
  7987. }
  7988. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  7989. // Port number that overflows int — should not crash, client becomes invalid
  7990. httplib::Client cli("http://www.google.com:99999999999999999999");
  7991. ASSERT_FALSE(cli.is_valid());
  7992. }
  7993. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  7994. // Port 99999 exceeds valid range (1-65535) — should not crash
  7995. httplib::Client cli("http://www.google.com:99999");
  7996. ASSERT_FALSE(cli.is_valid());
  7997. }
  7998. #ifdef CPPHTTPLIB_SSL_ENABLED
  7999. TEST(HostAndPortPropertiesTest, SSL) {
  8000. httplib::SSLClient cli("www.google.com");
  8001. ASSERT_EQ("www.google.com", cli.host());
  8002. ASSERT_EQ(443, cli.port());
  8003. }
  8004. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8005. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8006. std::string cert;
  8007. read_file(CA_CERT_FILE, cert);
  8008. httplib::SSLClient httplib_client("www.google.com");
  8009. // Load CA store first time
  8010. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8011. // Load CA store second time (update)
  8012. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8013. // Verify client is still valid and can make connections
  8014. httplib_client.enable_server_certificate_verification(true);
  8015. auto res = httplib_client.Get("/");
  8016. ASSERT_TRUE(res);
  8017. // Google may return 200 or 301 depending on various factors
  8018. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8019. res->status == StatusCode::MovedPermanently_301);
  8020. }
  8021. TEST(SSLClientTest, ServerNameIndication_Online) {
  8022. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  8023. auto host = "httpcan.org";
  8024. auto path = std::string{"/get"};
  8025. #else
  8026. auto host = "nghttp2.org";
  8027. auto path = std::string{"/httpbin/get"};
  8028. #endif
  8029. SSLClient cli(host, 443);
  8030. auto res = cli.Get(path);
  8031. ASSERT_TRUE(res);
  8032. ASSERT_EQ(StatusCode::OK_200, res->status);
  8033. }
  8034. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8035. // Use a site that will cause SSL verification failure due to self-signed cert
  8036. SSLClient cli("self-signed.badssl.com", 443);
  8037. cli.enable_server_certificate_verification(true);
  8038. auto res = cli.Get("/");
  8039. ASSERT_TRUE(!res);
  8040. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8041. // Verify backend error is captured for SSLServerVerification
  8042. // This occurs when certificate verification fails
  8043. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8044. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8045. EXPECT_NE(0UL, res.ssl_backend_error());
  8046. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8047. // For OpenSSL, ssl_error is 0 for verification errors
  8048. EXPECT_EQ(0, res.ssl_error());
  8049. #if !defined(_WIN32) || \
  8050. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8051. // On non-Windows or when Windows Schannel is disabled, the error comes
  8052. // from OpenSSL's verification
  8053. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8054. res.ssl_backend_error());
  8055. #endif
  8056. #endif
  8057. }
  8058. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8059. // Use a site where hostname doesn't match the certificate
  8060. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8061. SSLClient cli("wrong.host.badssl.com", 443);
  8062. cli.enable_server_certificate_verification(true);
  8063. cli.enable_server_hostname_verification(true);
  8064. auto res = cli.Get("/");
  8065. ASSERT_TRUE(!res);
  8066. // The error type depends on when hostname verification occurs:
  8067. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8068. // - Mbed TLS: SSLServerVerification (during handshake)
  8069. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8070. res.error() == Error::SSLServerVerification);
  8071. // Verify backend error is captured for hostname verification failure
  8072. EXPECT_NE(0UL, res.ssl_backend_error());
  8073. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8074. // For OpenSSL, ssl_error is 0 for verification errors
  8075. EXPECT_EQ(0, res.ssl_error());
  8076. #if !defined(_WIN32) || \
  8077. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8078. // On non-Windows or when Windows Schannel is disabled, the error comes
  8079. // from OpenSSL's hostname verification
  8080. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8081. res.ssl_backend_error());
  8082. #endif
  8083. #endif
  8084. }
  8085. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8086. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8087. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8088. SSLClient cli("www.google.com", 443);
  8089. cli.enable_server_certificate_verification(true);
  8090. auto res = cli.Get("/");
  8091. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8092. }
  8093. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8094. SSLClient cli("www.google.com", 443);
  8095. cli.enable_server_certificate_verification(true);
  8096. cli.enable_windows_certificate_verification(false);
  8097. auto res = cli.Get("/");
  8098. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8099. }
  8100. #endif
  8101. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8102. Client cli("https://google.com");
  8103. auto res = cli.Get("/");
  8104. ASSERT_TRUE(res);
  8105. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8106. }
  8107. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8108. SSLClient cli("google.com");
  8109. cli.set_ca_cert_path(CA_CERT_FILE);
  8110. auto res = cli.Get("/");
  8111. ASSERT_TRUE(res);
  8112. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8113. }
  8114. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8115. SSLClient cli("google.com");
  8116. cli.enable_server_certificate_verification(true);
  8117. cli.set_ca_cert_path("hello");
  8118. auto res = cli.Get("/");
  8119. ASSERT_TRUE(!res);
  8120. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8121. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8122. // should be set
  8123. EXPECT_EQ(0, res.ssl_error());
  8124. // Verify backend error is captured for SSLLoadingCerts
  8125. // This error occurs when loading CA certificates fails
  8126. EXPECT_NE(0UL, res.ssl_backend_error());
  8127. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8128. // OpenSSL specific error codes:
  8129. // > openssl errstr 0x80000002
  8130. // error:80000002:system library::No such file or directory
  8131. // > openssl errstr 0xA000126
  8132. // error:0A000126:SSL routines::unexpected eof while reading
  8133. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8134. res.ssl_backend_error() == 0xA000126);
  8135. #endif
  8136. }
  8137. TEST(SSLClientTest, ServerCertificateVerification4) {
  8138. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8139. ASSERT_TRUE(svr.is_valid());
  8140. svr.Get("/test", [&](const Request &, Response &res) {
  8141. res.set_content("test", "text/plain");
  8142. svr.stop();
  8143. ASSERT_TRUE(true);
  8144. });
  8145. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8146. auto se = detail::scope_exit([&] {
  8147. t.join();
  8148. ASSERT_FALSE(svr.is_running());
  8149. });
  8150. svr.wait_until_ready();
  8151. SSLClient cli("127.0.0.1", PORT);
  8152. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8153. cli.enable_server_certificate_verification(true);
  8154. cli.set_connection_timeout(30);
  8155. auto res = cli.Get("/test");
  8156. ASSERT_TRUE(res);
  8157. ASSERT_EQ(StatusCode::OK_200, res->status);
  8158. }
  8159. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8160. std::string cert;
  8161. read_file(CA_CERT_FILE, cert);
  8162. SSLClient cli("google.com");
  8163. cli.load_ca_cert_store(cert.data(), cert.size());
  8164. const auto res = cli.Get("/");
  8165. ASSERT_TRUE(res);
  8166. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8167. }
  8168. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8169. // clang-format off
  8170. static constexpr char cert[] =
  8171. "GlobalSign Root CA\n"
  8172. "==================\n"
  8173. "-----BEGIN CERTIFICATE-----\n"
  8174. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8175. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8176. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8177. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8178. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8179. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8180. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8181. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8182. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8183. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8184. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8185. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8186. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8187. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8188. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8189. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8190. "-----END CERTIFICATE-----\n";
  8191. // clang-format on
  8192. SSLClient cli("google.com");
  8193. cli.load_ca_cert_store(cert, sizeof(cert));
  8194. const auto res = cli.Get("/");
  8195. ASSERT_TRUE(res);
  8196. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8197. }
  8198. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8199. SSLClient cli("www.youtube.com");
  8200. cli.set_ca_cert_path(CA_CERT_FILE);
  8201. cli.enable_server_certificate_verification(true);
  8202. cli.set_follow_location(true);
  8203. auto res = cli.Get("/");
  8204. ASSERT_TRUE(res);
  8205. ASSERT_EQ(StatusCode::OK_200, res->status);
  8206. }
  8207. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8208. SSLClient cli("wWw.YouTube.Com");
  8209. cli.set_ca_cert_path(CA_CERT_FILE);
  8210. cli.enable_server_certificate_verification(true);
  8211. cli.enable_server_hostname_verification(true);
  8212. cli.set_follow_location(true);
  8213. auto res = cli.Get("/");
  8214. ASSERT_TRUE(res);
  8215. ASSERT_EQ(StatusCode::OK_200, res->status);
  8216. }
  8217. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8218. SSLClient cli("gOoGlE.COm");
  8219. cli.enable_server_certificate_verification(true);
  8220. cli.enable_server_hostname_verification(true);
  8221. cli.set_follow_location(true);
  8222. auto res = cli.Get("/");
  8223. ASSERT_TRUE(res);
  8224. ASSERT_EQ(StatusCode::OK_200, res->status);
  8225. }
  8226. TEST(SSLClientTest, Issue2004_Online) {
  8227. Client client("https://google.com");
  8228. client.set_follow_location(true);
  8229. auto res = client.Get("/");
  8230. ASSERT_TRUE(res);
  8231. ASSERT_EQ(StatusCode::OK_200, res->status);
  8232. auto body = res->body;
  8233. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8234. }
  8235. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8236. // Create SSLClient with invalid cert/key to make is_valid() return false
  8237. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8238. "nonexistent_key.pem");
  8239. // is_valid() should be false due to cert loading failure
  8240. ASSERT_FALSE(cli.is_valid());
  8241. auto res = cli.Get("/");
  8242. ASSERT_FALSE(res);
  8243. EXPECT_EQ(Error::SSLConnection, res.error());
  8244. }
  8245. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8246. // Test for Issue #2251: SSL error not properly reported when client cert
  8247. // and key paths are swapped or mismatched
  8248. // This simulates the scenario where user accidentally swaps the cert and key
  8249. // files
  8250. // Using client cert file as private key and vice versa (completely wrong)
  8251. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8252. // Should fail validation due to cert/key mismatch
  8253. ASSERT_FALSE(cli.is_valid());
  8254. // Attempt to make a request should fail with proper error
  8255. auto res = cli.Get("/");
  8256. ASSERT_FALSE(res);
  8257. EXPECT_EQ(Error::SSLConnection, res.error());
  8258. // SSL error should be recorded in the Result object (this is the key fix for
  8259. // Issue #2251)
  8260. auto backend_error = res.ssl_backend_error();
  8261. EXPECT_NE(0u, backend_error);
  8262. }
  8263. // Tests cert/key mismatch detection at the TLS context level
  8264. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8265. // Test that using mismatched cert/key causes connection failure.
  8266. // We verify this at the SSLClient level rather than through internal
  8267. // TLS API functions.
  8268. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8269. cli.enable_server_certificate_verification(false);
  8270. cli.set_connection_timeout(2);
  8271. // The mismatch should cause a connection or handshake error
  8272. auto res = cli.Get("/test");
  8273. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8274. // Either way, the request should fail
  8275. EXPECT_FALSE(res);
  8276. }
  8277. #endif
  8278. #if 0
  8279. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8280. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8281. ASSERT_TRUE(cli != nullptr);
  8282. cli->set_address_family(AF_INET6);
  8283. cli->set_interface("en0");
  8284. auto res = cli->Get("/get");
  8285. ASSERT_TRUE(res);
  8286. ASSERT_EQ(StatusCode::OK_200, res->status);
  8287. }
  8288. #endif
  8289. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8290. #ifdef CPPHTTPLIB_SSL_ENABLED
  8291. void ClientCertPresent(
  8292. const std::string &client_cert_file,
  8293. const std::string &client_private_key_file,
  8294. const std::string &client_encrypted_private_key_pass = std::string()) {
  8295. using namespace httplib::tls;
  8296. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8297. CLIENT_CA_CERT_DIR);
  8298. ASSERT_TRUE(svr.is_valid());
  8299. svr.Get("/test", [&](const Request &req, Response &res) {
  8300. res.set_content("test", "text/plain");
  8301. auto cert = req.peer_cert();
  8302. ASSERT_TRUE(static_cast<bool>(cert));
  8303. std::string common_name = cert.subject_cn();
  8304. EXPECT_EQ("Common Name", common_name);
  8305. });
  8306. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8307. auto se = detail::scope_exit([&] {
  8308. svr.stop();
  8309. t.join();
  8310. ASSERT_FALSE(svr.is_running());
  8311. });
  8312. svr.wait_until_ready();
  8313. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8314. client_encrypted_private_key_pass);
  8315. cli.enable_server_certificate_verification(false);
  8316. cli.set_connection_timeout(30);
  8317. auto res = cli.Get("/test");
  8318. ASSERT_TRUE(res);
  8319. ASSERT_EQ(StatusCode::OK_200, res->status);
  8320. }
  8321. TEST(SSLClientServerTest, ClientCertPresent) {
  8322. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8323. }
  8324. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8325. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8326. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8327. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8328. }
  8329. // PEM memory-based constructor tests (works with all TLS backends)
  8330. void PemMemoryClientCertPresent(
  8331. const std::string &client_cert_file,
  8332. const std::string &client_private_key_file,
  8333. const std::string &client_encrypted_private_key_pass = std::string()) {
  8334. // Read PEM files into memory
  8335. std::string server_cert_pem, server_key_pem;
  8336. std::string client_ca_pem;
  8337. std::string client_cert_pem, client_key_pem;
  8338. read_file(SERVER_CERT_FILE, server_cert_pem);
  8339. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8340. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8341. read_file(client_cert_file, client_cert_pem);
  8342. read_file(client_private_key_file, client_key_pem);
  8343. // Create server with PEM memory
  8344. SSLServer::PemMemory server_pem = {
  8345. server_cert_pem.c_str(),
  8346. server_cert_pem.size(),
  8347. server_key_pem.c_str(),
  8348. server_key_pem.size(),
  8349. client_ca_pem.c_str(),
  8350. client_ca_pem.size(),
  8351. nullptr // no password for server key
  8352. };
  8353. SSLServer svr(server_pem);
  8354. ASSERT_TRUE(svr.is_valid());
  8355. svr.Get("/test", [&](const Request &, Response &res) {
  8356. res.set_content("test", "text/plain");
  8357. });
  8358. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8359. auto se = detail::scope_exit([&] {
  8360. svr.stop();
  8361. t.join();
  8362. ASSERT_FALSE(svr.is_running());
  8363. });
  8364. svr.wait_until_ready();
  8365. // Create client with PEM memory
  8366. const char *password = client_encrypted_private_key_pass.empty()
  8367. ? nullptr
  8368. : client_encrypted_private_key_pass.c_str();
  8369. SSLClient::PemMemory client_pem = {
  8370. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8371. client_key_pem.size(), password};
  8372. SSLClient cli(HOST, PORT, client_pem);
  8373. cli.enable_server_certificate_verification(false);
  8374. cli.set_connection_timeout(30);
  8375. auto res = cli.Get("/test");
  8376. ASSERT_TRUE(res);
  8377. ASSERT_EQ(StatusCode::OK_200, res->status);
  8378. }
  8379. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8380. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8381. }
  8382. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8383. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8384. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8385. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8386. }
  8387. TEST(SSLClientServerTest, ClientCertMissing) {
  8388. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8389. CLIENT_CA_CERT_DIR);
  8390. ASSERT_TRUE(svr.is_valid());
  8391. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8392. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8393. auto se = detail::scope_exit([&] {
  8394. svr.stop();
  8395. t.join();
  8396. ASSERT_FALSE(svr.is_running());
  8397. });
  8398. svr.wait_until_ready();
  8399. SSLClient cli(HOST, PORT);
  8400. cli.set_connection_timeout(30);
  8401. auto res = cli.Get("/test");
  8402. ASSERT_TRUE(!res);
  8403. // When client cert is missing and server requires it, connection fails
  8404. // Error type depends on backend implementation
  8405. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8406. res.error() == Error::SSLConnection);
  8407. // Verify backend error is captured
  8408. // Note: This test may have different error codes depending on the exact
  8409. // verification failure
  8410. EXPECT_NE(0UL, res.ssl_backend_error());
  8411. }
  8412. TEST(SSLClientServerTest, TrustDirOptional) {
  8413. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8414. ASSERT_TRUE(svr.is_valid());
  8415. svr.Get("/test", [&](const Request &, Response &res) {
  8416. res.set_content("test", "text/plain");
  8417. });
  8418. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8419. auto se = detail::scope_exit([&] {
  8420. svr.stop();
  8421. t.join();
  8422. ASSERT_FALSE(svr.is_running());
  8423. });
  8424. svr.wait_until_ready();
  8425. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8426. cli.enable_server_certificate_verification(false);
  8427. cli.set_connection_timeout(30);
  8428. auto res = cli.Get("/test");
  8429. ASSERT_TRUE(res);
  8430. ASSERT_EQ(StatusCode::OK_200, res->status);
  8431. }
  8432. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8433. class NoListenSSLServer : public SSLServer {
  8434. public:
  8435. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8436. const char *client_ca_cert_file_path,
  8437. const char *client_ca_cert_dir_path = nullptr)
  8438. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8439. client_ca_cert_dir_path),
  8440. stop_(false) {}
  8441. std::atomic_bool stop_;
  8442. private:
  8443. bool process_and_close_socket(socket_t /*sock*/) override {
  8444. // Don't create SSL context
  8445. while (!stop_.load()) {
  8446. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8447. }
  8448. return true;
  8449. }
  8450. };
  8451. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8452. CLIENT_CA_CERT_FILE);
  8453. ASSERT_TRUE(svr.is_valid());
  8454. svr.Get("/test", [&](const Request &, Response &res) {
  8455. res.set_content("test", "text/plain");
  8456. });
  8457. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8458. auto se = detail::scope_exit([&] {
  8459. svr.stop_ = true;
  8460. svr.stop();
  8461. t.join();
  8462. ASSERT_FALSE(svr.is_running());
  8463. });
  8464. svr.wait_until_ready();
  8465. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8466. cli.enable_server_certificate_verification(false);
  8467. cli.set_connection_timeout(1);
  8468. auto res = cli.Get("/test");
  8469. ASSERT_TRUE(!res);
  8470. EXPECT_EQ(Error::SSLConnection, res.error());
  8471. // Timeout results in WantRead error code (maps to backend-specific value)
  8472. EXPECT_NE(0, res.ssl_error());
  8473. }
  8474. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8475. // Test SSLServer with client certificate verification using the standard
  8476. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8477. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8478. CLIENT_CA_CERT_DIR);
  8479. ASSERT_TRUE(svr.is_valid());
  8480. svr.Get("/test", [&](const Request &req, Response &res) {
  8481. res.set_content("test", "text/plain");
  8482. auto cert = req.peer_cert();
  8483. ASSERT_TRUE(static_cast<bool>(cert));
  8484. auto common_name = cert.subject_cn();
  8485. EXPECT_EQ("Common Name", common_name);
  8486. });
  8487. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8488. auto se = detail::scope_exit([&] {
  8489. svr.stop();
  8490. t.join();
  8491. ASSERT_FALSE(svr.is_running());
  8492. });
  8493. svr.wait_until_ready();
  8494. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8495. cli.enable_server_certificate_verification(false);
  8496. cli.set_connection_timeout(30);
  8497. auto res = cli.Get("/test");
  8498. ASSERT_TRUE(res);
  8499. ASSERT_EQ(StatusCode::OK_200, res->status);
  8500. }
  8501. // Test verify_hostname for both OpenSSL and MbedTLS backends
  8502. // Verifies that wildcard matching and exact matching work consistently
  8503. TEST(SSLClientServerTest, TlsVerifyHostname) {
  8504. using namespace httplib::tls;
  8505. // We need a running server to test against
  8506. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8507. ASSERT_TRUE(svr.is_valid());
  8508. svr.Get("/test", [](const Request &, Response &res) {
  8509. res.set_content("ok", "text/plain");
  8510. });
  8511. thread t([&]() { svr.listen(HOST, PORT); });
  8512. auto se = detail::scope_exit([&] {
  8513. svr.stop();
  8514. t.join();
  8515. });
  8516. svr.wait_until_ready();
  8517. bool verify_callback_called = false;
  8518. bool verify_result_wrong = false;
  8519. SSLClient cli(HOST, PORT);
  8520. cli.enable_server_certificate_verification(true);
  8521. cli.set_ca_cert_path(CA_CERT_FILE);
  8522. cli.set_connection_timeout(5);
  8523. // Note: Test certificate has CN="Common Name", not "localhost"
  8524. bool verify_result_cn = false;
  8525. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8526. verify_callback_called = true;
  8527. if (!ctx.cert) return false;
  8528. // Test 1: "Common Name" should match (our test server cert CN)
  8529. verify_result_cn = ctx.check_hostname("Common Name");
  8530. // Test 2: wrong hostname should not match
  8531. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  8532. return true; // Accept for the purpose of this test
  8533. });
  8534. auto res = cli.Get("/test");
  8535. // The request may succeed or fail depending on cert configuration
  8536. // but the callback should have been called
  8537. ASSERT_TRUE(verify_callback_called)
  8538. << "Verify callback should have been called";
  8539. // CN="Common Name" should match our test certificate
  8540. EXPECT_TRUE(verify_result_cn)
  8541. << "verify_hostname should match 'Common Name' (certificate CN)";
  8542. // Wrong hostname should not match
  8543. EXPECT_FALSE(verify_result_wrong)
  8544. << "verify_hostname should not match 'wronghost.example.com'";
  8545. }
  8546. #endif
  8547. // mbedTLS-specific callback constructor test
  8548. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8549. #ifdef CPPHTTPLIB_SSL_ENABLED
  8550. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8551. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8552. ASSERT_TRUE(svr.is_valid());
  8553. // Set up a handler to verify client certificate is present
  8554. bool client_cert_verified = false;
  8555. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8556. // Verify that client certificate was provided
  8557. client_cert_verified = true;
  8558. res.set_content("success", "text/plain");
  8559. });
  8560. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8561. auto se = detail::scope_exit([&] {
  8562. svr.stop();
  8563. t.join();
  8564. ASSERT_FALSE(svr.is_running());
  8565. });
  8566. svr.wait_until_ready();
  8567. // Client with certificate
  8568. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8569. cli.enable_server_certificate_verification(false);
  8570. cli.set_connection_timeout(30);
  8571. auto res = cli.Get("/test");
  8572. ASSERT_TRUE(res);
  8573. ASSERT_EQ(StatusCode::OK_200, res->status);
  8574. ASSERT_TRUE(client_cert_verified);
  8575. EXPECT_EQ("success", res->body);
  8576. }
  8577. #endif
  8578. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  8579. // backends
  8580. #ifdef CPPHTTPLIB_SSL_ENABLED
  8581. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  8582. using namespace httplib::tls;
  8583. // Test that when client CA cert file is provided,
  8584. // the server properly requests and validates client certificates
  8585. // Create a server with client authentication
  8586. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8587. ASSERT_TRUE(svr.is_valid());
  8588. bool handler_called = false;
  8589. svr.Get("/test", [&](const Request &req, Response &res) {
  8590. handler_called = true;
  8591. // Verify that a client certificate was provided
  8592. auto cert = req.peer_cert();
  8593. ASSERT_TRUE(static_cast<bool>(cert));
  8594. // Get the issuer name
  8595. std::string issuer_str = cert.issuer_name();
  8596. ASSERT_FALSE(issuer_str.empty());
  8597. // The client certificate should be issued by our test CA
  8598. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  8599. res.set_content("authenticated", "text/plain");
  8600. });
  8601. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8602. auto se = detail::scope_exit([&] {
  8603. svr.stop();
  8604. t.join();
  8605. ASSERT_FALSE(svr.is_running());
  8606. });
  8607. svr.wait_until_ready();
  8608. // Connect with a client certificate issued by the CA
  8609. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8610. cli.enable_server_certificate_verification(false);
  8611. cli.set_connection_timeout(30);
  8612. auto res = cli.Get("/test");
  8613. ASSERT_TRUE(res);
  8614. ASSERT_EQ(StatusCode::OK_200, res->status);
  8615. ASSERT_TRUE(handler_called);
  8616. EXPECT_EQ("authenticated", res->body);
  8617. }
  8618. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  8619. using namespace httplib::tls;
  8620. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8621. ASSERT_TRUE(svr.is_valid());
  8622. svr.Get("/test", [](const Request &, Response &res) {
  8623. res.set_content("ok", "text/plain");
  8624. });
  8625. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8626. auto se = detail::scope_exit([&] {
  8627. svr.stop();
  8628. t.join();
  8629. });
  8630. svr.wait_until_ready();
  8631. SSLClient cli(HOST, PORT);
  8632. cli.enable_server_certificate_verification(false);
  8633. cli.set_connection_timeout(30);
  8634. bool cert_checked = false;
  8635. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8636. if (ctx.cert) {
  8637. auto sans = ctx.sans();
  8638. // Test certificate may or may not have SANs - just verify the API
  8639. // works If SANs exist, verify the types are valid
  8640. for (const auto &san : sans) {
  8641. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  8642. san.type == SanType::EMAIL || san.type == SanType::URI ||
  8643. san.type == SanType::OTHER);
  8644. EXPECT_FALSE(san.value.empty());
  8645. }
  8646. cert_checked = true;
  8647. }
  8648. return true;
  8649. });
  8650. auto res = cli.Get("/test");
  8651. ASSERT_TRUE(res);
  8652. EXPECT_TRUE(cert_checked);
  8653. }
  8654. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  8655. using namespace httplib::tls;
  8656. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8657. ASSERT_TRUE(svr.is_valid());
  8658. svr.Get("/test", [](const Request &, Response &res) {
  8659. res.set_content("ok", "text/plain");
  8660. });
  8661. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8662. auto se = detail::scope_exit([&] {
  8663. svr.stop();
  8664. t.join();
  8665. });
  8666. svr.wait_until_ready();
  8667. SSLClient cli(HOST, PORT);
  8668. cli.enable_server_certificate_verification(false);
  8669. cli.set_connection_timeout(30);
  8670. bool validity_checked = false;
  8671. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8672. if (ctx.cert) {
  8673. time_t not_before = 0, not_after = 0;
  8674. bool result = ctx.validity(not_before, not_after);
  8675. EXPECT_TRUE(result);
  8676. // Verify that not_before < now < not_after for a valid cert
  8677. time_t now = time(nullptr);
  8678. EXPECT_LT(not_before, now);
  8679. EXPECT_GT(not_after, now);
  8680. validity_checked = true;
  8681. }
  8682. return true;
  8683. });
  8684. auto res = cli.Get("/test");
  8685. ASSERT_TRUE(res);
  8686. EXPECT_TRUE(validity_checked);
  8687. }
  8688. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  8689. using namespace httplib::tls;
  8690. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8691. ASSERT_TRUE(svr.is_valid());
  8692. svr.Get("/test", [](const Request &, Response &res) {
  8693. res.set_content("ok", "text/plain");
  8694. });
  8695. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8696. auto se = detail::scope_exit([&] {
  8697. svr.stop();
  8698. t.join();
  8699. });
  8700. svr.wait_until_ready();
  8701. SSLClient cli(HOST, PORT);
  8702. cli.enable_server_certificate_verification(false);
  8703. cli.set_connection_timeout(30);
  8704. bool serial_checked = false;
  8705. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8706. if (ctx.cert) {
  8707. std::string serial = ctx.serial();
  8708. EXPECT_FALSE(serial.empty());
  8709. // Serial should be a hex string
  8710. for (char c : serial) {
  8711. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  8712. (c >= 'a' && c <= 'f'));
  8713. }
  8714. serial_checked = true;
  8715. }
  8716. return true;
  8717. });
  8718. auto res = cli.Get("/test");
  8719. ASSERT_TRUE(res);
  8720. EXPECT_TRUE(serial_checked);
  8721. }
  8722. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  8723. // Test 1: Valid CA file - no error should be recorded
  8724. {
  8725. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8726. CLIENT_CA_CERT_FILE);
  8727. ASSERT_TRUE(svr.is_valid());
  8728. // With valid setup, last_ssl_error should be 0
  8729. EXPECT_EQ(0, svr.ssl_last_error());
  8730. }
  8731. // Test 2: Invalid CA file content
  8732. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  8733. {
  8734. // Create a temporary file with completely invalid content
  8735. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  8736. {
  8737. std::ofstream ofs(temp_invalid_ca);
  8738. ofs << "This is not a certificate file at all\n";
  8739. ofs << "Just plain text content\n";
  8740. }
  8741. // Create server with invalid CA file
  8742. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  8743. // Clean up temporary file
  8744. std::remove(temp_invalid_ca);
  8745. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  8746. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  8747. // Note: SSL_CTX_load_verify_locations typically fails first,
  8748. // but our error handling code path is still exercised
  8749. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  8750. }
  8751. }
  8752. TEST(VerifyCallbackTest, VerifyContextFields) {
  8753. using namespace httplib::tls;
  8754. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8755. ASSERT_TRUE(svr.is_valid());
  8756. svr.Get("/test", [](const Request &, Response &res) {
  8757. res.set_content("ok", "text/plain");
  8758. });
  8759. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8760. auto se = detail::scope_exit([&] {
  8761. svr.stop();
  8762. t.join();
  8763. });
  8764. svr.wait_until_ready();
  8765. SSLClient cli(HOST, PORT);
  8766. cli.enable_server_certificate_verification(false);
  8767. cli.set_connection_timeout(30);
  8768. int callback_count = 0;
  8769. bool saw_leaf_cert = false;
  8770. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8771. if (ctx.cert) {
  8772. callback_count++;
  8773. // We should see at least one certificate (the leaf)
  8774. std::string cn = ctx.subject_cn();
  8775. if (!cn.empty()) { saw_leaf_cert = true; }
  8776. // Verify context fields are populated
  8777. EXPECT_NE(ctx.session, nullptr);
  8778. EXPECT_GE(ctx.depth, 0);
  8779. }
  8780. return true;
  8781. });
  8782. auto res = cli.Get("/test");
  8783. ASSERT_TRUE(res);
  8784. EXPECT_GT(callback_count, 0);
  8785. EXPECT_TRUE(saw_leaf_cert);
  8786. }
  8787. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  8788. using httplib::tls::TlsError;
  8789. // Test that verify_error_to_string returns empty for success
  8790. std::string success_str = TlsError::verify_error_to_string(0);
  8791. EXPECT_TRUE(success_str.empty());
  8792. // Test that verify_error_to_string returns non-empty for error codes
  8793. // Using a common error code (certificate expired)
  8794. std::string error_str =
  8795. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  8796. EXPECT_FALSE(error_str.empty());
  8797. }
  8798. TEST(SessionVerifierTest, CertificateAccepted) {
  8799. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8800. ASSERT_TRUE(svr.is_valid());
  8801. svr.Get("/test", [](const Request &, Response &res) {
  8802. res.set_content("ok", "text/plain");
  8803. });
  8804. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8805. auto se = detail::scope_exit([&] {
  8806. svr.stop();
  8807. t.join();
  8808. });
  8809. svr.wait_until_ready();
  8810. SSLClient cli(HOST, PORT);
  8811. cli.enable_server_certificate_verification(false);
  8812. cli.set_connection_timeout(30);
  8813. bool callback_called = false;
  8814. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8815. EXPECT_NE(session, nullptr);
  8816. callback_called = true;
  8817. return SSLVerifierResponse::CertificateAccepted;
  8818. });
  8819. auto res = cli.Get("/test");
  8820. ASSERT_TRUE(res);
  8821. EXPECT_EQ(200, res->status);
  8822. EXPECT_TRUE(callback_called);
  8823. }
  8824. TEST(SessionVerifierTest, CertificateRejected) {
  8825. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8826. ASSERT_TRUE(svr.is_valid());
  8827. svr.Get("/test", [](const Request &, Response &res) {
  8828. res.set_content("ok", "text/plain");
  8829. });
  8830. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8831. auto se = detail::scope_exit([&] {
  8832. svr.stop();
  8833. t.join();
  8834. });
  8835. svr.wait_until_ready();
  8836. SSLClient cli(HOST, PORT);
  8837. cli.enable_server_certificate_verification(false);
  8838. cli.set_connection_timeout(30);
  8839. bool callback_called = false;
  8840. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8841. EXPECT_NE(session, nullptr);
  8842. callback_called = true;
  8843. return SSLVerifierResponse::CertificateRejected;
  8844. });
  8845. auto res = cli.Get("/test");
  8846. EXPECT_FALSE(res);
  8847. EXPECT_TRUE(callback_called);
  8848. }
  8849. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  8850. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8851. ASSERT_TRUE(svr.is_valid());
  8852. svr.Get("/test", [](const Request &, Response &res) {
  8853. res.set_content("ok", "text/plain");
  8854. });
  8855. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8856. auto se = detail::scope_exit([&] {
  8857. svr.stop();
  8858. t.join();
  8859. });
  8860. svr.wait_until_ready();
  8861. // NoDecisionMade with verification disabled should succeed (no default check)
  8862. SSLClient cli(HOST, PORT);
  8863. cli.enable_server_certificate_verification(false);
  8864. cli.set_connection_timeout(30);
  8865. bool callback_called = false;
  8866. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8867. EXPECT_NE(session, nullptr);
  8868. callback_called = true;
  8869. return SSLVerifierResponse::NoDecisionMade;
  8870. });
  8871. auto res = cli.Get("/test");
  8872. ASSERT_TRUE(res);
  8873. EXPECT_EQ(200, res->status);
  8874. EXPECT_TRUE(callback_called);
  8875. }
  8876. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  8877. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8878. ASSERT_TRUE(svr.is_valid());
  8879. svr.Get("/test", [](const Request &, Response &res) {
  8880. res.set_content("ok", "text/plain");
  8881. });
  8882. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8883. auto se = detail::scope_exit([&] {
  8884. svr.stop();
  8885. t.join();
  8886. });
  8887. svr.wait_until_ready();
  8888. // NoDecisionMade with verification enabled should fail (self-signed cert).
  8889. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  8890. // so we only check that the request fails, not whether the callback was
  8891. // called.
  8892. SSLClient cli(HOST, PORT);
  8893. cli.enable_server_certificate_verification(true);
  8894. cli.set_connection_timeout(30);
  8895. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8896. EXPECT_NE(session, nullptr);
  8897. return SSLVerifierResponse::NoDecisionMade;
  8898. });
  8899. auto res = cli.Get("/test");
  8900. EXPECT_FALSE(res);
  8901. }
  8902. TEST(SSLClientServerTest, ClientCAListFromPem) {
  8903. // Test SSL server using PemMemory constructor with client CA certificates
  8904. // Read PEM files
  8905. std::string server_cert_pem, server_key_pem, client_ca_pem;
  8906. read_file(SERVER_CERT_FILE, server_cert_pem);
  8907. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8908. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8909. // Create SSLServer with PemMemory constructor including client CA
  8910. SSLServer::PemMemory server_pem = {
  8911. server_cert_pem.c_str(),
  8912. server_cert_pem.size(),
  8913. server_key_pem.c_str(),
  8914. server_key_pem.size(),
  8915. client_ca_pem.c_str(),
  8916. client_ca_pem.size(),
  8917. nullptr // no password for server key
  8918. };
  8919. SSLServer svr(server_pem);
  8920. ASSERT_TRUE(svr.is_valid());
  8921. // No SSL error should be recorded for valid setup
  8922. EXPECT_EQ(0, svr.ssl_last_error());
  8923. // Set up server endpoints
  8924. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  8925. res.set_content("ok", "text/plain");
  8926. });
  8927. // Start server in a thread
  8928. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  8929. svr.wait_until_ready();
  8930. // Connect with client certificate (using constructor with paths)
  8931. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8932. cli.enable_server_certificate_verification(false);
  8933. auto res = cli.Get("/test-pem-ca");
  8934. ASSERT_TRUE(res);
  8935. EXPECT_EQ(200, res->status);
  8936. EXPECT_EQ("ok", res->body);
  8937. svr.stop();
  8938. server_thread.join();
  8939. }
  8940. #endif
  8941. #ifdef _WIN32
  8942. TEST(CleanupTest, WSACleanup) {
  8943. int ret = WSACleanup();
  8944. ASSERT_EQ(0, ret);
  8945. }
  8946. #endif
  8947. #ifndef CPPHTTPLIB_SSL_ENABLED
  8948. TEST(NoSSLSupport, SimpleInterface) {
  8949. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  8950. }
  8951. #endif
  8952. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8953. TEST(InvalidScheme, SimpleInterface) {
  8954. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  8955. }
  8956. #endif
  8957. TEST(NoScheme, SimpleInterface) {
  8958. Client cli("yahoo.com:80");
  8959. ASSERT_TRUE(cli.is_valid());
  8960. }
  8961. TEST(SendAPI, SimpleInterface_Online) {
  8962. Client cli("http://yahoo.com");
  8963. Request req;
  8964. req.method = "GET";
  8965. req.path = "/";
  8966. auto res = cli.send(req);
  8967. ASSERT_TRUE(res);
  8968. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8969. }
  8970. TEST(SendAPI, WithParamsInRequest) {
  8971. Server svr;
  8972. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  8973. EXPECT_TRUE(req.has_param("test"));
  8974. EXPECT_EQ("test_value", req.get_param_value("test"));
  8975. });
  8976. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  8977. auto se = detail::scope_exit([&] {
  8978. svr.stop();
  8979. t.join();
  8980. ASSERT_FALSE(svr.is_running());
  8981. });
  8982. svr.wait_until_ready();
  8983. Client cli(HOST, PORT);
  8984. {
  8985. Request req;
  8986. req.method = "GET";
  8987. req.path = "/";
  8988. req.params.emplace("test", "test_value");
  8989. auto res = cli.send(req);
  8990. ASSERT_TRUE(res);
  8991. }
  8992. {
  8993. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  8994. ASSERT_TRUE(res);
  8995. }
  8996. }
  8997. TEST(ClientImplMethods, GetSocketTest) {
  8998. httplib::Server svr;
  8999. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9000. res.status = StatusCode::OK_200;
  9001. });
  9002. auto port = svr.bind_to_any_port("127.0.0.1");
  9003. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9004. auto se = detail::scope_exit([&] {
  9005. svr.stop();
  9006. thread.join();
  9007. ASSERT_FALSE(svr.is_running());
  9008. });
  9009. svr.wait_until_ready();
  9010. {
  9011. httplib::Client cli("127.0.0.1", port);
  9012. cli.set_keep_alive(true);
  9013. // Use the behavior of cpp-httplib of opening the connection
  9014. // only when the first request happens. If that changes,
  9015. // this test would be obsolete.
  9016. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9017. // This also implicitly tests the server. But other tests would fail much
  9018. // earlier than this one to be considered.
  9019. auto res = cli.Get("/");
  9020. ASSERT_TRUE(res);
  9021. EXPECT_EQ(StatusCode::OK_200, res->status);
  9022. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9023. }
  9024. }
  9025. // Disabled due to out-of-memory problem on GitHub Actions
  9026. #ifdef _WIN64
  9027. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  9028. // allocate content size larger than 2GB in memory
  9029. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  9030. char *content = (char *)malloc(content_size);
  9031. ASSERT_TRUE(content);
  9032. Server svr;
  9033. svr.Get("/foo",
  9034. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  9035. res.set_content(content, content_size, "application/octet-stream");
  9036. });
  9037. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9038. auto se = detail::scope_exit([&] {
  9039. svr.stop();
  9040. listen_thread.join();
  9041. if (content) free(content);
  9042. ASSERT_FALSE(svr.is_running());
  9043. });
  9044. svr.wait_until_ready();
  9045. Client cli(HOST, PORT);
  9046. auto res = cli.Get("/foo");
  9047. ASSERT_TRUE(res);
  9048. EXPECT_EQ(StatusCode::OK_200, res->status);
  9049. EXPECT_EQ(content_size, res->body.length());
  9050. }
  9051. #endif
  9052. #ifdef CPPHTTPLIB_SSL_ENABLED
  9053. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9054. Client cli("http://yahoo.com");
  9055. auto res = cli.Get("/");
  9056. ASSERT_TRUE(res);
  9057. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9058. cli.set_follow_location(true);
  9059. res = cli.Get("/");
  9060. ASSERT_TRUE(res);
  9061. EXPECT_EQ(StatusCode::OK_200, res->status);
  9062. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9063. }
  9064. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9065. Client cli("https://yahoo.com");
  9066. auto res = cli.Get("/");
  9067. ASSERT_TRUE(res);
  9068. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9069. cli.set_follow_location(true);
  9070. res = cli.Get("/");
  9071. ASSERT_TRUE(res);
  9072. EXPECT_EQ(StatusCode::OK_200, res->status);
  9073. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9074. }
  9075. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9076. Client cli("https://yahoo.com");
  9077. auto res = cli.Get("/");
  9078. ASSERT_TRUE(res);
  9079. ASSERT_FALSE(!res);
  9080. ASSERT_TRUE(res);
  9081. ASSERT_FALSE(res == nullptr);
  9082. ASSERT_TRUE(res != nullptr);
  9083. EXPECT_EQ(Error::Success, res.error());
  9084. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9085. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9086. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9087. cli.set_follow_location(true);
  9088. res = cli.Get("/");
  9089. ASSERT_TRUE(res);
  9090. EXPECT_EQ(Error::Success, res.error());
  9091. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9092. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9093. EXPECT_EQ(StatusCode::OK_200, res->status);
  9094. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9095. }
  9096. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9097. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9098. Client cli("https://cdnjs.cloudflare.com");
  9099. auto res =
  9100. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9101. ASSERT_TRUE(res);
  9102. EXPECT_EQ(StatusCode::OK_200, res->status);
  9103. EXPECT_EQ(287630U, res->body.size());
  9104. EXPECT_EQ("application/javascript; charset=utf-8",
  9105. res->get_header_value("Content-Type"));
  9106. }
  9107. #endif
  9108. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9109. #undef REDIR_HOST // Silence compiler warning
  9110. #define REDIR_HOST "https://httpbingo.org"
  9111. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9112. Client cli(REDIR_HOST);
  9113. cli.set_follow_location(true);
  9114. auto res =
  9115. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9116. ASSERT_TRUE(res);
  9117. EXPECT_EQ(StatusCode::OK_200, res->status);
  9118. }
  9119. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9120. Client cli(REDIR_HOST);
  9121. cli.set_follow_location(true);
  9122. Params params;
  9123. params.emplace("url", "http://example.com");
  9124. params.emplace("status_code", "302");
  9125. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9126. ASSERT_TRUE(res);
  9127. EXPECT_EQ(StatusCode::OK_200, res->status);
  9128. }
  9129. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9130. Client cli(REDIR_HOST);
  9131. cli.set_follow_location(true);
  9132. Params params;
  9133. params.emplace("url", "http://example.com");
  9134. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9135. ASSERT_TRUE(res);
  9136. EXPECT_EQ(StatusCode::OK_200, res->status);
  9137. }
  9138. TEST(HttpToHttpsRedirectTest, CertFile) {
  9139. auto ssl_port = PORT + 1;
  9140. Server svr;
  9141. ASSERT_TRUE(svr.is_valid());
  9142. svr.Get("/index", [&](const Request &, Response &res) {
  9143. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9144. "/index");
  9145. svr.stop();
  9146. });
  9147. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9148. ASSERT_TRUE(ssl_svr.is_valid());
  9149. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9150. res.set_content("test", "text/plain");
  9151. ssl_svr.stop();
  9152. });
  9153. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9154. thread t2 =
  9155. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9156. auto se = detail::scope_exit([&] {
  9157. t2.join();
  9158. t.join();
  9159. ASSERT_FALSE(svr.is_running());
  9160. });
  9161. svr.wait_until_ready();
  9162. ssl_svr.wait_until_ready();
  9163. Client cli("127.0.0.1", PORT);
  9164. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9165. cli.enable_server_certificate_verification(true);
  9166. cli.set_follow_location(true);
  9167. cli.set_connection_timeout(30);
  9168. auto res = cli.Get("/index");
  9169. ASSERT_TRUE(res);
  9170. ASSERT_EQ(StatusCode::OK_200, res->status);
  9171. }
  9172. TEST(SSLClientRedirectTest, CertFile) {
  9173. auto ssl_port = PORT + 1;
  9174. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9175. ASSERT_TRUE(ssl_svr1.is_valid());
  9176. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9177. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9178. "/index");
  9179. ssl_svr1.stop();
  9180. });
  9181. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9182. ASSERT_TRUE(ssl_svr2.is_valid());
  9183. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9184. res.set_content("test", "text/plain");
  9185. ssl_svr2.stop();
  9186. });
  9187. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9188. thread t2 =
  9189. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9190. auto se = detail::scope_exit([&] {
  9191. t2.join();
  9192. t.join();
  9193. ASSERT_FALSE(ssl_svr1.is_running());
  9194. });
  9195. ssl_svr1.wait_until_ready();
  9196. ssl_svr2.wait_until_ready();
  9197. SSLClient cli("127.0.0.1", PORT);
  9198. std::string cert;
  9199. read_file(SERVER_CERT2_FILE, cert);
  9200. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9201. cli.enable_server_certificate_verification(true);
  9202. cli.set_follow_location(true);
  9203. cli.set_connection_timeout(30);
  9204. auto res = cli.Get("/index");
  9205. ASSERT_TRUE(res);
  9206. ASSERT_EQ(StatusCode::OK_200, res->status);
  9207. }
  9208. #endif
  9209. #ifdef CPPHTTPLIB_SSL_ENABLED
  9210. // Test that set_ca_cert_store() skips system certs (consistent with
  9211. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9212. // should be trusted - system certs should NOT be loaded.
  9213. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9214. // Load a specific cert that is NOT a system CA cert
  9215. std::string cert;
  9216. read_file(SERVER_CERT2_FILE, cert);
  9217. SSLClient cli("google.com");
  9218. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9219. cli.enable_server_certificate_verification(true);
  9220. // This should FAIL because:
  9221. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9222. // 2. System certs should NOT be loaded when custom store is set
  9223. // If system certs WERE loaded, this would succeed
  9224. auto res = cli.Get("/");
  9225. ASSERT_FALSE(res);
  9226. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9227. }
  9228. TEST(MultipartFormDataTest, LargeData) {
  9229. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9230. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9231. const ContentReader &content_reader) {
  9232. if (req.is_multipart_form_data()) {
  9233. std::vector<FormData> items;
  9234. content_reader(
  9235. [&](const FormData &file) {
  9236. items.push_back(file);
  9237. return true;
  9238. },
  9239. [&](const char *data, size_t data_length) {
  9240. items.back().content.append(data, data_length);
  9241. return true;
  9242. });
  9243. EXPECT_TRUE(std::string(items[0].name) == "document");
  9244. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9245. EXPECT_TRUE(items[0].filename == "2MB_data");
  9246. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9247. EXPECT_TRUE(items[1].name == "hello");
  9248. EXPECT_TRUE(items[1].content == "world");
  9249. EXPECT_TRUE(items[1].filename == "");
  9250. EXPECT_TRUE(items[1].content_type == "");
  9251. } else {
  9252. std::string body;
  9253. content_reader([&](const char *data, size_t data_length) {
  9254. body.append(data, data_length);
  9255. return true;
  9256. });
  9257. }
  9258. });
  9259. auto port = svr.bind_to_any_port(HOST);
  9260. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9261. auto se = detail::scope_exit([&] {
  9262. svr.stop();
  9263. t.join();
  9264. ASSERT_FALSE(svr.is_running());
  9265. });
  9266. svr.wait_until_ready();
  9267. {
  9268. std::string data(1024 * 1024 * 2, '.');
  9269. std::stringstream buffer;
  9270. buffer << data;
  9271. SSLClient cli(HOST, port);
  9272. cli.enable_server_certificate_verification(false);
  9273. UploadFormDataItems items{
  9274. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9275. {"hello", "world", "", ""},
  9276. };
  9277. auto res = cli.Post("/post", items);
  9278. ASSERT_TRUE(res);
  9279. ASSERT_EQ(StatusCode::OK_200, res->status);
  9280. }
  9281. }
  9282. TEST(MultipartFormDataTest, DataProviderItems) {
  9283. std::random_device seed_gen;
  9284. std::mt19937 random(seed_gen());
  9285. std::string rand1;
  9286. rand1.resize(1000);
  9287. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9288. std::string rand2;
  9289. rand2.resize(3000);
  9290. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9291. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9292. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9293. const ContentReader &content_reader) {
  9294. ASSERT_FALSE(req.is_multipart_form_data());
  9295. std::string body;
  9296. content_reader([&](const char *data, size_t data_length) {
  9297. body.append(data, data_length);
  9298. return true;
  9299. });
  9300. EXPECT_EQ(body, "");
  9301. });
  9302. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9303. const ContentReader &content_reader) {
  9304. ASSERT_TRUE(req.is_multipart_form_data());
  9305. std::vector<FormData> items;
  9306. content_reader(
  9307. [&](const FormData &file) {
  9308. items.push_back(file);
  9309. return true;
  9310. },
  9311. [&](const char *data, size_t data_length) {
  9312. items.back().content.append(data, data_length);
  9313. return true;
  9314. });
  9315. ASSERT_TRUE(items.size() == 2);
  9316. EXPECT_EQ(std::string(items[0].name), "name1");
  9317. EXPECT_EQ(items[0].content, "Testing123");
  9318. EXPECT_EQ(items[0].filename, "filename1");
  9319. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9320. EXPECT_EQ(items[1].name, "name2");
  9321. EXPECT_EQ(items[1].content, "Testing456");
  9322. EXPECT_EQ(items[1].filename, "");
  9323. EXPECT_EQ(items[1].content_type, "");
  9324. });
  9325. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9326. const ContentReader &content_reader) {
  9327. ASSERT_TRUE(req.is_multipart_form_data());
  9328. std::vector<FormData> items;
  9329. content_reader(
  9330. [&](const FormData &file) {
  9331. items.push_back(file);
  9332. return true;
  9333. },
  9334. [&](const char *data, size_t data_length) {
  9335. items.back().content.append(data, data_length);
  9336. return true;
  9337. });
  9338. ASSERT_TRUE(items.size() == 2);
  9339. EXPECT_EQ(items[0].name, "name3");
  9340. EXPECT_EQ(items[0].content, rand1);
  9341. EXPECT_EQ(items[0].filename, "filename3");
  9342. EXPECT_EQ(items[0].content_type, "");
  9343. EXPECT_EQ(items[1].name, "name4");
  9344. EXPECT_EQ(items[1].content, rand2);
  9345. EXPECT_EQ(items[1].filename, "filename4");
  9346. EXPECT_EQ(items[1].content_type, "");
  9347. });
  9348. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9349. const ContentReader &content_reader) {
  9350. ASSERT_TRUE(req.is_multipart_form_data());
  9351. std::vector<FormData> items;
  9352. content_reader(
  9353. [&](const FormData &file) {
  9354. items.push_back(file);
  9355. return true;
  9356. },
  9357. [&](const char *data, size_t data_length) {
  9358. items.back().content.append(data, data_length);
  9359. return true;
  9360. });
  9361. ASSERT_TRUE(items.size() == 4);
  9362. EXPECT_EQ(std::string(items[0].name), "name1");
  9363. EXPECT_EQ(items[0].content, "Testing123");
  9364. EXPECT_EQ(items[0].filename, "filename1");
  9365. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9366. EXPECT_EQ(items[1].name, "name2");
  9367. EXPECT_EQ(items[1].content, "Testing456");
  9368. EXPECT_EQ(items[1].filename, "");
  9369. EXPECT_EQ(items[1].content_type, "");
  9370. EXPECT_EQ(items[2].name, "name3");
  9371. EXPECT_EQ(items[2].content, rand1);
  9372. EXPECT_EQ(items[2].filename, "filename3");
  9373. EXPECT_EQ(items[2].content_type, "");
  9374. EXPECT_EQ(items[3].name, "name4");
  9375. EXPECT_EQ(items[3].content, rand2);
  9376. EXPECT_EQ(items[3].filename, "filename4");
  9377. EXPECT_EQ(items[3].content_type, "");
  9378. });
  9379. auto port = svr.bind_to_any_port("localhost");
  9380. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9381. auto se = detail::scope_exit([&] {
  9382. svr.stop();
  9383. t.join();
  9384. ASSERT_FALSE(svr.is_running());
  9385. });
  9386. svr.wait_until_ready();
  9387. {
  9388. SSLClient cli("localhost", port);
  9389. cli.enable_server_certificate_verification(false);
  9390. UploadFormDataItems items{
  9391. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9392. {"name2", "Testing456", "", ""}, // not a file
  9393. };
  9394. {
  9395. auto res = cli.Post("/post-none", {}, {}, {});
  9396. ASSERT_TRUE(res);
  9397. ASSERT_EQ(StatusCode::OK_200, res->status);
  9398. }
  9399. FormDataProviderItems providers;
  9400. {
  9401. auto res =
  9402. cli.Post("/post-items", {}, items, providers); // empty providers
  9403. ASSERT_TRUE(res);
  9404. ASSERT_EQ(StatusCode::OK_200, res->status);
  9405. }
  9406. providers.push_back({"name3",
  9407. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9408. // test the offset is given correctly at each step
  9409. if (!offset)
  9410. sink.os.write(rand1.data(), 30);
  9411. else if (offset == 30)
  9412. sink.os.write(rand1.data() + 30, 300);
  9413. else if (offset == 330)
  9414. sink.os.write(rand1.data() + 330, 670);
  9415. else if (offset == rand1.size())
  9416. sink.done();
  9417. return true;
  9418. },
  9419. "filename3",
  9420. {}});
  9421. providers.push_back({"name4",
  9422. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9423. // test the offset is given correctly at each step
  9424. if (!offset)
  9425. sink.os.write(rand2.data(), 2000);
  9426. else if (offset == 2000)
  9427. sink.os.write(rand2.data() + 2000, 1);
  9428. else if (offset == 2001)
  9429. sink.os.write(rand2.data() + 2001, 999);
  9430. else if (offset == rand2.size())
  9431. sink.done();
  9432. return true;
  9433. },
  9434. "filename4",
  9435. {}});
  9436. {
  9437. auto res = cli.Post("/post-providers", {}, {}, providers);
  9438. ASSERT_TRUE(res);
  9439. ASSERT_EQ(StatusCode::OK_200, res->status);
  9440. }
  9441. {
  9442. auto res = cli.Post("/post-both", {}, items, providers);
  9443. ASSERT_TRUE(res);
  9444. ASSERT_EQ(StatusCode::OK_200, res->status);
  9445. }
  9446. }
  9447. }
  9448. TEST(MultipartFormDataTest, BadHeader) {
  9449. Server svr;
  9450. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9451. res.set_content("ok", "text/plain");
  9452. });
  9453. thread t = thread([&] { svr.listen(HOST, PORT); });
  9454. auto se = detail::scope_exit([&] {
  9455. svr.stop();
  9456. t.join();
  9457. ASSERT_FALSE(svr.is_running());
  9458. });
  9459. svr.wait_until_ready();
  9460. const std::string body =
  9461. "This is the preamble. It is to be ignored, though it\r\n"
  9462. "is a handy place for composition agents to include an\r\n"
  9463. "explanatory note to non-MIME conformant readers.\r\n"
  9464. "\r\n"
  9465. "\r\n"
  9466. "--simple boundary\r\n"
  9467. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9468. ": BAD...\r\n"
  9469. "\r\n"
  9470. "value1\r\n"
  9471. "--simple boundary\r\n"
  9472. "Content-Disposition: form-data; name=\"field2\"; "
  9473. "filename=\"example.txt\"\r\n"
  9474. "\r\n"
  9475. "value2\r\n"
  9476. "--simple boundary--\r\n"
  9477. "This is the epilogue. It is also to be ignored.\r\n";
  9478. std::string content_type =
  9479. R"(multipart/form-data; boundary="simple boundary")";
  9480. Client cli(HOST, PORT);
  9481. auto res = cli.Post("/post", body, content_type.c_str());
  9482. ASSERT_TRUE(res);
  9483. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9484. }
  9485. TEST(MultipartFormDataTest, WithPreamble) {
  9486. Server svr;
  9487. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9488. res.set_content("ok", "text/plain");
  9489. });
  9490. thread t = thread([&] { svr.listen(HOST, PORT); });
  9491. auto se = detail::scope_exit([&] {
  9492. svr.stop();
  9493. t.join();
  9494. ASSERT_FALSE(svr.is_running());
  9495. });
  9496. svr.wait_until_ready();
  9497. const std::string body =
  9498. "This is the preamble. It is to be ignored, though it\r\n"
  9499. "is a handy place for composition agents to include an\r\n"
  9500. "explanatory note to non-MIME conformant readers.\r\n"
  9501. "\r\n"
  9502. "\r\n"
  9503. "--simple boundary\r\n"
  9504. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9505. "\r\n"
  9506. "value1\r\n"
  9507. "--simple boundary\r\n"
  9508. "Content-Disposition: form-data; name=\"field2\"; "
  9509. "filename=\"example.txt\"\r\n"
  9510. "\r\n"
  9511. "value2\r\n"
  9512. "--simple boundary--\r\n"
  9513. "This is the epilogue. It is also to be ignored.\r\n";
  9514. std::string content_type =
  9515. R"(multipart/form-data; boundary="simple boundary")";
  9516. Client cli(HOST, PORT);
  9517. auto res = cli.Post("/post", body, content_type.c_str());
  9518. ASSERT_TRUE(res);
  9519. EXPECT_EQ(StatusCode::OK_200, res->status);
  9520. }
  9521. TEST(MultipartFormDataTest, PostCustomBoundary) {
  9522. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9523. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  9524. const ContentReader &content_reader) {
  9525. if (req.is_multipart_form_data()) {
  9526. std::vector<FormData> items;
  9527. content_reader(
  9528. [&](const FormData &file) {
  9529. items.push_back(file);
  9530. return true;
  9531. },
  9532. [&](const char *data, size_t data_length) {
  9533. items.back().content.append(data, data_length);
  9534. return true;
  9535. });
  9536. EXPECT_TRUE(std::string(items[0].name) == "document");
  9537. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9538. EXPECT_TRUE(items[0].filename == "2MB_data");
  9539. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9540. EXPECT_TRUE(items[1].name == "hello");
  9541. EXPECT_TRUE(items[1].content == "world");
  9542. EXPECT_TRUE(items[1].filename == "");
  9543. EXPECT_TRUE(items[1].content_type == "");
  9544. } else {
  9545. std::string body;
  9546. content_reader([&](const char *data, size_t data_length) {
  9547. body.append(data, data_length);
  9548. return true;
  9549. });
  9550. }
  9551. });
  9552. auto port = svr.bind_to_any_port("localhost");
  9553. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9554. auto se = detail::scope_exit([&] {
  9555. svr.stop();
  9556. t.join();
  9557. ASSERT_FALSE(svr.is_running());
  9558. });
  9559. svr.wait_until_ready();
  9560. {
  9561. std::string data(1024 * 1024 * 2, '.');
  9562. std::stringstream buffer;
  9563. buffer << data;
  9564. SSLClient cli("localhost", port);
  9565. cli.enable_server_certificate_verification(false);
  9566. UploadFormDataItems items{
  9567. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9568. {"hello", "world", "", ""},
  9569. };
  9570. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9571. ASSERT_TRUE(res);
  9572. ASSERT_EQ(StatusCode::OK_200, res->status);
  9573. }
  9574. }
  9575. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9576. std::string data(1024 * 1024 * 2, '&');
  9577. std::stringstream buffer;
  9578. buffer << data;
  9579. Client cli("https://localhost:8080");
  9580. UploadFormDataItems items{
  9581. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9582. {"hello", "world", "", ""},
  9583. };
  9584. for (const char &c : " \t\r\n") {
  9585. auto res =
  9586. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9587. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9588. ASSERT_FALSE(res);
  9589. }
  9590. }
  9591. TEST(MultipartFormDataTest, PutFormData) {
  9592. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9593. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9594. const ContentReader &content_reader) {
  9595. if (req.is_multipart_form_data()) {
  9596. std::vector<FormData> items;
  9597. content_reader(
  9598. [&](const FormData &file) {
  9599. items.push_back(file);
  9600. return true;
  9601. },
  9602. [&](const char *data, size_t data_length) {
  9603. items.back().content.append(data, data_length);
  9604. return true;
  9605. });
  9606. EXPECT_TRUE(std::string(items[0].name) == "document");
  9607. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9608. EXPECT_TRUE(items[0].filename == "2MB_data");
  9609. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9610. EXPECT_TRUE(items[1].name == "hello");
  9611. EXPECT_TRUE(items[1].content == "world");
  9612. EXPECT_TRUE(items[1].filename == "");
  9613. EXPECT_TRUE(items[1].content_type == "");
  9614. } else {
  9615. std::string body;
  9616. content_reader([&](const char *data, size_t data_length) {
  9617. body.append(data, data_length);
  9618. return true;
  9619. });
  9620. }
  9621. });
  9622. auto port = svr.bind_to_any_port("localhost");
  9623. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9624. auto se = detail::scope_exit([&] {
  9625. svr.stop();
  9626. t.join();
  9627. ASSERT_FALSE(svr.is_running());
  9628. });
  9629. svr.wait_until_ready();
  9630. {
  9631. std::string data(1024 * 1024 * 2, '&');
  9632. std::stringstream buffer;
  9633. buffer << data;
  9634. SSLClient cli("localhost", port);
  9635. cli.enable_server_certificate_verification(false);
  9636. UploadFormDataItems items{
  9637. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9638. {"hello", "world", "", ""},
  9639. };
  9640. auto res = cli.Put("/put", items);
  9641. ASSERT_TRUE(res);
  9642. ASSERT_EQ(StatusCode::OK_200, res->status);
  9643. }
  9644. }
  9645. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  9646. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9647. svr.Put("/put_customboundary",
  9648. [&](const Request &req, const Response & /*res*/,
  9649. const ContentReader &content_reader) {
  9650. if (req.is_multipart_form_data()) {
  9651. std::vector<FormData> items;
  9652. content_reader(
  9653. [&](const FormData &file) {
  9654. items.push_back(file);
  9655. return true;
  9656. },
  9657. [&](const char *data, size_t data_length) {
  9658. items.back().content.append(data, data_length);
  9659. return true;
  9660. });
  9661. EXPECT_TRUE(std::string(items[0].name) == "document");
  9662. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9663. EXPECT_TRUE(items[0].filename == "2MB_data");
  9664. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9665. EXPECT_TRUE(items[1].name == "hello");
  9666. EXPECT_TRUE(items[1].content == "world");
  9667. EXPECT_TRUE(items[1].filename == "");
  9668. EXPECT_TRUE(items[1].content_type == "");
  9669. } else {
  9670. std::string body;
  9671. content_reader([&](const char *data, size_t data_length) {
  9672. body.append(data, data_length);
  9673. return true;
  9674. });
  9675. }
  9676. });
  9677. auto port = svr.bind_to_any_port("localhost");
  9678. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9679. auto se = detail::scope_exit([&] {
  9680. svr.stop();
  9681. t.join();
  9682. ASSERT_FALSE(svr.is_running());
  9683. });
  9684. svr.wait_until_ready();
  9685. {
  9686. std::string data(1024 * 1024 * 2, '&');
  9687. std::stringstream buffer;
  9688. buffer << data;
  9689. SSLClient cli("localhost", port);
  9690. cli.enable_server_certificate_verification(false);
  9691. UploadFormDataItems items{
  9692. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9693. {"hello", "world", "", ""},
  9694. };
  9695. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  9696. ASSERT_TRUE(res);
  9697. ASSERT_EQ(StatusCode::OK_200, res->status);
  9698. }
  9699. }
  9700. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  9701. std::string data(1024 * 1024 * 2, '&');
  9702. std::stringstream buffer;
  9703. buffer << data;
  9704. Client cli("https://localhost:8080");
  9705. cli.enable_server_certificate_verification(false);
  9706. UploadFormDataItems items{
  9707. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9708. {"hello", "world", "", ""},
  9709. };
  9710. for (const char &c : " \t\r\n") {
  9711. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  9712. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9713. ASSERT_FALSE(res);
  9714. }
  9715. }
  9716. TEST(MultipartFormDataTest, AlternateFilename) {
  9717. auto handled = false;
  9718. Server svr;
  9719. svr.Post("/test", [&](const Request &req, Response &res) {
  9720. ASSERT_EQ(2u, req.form.files.size());
  9721. ASSERT_EQ(1u, req.form.fields.size());
  9722. // Test files
  9723. const auto &file1 = req.form.get_file("file1");
  9724. ASSERT_EQ("file1", file1.name);
  9725. ASSERT_EQ("A.txt", file1.filename);
  9726. ASSERT_EQ("text/plain", file1.content_type);
  9727. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  9728. const auto &file2 = req.form.get_file("file2");
  9729. ASSERT_EQ("file2", file2.name);
  9730. ASSERT_EQ("a.html", file2.filename);
  9731. ASSERT_EQ("text/html", file2.content_type);
  9732. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  9733. file2.content);
  9734. // Test text field
  9735. const auto &text = req.form.get_field("text");
  9736. ASSERT_EQ("text default", text);
  9737. res.set_content("ok", "text/plain");
  9738. handled = true;
  9739. });
  9740. thread t = thread([&] { svr.listen(HOST, PORT); });
  9741. auto se = detail::scope_exit([&] {
  9742. svr.stop();
  9743. t.join();
  9744. ASSERT_FALSE(svr.is_running());
  9745. ASSERT_TRUE(handled);
  9746. });
  9747. svr.wait_until_ready();
  9748. auto req = "POST /test HTTP/1.1\r\n"
  9749. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9750. "Content-Length: 399\r\n"
  9751. "\r\n"
  9752. "----------\r\n"
  9753. "Content-Disposition: form-data; name=\"text\"\r\n"
  9754. "\r\n"
  9755. "text default\r\n"
  9756. "----------\r\n"
  9757. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  9758. "filename=\"a.txt\"; name=\"file1\"\r\n"
  9759. "Content-Type: text/plain\r\n"
  9760. "\r\n"
  9761. "Content of a.txt.\r\n"
  9762. "\r\n"
  9763. "----------\r\n"
  9764. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  9765. "\"a.html\"\r\n"
  9766. "Content-Type: text/html\r\n"
  9767. "\r\n"
  9768. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  9769. "\r\n"
  9770. "------------\r\n";
  9771. ASSERT_TRUE(send_request(1, req));
  9772. }
  9773. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  9774. auto handled = false;
  9775. Server svr;
  9776. svr.Post("/test", [&](const Request &req, Response &res) {
  9777. // Case-insensitive "utf-8''" prefix with a long value
  9778. const auto &file = req.form.get_file("file1");
  9779. ASSERT_EQ("file1", file.name);
  9780. // 8000 chars exercises both the Content-Disposition parser and the
  9781. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  9782. // Prior to the fix, std::regex_match on this header would cause O(N)
  9783. // stack recursion in libstdc++, leading to SIGSEGV.
  9784. std::string expected_filename(8000, 'A');
  9785. ASSERT_EQ(expected_filename, file.filename);
  9786. res.set_content("ok", "text/plain");
  9787. handled = true;
  9788. });
  9789. thread t = thread([&] { svr.listen(HOST, PORT); });
  9790. auto se = detail::scope_exit([&] {
  9791. svr.stop();
  9792. t.join();
  9793. ASSERT_FALSE(svr.is_running());
  9794. ASSERT_TRUE(handled);
  9795. });
  9796. svr.wait_until_ready();
  9797. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  9798. // Regression test for GHSA-qq6v-r583-3h69
  9799. std::string long_filename(8000, 'A');
  9800. std::string body = "----------\r\n"
  9801. "Content-Disposition: form-data; name=\"file1\"; "
  9802. "filename*=\"Utf-8''" +
  9803. long_filename +
  9804. "\"\r\n"
  9805. "\r\n"
  9806. "hello\r\n"
  9807. "------------\r\n";
  9808. auto req = "POST /test HTTP/1.1\r\n"
  9809. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9810. "Content-Length: " +
  9811. std::to_string(body.size()) + "\r\n\r\n" + body;
  9812. ASSERT_TRUE(send_request(1, req));
  9813. }
  9814. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  9815. auto handled = false;
  9816. Server svr;
  9817. svr.Post("/test", [&](const Request &req, Response &) {
  9818. ASSERT_EQ(2u, req.form.fields.size());
  9819. const auto &text1 = req.form.get_field("text1");
  9820. ASSERT_EQ("text1", text1);
  9821. const auto &text2 = req.form.get_field("text2");
  9822. ASSERT_EQ("text2", text2);
  9823. handled = true;
  9824. });
  9825. thread t = thread([&] { svr.listen(HOST, PORT); });
  9826. auto se = detail::scope_exit([&] {
  9827. svr.stop();
  9828. t.join();
  9829. ASSERT_FALSE(svr.is_running());
  9830. ASSERT_TRUE(handled);
  9831. });
  9832. svr.wait_until_ready();
  9833. auto req = "POST /test HTTP/1.1\r\n"
  9834. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9835. "Content-Length: 146\r\n"
  9836. "\r\n----------\r\n"
  9837. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9838. "\r\n"
  9839. "text1"
  9840. "\r\n----------\r\n"
  9841. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9842. "\r\n"
  9843. "text2"
  9844. "\r\n------------";
  9845. std::string response;
  9846. ASSERT_TRUE(send_request(1, req, &response));
  9847. ASSERT_EQ("200", response.substr(9, 3));
  9848. }
  9849. TEST(MultipartFormDataTest, ContentLength) {
  9850. auto handled = false;
  9851. Server svr;
  9852. svr.Post("/test", [&](const Request &req, Response &) {
  9853. ASSERT_EQ(2u, req.form.fields.size());
  9854. const auto &text1 = req.form.get_field("text1");
  9855. ASSERT_EQ("text1", text1);
  9856. const auto &text2 = req.form.get_field("text2");
  9857. ASSERT_EQ("text2", text2);
  9858. handled = true;
  9859. });
  9860. thread t = thread([&] { svr.listen(HOST, PORT); });
  9861. auto se = detail::scope_exit([&] {
  9862. svr.stop();
  9863. t.join();
  9864. ASSERT_FALSE(svr.is_running());
  9865. ASSERT_TRUE(handled);
  9866. });
  9867. svr.wait_until_ready();
  9868. auto req = "POST /test HTTP/1.1\r\n"
  9869. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9870. "Content-Length: 167\r\n"
  9871. "\r\n----------\r\n"
  9872. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9873. "Content-Length: 5\r\n"
  9874. "\r\n"
  9875. "text1"
  9876. "\r\n----------\r\n"
  9877. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9878. "\r\n"
  9879. "text2"
  9880. "\r\n------------\r\n";
  9881. std::string response;
  9882. ASSERT_TRUE(send_request(1, req, &response));
  9883. ASSERT_EQ("200", response.substr(9, 3));
  9884. }
  9885. TEST(MultipartFormDataTest, AccessPartHeaders) {
  9886. auto handled = false;
  9887. Server svr;
  9888. svr.Post("/test", [&](const Request &req, Response &) {
  9889. ASSERT_EQ(2u, req.form.fields.size());
  9890. const auto &text1 = req.form.get_field("text1");
  9891. ASSERT_EQ("text1", text1);
  9892. // TODO: Add header access for text fields if needed
  9893. const auto &text2 = req.form.get_field("text2");
  9894. ASSERT_EQ("text2", text2);
  9895. // TODO: Header access for text fields needs to be implemented
  9896. // auto &headers = it->second.headers;
  9897. // ASSERT_EQ(3U, headers.size());
  9898. // auto custom_header = headers.find("x-whatever");
  9899. // ASSERT_TRUE(custom_header != headers.end());
  9900. // ASSERT_NE("customvalue", custom_header->second);
  9901. // ASSERT_EQ("CustomValue", custom_header->second);
  9902. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  9903. handled = true;
  9904. });
  9905. thread t = thread([&] { svr.listen(HOST, PORT); });
  9906. auto se = detail::scope_exit([&] {
  9907. svr.stop();
  9908. t.join();
  9909. ASSERT_FALSE(svr.is_running());
  9910. ASSERT_TRUE(handled);
  9911. });
  9912. svr.wait_until_ready();
  9913. auto req = "POST /test HTTP/1.1\r\n"
  9914. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9915. "Content-Length: 232\r\n"
  9916. "\r\n----------\r\n"
  9917. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9918. "Content-Length: 5\r\n"
  9919. "X-Test: 1\r\n"
  9920. "\r\n"
  9921. "text1"
  9922. "\r\n----------\r\n"
  9923. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9924. "Content-Type: text/plain\r\n"
  9925. "X-Whatever: CustomValue\r\n"
  9926. "\r\n"
  9927. "text2"
  9928. "\r\n------------\r\n"
  9929. "That should be disregarded. Not even read";
  9930. std::string response;
  9931. ASSERT_TRUE(send_request(1, req, &response));
  9932. ASSERT_EQ("200", response.substr(9, 3));
  9933. }
  9934. TEST(MultipartFormDataTest, LargeHeader) {
  9935. auto handled = false;
  9936. Server svr;
  9937. svr.Post("/test", [&](const Request &req, Response &) {
  9938. ASSERT_EQ(1u, req.form.fields.size());
  9939. const auto &text = req.form.get_field("name1");
  9940. ASSERT_EQ("text1", text);
  9941. handled = true;
  9942. });
  9943. thread t = thread([&] { svr.listen(HOST, PORT); });
  9944. auto se = detail::scope_exit([&] {
  9945. svr.stop();
  9946. t.join();
  9947. ASSERT_FALSE(svr.is_running());
  9948. ASSERT_TRUE(handled);
  9949. });
  9950. svr.wait_until_ready();
  9951. auto boundary = std::string("cpp-httplib-multipart-data");
  9952. std::string content = "--" + boundary +
  9953. "\r\n"
  9954. "Content-Disposition: form-data; name=\"name1\"\r\n"
  9955. "\r\n"
  9956. "text1\r\n"
  9957. "--" +
  9958. boundary + "--\r\n";
  9959. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  9960. "Content-Type: multipart/form-data;boundary=" +
  9961. boundary +
  9962. "\r\n"
  9963. "Content-Length: " +
  9964. std::to_string(content.size()) +
  9965. "\r\n"
  9966. "Dummy-Header: ";
  9967. std::string header_suffix = "\r\n"
  9968. "\r\n";
  9969. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  9970. size_t header_dummy_size =
  9971. read_buff_size -
  9972. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  9973. auto header_dummy = std::string(header_dummy_size, '@');
  9974. auto req = header_prefix + header_dummy + header_suffix + content;
  9975. std::string response;
  9976. ASSERT_TRUE(send_request(1, req, &response));
  9977. ASSERT_EQ("200", response.substr(9, 3));
  9978. }
  9979. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  9980. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  9981. // (not chunked Transfer-Encoding) after the streaming refactor.
  9982. auto handled = false;
  9983. Server svr;
  9984. svr.Post("/upload", [&](const Request &req, Response &res) {
  9985. auto cl_it = req.headers.find("Content-Length");
  9986. EXPECT_TRUE(cl_it != req.headers.end());
  9987. auto te_it = req.headers.find("Transfer-Encoding");
  9988. EXPECT_TRUE(te_it == req.headers.end());
  9989. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  9990. res.set_content("ok", "text/plain");
  9991. handled = true;
  9992. });
  9993. auto port = svr.bind_to_any_port(HOST);
  9994. auto t = thread([&] { svr.listen_after_bind(); });
  9995. auto se = detail::scope_exit([&] {
  9996. svr.stop();
  9997. t.join();
  9998. ASSERT_FALSE(svr.is_running());
  9999. ASSERT_TRUE(handled);
  10000. });
  10001. svr.wait_until_ready();
  10002. UploadFormDataItems items = {
  10003. {"field1", "hello", "", "text/plain"},
  10004. {"file1", "world", "test.txt", "application/octet-stream"},
  10005. };
  10006. Client cli(HOST, port);
  10007. auto res = cli.Post("/upload", {}, items);
  10008. ASSERT_TRUE(res);
  10009. EXPECT_EQ(StatusCode::OK_200, res->status);
  10010. }
  10011. TEST(MultipartFormDataTest, MakeFileProvider) {
  10012. // Verify make_file_provider sends a file's contents correctly.
  10013. const std::string file_content(4096, 'Z');
  10014. const std::string tmp_path = "/tmp/httplib_test_make_file_provider.bin";
  10015. {
  10016. std::ofstream ofs(tmp_path, std::ios::binary);
  10017. ofs.write(file_content.data(),
  10018. static_cast<std::streamsize>(file_content.size()));
  10019. }
  10020. auto handled = false;
  10021. Server svr;
  10022. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  10023. const ContentReader &content_reader) {
  10024. ASSERT_TRUE(req.is_multipart_form_data());
  10025. std::vector<FormData> items;
  10026. content_reader(
  10027. [&](const FormData &file) {
  10028. items.push_back(file);
  10029. return true;
  10030. },
  10031. [&](const char *data, size_t data_length) {
  10032. items.back().content.append(data, data_length);
  10033. return true;
  10034. });
  10035. ASSERT_EQ(1u, items.size());
  10036. EXPECT_EQ("myfile", items[0].name);
  10037. EXPECT_EQ("data.bin", items[0].filename);
  10038. EXPECT_EQ("application/octet-stream", items[0].content_type);
  10039. EXPECT_EQ(file_content, items[0].content);
  10040. handled = true;
  10041. });
  10042. auto port = svr.bind_to_any_port(HOST);
  10043. auto t = thread([&] { svr.listen_after_bind(); });
  10044. auto se = detail::scope_exit([&] {
  10045. svr.stop();
  10046. t.join();
  10047. ASSERT_FALSE(svr.is_running());
  10048. ASSERT_TRUE(handled);
  10049. std::remove(tmp_path.c_str());
  10050. });
  10051. svr.wait_until_ready();
  10052. FormDataProviderItems providers;
  10053. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  10054. "application/octet-stream"));
  10055. Client cli(HOST, port);
  10056. auto res = cli.Post("/upload", {}, {}, providers);
  10057. ASSERT_TRUE(res);
  10058. EXPECT_EQ(StatusCode::OK_200, res->status);
  10059. }
  10060. TEST(MakeFileBodyTest, Basic) {
  10061. const std::string file_content(4096, 'Z');
  10062. const std::string tmp_path = "/tmp/httplib_test_make_file_body.bin";
  10063. {
  10064. std::ofstream ofs(tmp_path, std::ios::binary);
  10065. ofs.write(file_content.data(),
  10066. static_cast<std::streamsize>(file_content.size()));
  10067. }
  10068. auto handled = false;
  10069. Server svr;
  10070. svr.Post("/upload", [&](const Request &req, Response &res) {
  10071. EXPECT_EQ(file_content, req.body);
  10072. handled = true;
  10073. res.status = StatusCode::OK_200;
  10074. });
  10075. auto port = svr.bind_to_any_port(HOST);
  10076. auto t = thread([&] { svr.listen_after_bind(); });
  10077. auto se = detail::scope_exit([&] {
  10078. svr.stop();
  10079. t.join();
  10080. ASSERT_FALSE(svr.is_running());
  10081. ASSERT_TRUE(handled);
  10082. std::remove(tmp_path.c_str());
  10083. });
  10084. svr.wait_until_ready();
  10085. auto fb = make_file_body(tmp_path);
  10086. ASSERT_GT(fb.first, 0u);
  10087. Client cli(HOST, port);
  10088. auto res =
  10089. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  10090. ASSERT_TRUE(res);
  10091. EXPECT_EQ(StatusCode::OK_200, res->status);
  10092. }
  10093. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  10094. static constexpr unsigned int number_of_tasks{1000000};
  10095. std::atomic_uint count{0};
  10096. std::unique_ptr<TaskQueue> task_queue{
  10097. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  10098. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10099. auto queued = task_queue->enqueue(
  10100. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  10101. EXPECT_TRUE(queued);
  10102. }
  10103. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10104. task_queue->shutdown();
  10105. #else
  10106. EXPECT_NO_THROW(task_queue->shutdown());
  10107. #endif
  10108. EXPECT_EQ(number_of_tasks, count.load());
  10109. }
  10110. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  10111. static constexpr unsigned int number_of_tasks{1000000};
  10112. static constexpr unsigned int qlimit{2};
  10113. unsigned int queued_count{0};
  10114. std::atomic_uint count{0};
  10115. std::unique_ptr<TaskQueue> task_queue{
  10116. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  10117. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10118. if (task_queue->enqueue(
  10119. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  10120. queued_count++;
  10121. }
  10122. }
  10123. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10124. task_queue->shutdown();
  10125. #else
  10126. EXPECT_NO_THROW(task_queue->shutdown());
  10127. #endif
  10128. EXPECT_EQ(queued_count, count.load());
  10129. EXPECT_TRUE(queued_count <= number_of_tasks);
  10130. EXPECT_TRUE(queued_count >= qlimit);
  10131. }
  10132. TEST(TaskQueueTest, MaxQueuedRequests) {
  10133. static constexpr unsigned int qlimit{3};
  10134. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  10135. std::condition_variable sem_cv;
  10136. std::mutex sem_mtx;
  10137. int credits = 0;
  10138. bool queued;
  10139. /* Fill up the queue with tasks that will block until we give them credits to
  10140. * complete. */
  10141. for (unsigned int n = 0; n <= qlimit;) {
  10142. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  10143. std::unique_lock<std::mutex> lock(sem_mtx);
  10144. while (credits <= 0) {
  10145. sem_cv.wait(lock);
  10146. }
  10147. /* Consume the credit and signal the test code if they are all gone. */
  10148. if (--credits == 0) { sem_cv.notify_one(); }
  10149. });
  10150. if (n < qlimit) {
  10151. /* The first qlimit enqueues must succeed. */
  10152. EXPECT_TRUE(queued);
  10153. } else {
  10154. /* The last one will succeed only when the worker thread
  10155. * starts and dequeues the first blocking task. Although
  10156. * not necessary for the correctness of this test, we sleep for
  10157. * a short while to avoid busy waiting. */
  10158. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10159. }
  10160. if (queued) { n++; }
  10161. }
  10162. /* Further enqueues must fail since the queue is full. */
  10163. for (auto i = 0; i < 4; i++) {
  10164. queued = task_queue->enqueue([] {});
  10165. EXPECT_FALSE(queued);
  10166. }
  10167. /* Give the credits to allow the previous tasks to complete. */
  10168. {
  10169. std::unique_lock<std::mutex> lock(sem_mtx);
  10170. credits += qlimit + 1;
  10171. }
  10172. sem_cv.notify_all();
  10173. /* Wait for all the credits to be consumed. */
  10174. {
  10175. std::unique_lock<std::mutex> lock(sem_mtx);
  10176. while (credits > 0) {
  10177. sem_cv.wait(lock);
  10178. }
  10179. }
  10180. /* Check that we are able again to enqueue at least qlimit tasks. */
  10181. for (unsigned int i = 0; i < qlimit; i++) {
  10182. queued = task_queue->enqueue([] {});
  10183. EXPECT_TRUE(queued);
  10184. }
  10185. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10186. task_queue->shutdown();
  10187. #else
  10188. EXPECT_NO_THROW(task_queue->shutdown());
  10189. #endif
  10190. }
  10191. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  10192. Server svr;
  10193. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10194. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  10195. });
  10196. svr.Get("/hello", [](const Request &req, Response &res) {
  10197. res.set_content(req.get_param_value("key"), "text/plain");
  10198. });
  10199. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10200. auto se = detail::scope_exit([&] {
  10201. svr.stop();
  10202. thread.join();
  10203. ASSERT_FALSE(svr.is_running());
  10204. });
  10205. svr.wait_until_ready();
  10206. {
  10207. Client cli(HOST, PORT);
  10208. cli.set_follow_location(true);
  10209. auto res = cli.Get("/");
  10210. ASSERT_TRUE(res);
  10211. EXPECT_EQ(StatusCode::OK_200, res->status);
  10212. EXPECT_EQ("val&key2=val2", res->body);
  10213. }
  10214. }
  10215. #endif
  10216. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  10217. Server svr;
  10218. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10219. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  10220. });
  10221. svr.Get("/hello", [](const Request &req, Response &res) {
  10222. res.set_content(req.get_param_value("key"), "text/plain");
  10223. });
  10224. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10225. auto se = detail::scope_exit([&] {
  10226. svr.stop();
  10227. thread.join();
  10228. ASSERT_FALSE(svr.is_running());
  10229. });
  10230. svr.wait_until_ready();
  10231. {
  10232. Client cli(HOST, PORT);
  10233. cli.set_follow_location(true);
  10234. auto res = cli.Get("/");
  10235. ASSERT_TRUE(res);
  10236. EXPECT_EQ(StatusCode::OK_200, res->status);
  10237. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  10238. }
  10239. }
  10240. #ifdef CPPHTTPLIB_SSL_ENABLED
  10241. TEST(RedirectTest, Issue2185_Online) {
  10242. SSLClient client("github.com");
  10243. client.set_follow_location(true);
  10244. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  10245. "Coollab-Windows.zip");
  10246. ASSERT_TRUE(res);
  10247. EXPECT_EQ(StatusCode::OK_200, res->status);
  10248. EXPECT_EQ(9920427U, res->body.size());
  10249. }
  10250. #endif
  10251. TEST(VulnerabilityTest, CRLFInjection) {
  10252. Server svr;
  10253. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  10254. res.set_content("Hello 1", "text/plain");
  10255. });
  10256. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  10257. res.set_content("Hello 2", "text/plain");
  10258. });
  10259. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  10260. res.set_content("Hello 3", "text/plain");
  10261. });
  10262. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  10263. res.set_content("Hello 4", "text/plain");
  10264. });
  10265. svr.set_logger([](const Request &req, const Response & /*res*/) {
  10266. for (const auto &x : req.headers) {
  10267. auto key = x.first;
  10268. EXPECT_STRNE("evil", key.c_str());
  10269. }
  10270. });
  10271. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10272. auto se = detail::scope_exit([&] {
  10273. svr.stop();
  10274. thread.join();
  10275. ASSERT_FALSE(svr.is_running());
  10276. });
  10277. svr.wait_until_ready();
  10278. {
  10279. Client cli(HOST, PORT);
  10280. cli.Post("/test1", "A=B",
  10281. "application/x-www-form-urlencoded\r\nevil: hello1");
  10282. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  10283. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  10284. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  10285. }
  10286. }
  10287. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  10288. auto server_thread = std::thread([] {
  10289. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10290. default_socket_options(srv);
  10291. sockaddr_in addr{};
  10292. addr.sin_family = AF_INET;
  10293. addr.sin_port = htons(PORT + 1);
  10294. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10295. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10296. ::listen(srv, 1);
  10297. sockaddr_in cli_addr{};
  10298. socklen_t cli_len = sizeof(cli_addr);
  10299. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10300. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  10301. std::string buf_all;
  10302. char buf[2048];
  10303. ssize_t n;
  10304. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  10305. buf_all.append(buf, static_cast<size_t>(n));
  10306. size_t pos;
  10307. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  10308. auto request_block = buf_all.substr(0, pos + 4); // include separator
  10309. auto e = request_block.find("\r\n");
  10310. if (e != std::string::npos) {
  10311. auto request_line = request_block.substr(0, e);
  10312. std::string msg =
  10313. "CRLF injection detected in request line: '" + request_line + "'";
  10314. EXPECT_FALSE(true) << msg;
  10315. }
  10316. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  10317. ::send(cli,
  10318. #ifdef _WIN32
  10319. static_cast<const char *>(resp.c_str()),
  10320. static_cast<int>(resp.size()),
  10321. #else
  10322. resp.c_str(), resp.size(),
  10323. #endif
  10324. 0);
  10325. buf_all.erase(0, pos + 4);
  10326. }
  10327. }
  10328. detail::close_socket(cli);
  10329. detail::close_socket(srv);
  10330. });
  10331. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10332. auto cli = Client("127.0.0.1", PORT + 1);
  10333. auto headers = Headers{
  10334. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  10335. {"Connection", "keep-alive"}};
  10336. auto res = cli.Get("/hi", headers);
  10337. EXPECT_FALSE(res);
  10338. EXPECT_EQ(Error::InvalidHeaders, res.error());
  10339. server_thread.join();
  10340. }
  10341. TEST(PathParamsTest, StaticMatch) {
  10342. const auto pattern = "/users/all";
  10343. detail::PathParamsMatcher matcher(pattern);
  10344. Request request;
  10345. request.path = "/users/all";
  10346. ASSERT_TRUE(matcher.match(request));
  10347. std::unordered_map<std::string, std::string> expected_params = {};
  10348. EXPECT_EQ(request.path_params, expected_params);
  10349. }
  10350. TEST(PathParamsTest, StaticMismatch) {
  10351. const auto pattern = "/users/all";
  10352. detail::PathParamsMatcher matcher(pattern);
  10353. Request request;
  10354. request.path = "/users/1";
  10355. ASSERT_FALSE(matcher.match(request));
  10356. }
  10357. TEST(PathParamsTest, SingleParamInTheMiddle) {
  10358. const auto pattern = "/users/:id/subscriptions";
  10359. detail::PathParamsMatcher matcher(pattern);
  10360. Request request;
  10361. request.path = "/users/42/subscriptions";
  10362. ASSERT_TRUE(matcher.match(request));
  10363. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10364. EXPECT_EQ(request.path_params, expected_params);
  10365. }
  10366. TEST(PathParamsTest, SingleParamInTheEnd) {
  10367. const auto pattern = "/users/:id";
  10368. detail::PathParamsMatcher matcher(pattern);
  10369. Request request;
  10370. request.path = "/users/24";
  10371. ASSERT_TRUE(matcher.match(request));
  10372. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  10373. EXPECT_EQ(request.path_params, expected_params);
  10374. }
  10375. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  10376. const auto pattern = "/users/:id/";
  10377. detail::PathParamsMatcher matcher(pattern);
  10378. Request request;
  10379. request.path = "/users/42/";
  10380. ASSERT_TRUE(matcher.match(request));
  10381. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10382. EXPECT_EQ(request.path_params, expected_params);
  10383. }
  10384. TEST(PathParamsTest, EmptyParam) {
  10385. const auto pattern = "/users/:id/";
  10386. detail::PathParamsMatcher matcher(pattern);
  10387. Request request;
  10388. request.path = "/users//";
  10389. ASSERT_TRUE(matcher.match(request));
  10390. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10391. EXPECT_EQ(request.path_params, expected_params);
  10392. }
  10393. TEST(PathParamsTest, FragmentMismatch) {
  10394. const auto pattern = "/users/:id/";
  10395. detail::PathParamsMatcher matcher(pattern);
  10396. Request request;
  10397. request.path = "/admins/24/";
  10398. ASSERT_FALSE(matcher.match(request));
  10399. }
  10400. TEST(PathParamsTest, ExtraFragments) {
  10401. const auto pattern = "/users/:id";
  10402. detail::PathParamsMatcher matcher(pattern);
  10403. Request request;
  10404. request.path = "/users/42/subscriptions";
  10405. ASSERT_FALSE(matcher.match(request));
  10406. }
  10407. TEST(PathParamsTest, MissingTrailingParam) {
  10408. const auto pattern = "/users/:id";
  10409. detail::PathParamsMatcher matcher(pattern);
  10410. Request request;
  10411. request.path = "/users";
  10412. ASSERT_FALSE(matcher.match(request));
  10413. }
  10414. TEST(PathParamsTest, MissingParamInTheMiddle) {
  10415. const auto pattern = "/users/:id/subscriptions";
  10416. detail::PathParamsMatcher matcher(pattern);
  10417. Request request;
  10418. request.path = "/users/subscriptions";
  10419. ASSERT_FALSE(matcher.match(request));
  10420. }
  10421. TEST(PathParamsTest, MultipleParams) {
  10422. const auto pattern = "/users/:userid/subscriptions/:subid";
  10423. detail::PathParamsMatcher matcher(pattern);
  10424. Request request;
  10425. request.path = "/users/42/subscriptions/2";
  10426. ASSERT_TRUE(matcher.match(request));
  10427. std::unordered_map<std::string, std::string> expected_params = {
  10428. {"userid", "42"}, {"subid", "2"}};
  10429. EXPECT_EQ(request.path_params, expected_params);
  10430. }
  10431. TEST(PathParamsTest, SequenceOfParams) {
  10432. const auto pattern = "/values/:x/:y/:z";
  10433. detail::PathParamsMatcher matcher(pattern);
  10434. Request request;
  10435. request.path = "/values/1/2/3";
  10436. ASSERT_TRUE(matcher.match(request));
  10437. std::unordered_map<std::string, std::string> expected_params = {
  10438. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  10439. EXPECT_EQ(request.path_params, expected_params);
  10440. }
  10441. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  10442. const auto pattern = "/prefix:suffix";
  10443. detail::PathParamsMatcher matcher(pattern);
  10444. Request request;
  10445. request.path = "/prefix:suffix";
  10446. ASSERT_TRUE(matcher.match(request));
  10447. const std::unordered_map<std::string, std::string> expected_params = {};
  10448. EXPECT_EQ(request.path_params, expected_params);
  10449. }
  10450. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  10451. // If ipv6 regex working, regex match codepath is taken.
  10452. // else port will default to 80 in Client impl
  10453. int clientImplMagicPort = 80;
  10454. int port = 4321;
  10455. // above ports must be different to avoid false negative
  10456. EXPECT_NE(clientImplMagicPort, port);
  10457. std::string ipV6TestURL = "http://[ff06::c3]";
  10458. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  10459. CLIENT_PRIVATE_KEY_FILE);
  10460. EXPECT_EQ(cli.port(), port);
  10461. }
  10462. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  10463. auto file_path = "./www/dir/index.html";
  10464. auto dir_path = "./www/dir";
  10465. detail::FileStat stat_file(file_path);
  10466. EXPECT_TRUE(stat_file.is_file());
  10467. EXPECT_FALSE(stat_file.is_dir());
  10468. detail::FileStat stat_dir(dir_path);
  10469. EXPECT_FALSE(stat_dir.is_file());
  10470. EXPECT_TRUE(stat_dir.is_dir());
  10471. }
  10472. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  10473. // IPv4 with default HTTP port (80)
  10474. EXPECT_EQ("example.com",
  10475. detail::make_host_and_port_string("example.com", 80, false));
  10476. // IPv4 with default HTTPS port (443)
  10477. EXPECT_EQ("example.com",
  10478. detail::make_host_and_port_string("example.com", 443, true));
  10479. // IPv4 with non-default HTTP port
  10480. EXPECT_EQ("example.com:8080",
  10481. detail::make_host_and_port_string("example.com", 8080, false));
  10482. // IPv4 with non-default HTTPS port
  10483. EXPECT_EQ("example.com:8443",
  10484. detail::make_host_and_port_string("example.com", 8443, true));
  10485. // IPv6 with default HTTP port (80)
  10486. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  10487. // IPv6 with default HTTPS port (443)
  10488. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  10489. // IPv6 with non-default HTTP port
  10490. EXPECT_EQ("[::1]:8080",
  10491. detail::make_host_and_port_string("::1", 8080, false));
  10492. // IPv6 with non-default HTTPS port
  10493. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  10494. // IPv6 full address with default port
  10495. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  10496. detail::make_host_and_port_string(
  10497. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  10498. // IPv6 full address with non-default port
  10499. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  10500. detail::make_host_and_port_string(
  10501. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  10502. // IPv6 localhost with non-default port
  10503. EXPECT_EQ("[::1]:3000",
  10504. detail::make_host_and_port_string("::1", 3000, false));
  10505. // IPv6 with zone ID (link-local address) with default port
  10506. EXPECT_EQ("[fe80::1%eth0]",
  10507. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  10508. // IPv6 with zone ID (link-local address) with non-default port
  10509. EXPECT_EQ("[fe80::1%eth0]:8080",
  10510. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  10511. // Edge case: Port 443 with is_ssl=false (should add port)
  10512. EXPECT_EQ("example.com:443",
  10513. detail::make_host_and_port_string("example.com", 443, false));
  10514. // Edge case: Port 80 with is_ssl=true (should add port)
  10515. EXPECT_EQ("example.com:80",
  10516. detail::make_host_and_port_string("example.com", 80, true));
  10517. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  10518. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  10519. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  10520. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  10521. // Security fix: Already bracketed IPv6 should not get double brackets
  10522. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  10523. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  10524. EXPECT_EQ("[::1]:8080",
  10525. detail::make_host_and_port_string("[::1]", 8080, false));
  10526. EXPECT_EQ("[2001:db8::1]:8080",
  10527. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  10528. EXPECT_EQ("[fe80::1%eth0]",
  10529. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  10530. EXPECT_EQ("[fe80::1%eth0]:8080",
  10531. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  10532. // Edge case: Empty host (should return as-is)
  10533. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  10534. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  10535. // This is a known limitation but shouldn't crash
  10536. EXPECT_EQ("[host:name]",
  10537. detail::make_host_and_port_string("host:name", 80, false));
  10538. // Port number edge cases (no validation, but should not crash)
  10539. EXPECT_EQ("example.com:0",
  10540. detail::make_host_and_port_string("example.com", 0, false));
  10541. EXPECT_EQ("example.com:-1",
  10542. detail::make_host_and_port_string("example.com", -1, false));
  10543. EXPECT_EQ("example.com:65535",
  10544. detail::make_host_and_port_string("example.com", 65535, false));
  10545. EXPECT_EQ("example.com:65536",
  10546. detail::make_host_and_port_string("example.com", 65536, false));
  10547. }
  10548. #ifdef CPPHTTPLIB_SSL_ENABLED
  10549. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  10550. httplib::SSLClient cli("roblox.com", 443);
  10551. cli.set_follow_location(true);
  10552. auto res = cli.Get("/");
  10553. ASSERT_TRUE(res);
  10554. EXPECT_EQ(StatusCode::OK_200, res->status);
  10555. }
  10556. #endif
  10557. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  10558. Server svr;
  10559. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10560. EXPECT_EQ(res.status, 400);
  10561. });
  10562. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10563. auto se = detail::scope_exit([&] {
  10564. svr.stop();
  10565. thread.join();
  10566. ASSERT_FALSE(svr.is_running());
  10567. });
  10568. svr.wait_until_ready();
  10569. Client cli(HOST, PORT);
  10570. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  10571. }
  10572. TEST(InvalidHeaderCharsTest, is_field_name) {
  10573. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  10574. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  10575. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  10576. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  10577. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  10578. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  10579. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  10580. EXPECT_FALSE(detail::fields::is_field_name(""));
  10581. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  10582. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  10583. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  10584. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  10585. }
  10586. TEST(InvalidHeaderCharsTest, is_field_value) {
  10587. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  10588. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  10589. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  10590. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  10591. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  10592. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  10593. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  10594. EXPECT_TRUE(detail::fields::is_field_value(""));
  10595. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  10596. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  10597. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  10598. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  10599. EXPECT_TRUE(detail::fields::is_field_value("0"));
  10600. }
  10601. TEST(InvalidHeaderCharsTest, OnServer) {
  10602. Server svr;
  10603. svr.Get("/test_name", [&](const Request &req, Response &res) {
  10604. std::string header = "Not Set";
  10605. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10606. res.set_header(header, "value");
  10607. res.set_content("Page Content Page Content", "text/plain");
  10608. });
  10609. svr.Get("/test_value", [&](const Request &req, Response &res) {
  10610. std::string header = "Not Set";
  10611. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10612. res.set_header("X-Test", header);
  10613. res.set_content("Page Content Page Content", "text/plain");
  10614. });
  10615. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10616. auto se = detail::scope_exit([&] {
  10617. svr.stop();
  10618. thread.join();
  10619. ASSERT_FALSE(svr.is_running());
  10620. });
  10621. svr.wait_until_ready();
  10622. Client cli(HOST, PORT);
  10623. {
  10624. auto res = cli.Get(
  10625. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10626. ASSERT_TRUE(res);
  10627. EXPECT_EQ("Page Content Page Content", res->body);
  10628. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10629. }
  10630. {
  10631. auto res = cli.Get(
  10632. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10633. ASSERT_TRUE(res);
  10634. EXPECT_EQ("Page Content Page Content", res->body);
  10635. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10636. }
  10637. }
  10638. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  10639. auto handled = false;
  10640. Server svr;
  10641. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10642. thread t = thread([&] { svr.listen(HOST, PORT); });
  10643. auto se = detail::scope_exit([&] {
  10644. svr.stop();
  10645. t.join();
  10646. ASSERT_FALSE(svr.is_running());
  10647. ASSERT_FALSE(handled);
  10648. });
  10649. svr.wait_until_ready();
  10650. auto req = "POST /test HTTP/1.1\r\n"
  10651. "Content-Length: x\r\n"
  10652. "\r\n";
  10653. std::string response;
  10654. ASSERT_TRUE(send_request(1, req, &response));
  10655. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10656. response.substr(0, response.find("\r\n")));
  10657. }
  10658. #ifndef _WIN32
  10659. TEST(Expect100ContinueTest, ServerClosesConnection) {
  10660. static constexpr char reject[] = "Unauthorized";
  10661. static constexpr char accept[] = "Upload accepted";
  10662. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  10663. Server svr;
  10664. svr.set_expect_100_continue_handler(
  10665. [](const Request & /*req*/, Response &res) {
  10666. res.status = StatusCode::Unauthorized_401;
  10667. res.set_content(reject, "text/plain");
  10668. return res.status;
  10669. });
  10670. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  10671. res.set_content(accept, "text/plain");
  10672. });
  10673. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10674. auto se = detail::scope_exit([&] {
  10675. svr.stop();
  10676. thread.join();
  10677. ASSERT_FALSE(svr.is_running());
  10678. });
  10679. svr.wait_until_ready();
  10680. {
  10681. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  10682. curl_easy_init(), &curl_easy_cleanup};
  10683. ASSERT_NE(curl, nullptr);
  10684. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  10685. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  10686. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  10687. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  10688. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  10689. &curl_slist_free_all};
  10690. ASSERT_NE(list, nullptr);
  10691. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  10692. struct read_data {
  10693. size_t read_size;
  10694. size_t total_size;
  10695. } data = {0, total_size};
  10696. using read_callback_t =
  10697. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10698. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  10699. void *userdata) -> size_t {
  10700. read_data *data = (read_data *)userdata;
  10701. if (!userdata || data->read_size >= data->total_size) { return 0; }
  10702. std::fill_n(ptr, size * nmemb, 'A');
  10703. data->read_size += size * nmemb;
  10704. return size * nmemb;
  10705. };
  10706. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  10707. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  10708. std::vector<char> buffer;
  10709. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  10710. using write_callback_t =
  10711. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10712. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  10713. void *userdata) -> size_t {
  10714. std::vector<char> *buffer = (std::vector<char> *)userdata;
  10715. buffer->reserve(buffer->size() + size * nmemb + 1);
  10716. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  10717. return size * nmemb;
  10718. };
  10719. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  10720. {
  10721. const auto res = curl_easy_perform(curl.get());
  10722. ASSERT_EQ(res, CURLE_OK);
  10723. }
  10724. {
  10725. auto response_code = long{};
  10726. const auto res =
  10727. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  10728. ASSERT_EQ(res, CURLE_OK);
  10729. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  10730. }
  10731. {
  10732. auto dl = curl_off_t{};
  10733. const auto res =
  10734. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  10735. ASSERT_EQ(res, CURLE_OK);
  10736. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  10737. }
  10738. {
  10739. buffer.push_back('\0');
  10740. ASSERT_STRCASEEQ(buffer.data(), reject);
  10741. }
  10742. }
  10743. }
  10744. #endif
  10745. template <typename S, typename C>
  10746. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  10747. svr.Get("/stream", [&](const Request &, Response &res) {
  10748. auto data = new std::string("01234567890123456789");
  10749. res.set_content_provider(
  10750. data->size(), "text/plain",
  10751. [&, data](size_t offset, size_t length, DataSink &sink) {
  10752. const size_t DATA_CHUNK_SIZE = 4;
  10753. const auto &d = *data;
  10754. std::this_thread::sleep_for(std::chrono::seconds(1));
  10755. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  10756. return true;
  10757. },
  10758. [data](bool success) {
  10759. EXPECT_FALSE(success);
  10760. delete data;
  10761. });
  10762. });
  10763. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  10764. auto i = new size_t(0);
  10765. res.set_content_provider(
  10766. "text/plain",
  10767. [i](size_t, DataSink &sink) {
  10768. if (*i < 5) {
  10769. std::this_thread::sleep_for(std::chrono::seconds(1));
  10770. sink.write("abcd", 4);
  10771. (*i)++;
  10772. } else {
  10773. sink.done();
  10774. }
  10775. return true;
  10776. },
  10777. [i](bool success) {
  10778. EXPECT_FALSE(success);
  10779. delete i;
  10780. });
  10781. });
  10782. svr.Get("/chunked", [&](const Request &, Response &res) {
  10783. auto i = new size_t(0);
  10784. res.set_chunked_content_provider(
  10785. "text/plain",
  10786. [i](size_t, DataSink &sink) {
  10787. if (*i < 5) {
  10788. std::this_thread::sleep_for(std::chrono::seconds(1));
  10789. sink.os << "abcd";
  10790. (*i)++;
  10791. } else {
  10792. sink.done();
  10793. }
  10794. return true;
  10795. },
  10796. [i](bool success) {
  10797. EXPECT_FALSE(success);
  10798. delete i;
  10799. });
  10800. });
  10801. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10802. auto se = detail::scope_exit([&] {
  10803. svr.stop();
  10804. listen_thread.join();
  10805. ASSERT_FALSE(svr.is_running());
  10806. });
  10807. svr.wait_until_ready();
  10808. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  10809. {
  10810. auto start = std::chrono::steady_clock::now();
  10811. auto res = cli.Get("/stream");
  10812. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10813. std::chrono::steady_clock::now() - start)
  10814. .count();
  10815. ASSERT_FALSE(res);
  10816. EXPECT_EQ(Error::Read, res.error());
  10817. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10818. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10819. }
  10820. {
  10821. auto start = std::chrono::steady_clock::now();
  10822. auto res = cli.Get("/stream_without_length");
  10823. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10824. std::chrono::steady_clock::now() - start)
  10825. .count();
  10826. ASSERT_FALSE(res);
  10827. EXPECT_EQ(Error::Read, res.error());
  10828. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10829. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10830. }
  10831. {
  10832. auto start = std::chrono::steady_clock::now();
  10833. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  10834. EXPECT_EQ("abcd", string(data, data_length));
  10835. return true;
  10836. });
  10837. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10838. std::chrono::steady_clock::now() - start)
  10839. .count();
  10840. ASSERT_FALSE(res);
  10841. EXPECT_EQ(Error::Read, res.error());
  10842. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10843. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10844. }
  10845. }
  10846. TEST(MaxTimeoutTest, ContentStream) {
  10847. time_t timeout = 2000;
  10848. time_t threshold = 200;
  10849. Server svr;
  10850. Client cli("localhost", PORT);
  10851. max_timeout_test(svr, cli, timeout, threshold);
  10852. }
  10853. #ifdef CPPHTTPLIB_SSL_ENABLED
  10854. TEST(MaxTimeoutTest, ContentStreamSSL) {
  10855. time_t timeout = 2000;
  10856. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  10857. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10858. SSLClient cli("localhost", PORT);
  10859. cli.enable_server_certificate_verification(false);
  10860. max_timeout_test(svr, cli, timeout, threshold);
  10861. }
  10862. #endif
  10863. class EventDispatcher {
  10864. public:
  10865. EventDispatcher() {}
  10866. bool wait_event(DataSink *sink) {
  10867. unique_lock<mutex> lk(m_);
  10868. int id = id_;
  10869. // Wait with timeout to prevent hanging if client disconnects
  10870. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  10871. [&] { return cid_ == id; })) {
  10872. return false; // Timeout occurred
  10873. }
  10874. sink->write(message_.data(), message_.size());
  10875. return true;
  10876. }
  10877. void send_event(const string &message) {
  10878. lock_guard<mutex> lk(m_);
  10879. cid_ = id_++;
  10880. message_ = message;
  10881. cv_.notify_all();
  10882. }
  10883. private:
  10884. mutex m_;
  10885. condition_variable cv_;
  10886. atomic_int id_{0};
  10887. atomic_int cid_{-1};
  10888. string message_;
  10889. };
  10890. TEST(ClientInThreadTest, Issue2068) {
  10891. EventDispatcher ed;
  10892. Server svr;
  10893. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  10894. res.set_chunked_content_provider("text/event-stream",
  10895. [&](size_t /*offset*/, DataSink &sink) {
  10896. return ed.wait_event(&sink);
  10897. });
  10898. });
  10899. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10900. svr.wait_until_ready();
  10901. thread event_thread([&] {
  10902. int id = 0;
  10903. while (svr.is_running()) {
  10904. this_thread::sleep_for(chrono::milliseconds(500));
  10905. std::stringstream ss;
  10906. ss << "data: " << id << "\n\n";
  10907. ed.send_event(ss.str());
  10908. id++;
  10909. }
  10910. });
  10911. auto se = detail::scope_exit([&] {
  10912. svr.stop();
  10913. listen_thread.join();
  10914. event_thread.join();
  10915. ASSERT_FALSE(svr.is_running());
  10916. });
  10917. {
  10918. auto client = detail::make_unique<Client>(HOST, PORT);
  10919. client->set_read_timeout(std::chrono::minutes(10));
  10920. std::atomic<bool> stop{false};
  10921. std::thread t([&] {
  10922. client->Get("/event1",
  10923. [&](const char *, size_t) -> bool { return !stop; });
  10924. });
  10925. std::this_thread::sleep_for(std::chrono::seconds(2));
  10926. stop = true;
  10927. client->stop();
  10928. t.join();
  10929. // Reset client after thread has finished
  10930. client.reset();
  10931. }
  10932. }
  10933. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  10934. auto handled = false;
  10935. Server svr;
  10936. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10937. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10938. auto se = detail::scope_exit([&] {
  10939. svr.stop();
  10940. t.join();
  10941. ASSERT_FALSE(svr.is_running());
  10942. ASSERT_FALSE(handled);
  10943. });
  10944. svr.wait_until_ready();
  10945. // Two Content-Length headers with different values — must be rejected
  10946. auto req = "POST /test HTTP/1.1\r\n"
  10947. "Content-Length: 5\r\n"
  10948. "Content-Length: 10\r\n"
  10949. "\r\n"
  10950. "hello";
  10951. std::string response;
  10952. ASSERT_TRUE(send_request(1, req, &response));
  10953. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10954. response.substr(0, response.find("\r\n")));
  10955. }
  10956. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  10957. auto handled = false;
  10958. Server svr;
  10959. svr.Post("/test", [&](const Request &, Response &res) {
  10960. handled = true;
  10961. res.set_content("ok", "text/plain");
  10962. });
  10963. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10964. auto se = detail::scope_exit([&] {
  10965. svr.stop();
  10966. t.join();
  10967. ASSERT_FALSE(svr.is_running());
  10968. ASSERT_TRUE(handled);
  10969. });
  10970. svr.wait_until_ready();
  10971. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  10972. auto req = "POST /test HTTP/1.1\r\n"
  10973. "Content-Length: 5\r\n"
  10974. "Content-Length: 5\r\n"
  10975. "\r\n"
  10976. "hello";
  10977. std::string response;
  10978. ASSERT_TRUE(send_request(1, req, &response));
  10979. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  10980. }
  10981. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  10982. Server svr;
  10983. svr.Get("/", [](const Request &req, Response &res) {
  10984. EXPECT_EQ(2U, req.trailers.size());
  10985. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  10986. // Denied
  10987. EXPECT_FALSE(req.has_trailer("Content-Length"));
  10988. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  10989. // Accepted
  10990. EXPECT_TRUE(req.has_trailer("X-Hello"));
  10991. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  10992. EXPECT_TRUE(req.has_trailer("X-World"));
  10993. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  10994. res.set_content("ok", "text/plain");
  10995. });
  10996. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10997. auto se = detail::scope_exit([&] {
  10998. svr.stop();
  10999. t.join();
  11000. ASSERT_FALSE(svr.is_running());
  11001. });
  11002. svr.wait_until_ready();
  11003. const std::string req = "GET / HTTP/1.1\r\n"
  11004. "Transfer-Encoding: chunked\r\n"
  11005. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  11006. "\r\n"
  11007. "0\r\n"
  11008. "Content-Length: 10\r\n"
  11009. "Host: internal.local\r\n"
  11010. "Content-Type: malicious/content\r\n"
  11011. "Cookie: any\r\n"
  11012. "Set-Cookie: any\r\n"
  11013. "X-Forwarded-For: attacker.com\r\n"
  11014. "X-Real-Ip: 1.1.1.1\r\n"
  11015. "X-Hello: hello\r\n"
  11016. "X-World: world\r\n"
  11017. "\r\n";
  11018. std::string res;
  11019. ASSERT_TRUE(send_request(1, req, &res));
  11020. }
  11021. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  11022. Server svr;
  11023. std::string observed_remote_addr;
  11024. std::string observed_xff;
  11025. svr.Get("/ip", [&](const Request &req, Response &res) {
  11026. observed_remote_addr = req.remote_addr;
  11027. observed_xff = req.get_header_value("X-Forwarded-For");
  11028. res.set_content("ok", "text/plain");
  11029. });
  11030. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11031. auto se = detail::scope_exit([&] {
  11032. svr.stop();
  11033. t.join();
  11034. ASSERT_FALSE(svr.is_running());
  11035. });
  11036. svr.wait_until_ready();
  11037. Client cli(HOST, PORT);
  11038. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  11039. ASSERT_TRUE(res);
  11040. EXPECT_EQ(StatusCode::OK_200, res->status);
  11041. EXPECT_EQ(observed_xff, "203.0.113.66");
  11042. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11043. observed_remote_addr == "127.0.0.1");
  11044. }
  11045. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  11046. Server svr;
  11047. svr.set_trusted_proxies({"203.0.113.66"});
  11048. std::string observed_remote_addr;
  11049. std::string observed_xff;
  11050. svr.Get("/ip", [&](const Request &req, Response &res) {
  11051. observed_remote_addr = req.remote_addr;
  11052. observed_xff = req.get_header_value("X-Forwarded-For");
  11053. res.set_content("ok", "text/plain");
  11054. });
  11055. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11056. auto se = detail::scope_exit([&] {
  11057. svr.stop();
  11058. t.join();
  11059. ASSERT_FALSE(svr.is_running());
  11060. });
  11061. svr.wait_until_ready();
  11062. Client cli(HOST, PORT);
  11063. auto res = cli.Get("/ip");
  11064. ASSERT_TRUE(res);
  11065. EXPECT_EQ(StatusCode::OK_200, res->status);
  11066. EXPECT_EQ(observed_xff, "");
  11067. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11068. observed_remote_addr == "127.0.0.1");
  11069. }
  11070. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  11071. Server svr;
  11072. svr.set_trusted_proxies({"203.0.113.66"});
  11073. std::string observed_remote_addr;
  11074. std::string observed_xff;
  11075. svr.Get("/ip", [&](const Request &req, Response &res) {
  11076. observed_remote_addr = req.remote_addr;
  11077. observed_xff = req.get_header_value("X-Forwarded-For");
  11078. res.set_content("ok", "text/plain");
  11079. });
  11080. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11081. auto se = detail::scope_exit([&] {
  11082. svr.stop();
  11083. t.join();
  11084. ASSERT_FALSE(svr.is_running());
  11085. });
  11086. svr.wait_until_ready();
  11087. Client cli(HOST, PORT);
  11088. auto res =
  11089. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  11090. ASSERT_TRUE(res);
  11091. EXPECT_EQ(StatusCode::OK_200, res->status);
  11092. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  11093. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11094. }
  11095. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  11096. Server svr;
  11097. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  11098. std::string observed_remote_addr;
  11099. std::string observed_xff;
  11100. svr.Get("/ip", [&](const Request &req, Response &res) {
  11101. observed_remote_addr = req.remote_addr;
  11102. observed_xff = req.get_header_value("X-Forwarded-For");
  11103. res.set_content("ok", "text/plain");
  11104. });
  11105. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11106. auto se = detail::scope_exit([&] {
  11107. svr.stop();
  11108. t.join();
  11109. ASSERT_FALSE(svr.is_running());
  11110. });
  11111. svr.wait_until_ready();
  11112. Client cli(HOST, PORT);
  11113. auto res = cli.Get(
  11114. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11115. ASSERT_TRUE(res);
  11116. EXPECT_EQ(StatusCode::OK_200, res->status);
  11117. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11118. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11119. }
  11120. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  11121. Server svr;
  11122. svr.set_trusted_proxies({"192.0.2.45"});
  11123. std::string observed_remote_addr;
  11124. std::string observed_xff;
  11125. svr.Get("/ip", [&](const Request &req, Response &res) {
  11126. observed_remote_addr = req.remote_addr;
  11127. observed_xff = req.get_header_value("X-Forwarded-For");
  11128. res.set_content("ok", "text/plain");
  11129. });
  11130. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11131. auto se = detail::scope_exit([&] {
  11132. svr.stop();
  11133. t.join();
  11134. ASSERT_FALSE(svr.is_running());
  11135. });
  11136. svr.wait_until_ready();
  11137. Client cli(HOST, PORT);
  11138. auto res =
  11139. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  11140. ASSERT_TRUE(res);
  11141. EXPECT_EQ(StatusCode::OK_200, res->status);
  11142. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  11143. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11144. }
  11145. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  11146. Server svr;
  11147. svr.set_trusted_proxies({"192.0.2.45"});
  11148. std::string observed_remote_addr;
  11149. std::string observed_xff;
  11150. svr.Get("/ip", [&](const Request &req, Response &res) {
  11151. observed_remote_addr = req.remote_addr;
  11152. observed_xff = req.get_header_value("X-Forwarded-For");
  11153. res.set_content("ok", "text/plain");
  11154. });
  11155. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11156. auto se = detail::scope_exit([&] {
  11157. svr.stop();
  11158. t.join();
  11159. ASSERT_FALSE(svr.is_running());
  11160. });
  11161. svr.wait_until_ready();
  11162. Client cli(HOST, PORT);
  11163. auto res = cli.Get(
  11164. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11165. ASSERT_TRUE(res);
  11166. EXPECT_EQ(StatusCode::OK_200, res->status);
  11167. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11168. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11169. }
  11170. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  11171. Server svr;
  11172. svr.set_trusted_proxies({"192.0.2.45"});
  11173. std::string observed_remote_addr;
  11174. std::string observed_xff;
  11175. svr.Get("/ip", [&](const Request &req, Response &res) {
  11176. observed_remote_addr = req.remote_addr;
  11177. observed_xff = req.get_header_value("X-Forwarded-For");
  11178. res.set_content("ok", "text/plain");
  11179. });
  11180. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11181. auto se = detail::scope_exit([&] {
  11182. svr.stop();
  11183. t.join();
  11184. ASSERT_FALSE(svr.is_running());
  11185. });
  11186. svr.wait_until_ready();
  11187. std::string raw_req =
  11188. "GET /ip HTTP/1.1\r\n"
  11189. "Host: localhost\r\n"
  11190. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  11191. "Connection: close\r\n"
  11192. "\r\n";
  11193. std::string out;
  11194. ASSERT_TRUE(send_request(5, raw_req, &out));
  11195. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11196. // Header parser trims surrounding whitespace of the header value
  11197. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  11198. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11199. }
  11200. #ifndef _WIN32
  11201. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  11202. Server svr;
  11203. svr.Post("/post", [&](const Request &req, Response &res) {
  11204. res.set_content(req.body, "text/plain");
  11205. });
  11206. svr.Put("/put", [&](const Request &req, Response &res) {
  11207. res.set_content(req.body, "text/plain");
  11208. });
  11209. svr.Patch("/patch", [&](const Request &req, Response &res) {
  11210. res.set_content(req.body, "text/plain");
  11211. });
  11212. svr.Delete("/delete", [&](const Request &req, Response &res) {
  11213. res.set_content(req.body, "text/plain");
  11214. });
  11215. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11216. auto se = detail::scope_exit([&] {
  11217. svr.stop();
  11218. t.join();
  11219. ASSERT_FALSE(svr.is_running());
  11220. });
  11221. svr.wait_until_ready();
  11222. std::string resp;
  11223. // POST without Content-Length
  11224. ASSERT_TRUE(send_request(5,
  11225. "POST /post HTTP/1.1\r\n"
  11226. "Host: localhost\r\n"
  11227. "Connection: close\r\n"
  11228. "\r\n",
  11229. &resp));
  11230. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11231. // PUT without Content-Length
  11232. resp.clear();
  11233. ASSERT_TRUE(send_request(5,
  11234. "PUT /put HTTP/1.1\r\n"
  11235. "Host: localhost\r\n"
  11236. "Connection: close\r\n"
  11237. "\r\n",
  11238. &resp));
  11239. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11240. // PATCH without Content-Length
  11241. resp.clear();
  11242. ASSERT_TRUE(send_request(5,
  11243. "PATCH /patch HTTP/1.1\r\n"
  11244. "Host: localhost\r\n"
  11245. "Connection: close\r\n"
  11246. "\r\n",
  11247. &resp));
  11248. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11249. // DELETE without Content-Length
  11250. resp.clear();
  11251. ASSERT_TRUE(send_request(5,
  11252. "DELETE /delete HTTP/1.1\r\n"
  11253. "Host: localhost\r\n"
  11254. "Connection: close\r\n"
  11255. "\r\n",
  11256. &resp));
  11257. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11258. }
  11259. #endif
  11260. //==============================================================================
  11261. // open_stream() Tests
  11262. //==============================================================================
  11263. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  11264. std::string result;
  11265. char buf[8192];
  11266. ssize_t n;
  11267. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11268. result.append(buf, static_cast<size_t>(n));
  11269. }
  11270. return result;
  11271. }
  11272. // Mock stream for unit tests
  11273. class MockStream : public Stream {
  11274. public:
  11275. std::string data;
  11276. size_t pos = 0;
  11277. ssize_t error_after = -1; // -1 = no error
  11278. explicit MockStream(const std::string &d, ssize_t err = -1)
  11279. : data(d), error_after(err) {}
  11280. bool is_readable() const override { return true; }
  11281. bool wait_readable() const override { return true; }
  11282. bool wait_writable() const override { return true; }
  11283. ssize_t read(char *ptr, size_t size) override {
  11284. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  11285. if (pos >= data.size()) return 0;
  11286. size_t limit =
  11287. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  11288. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  11289. std::memcpy(ptr, data.data() + pos, to_read);
  11290. pos += to_read;
  11291. return static_cast<ssize_t>(to_read);
  11292. }
  11293. ssize_t write(const char *, size_t) override { return -1; }
  11294. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  11295. ip = "127.0.0.1";
  11296. port = 0;
  11297. }
  11298. void get_local_ip_and_port(std::string &ip, int &port) const override {
  11299. ip = "127.0.0.1";
  11300. port = 0;
  11301. }
  11302. socket_t socket() const override { return INVALID_SOCKET; }
  11303. time_t duration() const override { return 0; }
  11304. };
  11305. TEST(StreamHandleTest, Basic) {
  11306. ClientImpl::StreamHandle handle;
  11307. EXPECT_FALSE(handle.is_valid());
  11308. handle.response = detail::make_unique<Response>();
  11309. handle.error = Error::Connection;
  11310. EXPECT_FALSE(handle.is_valid());
  11311. handle.error = Error::Success;
  11312. EXPECT_TRUE(handle.is_valid());
  11313. }
  11314. TEST(BodyReaderTest, Basic) {
  11315. MockStream stream("Hello, World!");
  11316. detail::BodyReader reader;
  11317. reader.stream = &stream;
  11318. reader.content_length = 13;
  11319. char buf[32];
  11320. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  11321. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  11322. EXPECT_TRUE(reader.eof);
  11323. }
  11324. TEST(BodyReaderTest, NoStream) {
  11325. detail::BodyReader reader;
  11326. char buf[32];
  11327. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11328. EXPECT_EQ(Error::Connection, reader.last_error);
  11329. }
  11330. TEST(BodyReaderTest, Error) {
  11331. MockStream stream("Hello, World!", 5);
  11332. detail::BodyReader reader;
  11333. reader.stream = &stream;
  11334. reader.content_length = 13;
  11335. char buf[32];
  11336. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  11337. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11338. EXPECT_EQ(Error::Read, reader.last_error);
  11339. }
  11340. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  11341. // Mock-based StreamHandle tests relying on private internals are removed.
  11342. class OpenStreamTest : public ::testing::Test {
  11343. protected:
  11344. void SetUp() override {
  11345. svr_.Get("/hello", [](const Request &, Response &res) {
  11346. res.set_content("Hello World!", "text/plain");
  11347. });
  11348. svr_.Get("/large", [](const Request &, Response &res) {
  11349. res.set_content(std::string(10000, 'X'), "text/plain");
  11350. });
  11351. svr_.Get("/chunked", [](const Request &, Response &res) {
  11352. res.set_chunked_content_provider("text/plain",
  11353. [](size_t offset, DataSink &sink) {
  11354. if (offset < 15) {
  11355. sink.write("chunk", 5);
  11356. return true;
  11357. }
  11358. sink.done();
  11359. return true;
  11360. });
  11361. });
  11362. svr_.Get("/compressible", [](const Request &, Response &res) {
  11363. res.set_chunked_content_provider("text/plain", [](size_t offset,
  11364. DataSink &sink) {
  11365. if (offset < 100 * 1024) {
  11366. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  11367. sink.write(chunk.data(), chunk.size());
  11368. return true;
  11369. }
  11370. sink.done();
  11371. return true;
  11372. });
  11373. });
  11374. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  11375. [](const Request & /*req*/, Response &res) {
  11376. auto i = new int(0);
  11377. res.set_header("Trailer", "Content-Length, X-Allowed");
  11378. res.set_chunked_content_provider(
  11379. "text/plain",
  11380. [i](size_t /*offset*/, DataSink &sink) {
  11381. switch (*i) {
  11382. case 0: sink.os << "123"; break;
  11383. case 1: sink.os << "456"; break;
  11384. case 2: sink.os << "789"; break;
  11385. case 3: {
  11386. sink.done_with_trailer(
  11387. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  11388. } break;
  11389. }
  11390. (*i)++;
  11391. return true;
  11392. },
  11393. [i](bool success) {
  11394. EXPECT_TRUE(success);
  11395. delete i;
  11396. });
  11397. });
  11398. // Echo headers endpoint for header-related tests
  11399. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  11400. std::string body;
  11401. for (const auto &h : req.headers) {
  11402. body.append(h.first);
  11403. body.push_back(':');
  11404. body.append(h.second);
  11405. body.push_back('\n');
  11406. }
  11407. res.set_content(body, "text/plain");
  11408. });
  11409. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  11410. std::string body;
  11411. for (const auto &h : req.headers) {
  11412. body.append(h.first);
  11413. body.push_back(':');
  11414. body.append(h.second);
  11415. body.push_back('\n');
  11416. }
  11417. res.set_content(body, "text/plain");
  11418. });
  11419. port_ = svr_.bind_to_any_port("127.0.0.1");
  11420. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11421. svr_.wait_until_ready();
  11422. }
  11423. void TearDown() override {
  11424. svr_.stop();
  11425. if (thread_.joinable()) thread_.join();
  11426. }
  11427. Server svr_;
  11428. std::thread thread_;
  11429. int port_ = 0;
  11430. };
  11431. TEST_F(OpenStreamTest, Basic) {
  11432. Client cli("127.0.0.1", port_);
  11433. auto handle = cli.open_stream("GET", "/hello");
  11434. EXPECT_TRUE(handle.is_valid());
  11435. EXPECT_EQ("Hello World!", read_all(handle));
  11436. }
  11437. TEST_F(OpenStreamTest, SmallBuffer) {
  11438. Client cli("127.0.0.1", port_);
  11439. auto handle = cli.open_stream("GET", "/hello");
  11440. std::string result;
  11441. char buf[4];
  11442. ssize_t n;
  11443. while ((n = handle.read(buf, sizeof(buf))) > 0)
  11444. result.append(buf, static_cast<size_t>(n));
  11445. EXPECT_EQ("Hello World!", result);
  11446. }
  11447. TEST_F(OpenStreamTest, DefaultHeaders) {
  11448. Client cli("127.0.0.1", port_);
  11449. // open_stream GET should include Host, User-Agent and Accept-Encoding
  11450. {
  11451. auto handle = cli.open_stream("GET", "/echo-headers");
  11452. ASSERT_TRUE(handle.is_valid());
  11453. auto body = read_all(handle);
  11454. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  11455. std::string::npos);
  11456. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  11457. std::string::npos);
  11458. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  11459. }
  11460. // open_stream POST with body and no explicit content_type should NOT add
  11461. // text/plain Content-Type (behavior differs from non-streaming path), but
  11462. // should include Content-Length
  11463. {
  11464. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  11465. ASSERT_TRUE(handle.is_valid());
  11466. auto body = read_all(handle);
  11467. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  11468. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  11469. }
  11470. // open_stream POST with explicit Content-Type should preserve it
  11471. {
  11472. auto handle = cli.open_stream("POST", "/echo-headers", {},
  11473. {{"Content-Type", "application/custom"}},
  11474. "{}", "application/custom");
  11475. ASSERT_TRUE(handle.is_valid());
  11476. auto body = read_all(handle);
  11477. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  11478. }
  11479. // User-specified User-Agent must not be overwritten for stream API
  11480. {
  11481. auto handle = cli.open_stream("GET", "/echo-headers", {},
  11482. {{"User-Agent", "MyAgent/1.2"}});
  11483. ASSERT_TRUE(handle.is_valid());
  11484. auto body = read_all(handle);
  11485. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  11486. }
  11487. }
  11488. TEST_F(OpenStreamTest, Large) {
  11489. Client cli("127.0.0.1", port_);
  11490. auto handle = cli.open_stream("GET", "/large");
  11491. EXPECT_EQ(10000u, read_all(handle).size());
  11492. }
  11493. TEST_F(OpenStreamTest, ConnectionError) {
  11494. Client cli("127.0.0.1", 9999);
  11495. auto handle = cli.open_stream("GET", "/hello");
  11496. EXPECT_FALSE(handle.is_valid());
  11497. }
  11498. TEST_F(OpenStreamTest, Chunked) {
  11499. Client cli("127.0.0.1", port_);
  11500. auto handle = cli.open_stream("GET", "/chunked");
  11501. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11502. "Transfer-Encoding") == "chunked");
  11503. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  11504. }
  11505. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  11506. Client cli("127.0.0.1", port_);
  11507. auto handle =
  11508. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  11509. ASSERT_TRUE(handle.is_valid());
  11510. // Consume body to allow trailers to be received/parsed
  11511. auto body = read_all(handle);
  11512. // Explicitly parse trailers (ensure trailers are available for assertion)
  11513. handle.parse_trailers_if_needed();
  11514. EXPECT_EQ(std::string("123456789"), body);
  11515. // The response should include a Trailer header declaring both names
  11516. ASSERT_TRUE(handle.response);
  11517. EXPECT_TRUE(handle.response->has_header("Trailer"));
  11518. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  11519. handle.response->get_header_value("Trailer"));
  11520. // Prohibited trailer must not be present
  11521. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  11522. // Allowed trailer should be present
  11523. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  11524. EXPECT_EQ(std::string("yes"),
  11525. handle.response->get_trailer_value("X-Allowed"));
  11526. // Verify trailers are NOT present as regular headers
  11527. EXPECT_EQ(std::string(""),
  11528. handle.response->get_header_value("Content-Length"));
  11529. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  11530. }
  11531. static std::thread serve_single_response(int port,
  11532. const std::string &response) {
  11533. return std::thread([port, response] {
  11534. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11535. default_socket_options(srv);
  11536. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11537. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11538. sockaddr_in addr{};
  11539. addr.sin_family = AF_INET;
  11540. addr.sin_port = htons(static_cast<uint16_t>(port));
  11541. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11542. int opt = 1;
  11543. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11544. #ifdef _WIN32
  11545. reinterpret_cast<const char *>(&opt),
  11546. #else
  11547. &opt,
  11548. #endif
  11549. sizeof(opt));
  11550. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11551. ::listen(srv, 1);
  11552. sockaddr_in cli_addr{};
  11553. socklen_t cli_len = sizeof(cli_addr);
  11554. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11555. if (cli != INVALID_SOCKET) {
  11556. char buf[4096];
  11557. ::recv(cli, buf, sizeof(buf), 0);
  11558. ::send(cli,
  11559. #ifdef _WIN32
  11560. static_cast<const char *>(response.c_str()),
  11561. static_cast<int>(response.size()),
  11562. #else
  11563. response.c_str(), response.size(),
  11564. #endif
  11565. 0);
  11566. detail::close_socket(cli);
  11567. }
  11568. detail::close_socket(srv);
  11569. });
  11570. }
  11571. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  11572. #ifndef _WIN32
  11573. signal(SIGPIPE, SIG_IGN);
  11574. #endif
  11575. auto server_thread =
  11576. serve_single_response(PORT + 2, "HTTP/1.1 200 OK\r\n"
  11577. "Content-Type: text/plain\r\n"
  11578. "Content-Length: not-a-number\r\n"
  11579. "Connection: close\r\n"
  11580. "\r\n"
  11581. "hello");
  11582. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11583. Client cli("127.0.0.1", PORT + 2);
  11584. auto handle = cli.open_stream("GET", "/");
  11585. EXPECT_FALSE(handle.is_valid());
  11586. server_thread.join();
  11587. }
  11588. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  11589. #ifndef _WIN32
  11590. signal(SIGPIPE, SIG_IGN);
  11591. #endif
  11592. auto server_thread = serve_single_response(
  11593. PORT + 2, "HTTP/1.1 200 OK\r\n"
  11594. "Content-Type: text/plain\r\n"
  11595. "Content-Length: 99999999999999999999999999\r\n"
  11596. "Connection: close\r\n"
  11597. "\r\n"
  11598. "hello");
  11599. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11600. // Before the fix, std::stoull would throw std::out_of_range here and
  11601. // crash the process. After the fix, strtoull silently clamps to
  11602. // ULLONG_MAX so the stream opens without crashing. The important thing
  11603. // is that the process does NOT terminate.
  11604. Client cli("127.0.0.1", PORT + 2);
  11605. auto handle = cli.open_stream("GET", "/");
  11606. EXPECT_TRUE(handle.is_valid());
  11607. server_thread.join();
  11608. }
  11609. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11610. TEST_F(OpenStreamTest, Gzip) {
  11611. Client cli("127.0.0.1", port_);
  11612. auto handle = cli.open_stream("GET", "/compressible", {},
  11613. {{"Accept-Encoding", "gzip"}});
  11614. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  11615. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11616. }
  11617. #endif
  11618. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11619. TEST_F(OpenStreamTest, Brotli) {
  11620. Client cli("127.0.0.1", port_);
  11621. auto handle =
  11622. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  11623. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  11624. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11625. }
  11626. #endif
  11627. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11628. TEST_F(OpenStreamTest, Zstd) {
  11629. Client cli("127.0.0.1", port_);
  11630. auto handle = cli.open_stream("GET", "/compressible", {},
  11631. {{"Accept-Encoding", "zstd"}});
  11632. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  11633. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11634. }
  11635. #endif
  11636. #ifdef CPPHTTPLIB_SSL_ENABLED
  11637. class SSLOpenStreamTest : public ::testing::Test {
  11638. protected:
  11639. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  11640. void SetUp() override {
  11641. svr_.Get("/hello", [](const Request &, Response &res) {
  11642. res.set_content("Hello SSL World!", "text/plain");
  11643. });
  11644. svr_.Get("/chunked", [](const Request &, Response &res) {
  11645. res.set_chunked_content_provider("text/plain",
  11646. [](size_t offset, DataSink &sink) {
  11647. if (offset < 15) {
  11648. sink.write("chunk", 5);
  11649. return true;
  11650. }
  11651. sink.done();
  11652. return true;
  11653. });
  11654. });
  11655. svr_.Post("/echo", [](const Request &req, Response &res) {
  11656. res.set_content(req.body, req.get_header_value("Content-Type"));
  11657. });
  11658. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  11659. std::string body = req.body;
  11660. res.set_chunked_content_provider(
  11661. "text/plain", [body](size_t offset, DataSink &sink) {
  11662. if (offset < body.size()) {
  11663. sink.write(body.data() + offset, body.size() - offset);
  11664. }
  11665. sink.done();
  11666. return true;
  11667. });
  11668. });
  11669. port_ = svr_.bind_to_any_port("127.0.0.1");
  11670. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11671. svr_.wait_until_ready();
  11672. }
  11673. void TearDown() override {
  11674. svr_.stop();
  11675. if (thread_.joinable()) thread_.join();
  11676. }
  11677. SSLServer svr_;
  11678. std::thread thread_;
  11679. int port_ = 0;
  11680. };
  11681. TEST_F(SSLOpenStreamTest, Basic) {
  11682. SSLClient cli("127.0.0.1", port_);
  11683. cli.enable_server_certificate_verification(false);
  11684. auto handle = cli.open_stream("GET", "/hello");
  11685. ASSERT_TRUE(handle.is_valid());
  11686. EXPECT_EQ("Hello SSL World!", read_all(handle));
  11687. }
  11688. TEST_F(SSLOpenStreamTest, Chunked) {
  11689. SSLClient cli("127.0.0.1", port_);
  11690. cli.enable_server_certificate_verification(false);
  11691. auto handle = cli.open_stream("GET", "/chunked");
  11692. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11693. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11694. "Transfer-Encoding") == "chunked");
  11695. auto body = read_all(handle);
  11696. EXPECT_EQ("chunkchunkchunk", body);
  11697. }
  11698. TEST_F(SSLOpenStreamTest, Post) {
  11699. SSLClient cli("127.0.0.1", port_);
  11700. cli.enable_server_certificate_verification(false);
  11701. auto handle =
  11702. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  11703. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11704. EXPECT_EQ(200, handle.response->status);
  11705. auto body = read_all(handle);
  11706. EXPECT_EQ("Hello SSL POST", body);
  11707. }
  11708. TEST_F(SSLOpenStreamTest, PostChunked) {
  11709. SSLClient cli("127.0.0.1", port_);
  11710. cli.enable_server_certificate_verification(false);
  11711. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  11712. "Chunked SSL Data", "text/plain");
  11713. ASSERT_TRUE(handle.is_valid());
  11714. EXPECT_EQ(200, handle.response->status);
  11715. auto body = read_all(handle);
  11716. EXPECT_EQ("Chunked SSL Data", body);
  11717. }
  11718. #endif // CPPHTTPLIB_SSL_ENABLED
  11719. //==============================================================================
  11720. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  11721. // results for various scenarios.
  11722. //==============================================================================
  11723. TEST(ParityTest, GetVsOpenStream) {
  11724. Server svr;
  11725. const std::string path = "/parity";
  11726. const std::string content = "Parity test content: hello world";
  11727. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11728. res.set_content(content, "text/plain");
  11729. });
  11730. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11731. auto se = detail::scope_exit([&] {
  11732. svr.stop();
  11733. t.join();
  11734. ASSERT_FALSE(svr.is_running());
  11735. });
  11736. svr.wait_until_ready();
  11737. Client cli(HOST, PORT);
  11738. // Non-stream path
  11739. auto r1 = cli.Get(path);
  11740. ASSERT_TRUE(r1);
  11741. EXPECT_EQ(StatusCode::OK_200, r1->status);
  11742. // Stream path
  11743. auto h = cli.open_stream("GET", path);
  11744. ASSERT_TRUE(h.is_valid());
  11745. EXPECT_EQ(r1->body, read_all(h));
  11746. }
  11747. // Helper to compress data with provided compressor type T
  11748. template <typename Compressor>
  11749. static std::string compress_payload_for_parity(const std::string &in) {
  11750. std::string out;
  11751. Compressor compressor;
  11752. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  11753. [&](const char *data, size_t n) {
  11754. out.append(data, n);
  11755. return true;
  11756. });
  11757. EXPECT_TRUE(ok);
  11758. return out;
  11759. }
  11760. // Helper function for compression parity tests
  11761. template <typename Compressor>
  11762. static void test_compression_parity(const std::string &original,
  11763. const std::string &path,
  11764. const std::string &encoding) {
  11765. const std::string compressed =
  11766. compress_payload_for_parity<Compressor>(original);
  11767. Server svr;
  11768. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11769. res.set_content(compressed, "application/octet-stream");
  11770. res.set_header("Content-Encoding", encoding);
  11771. });
  11772. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  11773. auto se = detail::scope_exit([&] {
  11774. svr.stop();
  11775. t.join();
  11776. ASSERT_FALSE(svr.is_running());
  11777. });
  11778. svr.wait_until_ready();
  11779. Client cli(HOST, PORT);
  11780. // Non-streaming
  11781. {
  11782. auto res = cli.Get(path);
  11783. ASSERT_TRUE(res);
  11784. EXPECT_EQ(StatusCode::OK_200, res->status);
  11785. EXPECT_EQ(original, res->body);
  11786. }
  11787. // Streaming
  11788. {
  11789. auto h = cli.open_stream("GET", path);
  11790. ASSERT_TRUE(h.is_valid());
  11791. EXPECT_EQ(original, read_all(h));
  11792. }
  11793. }
  11794. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11795. TEST(ParityTest, Gzip) {
  11796. test_compression_parity<detail::gzip_compressor>(
  11797. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  11798. }
  11799. #endif
  11800. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11801. TEST(ParityTest, Brotli) {
  11802. test_compression_parity<detail::brotli_compressor>(
  11803. "Hello, brotli parity test payload", "/parity-br", "br");
  11804. }
  11805. #endif
  11806. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11807. TEST(ParityTest, Zstd) {
  11808. test_compression_parity<detail::zstd_compressor>(
  11809. "Zstandard parity test payload", "/parity-zstd", "zstd");
  11810. }
  11811. #endif
  11812. //==============================================================================
  11813. // New Stream API Tests
  11814. //==============================================================================
  11815. inline std::string read_body(httplib::stream::Result &result) {
  11816. std::string body;
  11817. while (result.next()) {
  11818. body.append(result.data(), result.size());
  11819. }
  11820. return body;
  11821. }
  11822. TEST(ClientConnectionTest, Basic) {
  11823. httplib::ClientConnection conn;
  11824. EXPECT_FALSE(conn.is_open());
  11825. conn.sock = 1;
  11826. EXPECT_TRUE(conn.is_open());
  11827. httplib::ClientConnection conn2(std::move(conn));
  11828. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  11829. conn2.sock = INVALID_SOCKET;
  11830. }
  11831. // Unified test server for all stream::* tests
  11832. class StreamApiTest : public ::testing::Test {
  11833. protected:
  11834. void SetUp() override {
  11835. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11836. res.set_content("Hello World!", "text/plain");
  11837. });
  11838. svr_.Get("/echo-params",
  11839. [](const httplib::Request &req, httplib::Response &res) {
  11840. std::string r;
  11841. for (const auto &p : req.params) {
  11842. if (!r.empty()) r += "&";
  11843. r += p.first + "=" + p.second;
  11844. }
  11845. res.set_content(r, "text/plain");
  11846. });
  11847. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11848. res.set_content(req.body, req.get_header_value("Content-Type"));
  11849. });
  11850. svr_.Post("/echo-headers",
  11851. [](const httplib::Request &req, httplib::Response &res) {
  11852. std::string r;
  11853. for (const auto &h : req.headers)
  11854. r += h.first + ": " + h.second + "\n";
  11855. res.set_content(r, "text/plain");
  11856. });
  11857. svr_.Post("/echo-params",
  11858. [](const httplib::Request &req, httplib::Response &res) {
  11859. std::string r = "params:";
  11860. for (const auto &p : req.params)
  11861. r += p.first + "=" + p.second + ";";
  11862. res.set_content(r + " body:" + req.body, "text/plain");
  11863. });
  11864. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  11865. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  11866. });
  11867. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11868. res.set_content("PUT:" + req.body, "text/plain");
  11869. });
  11870. svr_.Patch("/echo",
  11871. [](const httplib::Request &req, httplib::Response &res) {
  11872. res.set_content("PATCH:" + req.body, "text/plain");
  11873. });
  11874. svr_.Delete(
  11875. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  11876. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  11877. "text/plain");
  11878. });
  11879. svr_.Get("/head-test",
  11880. [](const httplib::Request &, httplib::Response &res) {
  11881. res.set_content("body for HEAD", "text/plain");
  11882. });
  11883. svr_.Options("/options",
  11884. [](const httplib::Request &, httplib::Response &res) {
  11885. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  11886. });
  11887. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  11888. svr_.wait_until_ready();
  11889. }
  11890. void TearDown() override {
  11891. svr_.stop();
  11892. if (thread_.joinable()) thread_.join();
  11893. }
  11894. httplib::Server svr_;
  11895. std::thread thread_;
  11896. };
  11897. // stream::Get tests
  11898. TEST_F(StreamApiTest, GetBasic) {
  11899. httplib::Client cli(HOST, PORT);
  11900. auto result = httplib::stream::Get(cli, "/hello");
  11901. ASSERT_TRUE(result.is_valid());
  11902. EXPECT_EQ(200, result.status());
  11903. EXPECT_EQ("Hello World!", read_body(result));
  11904. }
  11905. TEST_F(StreamApiTest, GetWithParams) {
  11906. httplib::Client cli(HOST, PORT);
  11907. httplib::Params params{{"foo", "bar"}};
  11908. auto result = httplib::stream::Get(cli, "/echo-params", params);
  11909. ASSERT_TRUE(result.is_valid());
  11910. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  11911. }
  11912. TEST_F(StreamApiTest, GetConnectionError) {
  11913. httplib::Client cli(HOST, 9999);
  11914. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  11915. }
  11916. TEST_F(StreamApiTest, Get404) {
  11917. httplib::Client cli(HOST, PORT);
  11918. auto result = httplib::stream::Get(cli, "/nonexistent");
  11919. EXPECT_TRUE(result.is_valid());
  11920. EXPECT_EQ(404, result.status());
  11921. }
  11922. // stream::Post tests
  11923. TEST_F(StreamApiTest, PostBasic) {
  11924. httplib::Client cli(HOST, PORT);
  11925. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  11926. "application/json");
  11927. ASSERT_TRUE(result.is_valid());
  11928. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  11929. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  11930. }
  11931. TEST_F(StreamApiTest, PostWithHeaders) {
  11932. httplib::Client cli(HOST, PORT);
  11933. httplib::Headers headers{{"X-Custom", "value"}};
  11934. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  11935. "text/plain");
  11936. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  11937. }
  11938. TEST_F(StreamApiTest, PostWithParams) {
  11939. httplib::Client cli(HOST, PORT);
  11940. httplib::Params params{{"k", "v"}};
  11941. auto result =
  11942. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  11943. auto body = read_body(result);
  11944. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  11945. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  11946. }
  11947. TEST_F(StreamApiTest, PostLarge) {
  11948. httplib::Client cli(HOST, PORT);
  11949. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  11950. size_t total = 0;
  11951. while (result.next()) {
  11952. total += result.size();
  11953. }
  11954. EXPECT_EQ(100u * 1024u, total);
  11955. }
  11956. // stream::Put/Patch tests
  11957. TEST_F(StreamApiTest, PutAndPatch) {
  11958. httplib::Client cli(HOST, PORT);
  11959. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  11960. EXPECT_EQ("PUT:test", read_body(put));
  11961. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  11962. EXPECT_EQ("PATCH:test", read_body(patch));
  11963. }
  11964. // stream::Delete tests
  11965. TEST_F(StreamApiTest, Delete) {
  11966. httplib::Client cli(HOST, PORT);
  11967. auto del1 = httplib::stream::Delete(cli, "/resource");
  11968. EXPECT_EQ("Deleted", read_body(del1));
  11969. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  11970. EXPECT_EQ("Deleted:data", read_body(del2));
  11971. }
  11972. // stream::Head/Options tests
  11973. TEST_F(StreamApiTest, HeadAndOptions) {
  11974. httplib::Client cli(HOST, PORT);
  11975. auto head = httplib::stream::Head(cli, "/head-test");
  11976. EXPECT_TRUE(head.is_valid());
  11977. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  11978. auto opts = httplib::stream::Options(cli, "/options");
  11979. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  11980. }
  11981. // SSL stream::* tests
  11982. #ifdef CPPHTTPLIB_SSL_ENABLED
  11983. class SSLStreamApiTest : public ::testing::Test {
  11984. protected:
  11985. void SetUp() override {
  11986. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11987. res.set_content("Hello SSL!", "text/plain");
  11988. });
  11989. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11990. res.set_content(req.body, "text/plain");
  11991. });
  11992. port_ = svr_.bind_to_any_port("127.0.0.1");
  11993. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11994. svr_.wait_until_ready();
  11995. }
  11996. void TearDown() override {
  11997. svr_.stop();
  11998. if (thread_.joinable()) thread_.join();
  11999. }
  12000. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  12001. std::thread thread_;
  12002. int port_ = 0;
  12003. };
  12004. TEST_F(SSLStreamApiTest, GetAndPost) {
  12005. httplib::SSLClient cli("127.0.0.1", port_);
  12006. cli.enable_server_certificate_verification(false);
  12007. auto get = httplib::stream::Get(cli, "/hello");
  12008. EXPECT_EQ("Hello SSL!", read_body(get));
  12009. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  12010. EXPECT_EQ("test", read_body(post));
  12011. }
  12012. #endif
  12013. // Tests for Error::Timeout and Error::ConnectionClosed error types
  12014. // These errors are set in SocketStream/SSLSocketStream and propagated through
  12015. // BodyReader
  12016. TEST(ErrorHandlingTest, StreamReadTimeout) {
  12017. // Test that read timeout during streaming is detected
  12018. // Use a large content-length response where server delays mid-stream
  12019. Server svr;
  12020. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12021. // Send a large response with delay in the middle
  12022. res.set_content_provider(
  12023. 1000, // content_length
  12024. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  12025. if (offset < 100) {
  12026. // Send first 100 bytes immediately
  12027. std::string data(100, 'A');
  12028. sink.write(data.c_str(), data.size());
  12029. return true;
  12030. }
  12031. // Then delay longer than client timeout
  12032. std::this_thread::sleep_for(std::chrono::seconds(3));
  12033. std::string data(900, 'B');
  12034. sink.write(data.c_str(), data.size());
  12035. return true;
  12036. });
  12037. });
  12038. auto port = 8091;
  12039. std::thread t([&]() { svr.listen("localhost", port); });
  12040. svr.wait_until_ready();
  12041. Client cli("localhost", port);
  12042. cli.set_read_timeout(1, 0); // 1 second timeout
  12043. auto handle = cli.open_stream("GET", "/slow-stream");
  12044. ASSERT_TRUE(handle.is_valid());
  12045. char buf[256];
  12046. ssize_t total = 0;
  12047. ssize_t n;
  12048. bool got_error = false;
  12049. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12050. total += n;
  12051. }
  12052. if (n < 0) {
  12053. got_error = true;
  12054. // Should be timeout or read error
  12055. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12056. handle.get_read_error() == Error::Read)
  12057. << "Actual error: " << to_string(handle.get_read_error());
  12058. }
  12059. // Either we got an error, or we got less data than expected
  12060. EXPECT_TRUE(got_error || total < 1000)
  12061. << "Expected timeout but got all " << total << " bytes";
  12062. svr.stop();
  12063. t.join();
  12064. }
  12065. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  12066. // Test connection closed detection via BodyReader
  12067. Server svr;
  12068. std::atomic<bool> close_now{false};
  12069. svr.Get("/will-close", [&](const Request &, Response &res) {
  12070. res.set_content_provider(
  12071. 10000, // Large content_length that we won't fully send
  12072. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12073. if (offset < 100) {
  12074. std::string data(100, 'X');
  12075. sink.write(data.c_str(), data.size());
  12076. return true;
  12077. }
  12078. // Wait for signal then abort
  12079. while (!close_now) {
  12080. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12081. }
  12082. return false; // Abort - server will close connection
  12083. });
  12084. });
  12085. auto port = 8092;
  12086. std::thread t([&]() { svr.listen("localhost", port); });
  12087. svr.wait_until_ready();
  12088. Client cli("localhost", port);
  12089. auto handle = cli.open_stream("GET", "/will-close");
  12090. ASSERT_TRUE(handle.is_valid());
  12091. char buf[256];
  12092. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12093. EXPECT_GT(n, 0) << "First read should succeed";
  12094. // Signal server to close
  12095. close_now = true;
  12096. // Keep reading until error or EOF
  12097. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12098. // Keep reading
  12099. }
  12100. // Should get an error since content_length wasn't satisfied
  12101. if (n < 0) {
  12102. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12103. handle.get_read_error() == Error::Read)
  12104. << "Actual error: " << to_string(handle.get_read_error());
  12105. }
  12106. svr.stop();
  12107. t.join();
  12108. }
  12109. #ifdef CPPHTTPLIB_SSL_ENABLED
  12110. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  12111. // Test that read timeout during SSL streaming is detected
  12112. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12113. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12114. res.set_content_provider(
  12115. 1000, "text/plain",
  12116. [](size_t offset, size_t /*length*/, DataSink &sink) {
  12117. if (offset < 100) {
  12118. std::string data(100, 'A');
  12119. sink.write(data.c_str(), data.size());
  12120. return true;
  12121. }
  12122. std::this_thread::sleep_for(std::chrono::seconds(3));
  12123. std::string data(900, 'B');
  12124. sink.write(data.c_str(), data.size());
  12125. return true;
  12126. });
  12127. });
  12128. auto port = 8093;
  12129. std::thread t([&]() { svr.listen("localhost", port); });
  12130. svr.wait_until_ready();
  12131. SSLClient cli("localhost", port);
  12132. cli.enable_server_certificate_verification(false);
  12133. cli.set_read_timeout(1, 0); // 1 second timeout
  12134. auto handle = cli.open_stream("GET", "/slow-stream");
  12135. ASSERT_TRUE(handle.is_valid());
  12136. char buf[256];
  12137. ssize_t total = 0;
  12138. ssize_t n;
  12139. bool got_error = false;
  12140. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12141. total += n;
  12142. }
  12143. if (n < 0) {
  12144. got_error = true;
  12145. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12146. handle.get_read_error() == Error::Read)
  12147. << "Actual error: " << to_string(handle.get_read_error());
  12148. }
  12149. EXPECT_TRUE(got_error || total < 1000)
  12150. << "Expected timeout but got all " << total << " bytes";
  12151. svr.stop();
  12152. t.join();
  12153. }
  12154. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  12155. // Test SSL connection closed detection
  12156. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12157. std::atomic<bool> close_now{false};
  12158. svr.Get("/will-close", [&](const Request &, Response &res) {
  12159. res.set_content_provider(
  12160. 10000, "text/plain",
  12161. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12162. if (offset < 100) {
  12163. std::string data(100, 'X');
  12164. sink.write(data.c_str(), data.size());
  12165. return true;
  12166. }
  12167. while (!close_now) {
  12168. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12169. }
  12170. return false;
  12171. });
  12172. });
  12173. auto port = 8094;
  12174. std::thread t([&]() { svr.listen("localhost", port); });
  12175. svr.wait_until_ready();
  12176. SSLClient cli("localhost", port);
  12177. cli.enable_server_certificate_verification(false);
  12178. auto handle = cli.open_stream("GET", "/will-close");
  12179. ASSERT_TRUE(handle.is_valid());
  12180. char buf[256];
  12181. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12182. EXPECT_GT(n, 0);
  12183. // Signal server to close
  12184. close_now = true;
  12185. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12186. // Keep reading
  12187. }
  12188. if (n < 0) {
  12189. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12190. handle.get_read_error() == Error::Read)
  12191. << "Actual error: " << to_string(handle.get_read_error());
  12192. }
  12193. svr.stop();
  12194. t.join();
  12195. }
  12196. #endif
  12197. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  12198. using namespace httplib;
  12199. // Create a test file
  12200. const char *fname = "etag_testfile.txt";
  12201. const char *content = "etag-content";
  12202. {
  12203. std::ofstream ofs(fname);
  12204. ofs << content;
  12205. ASSERT_TRUE(ofs.good());
  12206. }
  12207. Server svr;
  12208. svr.set_mount_point("/static", ".");
  12209. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12210. svr.wait_until_ready();
  12211. Client cli(HOST, PORT);
  12212. // First request: should get 200 with ETag header
  12213. auto res1 = cli.Get("/static/etag_testfile.txt");
  12214. ASSERT_TRUE(res1);
  12215. ASSERT_EQ(200, res1->status);
  12216. ASSERT_TRUE(res1->has_header("ETag"));
  12217. std::string etag = res1->get_header_value("ETag");
  12218. EXPECT_FALSE(etag.empty());
  12219. // Verify ETag format: W/"hex-hex"
  12220. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  12221. EXPECT_EQ('W', etag[0]);
  12222. EXPECT_EQ('/', etag[1]);
  12223. EXPECT_EQ('"', etag[2]);
  12224. EXPECT_EQ('"', etag.back());
  12225. // Exact match: expect 304 Not Modified
  12226. Headers h2 = {{"If-None-Match", etag}};
  12227. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  12228. ASSERT_TRUE(res2);
  12229. EXPECT_EQ(304, res2->status);
  12230. // Wildcard match: expect 304 Not Modified
  12231. Headers h3 = {{"If-None-Match", "*"}};
  12232. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  12233. ASSERT_TRUE(res3);
  12234. EXPECT_EQ(304, res3->status);
  12235. // Non-matching ETag: expect 200
  12236. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  12237. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  12238. ASSERT_TRUE(res4);
  12239. EXPECT_EQ(200, res4->status);
  12240. // Multiple ETags with one matching: expect 304
  12241. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  12242. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  12243. ASSERT_TRUE(res5);
  12244. EXPECT_EQ(304, res5->status);
  12245. svr.stop();
  12246. t.join();
  12247. std::remove(fname);
  12248. }
  12249. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  12250. using namespace httplib;
  12251. Server svr;
  12252. svr.set_mount_point("/static", ".");
  12253. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12254. svr.wait_until_ready();
  12255. Client cli(HOST, PORT);
  12256. // Send If-None-Match: * to a non-existent file
  12257. Headers h = {{"If-None-Match", "*"}};
  12258. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  12259. ASSERT_TRUE(res);
  12260. EXPECT_EQ(404, res->status);
  12261. svr.stop();
  12262. t.join();
  12263. }
  12264. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  12265. using namespace httplib;
  12266. // Create a test file
  12267. const char *fname = "etag_boundary_testfile.txt";
  12268. const char *content = "boundary-test";
  12269. {
  12270. std::ofstream ofs(fname);
  12271. ofs << content;
  12272. ASSERT_TRUE(ofs.good());
  12273. }
  12274. Server svr;
  12275. svr.set_mount_point("/static", ".");
  12276. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12277. svr.wait_until_ready();
  12278. Client cli(HOST, PORT);
  12279. // Get the actual ETag
  12280. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  12281. ASSERT_TRUE(res1);
  12282. ASSERT_EQ(200, res1->status);
  12283. ASSERT_TRUE(res1->has_header("ETag"));
  12284. std::string etag = res1->get_header_value("ETag");
  12285. // Test 1: Very long ETag value (longer than actual ETag)
  12286. // Should NOT match and return 200 (not trigger out-of-bounds read)
  12287. Headers h1 = {{"If-None-Match", "W/"
  12288. "\"very-long-etag-value-that-is-much-longer-"
  12289. "than-the-actual-etag-value\""}};
  12290. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  12291. ASSERT_TRUE(res2);
  12292. EXPECT_EQ(200, res2->status); // Should not match
  12293. // Test 2: Long string followed by wildcard
  12294. // Should match on "*" and return 304 (without out-of-bounds read on the long
  12295. // string)
  12296. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  12297. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  12298. ASSERT_TRUE(res3);
  12299. EXPECT_EQ(304, res3->status); // Should match on "*"
  12300. // Test 3: Wildcard followed by long string
  12301. // Should match on "*" immediately and return 304
  12302. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  12303. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  12304. ASSERT_TRUE(res4);
  12305. EXPECT_EQ(304, res4->status); // Should match on "*"
  12306. // Test 4: Multiple long non-matching values
  12307. // Should NOT match and return 200 (test that all comparisons are safe)
  12308. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  12309. "W/\"second-long-non-matching-value\", "
  12310. "W/\"third-long-non-matching-value\""}};
  12311. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  12312. ASSERT_TRUE(res5);
  12313. EXPECT_EQ(200, res5->status); // Should not match
  12314. // Test 5: Single character that is not "*" (edge case)
  12315. Headers h5 = {{"If-None-Match", "X"}};
  12316. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  12317. ASSERT_TRUE(res6);
  12318. EXPECT_EQ(200, res6->status); // Should not match
  12319. svr.stop();
  12320. t.join();
  12321. std::remove(fname);
  12322. }
  12323. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  12324. using namespace httplib;
  12325. // Create a test file
  12326. const char *fname = "ims_testfile.txt";
  12327. const char *content = "if-modified-since-test";
  12328. {
  12329. std::ofstream ofs(fname);
  12330. ofs << content;
  12331. ASSERT_TRUE(ofs.good());
  12332. }
  12333. Server svr;
  12334. svr.set_mount_point("/static", ".");
  12335. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12336. svr.wait_until_ready();
  12337. Client cli(HOST, PORT);
  12338. // First request: should get 200 with Last-Modified header
  12339. auto res1 = cli.Get("/static/ims_testfile.txt");
  12340. ASSERT_TRUE(res1);
  12341. ASSERT_EQ(200, res1->status);
  12342. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12343. std::string last_modified = res1->get_header_value("Last-Modified");
  12344. EXPECT_FALSE(last_modified.empty());
  12345. // If-Modified-Since with same time: expect 304
  12346. Headers h2 = {{"If-Modified-Since", last_modified}};
  12347. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  12348. ASSERT_TRUE(res2);
  12349. EXPECT_EQ(304, res2->status);
  12350. // If-Modified-Since with future time: expect 304
  12351. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12352. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  12353. ASSERT_TRUE(res3);
  12354. EXPECT_EQ(304, res3->status);
  12355. // If-Modified-Since with past time: expect 200
  12356. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12357. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  12358. ASSERT_TRUE(res4);
  12359. EXPECT_EQ(200, res4->status);
  12360. // If-None-Match takes precedence over If-Modified-Since
  12361. // (send matching ETag with old If-Modified-Since -> should still be 304)
  12362. ASSERT_TRUE(res1->has_header("ETag"));
  12363. std::string etag = res1->get_header_value("ETag");
  12364. Headers h5 = {{"If-None-Match", etag},
  12365. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12366. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  12367. ASSERT_TRUE(res5);
  12368. EXPECT_EQ(304, res5->status);
  12369. svr.stop();
  12370. t.join();
  12371. std::remove(fname);
  12372. }
  12373. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  12374. using namespace httplib;
  12375. Server svr;
  12376. // Endpoint that returns compressible content
  12377. svr.Get("/compressible", [](const Request &, Response &res) {
  12378. // Return a large enough body to trigger compression
  12379. std::string body(1000, 'a');
  12380. res.set_content(body, "text/plain");
  12381. });
  12382. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12383. svr.wait_until_ready();
  12384. Client cli(HOST, PORT);
  12385. // Request with gzip support: should get Vary header when compressed
  12386. cli.set_compress(true);
  12387. auto res1 = cli.Get("/compressible");
  12388. ASSERT_TRUE(res1);
  12389. EXPECT_EQ(200, res1->status);
  12390. // If Content-Encoding is set, Vary should also be set
  12391. if (res1->has_header("Content-Encoding")) {
  12392. EXPECT_TRUE(res1->has_header("Vary"));
  12393. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  12394. }
  12395. // Request without Accept-Encoding header: should not have compression
  12396. Headers h_no_compress;
  12397. auto res2 = cli.Get("/compressible", h_no_compress);
  12398. ASSERT_TRUE(res2);
  12399. EXPECT_EQ(200, res2->status);
  12400. // Verify Vary header is present when compression is applied
  12401. // (the exact behavior depends on server configuration)
  12402. svr.stop();
  12403. t.join();
  12404. }
  12405. TEST(ETagTest, IfRangeWithETag) {
  12406. using namespace httplib;
  12407. // Create a test file with known content
  12408. const char *fname = "if_range_testfile.txt";
  12409. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  12410. {
  12411. std::ofstream ofs(fname);
  12412. ofs << content;
  12413. ASSERT_TRUE(ofs.good());
  12414. }
  12415. Server svr;
  12416. svr.set_mount_point("/static", ".");
  12417. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12418. svr.wait_until_ready();
  12419. Client cli(HOST, PORT);
  12420. // First request: get ETag
  12421. auto res1 = cli.Get("/static/if_range_testfile.txt");
  12422. ASSERT_TRUE(res1);
  12423. ASSERT_EQ(200, res1->status);
  12424. ASSERT_TRUE(res1->has_header("ETag"));
  12425. std::string etag = res1->get_header_value("ETag");
  12426. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  12427. // Since our server generates weak ETags (W/"..."), If-Range with our
  12428. // ETag should NOT result in partial content - it should return full content.
  12429. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  12430. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  12431. ASSERT_TRUE(res2);
  12432. // Weak ETag in If-Range -> full content (200), not partial (206)
  12433. EXPECT_EQ(200, res2->status);
  12434. EXPECT_EQ(content, res2->body);
  12435. EXPECT_FALSE(res2->has_header("Content-Range"));
  12436. // Range request with non-matching If-Range (ETag): should get 200 (full
  12437. // content)
  12438. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  12439. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  12440. ASSERT_TRUE(res3);
  12441. EXPECT_EQ(200, res3->status);
  12442. EXPECT_EQ(content, res3->body);
  12443. EXPECT_FALSE(res3->has_header("Content-Range"));
  12444. // Range request with strong ETag (hypothetical - our server doesn't generate
  12445. // strong ETags, but if client sends a strong ETag that doesn't match, it
  12446. // should return full content)
  12447. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  12448. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  12449. ASSERT_TRUE(res4);
  12450. EXPECT_EQ(200, res4->status);
  12451. EXPECT_EQ(content, res4->body);
  12452. EXPECT_FALSE(res4->has_header("Content-Range"));
  12453. svr.stop();
  12454. t.join();
  12455. std::remove(fname);
  12456. }
  12457. TEST(ETagTest, IfRangeWithDate) {
  12458. using namespace httplib;
  12459. // Create a test file
  12460. const char *fname = "if_range_date_testfile.txt";
  12461. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  12462. {
  12463. std::ofstream ofs(fname);
  12464. ofs << content;
  12465. ASSERT_TRUE(ofs.good());
  12466. }
  12467. Server svr;
  12468. svr.set_mount_point("/static", ".");
  12469. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12470. svr.wait_until_ready();
  12471. Client cli(HOST, PORT);
  12472. // First request: get Last-Modified
  12473. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  12474. ASSERT_TRUE(res1);
  12475. ASSERT_EQ(200, res1->status);
  12476. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12477. std::string last_modified = res1->get_header_value("Last-Modified");
  12478. // Range request with matching If-Range (date): should get 206
  12479. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  12480. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  12481. ASSERT_TRUE(res2);
  12482. EXPECT_EQ(206, res2->status);
  12483. EXPECT_EQ("FGHIJ", res2->body);
  12484. // Range request with old If-Range date: should get 200 (full content)
  12485. Headers h3 = {{"Range", "bytes=5-9"},
  12486. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12487. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  12488. ASSERT_TRUE(res3);
  12489. EXPECT_EQ(200, res3->status);
  12490. EXPECT_EQ(content, res3->body);
  12491. // Range request with future If-Range date: should get 206
  12492. Headers h4 = {{"Range", "bytes=0-4"},
  12493. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12494. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  12495. ASSERT_TRUE(res4);
  12496. EXPECT_EQ(206, res4->status);
  12497. EXPECT_EQ("ABCDE", res4->body);
  12498. svr.stop();
  12499. t.join();
  12500. std::remove(fname);
  12501. }
  12502. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  12503. using namespace httplib;
  12504. const char *fname = "etag_malformed.txt";
  12505. const char *content = "malformed-etag";
  12506. {
  12507. std::ofstream ofs(fname);
  12508. ofs << content;
  12509. ASSERT_TRUE(ofs.good());
  12510. }
  12511. Server svr;
  12512. svr.set_mount_point("/static", ".");
  12513. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12514. svr.wait_until_ready();
  12515. Client cli(HOST, PORT);
  12516. // baseline: should get 200 and an ETag
  12517. auto res1 = cli.Get("/static/etag_malformed.txt");
  12518. ASSERT_TRUE(res1);
  12519. ASSERT_EQ(200, res1->status);
  12520. ASSERT_TRUE(res1->has_header("ETag"));
  12521. // Malformed ETag value (missing quotes) should be treated as non-matching
  12522. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  12523. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  12524. ASSERT_TRUE(res_bad);
  12525. EXPECT_EQ(200, res_bad->status);
  12526. // Whitespace-only header value should be considered invalid / non-matching
  12527. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  12528. "Host: localhost\r\n"
  12529. "If-None-Match: \r\n"
  12530. "Connection: close\r\n"
  12531. "\r\n";
  12532. std::string out;
  12533. ASSERT_TRUE(send_request(5, raw_req, &out));
  12534. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12535. svr.stop();
  12536. t.join();
  12537. std::remove(fname);
  12538. }
  12539. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  12540. using namespace httplib;
  12541. const char *fname = "ims_invalid_format.txt";
  12542. const char *content = "ims-bad-format";
  12543. {
  12544. std::ofstream ofs(fname);
  12545. ofs << content;
  12546. ASSERT_TRUE(ofs.good());
  12547. }
  12548. Server svr;
  12549. svr.set_mount_point("/static", ".");
  12550. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12551. svr.wait_until_ready();
  12552. Client cli(HOST, PORT);
  12553. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  12554. ASSERT_TRUE(res1);
  12555. ASSERT_EQ(200, res1->status);
  12556. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12557. // If-Modified-Since with invalid format should not result in 304
  12558. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  12559. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  12560. ASSERT_TRUE(res_bad);
  12561. EXPECT_EQ(200, res_bad->status);
  12562. // If-Range with invalid date format should be treated as mismatch -> full
  12563. // content (200)
  12564. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  12565. {"If-Range", "invalid-date"}};
  12566. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  12567. ASSERT_TRUE(res_ifrange);
  12568. EXPECT_EQ(200, res_ifrange->status);
  12569. svr.stop();
  12570. t.join();
  12571. std::remove(fname);
  12572. }
  12573. TEST(ETagTest, IfRangeWithMalformedETag) {
  12574. using namespace httplib;
  12575. const char *fname = "ifrange_malformed.txt";
  12576. const std::string content = "0123456789";
  12577. {
  12578. std::ofstream ofs(fname);
  12579. ofs << content;
  12580. ASSERT_TRUE(ofs.good());
  12581. }
  12582. Server svr;
  12583. svr.set_mount_point("/static", ".");
  12584. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12585. svr.wait_until_ready();
  12586. Client cli(HOST, PORT);
  12587. // First request: get ETag
  12588. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  12589. ASSERT_TRUE(res1);
  12590. ASSERT_EQ(200, res1->status);
  12591. ASSERT_TRUE(res1->has_header("ETag"));
  12592. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  12593. // full content (200)
  12594. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  12595. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  12596. ASSERT_TRUE(res2);
  12597. EXPECT_EQ(200, res2->status);
  12598. EXPECT_EQ(content, res2->body);
  12599. svr.stop();
  12600. t.join();
  12601. std::remove(fname);
  12602. }
  12603. TEST(ETagTest, ExtremeLargeDateValues) {
  12604. using namespace httplib;
  12605. const char *fname = "ims_extreme_date.txt";
  12606. const char *content = "ims-extreme-date";
  12607. {
  12608. std::ofstream ofs(fname);
  12609. ofs << content;
  12610. ASSERT_TRUE(ofs.good());
  12611. }
  12612. Server svr;
  12613. svr.set_mount_point("/static", ".");
  12614. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12615. svr.wait_until_ready();
  12616. Client cli(HOST, PORT);
  12617. auto res1 = cli.Get(std::string("/static/") + fname);
  12618. ASSERT_TRUE(res1);
  12619. ASSERT_EQ(200, res1->status);
  12620. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12621. // Extremely large year that may overflow date parsing routines.
  12622. Headers h_large_date = {
  12623. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12624. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  12625. ASSERT_TRUE(res_bad);
  12626. // Expect server to treat this as invalid/mismatch and return full content
  12627. EXPECT_EQ(200, res_bad->status);
  12628. // If-Range with extremely large date should be treated as mismatch -> full
  12629. // content (200)
  12630. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  12631. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12632. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  12633. ASSERT_TRUE(res_ifrange);
  12634. EXPECT_EQ(200, res_ifrange->status);
  12635. svr.stop();
  12636. t.join();
  12637. std::remove(fname);
  12638. }
  12639. TEST(ETagTest, NegativeFileModificationTime) {
  12640. using namespace httplib;
  12641. const char *fname = "ims_negative_mtime.txt";
  12642. const std::string content = "negative-mtime";
  12643. {
  12644. std::ofstream ofs(fname);
  12645. ofs << content;
  12646. ASSERT_TRUE(ofs.good());
  12647. }
  12648. // Try to set file mtime to a negative value. This may fail on some
  12649. // platforms/filesystems; if it fails, the test will still verify server
  12650. // behaves safely by performing a regular conditional request.
  12651. #if defined(__APPLE__) || defined(__linux__)
  12652. bool set_negative = false;
  12653. do {
  12654. struct timeval times[2];
  12655. // access time: now
  12656. times[0].tv_sec = time(nullptr);
  12657. times[0].tv_usec = 0;
  12658. // modification time: negative (e.g., -1)
  12659. times[1].tv_sec = -1;
  12660. times[1].tv_usec = 0;
  12661. if (utimes(fname, times) == 0) { set_negative = true; }
  12662. } while (0);
  12663. #else
  12664. bool set_negative = false;
  12665. #endif
  12666. Server svr;
  12667. svr.set_mount_point("/static", ".");
  12668. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12669. svr.wait_until_ready();
  12670. Client cli(HOST, PORT);
  12671. auto res1 = cli.Get(std::string("/static/") + fname);
  12672. ASSERT_TRUE(res1);
  12673. ASSERT_EQ(200, res1->status);
  12674. bool has_last_modified = res1->has_header("Last-Modified");
  12675. std::string last_modified;
  12676. if (has_last_modified) {
  12677. last_modified = res1->get_header_value("Last-Modified");
  12678. }
  12679. if (set_negative) {
  12680. // If we successfully set a negative mtime, ensure server returns a
  12681. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  12682. // with an old date and ensure server handles it without crash.
  12683. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  12684. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  12685. ASSERT_TRUE(res2);
  12686. // Behavior may vary; at minimum ensure server responds (200 or 304).
  12687. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  12688. } else {
  12689. // Could not set negative mtime on this platform; fall back to verifying
  12690. // that normal invalid/malformed dates are treated safely (non-304).
  12691. Headers h_bad_date = {
  12692. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12693. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  12694. ASSERT_TRUE(res_bad);
  12695. EXPECT_EQ(200, res_bad->status);
  12696. }
  12697. svr.stop();
  12698. t.join();
  12699. std::remove(fname);
  12700. }
  12701. //==============================================================================
  12702. // SSE Parsing Tests
  12703. //==============================================================================
  12704. class SSEParsingTest : public ::testing::Test {
  12705. protected:
  12706. // Test helper that mimics SSE parsing behavior
  12707. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  12708. int &retry_ms) {
  12709. // Blank line signals end of event
  12710. if (line.empty() || line == "\r") { return true; }
  12711. // Lines starting with ':' are comments (ignored)
  12712. if (!line.empty() && line[0] == ':') { return false; }
  12713. // Find the colon separator
  12714. auto colon_pos = line.find(':');
  12715. if (colon_pos == std::string::npos) {
  12716. // Line with no colon is treated as field name with empty value
  12717. return false;
  12718. }
  12719. std::string field = line.substr(0, colon_pos);
  12720. std::string value;
  12721. // Value starts after colon, skip optional single space
  12722. if (colon_pos + 1 < line.size()) {
  12723. size_t value_start = colon_pos + 1;
  12724. if (line[value_start] == ' ') { value_start++; }
  12725. value = line.substr(value_start);
  12726. // Remove trailing \r if present
  12727. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  12728. }
  12729. // Handle known fields
  12730. if (field == "event") {
  12731. msg.event = value;
  12732. } else if (field == "data") {
  12733. // Multiple data lines are concatenated with newlines
  12734. if (!msg.data.empty()) { msg.data += "\n"; }
  12735. msg.data += value;
  12736. } else if (field == "id") {
  12737. // Empty id is valid (clears the last event ID)
  12738. msg.id = value;
  12739. } else if (field == "retry") {
  12740. // Parse retry interval in milliseconds
  12741. {
  12742. int v = 0;
  12743. auto res =
  12744. detail::from_chars(value.data(), value.data() + value.size(), v);
  12745. if (res.ec == std::errc{}) { retry_ms = v; }
  12746. }
  12747. }
  12748. // Unknown fields are ignored per SSE spec
  12749. return false;
  12750. }
  12751. };
  12752. // Test: Single-line data
  12753. TEST_F(SSEParsingTest, SingleLineData) {
  12754. sse::SSEMessage msg;
  12755. int retry_ms = 3000;
  12756. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  12757. EXPECT_EQ(msg.data, "hello");
  12758. EXPECT_EQ(msg.event, "message");
  12759. // Blank line ends event
  12760. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12761. }
  12762. // Test: Multi-line data
  12763. TEST_F(SSEParsingTest, MultiLineData) {
  12764. sse::SSEMessage msg;
  12765. int retry_ms = 3000;
  12766. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  12767. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  12768. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  12769. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  12770. }
  12771. // Test: Custom event types
  12772. TEST_F(SSEParsingTest, CustomEventType) {
  12773. sse::SSEMessage msg;
  12774. int retry_ms = 3000;
  12775. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  12776. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  12777. EXPECT_EQ(msg.event, "update");
  12778. EXPECT_EQ(msg.data, "payload");
  12779. }
  12780. // Test: Event ID handling
  12781. TEST_F(SSEParsingTest, EventIdHandling) {
  12782. sse::SSEMessage msg;
  12783. int retry_ms = 3000;
  12784. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  12785. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  12786. EXPECT_EQ(msg.id, "12345");
  12787. }
  12788. // Test: Empty event ID (clears last event ID)
  12789. TEST_F(SSEParsingTest, EmptyEventId) {
  12790. sse::SSEMessage msg;
  12791. msg.id = "previous";
  12792. int retry_ms = 3000;
  12793. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  12794. EXPECT_EQ(msg.id, "");
  12795. }
  12796. // Test: Retry field parsing
  12797. TEST_F(SSEParsingTest, RetryFieldParsing) {
  12798. sse::SSEMessage msg;
  12799. int retry_ms = 3000;
  12800. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  12801. EXPECT_EQ(retry_ms, 5000);
  12802. }
  12803. // Test: Invalid retry value
  12804. TEST_F(SSEParsingTest, InvalidRetryValue) {
  12805. sse::SSEMessage msg;
  12806. int retry_ms = 3000;
  12807. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  12808. EXPECT_EQ(retry_ms, 3000); // Unchanged
  12809. }
  12810. // Test: Comments (lines starting with :)
  12811. TEST_F(SSEParsingTest, CommentsIgnored) {
  12812. sse::SSEMessage msg;
  12813. int retry_ms = 3000;
  12814. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  12815. EXPECT_EQ(msg.data, "");
  12816. EXPECT_EQ(msg.event, "message");
  12817. }
  12818. // Test: Colon in value
  12819. TEST_F(SSEParsingTest, ColonInValue) {
  12820. sse::SSEMessage msg;
  12821. int retry_ms = 3000;
  12822. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  12823. EXPECT_EQ(msg.data, "hello:world:test");
  12824. }
  12825. // Test: Line with no colon (field name only)
  12826. TEST_F(SSEParsingTest, FieldNameOnly) {
  12827. sse::SSEMessage msg;
  12828. int retry_ms = 3000;
  12829. // According to SSE spec, this is treated as field name with empty value
  12830. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  12831. // Since we don't recognize "data" without colon, data should be empty
  12832. EXPECT_EQ(msg.data, "");
  12833. }
  12834. // Test: Trailing \r handling
  12835. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  12836. sse::SSEMessage msg;
  12837. int retry_ms = 3000;
  12838. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  12839. EXPECT_EQ(msg.data, "hello");
  12840. }
  12841. // Test: Unknown fields ignored
  12842. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  12843. sse::SSEMessage msg;
  12844. int retry_ms = 3000;
  12845. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  12846. EXPECT_EQ(msg.data, "");
  12847. EXPECT_EQ(msg.event, "message");
  12848. }
  12849. // Test: Space after colon is optional
  12850. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  12851. sse::SSEMessage msg1, msg2;
  12852. int retry_ms = 3000;
  12853. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  12854. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  12855. EXPECT_EQ(msg1.data, "hello");
  12856. EXPECT_EQ(msg2.data, "hello");
  12857. }
  12858. // Test: SSEMessage clear
  12859. TEST_F(SSEParsingTest, MessageClear) {
  12860. sse::SSEMessage msg;
  12861. msg.event = "custom";
  12862. msg.data = "some data";
  12863. msg.id = "123";
  12864. msg.clear();
  12865. EXPECT_EQ(msg.event, "message");
  12866. EXPECT_EQ(msg.data, "");
  12867. EXPECT_EQ(msg.id, "");
  12868. }
  12869. // Test: Complete event parsing
  12870. TEST_F(SSEParsingTest, CompleteEventParsing) {
  12871. sse::SSEMessage msg;
  12872. int retry_ms = 3000;
  12873. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  12874. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  12875. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  12876. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  12877. // Blank line ends event
  12878. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12879. EXPECT_EQ(msg.event, "notification");
  12880. EXPECT_EQ(msg.id, "evt-42");
  12881. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  12882. EXPECT_EQ(retry_ms, 1000);
  12883. }
  12884. //==============================================================================
  12885. // Integration Tests with Server
  12886. //==============================================================================
  12887. class SSEIntegrationTest : public ::testing::Test {
  12888. protected:
  12889. void SetUp() override {
  12890. stop_server_.store(false);
  12891. events_.clear();
  12892. server_ = httplib::detail::make_unique<Server>();
  12893. setup_server();
  12894. start_server();
  12895. }
  12896. void TearDown() override {
  12897. stop_server_.store(true);
  12898. event_cv_.notify_all();
  12899. server_->stop();
  12900. if (server_thread_.joinable()) { server_thread_.join(); }
  12901. }
  12902. void setup_server() {
  12903. // Simple SSE endpoint
  12904. server_->Get("/events", [this](const Request &req, Response &res) {
  12905. auto last_id = req.get_header_value("Last-Event-ID");
  12906. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  12907. res.set_chunked_content_provider(
  12908. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  12909. std::unique_lock<std::mutex> lock(event_mutex_);
  12910. if (event_cv_.wait_for(
  12911. lock, std::chrono::milliseconds(200), [this] {
  12912. return !events_.empty() || stop_server_.load();
  12913. })) {
  12914. if (stop_server_.load()) { return false; }
  12915. if (!events_.empty()) {
  12916. std::string event = events_.front();
  12917. events_.erase(events_.begin());
  12918. sink.write(event.data(), event.size());
  12919. return true;
  12920. }
  12921. }
  12922. return !stop_server_.load();
  12923. });
  12924. });
  12925. // Endpoint that returns error
  12926. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  12927. res.status = 500;
  12928. res.set_content("Internal Server Error", "text/plain");
  12929. });
  12930. // Endpoint for custom event types
  12931. server_->Get("/custom-events", [](const Request &, Response &res) {
  12932. res.set_chunked_content_provider(
  12933. "text/event-stream", [](size_t offset, DataSink &sink) {
  12934. if (offset == 0) {
  12935. std::string event = "event: update\ndata: updated\n\n"
  12936. "event: delete\ndata: deleted\n\n";
  12937. sink.write(event.data(), event.size());
  12938. }
  12939. return false; // End stream after sending
  12940. });
  12941. });
  12942. }
  12943. void start_server() {
  12944. port_ = server_->bind_to_any_port(HOST);
  12945. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  12946. // Wait for server to start
  12947. while (!server_->is_running()) {
  12948. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12949. }
  12950. }
  12951. int get_port() const { return port_; }
  12952. void send_event(const std::string &event) {
  12953. std::lock_guard<std::mutex> lock(event_mutex_);
  12954. events_.push_back(event);
  12955. event_cv_.notify_all();
  12956. }
  12957. std::unique_ptr<Server> server_;
  12958. std::thread server_thread_;
  12959. std::mutex event_mutex_;
  12960. std::condition_variable event_cv_;
  12961. std::vector<std::string> events_;
  12962. std::atomic<bool> stop_server_{false};
  12963. std::string last_received_event_id_;
  12964. int port_ = 0;
  12965. };
  12966. // Test: Successful connection and on_open callback
  12967. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  12968. // Add a simple endpoint that sends one event and closes
  12969. server_->Get("/simple-event", [](const Request &, Response &res) {
  12970. res.set_chunked_content_provider(
  12971. "text/event-stream", [](size_t offset, DataSink &sink) {
  12972. if (offset == 0) {
  12973. std::string event = "data: hello\n\n";
  12974. sink.write(event.data(), event.size());
  12975. }
  12976. return false; // Close stream after sending
  12977. });
  12978. });
  12979. Client client("localhost", get_port());
  12980. sse::SSEClient sse(client, "/simple-event");
  12981. std::atomic<bool> open_called{false};
  12982. std::atomic<bool> message_received{false};
  12983. sse.on_open([&open_called]() { open_called.store(true); });
  12984. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  12985. if (msg.data == "hello") { message_received.store(true); }
  12986. });
  12987. sse.set_reconnect_interval(100);
  12988. sse.set_max_reconnect_attempts(1);
  12989. // Start async
  12990. sse.start_async();
  12991. // Wait for message to be processed
  12992. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12993. sse.stop();
  12994. EXPECT_TRUE(open_called.load());
  12995. EXPECT_TRUE(message_received.load());
  12996. }
  12997. // Test: on_message callback
  12998. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  12999. // Endpoint that sends multiple events then closes
  13000. server_->Get("/multi-event", [](const Request &, Response &res) {
  13001. res.set_chunked_content_provider(
  13002. "text/event-stream", [](size_t offset, DataSink &sink) {
  13003. if (offset == 0) {
  13004. std::string events = "data: message1\n\ndata: message2\n\n";
  13005. sink.write(events.data(), events.size());
  13006. }
  13007. return false;
  13008. });
  13009. });
  13010. Client client("localhost", get_port());
  13011. sse::SSEClient sse(client, "/multi-event");
  13012. std::vector<std::string> received_messages;
  13013. std::mutex messages_mutex;
  13014. sse.on_message([&](const sse::SSEMessage &msg) {
  13015. std::lock_guard<std::mutex> lock(messages_mutex);
  13016. received_messages.push_back(msg.data);
  13017. });
  13018. sse.set_reconnect_interval(100);
  13019. sse.set_max_reconnect_attempts(1);
  13020. sse.start_async();
  13021. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13022. sse.stop();
  13023. std::lock_guard<std::mutex> lock(messages_mutex);
  13024. EXPECT_GE(received_messages.size(), 2u);
  13025. if (received_messages.size() >= 2) {
  13026. EXPECT_EQ(received_messages[0], "message1");
  13027. EXPECT_EQ(received_messages[1], "message2");
  13028. }
  13029. }
  13030. // Test: on_event for specific types
  13031. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  13032. Client client("localhost", get_port());
  13033. sse::SSEClient sse(client, "/custom-events");
  13034. std::atomic<bool> update_received{false};
  13035. std::atomic<bool> delete_received{false};
  13036. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  13037. if (msg.data == "updated") { update_received.store(true); }
  13038. });
  13039. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  13040. if (msg.data == "deleted") { delete_received.store(true); }
  13041. });
  13042. sse.set_max_reconnect_attempts(1);
  13043. sse.start_async();
  13044. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  13045. sse.stop();
  13046. EXPECT_TRUE(update_received.load());
  13047. EXPECT_TRUE(delete_received.load());
  13048. }
  13049. // Test: on_error callback on connection failure
  13050. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  13051. // Connect to a non-existent port
  13052. Client client("localhost", 59999);
  13053. sse::SSEClient sse(client, "/events");
  13054. std::atomic<bool> error_called{false};
  13055. Error received_error = Error::Success;
  13056. sse.on_error([&](Error err) {
  13057. error_called.store(true);
  13058. received_error = err;
  13059. });
  13060. sse.set_reconnect_interval(50);
  13061. sse.set_max_reconnect_attempts(1);
  13062. sse.start_async();
  13063. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13064. sse.stop();
  13065. EXPECT_TRUE(error_called.load());
  13066. EXPECT_NE(received_error, Error::Success);
  13067. }
  13068. // Test: Last-Event-ID header sent on reconnect
  13069. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  13070. // Endpoint that sends event with ID
  13071. server_->Get("/event-with-id", [](const Request &, Response &res) {
  13072. res.set_chunked_content_provider(
  13073. "text/event-stream", [](size_t offset, DataSink &sink) {
  13074. if (offset == 0) {
  13075. std::string event = "id: evt-123\ndata: test\n\n";
  13076. sink.write(event.data(), event.size());
  13077. }
  13078. return false;
  13079. });
  13080. });
  13081. Client client("localhost", get_port());
  13082. sse::SSEClient sse(client, "/event-with-id");
  13083. std::atomic<bool> id_received{false};
  13084. sse.on_message([&](const sse::SSEMessage &msg) {
  13085. if (!msg.id.empty()) { id_received.store(true); }
  13086. });
  13087. sse.set_reconnect_interval(100);
  13088. sse.set_max_reconnect_attempts(1);
  13089. sse.start_async();
  13090. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13091. sse.stop();
  13092. EXPECT_TRUE(id_received.load());
  13093. EXPECT_EQ(sse.last_event_id(), "evt-123");
  13094. }
  13095. // Test: Manual stop
  13096. TEST_F(SSEIntegrationTest, ManualStop) {
  13097. // Endpoint that sends one event and stays open briefly
  13098. std::atomic<bool> handler_running{true};
  13099. server_->Get("/stay-open", [&handler_running](const Request &,
  13100. Response &res) {
  13101. res.set_chunked_content_provider(
  13102. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  13103. if (offset == 0) {
  13104. std::string event = "data: connected\n\n";
  13105. sink.write(event.data(), event.size());
  13106. }
  13107. // Keep connection open while handler_running is true
  13108. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  13109. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13110. }
  13111. return false;
  13112. });
  13113. });
  13114. Client client("localhost", get_port());
  13115. sse::SSEClient sse(client, "/stay-open");
  13116. std::atomic<bool> connected{false};
  13117. sse.on_open([&connected]() { connected.store(true); });
  13118. sse.set_reconnect_interval(100);
  13119. sse.set_max_reconnect_attempts(1);
  13120. sse.start_async();
  13121. // Wait for connection to establish
  13122. for (int i = 0; i < 20 && !connected.load(); ++i) {
  13123. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13124. }
  13125. EXPECT_TRUE(connected.load());
  13126. EXPECT_TRUE(sse.is_connected());
  13127. // Signal handler to stop
  13128. handler_running.store(false);
  13129. // Stop SSE client
  13130. sse.stop();
  13131. EXPECT_FALSE(sse.is_connected());
  13132. }
  13133. // Test: SSEClient with custom headers
  13134. TEST_F(SSEIntegrationTest, CustomHeaders) {
  13135. // Setup a server endpoint that checks for custom header
  13136. std::atomic<bool> header_received{false};
  13137. server_->Get("/header-check", [&](const Request &req, Response &res) {
  13138. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  13139. header_received.store(true);
  13140. }
  13141. res.set_chunked_content_provider("text/event-stream",
  13142. [](size_t, DataSink &) { return false; });
  13143. });
  13144. Client client("localhost", get_port());
  13145. Headers headers = {{"X-Custom-Header", "custom-value"}};
  13146. sse::SSEClient sse(client, "/header-check", headers);
  13147. sse.set_max_reconnect_attempts(1);
  13148. sse.start_async();
  13149. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13150. sse.stop();
  13151. EXPECT_TRUE(header_received.load());
  13152. }
  13153. // Test: Reconnect interval configuration
  13154. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  13155. Client client("localhost", get_port());
  13156. sse::SSEClient sse(client, "/events");
  13157. auto &result = sse.set_reconnect_interval(500);
  13158. // Builder pattern should return reference to self
  13159. EXPECT_EQ(&result, &sse);
  13160. }
  13161. // Test: Max reconnect attempts
  13162. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  13163. // Connect to non-existent port to force reconnects
  13164. Client client("localhost", 59998);
  13165. sse::SSEClient sse(client, "/events");
  13166. std::atomic<int> error_count{0};
  13167. sse.on_error([&](Error) { error_count.fetch_add(1); });
  13168. sse.set_reconnect_interval(50);
  13169. sse.set_max_reconnect_attempts(2);
  13170. auto start = std::chrono::steady_clock::now();
  13171. sse.start(); // Blocking call
  13172. auto end = std::chrono::steady_clock::now();
  13173. // Should have stopped after 2 failed attempts
  13174. EXPECT_GE(error_count.load(), 2);
  13175. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  13176. auto duration =
  13177. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  13178. #ifdef _WIN32
  13179. // Windows is much slower for socket connection failures
  13180. EXPECT_LT(duration.count(), 7000);
  13181. #else
  13182. EXPECT_LT(duration.count(), 1000);
  13183. #endif
  13184. }
  13185. // Test: Multi-line data in integration
  13186. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  13187. // Endpoint with multi-line data
  13188. server_->Get("/multiline-data", [](const Request &, Response &res) {
  13189. res.set_chunked_content_provider(
  13190. "text/event-stream", [](size_t offset, DataSink &sink) {
  13191. if (offset == 0) {
  13192. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  13193. sink.write(event.data(), event.size());
  13194. }
  13195. return false;
  13196. });
  13197. });
  13198. Client client("localhost", get_port());
  13199. sse::SSEClient sse(client, "/multiline-data");
  13200. std::string received_data;
  13201. std::mutex data_mutex;
  13202. sse.on_message([&](const sse::SSEMessage &msg) {
  13203. std::lock_guard<std::mutex> lock(data_mutex);
  13204. received_data = msg.data;
  13205. });
  13206. sse.set_reconnect_interval(100);
  13207. sse.set_max_reconnect_attempts(1);
  13208. sse.start_async();
  13209. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13210. sse.stop();
  13211. std::lock_guard<std::mutex> lock(data_mutex);
  13212. EXPECT_EQ(received_data, "line1\nline2\nline3");
  13213. }
  13214. // Test: Auto-reconnect after server disconnection
  13215. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  13216. std::atomic<int> connection_count{0};
  13217. std::atomic<int> message_count{0};
  13218. // Endpoint that sends one event and closes, forcing reconnect
  13219. server_->Get("/reconnect-test",
  13220. [&connection_count](const Request &, Response &res) {
  13221. connection_count.fetch_add(1);
  13222. res.set_chunked_content_provider(
  13223. "text/event-stream", [](size_t offset, DataSink &sink) {
  13224. if (offset == 0) {
  13225. std::string event = "data: hello\n\n";
  13226. sink.write(event.data(), event.size());
  13227. }
  13228. return false; // Close connection after sending
  13229. });
  13230. });
  13231. Client client("localhost", get_port());
  13232. sse::SSEClient sse(client, "/reconnect-test");
  13233. sse.on_message([&message_count](const sse::SSEMessage &) {
  13234. message_count.fetch_add(1);
  13235. });
  13236. sse.set_reconnect_interval(100);
  13237. sse.set_max_reconnect_attempts(3);
  13238. sse.start_async();
  13239. // Wait long enough for multiple reconnects
  13240. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13241. sse.stop();
  13242. // Should have connected multiple times (initial + reconnects)
  13243. EXPECT_GE(connection_count.load(), 2);
  13244. // Should have received messages from multiple connections
  13245. EXPECT_GE(message_count.load(), 2);
  13246. }
  13247. // Test: Last-Event-ID sent on reconnect
  13248. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  13249. std::atomic<int> connection_count{0};
  13250. std::vector<std::string> received_last_event_ids;
  13251. std::mutex id_mutex;
  13252. // Endpoint that checks Last-Event-ID header and sends event with ID
  13253. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  13254. int conn = connection_count.fetch_add(1);
  13255. // Capture the Last-Event-ID header from each connection
  13256. {
  13257. std::lock_guard<std::mutex> lock(id_mutex);
  13258. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  13259. }
  13260. res.set_chunked_content_provider(
  13261. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  13262. if (offset == 0) {
  13263. std::string event =
  13264. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  13265. sink.write(event.data(), event.size());
  13266. }
  13267. return false;
  13268. });
  13269. });
  13270. Client client("localhost", get_port());
  13271. sse::SSEClient sse(client, "/reconnect-with-id");
  13272. sse.set_reconnect_interval(100);
  13273. sse.set_max_reconnect_attempts(3);
  13274. sse.start_async();
  13275. // Wait for at least 2 connections
  13276. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13277. sse.stop();
  13278. // Verify behavior
  13279. std::lock_guard<std::mutex> lock(id_mutex);
  13280. EXPECT_GE(received_last_event_ids.size(), 2u);
  13281. // First connection should have no Last-Event-ID
  13282. if (!received_last_event_ids.empty()) {
  13283. EXPECT_EQ(received_last_event_ids[0], "");
  13284. }
  13285. // Second connection should have Last-Event-ID from first connection
  13286. if (received_last_event_ids.size() >= 2) {
  13287. EXPECT_EQ(received_last_event_ids[1], "event-0");
  13288. }
  13289. }
  13290. TEST(Issue2318Test, EmptyHostString) {
  13291. {
  13292. httplib::Client cli_empty("", PORT);
  13293. auto res = cli_empty.Get("/");
  13294. ASSERT_FALSE(res);
  13295. EXPECT_EQ(httplib::Error::Connection, res.error());
  13296. }
  13297. {
  13298. httplib::Client cli(" ", PORT);
  13299. auto res = cli.Get("/");
  13300. ASSERT_FALSE(res);
  13301. EXPECT_EQ(httplib::Error::Connection, res.error());
  13302. }
  13303. }
  13304. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13305. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  13306. Server svr;
  13307. // Set a small payload limit (1KB)
  13308. svr.set_payload_max_length(1024);
  13309. svr.Post("/test", [&](const Request &req, Response &res) {
  13310. res.set_content("Body size: " + std::to_string(req.body.size()),
  13311. "text/plain");
  13312. });
  13313. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13314. auto se = detail::scope_exit([&] {
  13315. svr.stop();
  13316. listen_thread.join();
  13317. });
  13318. svr.wait_until_ready();
  13319. // Create data that compresses well but exceeds limit when decompressed
  13320. // 8KB of repeated null bytes compresses to a very small size
  13321. std::string original_data(8 * 1024, '\0');
  13322. // Compress the data using gzip
  13323. std::string compressed_data;
  13324. detail::gzip_compressor compressor;
  13325. compressor.compress(original_data.data(), original_data.size(), true,
  13326. [&](const char *data, size_t size) {
  13327. compressed_data.append(data, size);
  13328. return true;
  13329. });
  13330. // Verify compression worked (compressed should be much smaller)
  13331. ASSERT_LT(compressed_data.size(), original_data.size());
  13332. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  13333. // Send compressed data with Content-Encoding: gzip
  13334. Client cli(HOST, PORT);
  13335. Headers headers = {{"Content-Encoding", "gzip"}};
  13336. auto res =
  13337. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  13338. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  13339. ASSERT_TRUE(res);
  13340. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13341. }
  13342. #endif
  13343. // ============================================================================
  13344. // OpenSSL-Specific Tests
  13345. // ============================================================================
  13346. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13347. X509 *readCertificate(const std::string &strFileName) {
  13348. std::ifstream inStream(strFileName);
  13349. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  13350. std::istreambuf_iterator<char>());
  13351. if (strCertPEM.empty()) return (nullptr);
  13352. BIO *pbCert = BIO_new(BIO_s_mem());
  13353. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  13354. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  13355. BIO_free(pbCert);
  13356. return (pCert);
  13357. }
  13358. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  13359. std::ifstream inStream(strFileName);
  13360. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  13361. std::istreambuf_iterator<char>());
  13362. if (strPrivateKeyPEM.empty()) return (nullptr);
  13363. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  13364. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  13365. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  13366. BIO_free(pbPrivKey);
  13367. return (pPrivateKey);
  13368. }
  13369. TEST(BindServerTest, UpdateCerts) {
  13370. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13371. int port = svr.bind_to_any_port("0.0.0.0");
  13372. ASSERT_TRUE(svr.is_valid());
  13373. ASSERT_TRUE(port > 0);
  13374. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13375. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13376. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13377. ASSERT_TRUE(cert != nullptr);
  13378. ASSERT_TRUE(ca_cert != nullptr);
  13379. ASSERT_TRUE(key != nullptr);
  13380. X509_STORE *cert_store = X509_STORE_new();
  13381. X509_STORE_add_cert(cert_store, ca_cert);
  13382. // svr.update_certs(cert, key, cert_store); // deprecated
  13383. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13384. CLIENT_CA_CERT_FILE);
  13385. ASSERT_TRUE(svr.is_valid());
  13386. svr.stop();
  13387. X509_STORE_free(cert_store);
  13388. X509_free(cert);
  13389. X509_free(ca_cert);
  13390. EVP_PKEY_free(key);
  13391. }
  13392. // Test that SSLServer(X509*, EVP_PKEY*, X509_STORE*) constructor sets
  13393. // client CA list correctly for TLS handshake
  13394. TEST(SSLClientServerTest, X509ConstructorSetsClientCAList) {
  13395. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13396. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13397. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13398. ASSERT_TRUE(cert != nullptr);
  13399. ASSERT_TRUE(ca_cert != nullptr);
  13400. ASSERT_TRUE(key != nullptr);
  13401. X509_STORE *cert_store = X509_STORE_new();
  13402. X509_STORE_add_cert(cert_store, ca_cert);
  13403. // Use X509-based constructor (deprecated but should still work correctly)
  13404. #pragma GCC diagnostic push
  13405. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  13406. SSLServer svr(cert, key, cert_store);
  13407. #pragma GCC diagnostic pop
  13408. ASSERT_TRUE(svr.is_valid());
  13409. // Verify that client CA list is set in SSL_CTX
  13410. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13411. ASSERT_TRUE(ssl_ctx != nullptr);
  13412. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13413. ASSERT_TRUE(ca_list != nullptr);
  13414. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13415. X509_free(cert);
  13416. X509_free(ca_cert);
  13417. EVP_PKEY_free(key);
  13418. }
  13419. // Test that update_certs() updates client CA list correctly
  13420. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  13421. // Start with file-based constructor
  13422. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13423. ASSERT_TRUE(svr.is_valid());
  13424. // Initially no client CA list should be set
  13425. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13426. ASSERT_TRUE(ssl_ctx != nullptr);
  13427. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  13428. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  13429. EXPECT_EQ(0, count_before);
  13430. // Now update with client CA (PEM string)
  13431. std::string cert_pem, key_pem, ca_pem;
  13432. read_file(SERVER_CERT_FILE, cert_pem);
  13433. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13434. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13435. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  13436. ASSERT_TRUE(svr.is_valid());
  13437. // Now client CA list should be set
  13438. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  13439. ASSERT_TRUE(ca_list_after != nullptr);
  13440. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  13441. }
  13442. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  13443. // Test that the file-path SSLServer constructor properly sets the client CA
  13444. // list that is sent to clients during the TLS handshake (CertificateRequest)
  13445. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13446. ASSERT_TRUE(svr.is_valid());
  13447. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13448. ASSERT_TRUE(ssl_ctx != nullptr);
  13449. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13450. ASSERT_TRUE(ca_list != nullptr);
  13451. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13452. }
  13453. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  13454. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  13455. // prepare large data
  13456. std::random_device seed_gen;
  13457. std::mt19937 random(seed_gen());
  13458. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  13459. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  13460. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  13461. // server
  13462. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13463. ASSERT_TRUE(svr.is_valid());
  13464. svr.Post("/binary", [&](const Request &req, Response &res) {
  13465. EXPECT_EQ(large_size_byte, req.body.size());
  13466. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  13467. res.set_content(req.body, "application/octet-stream");
  13468. });
  13469. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  13470. auto se = detail::scope_exit([&] {
  13471. svr.stop();
  13472. listen_thread.join();
  13473. ASSERT_FALSE(svr.is_running());
  13474. });
  13475. svr.wait_until_ready();
  13476. // client POST
  13477. SSLClient cli("localhost", PORT);
  13478. cli.enable_server_certificate_verification(false);
  13479. cli.set_read_timeout(std::chrono::seconds(100));
  13480. cli.set_write_timeout(std::chrono::seconds(100));
  13481. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  13482. large_size_byte, "application/octet-stream");
  13483. // compare
  13484. EXPECT_EQ(StatusCode::OK_200, res->status);
  13485. EXPECT_EQ(large_size_byte, res->body.size());
  13486. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  13487. }
  13488. #endif
  13489. // ============================================================================
  13490. // MbedTLS-Specific Tests
  13491. // ============================================================================
  13492. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  13493. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  13494. using namespace httplib::tls;
  13495. // Track if callback was invoked
  13496. bool callback_invoked = false;
  13497. // The callback receives void* ctx which is actually MbedTlsContext*
  13498. // We can access the mbedtls_ssl_config via the context
  13499. auto setup_callback = [&callback_invoked](void *ctx) {
  13500. callback_invoked = true;
  13501. // Cast to MbedTlsContext* to access the ssl config
  13502. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  13503. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  13504. // Use static variables to hold certificate data (simplified for test)
  13505. static mbedtls_x509_crt own_cert;
  13506. static mbedtls_pk_context own_key;
  13507. static mbedtls_x509_crt ca_chain;
  13508. static bool initialized = false;
  13509. if (!initialized) {
  13510. mbedtls_x509_crt_init(&own_cert);
  13511. mbedtls_pk_init(&own_key);
  13512. mbedtls_x509_crt_init(&ca_chain);
  13513. // Load server certificate
  13514. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  13515. return false;
  13516. }
  13517. // Load server private key
  13518. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  13519. #if MBEDTLS_VERSION_MAJOR >= 3
  13520. ,
  13521. mbedtls_ctr_drbg_random, nullptr
  13522. #endif
  13523. ) != 0) {
  13524. return false;
  13525. }
  13526. // Load CA chain for client verification
  13527. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  13528. return false;
  13529. }
  13530. initialized = true;
  13531. }
  13532. // Configure the SSL config
  13533. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  13534. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  13535. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  13536. // Set minimum TLS version using mbedTLS native API
  13537. #if MBEDTLS_VERSION_MAJOR >= 3
  13538. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  13539. #else
  13540. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  13541. MBEDTLS_SSL_MINOR_VERSION_3);
  13542. #endif
  13543. return true;
  13544. };
  13545. SSLServer svr(setup_callback);
  13546. ASSERT_TRUE(svr.is_valid());
  13547. ASSERT_TRUE(callback_invoked);
  13548. svr.Get("/test", [&](const Request &req, Response &res) {
  13549. res.set_content("test", "text/plain");
  13550. auto cert = req.peer_cert();
  13551. ASSERT_TRUE(static_cast<bool>(cert));
  13552. auto common_name = cert.subject_cn();
  13553. EXPECT_EQ("Common Name", common_name);
  13554. });
  13555. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13556. auto se = detail::scope_exit([&] {
  13557. svr.stop();
  13558. t.join();
  13559. ASSERT_FALSE(svr.is_running());
  13560. });
  13561. svr.wait_until_ready();
  13562. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13563. cli.enable_server_certificate_verification(false);
  13564. cli.set_connection_timeout(30);
  13565. auto res = cli.Get("/test");
  13566. ASSERT_TRUE(res);
  13567. ASSERT_EQ(StatusCode::OK_200, res->status);
  13568. }
  13569. #endif
  13570. // WebSocket Tests
  13571. TEST(WebSocketTest, RSVBitsMustBeZero) {
  13572. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  13573. // defining the meaning of these bits has been negotiated.
  13574. auto make_frame = [](uint8_t first_byte) {
  13575. std::string frame;
  13576. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  13577. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  13578. frame += "Hello";
  13579. return frame;
  13580. };
  13581. // RSV1 set (0x40)
  13582. {
  13583. detail::BufferStream strm;
  13584. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  13585. ws::Opcode opcode;
  13586. std::string payload;
  13587. bool fin;
  13588. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13589. false, 1024));
  13590. }
  13591. // RSV2 set (0x20)
  13592. {
  13593. detail::BufferStream strm;
  13594. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  13595. ws::Opcode opcode;
  13596. std::string payload;
  13597. bool fin;
  13598. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13599. false, 1024));
  13600. }
  13601. // RSV3 set (0x10)
  13602. {
  13603. detail::BufferStream strm;
  13604. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  13605. ws::Opcode opcode;
  13606. std::string payload;
  13607. bool fin;
  13608. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13609. false, 1024));
  13610. }
  13611. // No RSV bits set - should succeed
  13612. {
  13613. detail::BufferStream strm;
  13614. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  13615. ws::Opcode opcode;
  13616. std::string payload;
  13617. bool fin;
  13618. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13619. false, 1024));
  13620. EXPECT_EQ(ws::Opcode::Text, opcode);
  13621. EXPECT_EQ("Hello", payload);
  13622. EXPECT_TRUE(fin);
  13623. }
  13624. }
  13625. TEST(WebSocketTest, ControlFrameValidation) {
  13626. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  13627. // payload length <= 125.
  13628. // Ping with FIN=0 - must be rejected
  13629. {
  13630. detail::BufferStream strm;
  13631. std::string frame;
  13632. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  13633. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13634. strm.write(frame.data(), frame.size());
  13635. ws::Opcode opcode;
  13636. std::string payload;
  13637. bool fin;
  13638. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13639. false, 1024));
  13640. }
  13641. // Close with FIN=0 - must be rejected
  13642. {
  13643. detail::BufferStream strm;
  13644. std::string frame;
  13645. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  13646. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13647. strm.write(frame.data(), frame.size());
  13648. ws::Opcode opcode;
  13649. std::string payload;
  13650. bool fin;
  13651. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13652. false, 1024));
  13653. }
  13654. // Ping with payload_len=126 (extended length) - must be rejected
  13655. {
  13656. detail::BufferStream strm;
  13657. std::string frame;
  13658. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13659. frame += static_cast<char>(126); // payload_len=126 (>125)
  13660. frame += static_cast<char>(0x00); // extended length high byte
  13661. frame += static_cast<char>(126); // extended length low byte
  13662. frame += std::string(126, 'x');
  13663. strm.write(frame.data(), frame.size());
  13664. ws::Opcode opcode;
  13665. std::string payload;
  13666. bool fin;
  13667. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13668. false, 1024));
  13669. }
  13670. // Ping with FIN=1 and payload_len=125 - should succeed
  13671. {
  13672. detail::BufferStream strm;
  13673. std::string frame;
  13674. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13675. frame += static_cast<char>(125); // payload_len=125
  13676. frame += std::string(125, 'x');
  13677. strm.write(frame.data(), frame.size());
  13678. ws::Opcode opcode;
  13679. std::string payload;
  13680. bool fin;
  13681. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13682. false, 1024));
  13683. EXPECT_EQ(ws::Opcode::Ping, opcode);
  13684. EXPECT_EQ(125u, payload.size());
  13685. EXPECT_TRUE(fin);
  13686. }
  13687. }
  13688. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  13689. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  13690. // length MUST be 0.
  13691. // MSB set - must be rejected
  13692. {
  13693. detail::BufferStream strm;
  13694. std::string frame;
  13695. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13696. frame += static_cast<char>(127); // 64-bit extended length
  13697. frame += static_cast<char>(0x80); // MSB set (invalid)
  13698. frame += std::string(7, '\0'); // remaining 7 bytes of length
  13699. strm.write(frame.data(), frame.size());
  13700. ws::Opcode opcode;
  13701. std::string payload;
  13702. bool fin;
  13703. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13704. false, 1024));
  13705. }
  13706. // MSB clear - should pass length parsing (will be rejected by max_len,
  13707. // but that's a different check; use a small length to verify)
  13708. {
  13709. detail::BufferStream strm;
  13710. std::string frame;
  13711. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13712. frame += static_cast<char>(127); // 64-bit extended length
  13713. frame += std::string(7, '\0'); // high bytes = 0
  13714. frame += static_cast<char>(0x03); // length = 3
  13715. frame += "abc";
  13716. strm.write(frame.data(), frame.size());
  13717. ws::Opcode opcode;
  13718. std::string payload;
  13719. bool fin;
  13720. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13721. false, 1024));
  13722. EXPECT_EQ(ws::Opcode::Text, opcode);
  13723. EXPECT_EQ("abc", payload);
  13724. }
  13725. }
  13726. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  13727. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  13728. // Valid UTF-8
  13729. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  13730. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  13731. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  13732. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  13733. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  13734. // Invalid UTF-8
  13735. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  13736. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  13737. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  13738. EXPECT_FALSE(
  13739. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  13740. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  13741. }
  13742. TEST(WebSocketTest, ConnectAndDisconnect) {
  13743. Server svr;
  13744. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  13745. std::string msg;
  13746. while (ws.read(msg)) {}
  13747. });
  13748. auto port = svr.bind_to_any_port(HOST);
  13749. std::thread t([&]() { svr.listen_after_bind(); });
  13750. svr.wait_until_ready();
  13751. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  13752. ASSERT_TRUE(client.connect());
  13753. EXPECT_TRUE(client.is_open());
  13754. client.close();
  13755. EXPECT_FALSE(client.is_open());
  13756. svr.stop();
  13757. t.join();
  13758. }
  13759. TEST(WebSocketTest, ValidURL) {
  13760. ws::WebSocketClient ws1("ws://localhost:8080/path");
  13761. EXPECT_TRUE(ws1.is_valid());
  13762. ws::WebSocketClient ws2("ws://example.com/path");
  13763. EXPECT_TRUE(ws2.is_valid());
  13764. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  13765. EXPECT_TRUE(ws3.is_valid());
  13766. #ifdef CPPHTTPLIB_SSL_ENABLED
  13767. ws::WebSocketClient wss1("wss://example.com/path");
  13768. EXPECT_TRUE(wss1.is_valid());
  13769. ws::WebSocketClient wss2("wss://example.com:443/path");
  13770. EXPECT_TRUE(wss2.is_valid());
  13771. #endif
  13772. }
  13773. TEST(WebSocketTest, InvalidURL) {
  13774. // No scheme
  13775. ws::WebSocketClient ws1("localhost:8080/path");
  13776. EXPECT_FALSE(ws1.is_valid());
  13777. // No path
  13778. ws::WebSocketClient ws2("ws://localhost:8080");
  13779. EXPECT_FALSE(ws2.is_valid());
  13780. // Empty string
  13781. ws::WebSocketClient ws3("");
  13782. EXPECT_FALSE(ws3.is_valid());
  13783. // Missing host
  13784. ws::WebSocketClient ws4("ws://:8080/path");
  13785. EXPECT_FALSE(ws4.is_valid());
  13786. // Port number overflow — should not crash
  13787. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  13788. EXPECT_FALSE(ws5.is_valid());
  13789. // Port out of range
  13790. ws::WebSocketClient ws6("ws://localhost:99999/path");
  13791. EXPECT_FALSE(ws6.is_valid());
  13792. }
  13793. TEST(WebSocketTest, UnsupportedScheme) {
  13794. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13795. ws::WebSocketClient ws1("http://localhost:8080/path");
  13796. EXPECT_FALSE(ws1.is_valid());
  13797. ws::WebSocketClient ws2("https://localhost:8080/path");
  13798. EXPECT_FALSE(ws2.is_valid());
  13799. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  13800. EXPECT_FALSE(ws3.is_valid());
  13801. #else
  13802. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  13803. std::invalid_argument);
  13804. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  13805. std::invalid_argument);
  13806. #endif
  13807. }
  13808. TEST(WebSocketTest, ConnectWhenInvalid) {
  13809. ws::WebSocketClient ws("not a valid url");
  13810. EXPECT_FALSE(ws.is_valid());
  13811. EXPECT_FALSE(ws.connect());
  13812. }
  13813. TEST(WebSocketTest, DefaultPort) {
  13814. ws::WebSocketClient ws1("ws://example.com/path");
  13815. EXPECT_TRUE(ws1.is_valid());
  13816. // ws:// defaults to port 80 (verified by successful parse)
  13817. #ifdef CPPHTTPLIB_SSL_ENABLED
  13818. ws::WebSocketClient ws2("wss://example.com/path");
  13819. EXPECT_TRUE(ws2.is_valid());
  13820. // wss:// defaults to port 443 (verified by successful parse)
  13821. #endif
  13822. }
  13823. TEST(WebSocketTest, IPv6LiteralAddress) {
  13824. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  13825. EXPECT_TRUE(ws1.is_valid());
  13826. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  13827. EXPECT_TRUE(ws2.is_valid());
  13828. }
  13829. TEST(WebSocketTest, ComplexPath) {
  13830. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  13831. EXPECT_TRUE(ws1.is_valid());
  13832. ws::WebSocketClient ws2("ws://localhost:8080/");
  13833. EXPECT_TRUE(ws2.is_valid());
  13834. }
  13835. class WebSocketIntegrationTest : public ::testing::Test {
  13836. protected:
  13837. void SetUp() override {
  13838. server_ = httplib::detail::make_unique<Server>();
  13839. setup_server();
  13840. start_server();
  13841. }
  13842. void TearDown() override {
  13843. server_->stop();
  13844. if (server_thread_.joinable()) { server_thread_.join(); }
  13845. }
  13846. void setup_server() {
  13847. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  13848. std::string msg;
  13849. ws::ReadResult ret;
  13850. while ((ret = ws.read(msg))) {
  13851. if (ret == ws::Binary) {
  13852. ws.send(msg.data(), msg.size());
  13853. } else {
  13854. ws.send(msg);
  13855. }
  13856. }
  13857. });
  13858. server_->WebSocket("/ws-echo-string",
  13859. [](const Request &, ws::WebSocket &ws) {
  13860. std::string msg;
  13861. while (ws.read(msg)) {
  13862. ws.send("echo: " + msg);
  13863. }
  13864. });
  13865. server_->WebSocket(
  13866. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  13867. // Echo back request metadata
  13868. ws.send("path:" + req.path);
  13869. ws.send("header:" + req.get_header_value("X-Test-Header"));
  13870. std::string msg;
  13871. while (ws.read(msg)) {}
  13872. });
  13873. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  13874. std::string msg;
  13875. ws.read(msg); // wait for a message
  13876. ws.close();
  13877. });
  13878. server_->WebSocket("/ws-close-status",
  13879. [](const Request &, ws::WebSocket &ws) {
  13880. std::string msg;
  13881. ws.read(msg); // wait for a message
  13882. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  13883. });
  13884. server_->WebSocket(
  13885. "/ws-subprotocol",
  13886. [](const Request &, ws::WebSocket &ws) {
  13887. std::string msg;
  13888. while (ws.read(msg)) {
  13889. ws.send(msg);
  13890. }
  13891. },
  13892. [](const std::vector<std::string> &protocols) -> std::string {
  13893. for (const auto &p : protocols) {
  13894. if (p == "graphql-ws") { return p; }
  13895. }
  13896. return "";
  13897. });
  13898. }
  13899. void start_server() {
  13900. port_ = server_->bind_to_any_port(HOST);
  13901. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13902. server_->wait_until_ready();
  13903. }
  13904. std::unique_ptr<Server> server_;
  13905. std::thread server_thread_;
  13906. int port_ = 0;
  13907. };
  13908. TEST_F(WebSocketIntegrationTest, TextEcho) {
  13909. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13910. "/ws-echo");
  13911. ASSERT_TRUE(client.connect());
  13912. ASSERT_TRUE(client.is_open());
  13913. ASSERT_TRUE(client.send("Hello WebSocket"));
  13914. std::string msg;
  13915. EXPECT_EQ(ws::Text, client.read(msg));
  13916. EXPECT_EQ("Hello WebSocket", msg);
  13917. client.close();
  13918. }
  13919. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  13920. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13921. "/ws-echo");
  13922. ASSERT_TRUE(client.connect());
  13923. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  13924. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  13925. std::string msg;
  13926. EXPECT_EQ(ws::Binary, client.read(msg));
  13927. EXPECT_EQ(binary_data, msg);
  13928. client.close();
  13929. }
  13930. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  13931. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13932. "/ws-echo");
  13933. ASSERT_TRUE(client.connect());
  13934. for (int i = 0; i < 10; i++) {
  13935. auto text = "message " + std::to_string(i);
  13936. ASSERT_TRUE(client.send(text));
  13937. std::string msg;
  13938. ASSERT_TRUE(client.read(msg));
  13939. EXPECT_EQ(text, msg);
  13940. }
  13941. client.close();
  13942. }
  13943. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  13944. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13945. "/ws-close");
  13946. ASSERT_TRUE(client.connect());
  13947. // Send a message to trigger the server to close
  13948. ASSERT_TRUE(client.send("trigger close"));
  13949. // The server will close, so read should return false
  13950. std::string msg;
  13951. EXPECT_FALSE(client.read(msg));
  13952. EXPECT_FALSE(client.is_open());
  13953. }
  13954. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  13955. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13956. "/ws-echo");
  13957. ASSERT_TRUE(client.connect());
  13958. // 128KB message
  13959. std::string large_data(128 * 1024, 'X');
  13960. ASSERT_TRUE(client.send(large_data));
  13961. std::string msg;
  13962. ASSERT_TRUE(client.read(msg));
  13963. EXPECT_EQ(large_data, msg);
  13964. client.close();
  13965. }
  13966. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  13967. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13968. "/ws-echo");
  13969. ASSERT_TRUE(client.connect());
  13970. const int num_threads = 4;
  13971. std::vector<std::thread> threads;
  13972. std::atomic<int> send_count{0};
  13973. for (int t = 0; t < num_threads; t++) {
  13974. threads.emplace_back([&client, &send_count, t]() {
  13975. for (int i = 0; i < 5; i++) {
  13976. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  13977. if (client.send(text)) { send_count++; }
  13978. }
  13979. });
  13980. }
  13981. for (auto &th : threads) {
  13982. th.join();
  13983. }
  13984. int received = 0;
  13985. std::string msg;
  13986. while (received < send_count.load()) {
  13987. if (!client.read(msg)) { break; }
  13988. received++;
  13989. }
  13990. EXPECT_EQ(send_count.load(), received);
  13991. client.close();
  13992. }
  13993. TEST_F(WebSocketIntegrationTest, ReadString) {
  13994. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13995. "/ws-echo-string");
  13996. ASSERT_TRUE(client.connect());
  13997. ASSERT_TRUE(client.send("hello"));
  13998. std::string msg;
  13999. ASSERT_TRUE(client.read(msg));
  14000. EXPECT_EQ("echo: hello", msg);
  14001. ASSERT_TRUE(client.send("world"));
  14002. ASSERT_TRUE(client.read(msg));
  14003. EXPECT_EQ("echo: world", msg);
  14004. client.close();
  14005. }
  14006. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  14007. Headers headers = {{"X-Test-Header", "test-value"}};
  14008. ws::WebSocketClient client(
  14009. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  14010. ASSERT_TRUE(client.connect());
  14011. std::string msg;
  14012. ASSERT_TRUE(client.read(msg));
  14013. EXPECT_EQ("path:/ws-request-info", msg);
  14014. ASSERT_TRUE(client.read(msg));
  14015. EXPECT_EQ("header:test-value", msg);
  14016. client.close();
  14017. }
  14018. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  14019. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14020. "/ws-echo");
  14021. client.set_read_timeout(1, 0); // 1 second
  14022. ASSERT_TRUE(client.connect());
  14023. // Don't send anything — server echo handler waits for a message,
  14024. // so read() should time out and return false.
  14025. std::string msg;
  14026. EXPECT_FALSE(client.read(msg));
  14027. }
  14028. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  14029. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14030. "/ws-echo");
  14031. client.set_read_timeout(5, 0);
  14032. ASSERT_TRUE(client.connect());
  14033. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14034. // The server should reject it and close the connection.
  14035. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  14036. client.send(oversized);
  14037. // The server's read() should have failed due to payload limit,
  14038. // so our read() should return false (connection closed).
  14039. std::string msg;
  14040. EXPECT_FALSE(client.read(msg));
  14041. }
  14042. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  14043. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14044. "/ws-echo");
  14045. client.set_read_timeout(10, 0);
  14046. ASSERT_TRUE(client.connect());
  14047. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14048. // This should succeed.
  14049. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  14050. ASSERT_TRUE(client.send(at_limit));
  14051. std::string msg;
  14052. ASSERT_TRUE(client.read(msg));
  14053. EXPECT_EQ(at_limit.size(), msg.size());
  14054. client.close();
  14055. }
  14056. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  14057. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14058. "/nonexistent");
  14059. EXPECT_FALSE(client.connect());
  14060. EXPECT_FALSE(client.is_open());
  14061. }
  14062. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  14063. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14064. "/ws-echo");
  14065. ASSERT_TRUE(client.connect());
  14066. ASSERT_TRUE(client.send(""));
  14067. std::string msg;
  14068. EXPECT_EQ(ws::Text, client.read(msg));
  14069. EXPECT_EQ("", msg);
  14070. client.close();
  14071. }
  14072. TEST_F(WebSocketIntegrationTest, Reconnect) {
  14073. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14074. "/ws-echo");
  14075. // First connection
  14076. ASSERT_TRUE(client.connect());
  14077. ASSERT_TRUE(client.send("first"));
  14078. std::string msg;
  14079. ASSERT_TRUE(client.read(msg));
  14080. EXPECT_EQ("first", msg);
  14081. client.close();
  14082. EXPECT_FALSE(client.is_open());
  14083. // Reconnect using the same client object
  14084. ASSERT_TRUE(client.connect());
  14085. ASSERT_TRUE(client.is_open());
  14086. ASSERT_TRUE(client.send("second"));
  14087. ASSERT_TRUE(client.read(msg));
  14088. EXPECT_EQ("second", msg);
  14089. client.close();
  14090. }
  14091. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  14092. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14093. "/ws-close-status");
  14094. ASSERT_TRUE(client.connect());
  14095. // Trigger the server to close with GoingAway status
  14096. ASSERT_TRUE(client.send("trigger"));
  14097. // read() should return false after receiving the close frame
  14098. std::string msg;
  14099. EXPECT_FALSE(client.read(msg));
  14100. EXPECT_FALSE(client.is_open());
  14101. }
  14102. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  14103. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14104. "/ws-echo");
  14105. ASSERT_TRUE(client.connect());
  14106. client.close(ws::CloseStatus::GoingAway, "client leaving");
  14107. EXPECT_FALSE(client.is_open());
  14108. }
  14109. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  14110. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  14111. ws::WebSocketClient client(
  14112. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14113. ASSERT_TRUE(client.connect());
  14114. // Server should have selected graphql-ws
  14115. EXPECT_EQ("graphql-ws", client.subprotocol());
  14116. client.close();
  14117. }
  14118. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  14119. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  14120. ws::WebSocketClient client(
  14121. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14122. ASSERT_TRUE(client.connect());
  14123. // Server should not have selected any subprotocol
  14124. EXPECT_TRUE(client.subprotocol().empty());
  14125. client.close();
  14126. }
  14127. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  14128. // Connect without requesting any subprotocol
  14129. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14130. "/ws-subprotocol");
  14131. ASSERT_TRUE(client.connect());
  14132. EXPECT_TRUE(client.subprotocol().empty());
  14133. client.close();
  14134. }
  14135. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  14136. Server svr;
  14137. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  14138. if (!req.has_header("Authorization")) {
  14139. res.status = StatusCode::Unauthorized_401;
  14140. res.set_content("Unauthorized", "text/plain");
  14141. return Server::HandlerResponse::Handled;
  14142. }
  14143. return Server::HandlerResponse::Unhandled;
  14144. });
  14145. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14146. std::string msg;
  14147. while (ws.read(msg)) {
  14148. ws.send(msg);
  14149. }
  14150. });
  14151. auto port = svr.bind_to_any_port("localhost");
  14152. std::thread t([&]() { svr.listen_after_bind(); });
  14153. svr.wait_until_ready();
  14154. // Without Authorization header - should be rejected before upgrade
  14155. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  14156. EXPECT_FALSE(client1.connect());
  14157. // With Authorization header - should succeed
  14158. Headers headers = {{"Authorization", "Bearer token123"}};
  14159. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  14160. headers);
  14161. ASSERT_TRUE(client2.connect());
  14162. ASSERT_TRUE(client2.send("hello"));
  14163. std::string msg;
  14164. ASSERT_TRUE(client2.read(msg));
  14165. EXPECT_EQ("hello", msg);
  14166. client2.close();
  14167. svr.stop();
  14168. t.join();
  14169. }
  14170. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14171. class WebSocketSSLIntegrationTest : public ::testing::Test {
  14172. protected:
  14173. void SetUp() override {
  14174. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  14175. SERVER_PRIVATE_KEY_FILE);
  14176. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14177. std::string msg;
  14178. ws::ReadResult ret;
  14179. while ((ret = ws.read(msg))) {
  14180. if (ret == ws::Binary) {
  14181. ws.send(msg.data(), msg.size());
  14182. } else {
  14183. ws.send(msg);
  14184. }
  14185. }
  14186. });
  14187. port_ = server_->bind_to_any_port(HOST);
  14188. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14189. server_->wait_until_ready();
  14190. }
  14191. void TearDown() override {
  14192. server_->stop();
  14193. if (server_thread_.joinable()) { server_thread_.join(); }
  14194. }
  14195. std::unique_ptr<SSLServer> server_;
  14196. std::thread server_thread_;
  14197. int port_ = 0;
  14198. };
  14199. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  14200. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  14201. "/ws-echo");
  14202. client.enable_server_certificate_verification(false);
  14203. ASSERT_TRUE(client.connect());
  14204. ASSERT_TRUE(client.is_open());
  14205. ASSERT_TRUE(client.send("Hello WSS"));
  14206. std::string msg;
  14207. EXPECT_EQ(ws::Text, client.read(msg));
  14208. EXPECT_EQ("Hello WSS", msg);
  14209. client.close();
  14210. }
  14211. #endif
  14212. #if !defined(_WIN32)
  14213. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  14214. auto secret_dir = std::string("./symlink_test_secret");
  14215. auto served_dir = std::string("./symlink_test_served");
  14216. auto secret_file = secret_dir + "/secret.txt";
  14217. auto symlink_path = served_dir + "/escape";
  14218. // Setup: create directories and files
  14219. mkdir(secret_dir.c_str(), 0755);
  14220. mkdir(served_dir.c_str(), 0755);
  14221. {
  14222. std::ofstream ofs(secret_file);
  14223. ofs << "SECRET_DATA";
  14224. }
  14225. // Create symlink using absolute path so it resolves correctly
  14226. char abs_secret[PATH_MAX];
  14227. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  14228. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  14229. auto se = detail::scope_exit([&] {
  14230. unlink(symlink_path.c_str());
  14231. unlink(secret_file.c_str());
  14232. rmdir(served_dir.c_str());
  14233. rmdir(secret_dir.c_str());
  14234. });
  14235. Server svr;
  14236. svr.set_mount_point("/", served_dir);
  14237. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  14238. auto se2 = detail::scope_exit([&] {
  14239. svr.stop();
  14240. listen_thread.join();
  14241. });
  14242. svr.wait_until_ready();
  14243. Client cli("localhost", PORT);
  14244. // Symlink pointing outside base dir should be blocked
  14245. auto res = cli.Get("/escape/secret.txt");
  14246. ASSERT_TRUE(res);
  14247. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  14248. }
  14249. #endif