test.cc 524 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #if __cplusplus >= 202002L
  28. inline std::string u8_to_string(const char8_t *s) {
  29. return std::string(reinterpret_cast<const char *>(s));
  30. }
  31. #define U8(x) u8_to_string(u8##x)
  32. #else
  33. #define U8(x) u8##x
  34. #endif
  35. #define SERVER_CERT_FILE "./cert.pem"
  36. #define SERVER_CERT2_FILE "./cert2.pem"
  37. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  38. #define CA_CERT_FILE "./ca-bundle.crt"
  39. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  40. #define CLIENT_CA_CERT_DIR "."
  41. #define CLIENT_CERT_FILE "./client.cert.pem"
  42. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  43. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  44. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  45. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  46. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  47. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  48. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  49. using namespace std;
  50. using namespace httplib;
  51. const char *HOST = "localhost";
  52. static int get_base_port() {
  53. const char *shard = getenv("GTEST_SHARD_INDEX");
  54. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  55. }
  56. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  57. // New standalone tests MUST use svr.bind_to_any_port() instead.
  58. const int PORT = get_base_port();
  59. const string LONG_QUERY_VALUE = string(25000, '@');
  60. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  61. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  62. const string TOO_LONG_QUERY_URL =
  63. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  64. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  65. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  66. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  67. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  68. return file.name == key;
  69. });
  70. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  71. return *it;
  72. #else
  73. if (it != items.end()) { return *it; }
  74. throw std::runtime_error("invalid multipart form data name error");
  75. #endif
  76. }
  77. static void read_file(const std::string &path, std::string &out) {
  78. std::ifstream fs(path, std::ios_base::binary);
  79. if (!fs) {
  80. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  81. return;
  82. #else
  83. throw std::runtime_error("File not found: " + path);
  84. #endif
  85. }
  86. fs.seekg(0, std::ios_base::end);
  87. auto size = fs.tellg();
  88. fs.seekg(0);
  89. out.resize(static_cast<size_t>(size));
  90. fs.read(&out[0], static_cast<std::streamsize>(size));
  91. }
  92. class UnixSocketTest : public ::testing::Test {
  93. protected:
  94. void TearDown() override { std::remove(pathname_.c_str()); }
  95. void client_GET(const std::string &addr) {
  96. httplib::Client cli{addr};
  97. cli.set_address_family(AF_UNIX);
  98. ASSERT_TRUE(cli.is_valid());
  99. const auto &result = cli.Get(pattern_);
  100. ASSERT_TRUE(result) << "error: " << result.error();
  101. const auto &resp = result.value();
  102. EXPECT_EQ(resp.status, StatusCode::OK_200);
  103. EXPECT_EQ(resp.body, content_);
  104. }
  105. static std::string make_sock_path() {
  106. const char *shard = getenv("GTEST_SHARD_INDEX");
  107. return shard ? std::string("./httplib-server-") + shard + ".sock"
  108. : "./httplib-server.sock";
  109. }
  110. const std::string pathname_{make_sock_path()};
  111. const std::string pattern_{"/hi"};
  112. const std::string content_{"Hello World!"};
  113. };
  114. TEST_F(UnixSocketTest, pathname) {
  115. httplib::Server svr;
  116. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  117. res.set_content(content_, "text/plain");
  118. });
  119. std::thread t{[&] {
  120. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  121. }};
  122. auto se = detail::scope_exit([&] {
  123. svr.stop();
  124. t.join();
  125. ASSERT_FALSE(svr.is_running());
  126. });
  127. svr.wait_until_ready();
  128. ASSERT_TRUE(svr.is_running());
  129. client_GET(pathname_);
  130. }
  131. #if defined(__linux__) || \
  132. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  133. TEST_F(UnixSocketTest, PeerPid) {
  134. httplib::Server svr;
  135. std::string remote_port_val;
  136. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  137. res.set_content(content_, "text/plain");
  138. remote_port_val = std::to_string(req.remote_port);
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  152. }
  153. #endif
  154. #ifdef __linux__
  155. TEST_F(UnixSocketTest, abstract) {
  156. constexpr char svr_path[]{"\x00httplib-server.sock"};
  157. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  158. httplib::Server svr;
  159. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  160. res.set_content(content_, "text/plain");
  161. });
  162. std::thread t{[&] {
  163. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  164. }};
  165. auto se = detail::scope_exit([&] {
  166. svr.stop();
  167. t.join();
  168. ASSERT_FALSE(svr.is_running());
  169. });
  170. svr.wait_until_ready();
  171. ASSERT_TRUE(svr.is_running());
  172. client_GET(abstract_addr);
  173. }
  174. #endif
  175. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  176. httplib::Server svr;
  177. std::string received_host_header;
  178. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  179. // Capture the Host header sent by the client
  180. auto host_iter = req.headers.find("Host");
  181. if (host_iter != req.headers.end()) {
  182. received_host_header = host_iter->second;
  183. }
  184. res.set_content(content_, "text/plain");
  185. });
  186. std::thread t{[&] {
  187. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  188. }};
  189. auto se = detail::scope_exit([&] {
  190. svr.stop();
  191. t.join();
  192. ASSERT_FALSE(svr.is_running());
  193. });
  194. svr.wait_until_ready();
  195. ASSERT_TRUE(svr.is_running());
  196. // Test that Host header is automatically set to "localhost" for Unix socket
  197. // connections
  198. httplib::Client cli{pathname_};
  199. cli.set_address_family(AF_UNIX);
  200. ASSERT_TRUE(cli.is_valid());
  201. const auto &result = cli.Get(pattern_);
  202. ASSERT_TRUE(result) << "error: " << result.error();
  203. const auto &resp = result.value();
  204. EXPECT_EQ(resp.status, StatusCode::OK_200);
  205. EXPECT_EQ(resp.body, content_);
  206. // Verify that Host header was automatically set to "localhost"
  207. EXPECT_EQ(received_host_header, "localhost");
  208. }
  209. #ifndef _WIN32
  210. TEST(SocketStream, wait_writable_UNIX) {
  211. int fds[2];
  212. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  213. const auto asSocketStream = [&](socket_t fd,
  214. std::function<bool(Stream &)> func) {
  215. return detail::process_client_socket(
  216. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  217. };
  218. asSocketStream(fds[0], [&](Stream &s0) {
  219. EXPECT_EQ(s0.socket(), fds[0]);
  220. EXPECT_TRUE(s0.wait_writable());
  221. EXPECT_TRUE(s0.is_peer_alive());
  222. EXPECT_EQ(0, close(fds[1]));
  223. EXPECT_FALSE(s0.is_peer_alive());
  224. return true;
  225. });
  226. EXPECT_EQ(0, close(fds[0]));
  227. }
  228. TEST(SocketStream, wait_writable_INET) {
  229. sockaddr_in addr;
  230. memset(&addr, 0, sizeof(addr));
  231. addr.sin_family = AF_INET;
  232. addr.sin_port = htons(PORT + 1);
  233. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  234. int disconnected_svr_sock = -1;
  235. std::thread svr{[&] {
  236. const int s = socket(AF_INET, SOCK_STREAM, 0);
  237. ASSERT_LE(0, s);
  238. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  239. ASSERT_EQ(0, listen(s, 1));
  240. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  241. ASSERT_EQ(0, close(s));
  242. }};
  243. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  244. std::thread cli{[&] {
  245. const int s = socket(AF_INET, SOCK_STREAM, 0);
  246. ASSERT_LE(0, s);
  247. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  248. ASSERT_EQ(0, close(s));
  249. }};
  250. cli.join();
  251. svr.join();
  252. ASSERT_NE(disconnected_svr_sock, -1);
  253. const auto asSocketStream = [&](socket_t fd,
  254. std::function<bool(Stream &)> func) {
  255. return detail::process_client_socket(
  256. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  257. };
  258. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  259. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  260. // wait_writable() returns true because select_write() only checks if the
  261. // send buffer has space. Peer disconnection is detected later by send().
  262. EXPECT_TRUE(ss.wait_writable());
  263. return true;
  264. });
  265. ASSERT_EQ(0, close(disconnected_svr_sock));
  266. }
  267. #endif // #ifndef _WIN32
  268. TEST(ClientTest, MoveConstructible) {
  269. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  270. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  271. }
  272. TEST(ClientTest, MoveAssignable) {
  273. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  274. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  275. }
  276. #ifdef _WIN32
  277. TEST(StartupTest, WSAStartup) {
  278. WSADATA wsaData;
  279. int ret = WSAStartup(0x0002, &wsaData);
  280. ASSERT_EQ(0, ret);
  281. }
  282. #endif
  283. TEST(DecodePathTest, PercentCharacter) {
  284. EXPECT_EQ(
  285. decode_path_component(
  286. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  287. U8("descrip=Gastos áéíóúñÑ 6"));
  288. }
  289. TEST(DecodePathTest, PercentCharacterNUL) {
  290. string expected;
  291. expected.push_back('x');
  292. expected.push_back('\0');
  293. expected.push_back('x');
  294. EXPECT_EQ(decode_path_component("x%00x"), expected);
  295. }
  296. TEST(DecodePathTest, UnicodeEncoding) {
  297. // %u0041 = 'A' (1-byte UTF-8)
  298. EXPECT_EQ("A", decode_path_component("%u0041"));
  299. // %u00E9 = 'é' (2-byte UTF-8)
  300. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  301. // %u3042 = 'あ' (3-byte UTF-8)
  302. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  303. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  304. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  305. // %uD800 = surrogate (invalid, silently dropped)
  306. EXPECT_EQ("", decode_path_component("%uD800"));
  307. }
  308. TEST(SanitizeFilenameTest, VariousPatterns) {
  309. // Path traversal
  310. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  311. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  312. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  313. // Normal and edge cases
  314. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  315. EXPECT_EQ("filename.txt",
  316. httplib::sanitize_filename("/path/to/filename.txt"));
  317. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  318. EXPECT_EQ("", httplib::sanitize_filename(".."));
  319. EXPECT_EQ("", httplib::sanitize_filename(""));
  320. // Null bytes stripped
  321. EXPECT_EQ("safe.txt",
  322. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  323. // Whitespace-only rejected
  324. EXPECT_EQ("", httplib::sanitize_filename(" "));
  325. }
  326. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  327. string unescapedCharacters = "-_.!~*'()";
  328. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  329. }
  330. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  331. string reservedCharacters = ";,/?:@&=+$";
  332. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  333. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  334. }
  335. TEST(ClientQueryOrder, PreserveOrder) {
  336. // This test reproduces Issue #2259: client may reorder query parameters
  337. // when sending a GET request. The expected behavior is that the client
  338. // preserves the original query string order when the caller supplied it
  339. // as part of the path.
  340. Server svr;
  341. svr.Get("/", [&](const Request &req, Response &res) {
  342. // Echo back the raw target so the test can assert ordering
  343. res.set_content(req.target, "text/plain");
  344. });
  345. std::thread t{[&] { svr.listen(HOST, PORT); }};
  346. auto se = detail::scope_exit([&] {
  347. svr.stop();
  348. t.join();
  349. ASSERT_FALSE(svr.is_running());
  350. });
  351. svr.wait_until_ready();
  352. Client cli(HOST, PORT);
  353. ASSERT_TRUE(cli.is_valid());
  354. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  355. auto res = cli.Get(original);
  356. ASSERT_TRUE(res);
  357. // Expect the echoed target to exactly match the original path (order
  358. // preserved)
  359. EXPECT_EQ(res->body, original);
  360. }
  361. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  362. string chineseCharacters = U8("中国語");
  363. string russianCharacters = U8("дом");
  364. string brazilianCharacters = U8("óculos");
  365. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  366. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  367. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  368. "%D0%B4%D0%BE%D0%BC");
  369. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  370. }
  371. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  372. string unescapedCharacters = "-_.!~*'()";
  373. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  374. }
  375. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  376. string reservedCharacters = ";,/?:@&=+$";
  377. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  378. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  379. }
  380. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  381. string chineseCharacters = U8("中国語");
  382. string russianCharacters = U8("дом");
  383. string brazilianCharacters = U8("óculos");
  384. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  385. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  386. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  387. "%D0%B4%D0%BE%D0%BC");
  388. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  389. }
  390. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  391. // Issue #2082 use case: encoding path component with ampersand
  392. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  393. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  394. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  395. }
  396. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  397. string unescapedCharacters = "-_.!~*'()";
  398. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  399. }
  400. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  401. string reservedCharacters = ";,/?:@&=+$#";
  402. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  403. }
  404. TEST(EncodeUriTest, TestUTF8Characters) {
  405. string chineseCharacters = U8("中国語");
  406. string russianCharacters = U8("дом");
  407. string brazilianCharacters = U8("óculos");
  408. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  409. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  410. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  411. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  412. }
  413. TEST(EncodeUriTest, TestCompleteUri) {
  414. string uri =
  415. "https://example.com/path/to/resource?query=value&param=test#fragment";
  416. EXPECT_EQ(
  417. httplib::encode_uri(uri),
  418. "https://example.com/path/to/resource?query=value&param=test#fragment");
  419. }
  420. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  421. string uri =
  422. "https://example.com/path with spaces/file name.html?q=hello world";
  423. EXPECT_EQ(httplib::encode_uri(uri),
  424. "https://example.com/path%20with%20spaces/"
  425. "file%20name.html?q=hello%20world");
  426. }
  427. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  428. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  429. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  430. }
  431. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  432. string unescapedCharacters = "-_.!~*'()";
  433. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  434. }
  435. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  436. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  437. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  438. string encodedBrazilian = "%C3%B3culos";
  439. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  440. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  441. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  442. }
  443. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  444. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  445. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  446. "Piri Tommy Villiers - on & on");
  447. }
  448. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  449. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  450. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  451. }
  452. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  453. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  454. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  455. }
  456. TEST(DecodeUriTest, TestUTF8Characters) {
  457. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  458. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  459. string encodedBrazilian = "%C3%B3culos";
  460. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  461. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  462. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  463. }
  464. TEST(DecodeUriTest, TestCompleteUri) {
  465. string encodedUri = "https://example.com/path%20with%20spaces/"
  466. "file%20name.html?q=hello%20world";
  467. EXPECT_EQ(
  468. httplib::decode_uri(encodedUri),
  469. "https://example.com/path with spaces/file name.html?q=hello world");
  470. }
  471. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  472. string original =
  473. "https://example.com/path with spaces/file name.html?q=hello world";
  474. string encoded = httplib::encode_uri(original);
  475. string decoded = httplib::decode_uri(encoded);
  476. EXPECT_EQ(decoded, original);
  477. }
  478. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  479. string original = "Piri Tommy Villiers - on & on";
  480. string encoded = httplib::encode_uri_component(original);
  481. string decoded = httplib::decode_uri_component(encoded);
  482. EXPECT_EQ(decoded, original);
  483. }
  484. TEST(TrimTests, TrimStringTests) {
  485. EXPECT_EQ("abc", detail::trim_copy("abc"));
  486. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  487. EXPECT_TRUE(detail::trim_copy("").empty());
  488. }
  489. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  490. // Simple case without quality values
  491. std::vector<std::string> result1;
  492. EXPECT_TRUE(detail::parse_accept_header(
  493. "text/html,application/json,text/plain", result1));
  494. EXPECT_EQ(result1.size(), 3U);
  495. EXPECT_EQ(result1[0], "text/html");
  496. EXPECT_EQ(result1[1], "application/json");
  497. EXPECT_EQ(result1[2], "text/plain");
  498. // With quality values
  499. std::vector<std::string> result2;
  500. EXPECT_TRUE(detail::parse_accept_header(
  501. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  502. EXPECT_EQ(result2.size(), 3U);
  503. EXPECT_EQ(result2[0], "application/json"); // highest q value
  504. EXPECT_EQ(result2[1], "text/html");
  505. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  506. }
  507. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  508. // Mixed with and without quality values
  509. std::vector<std::string> result;
  510. EXPECT_TRUE(detail::parse_accept_header(
  511. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  512. EXPECT_EQ(result.size(), 3U);
  513. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  514. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  515. EXPECT_EQ(result[2], "application/json"); // q=0.5
  516. }
  517. TEST(ParseAcceptHeaderTest, EdgeCases) {
  518. // Empty header
  519. std::vector<std::string> empty_result;
  520. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  521. EXPECT_TRUE(empty_result.empty());
  522. // Single type
  523. std::vector<std::string> single_result;
  524. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  525. EXPECT_EQ(single_result.size(), 1U);
  526. EXPECT_EQ(single_result[0], "application/json");
  527. // Wildcard types
  528. std::vector<std::string> wildcard_result;
  529. EXPECT_TRUE(detail::parse_accept_header(
  530. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  531. EXPECT_EQ(wildcard_result.size(), 3U);
  532. EXPECT_EQ(wildcard_result[0], "application/json");
  533. EXPECT_EQ(wildcard_result[1], "text/*");
  534. EXPECT_EQ(wildcard_result[2], "*/*");
  535. }
  536. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  537. // Common browser Accept header
  538. std::vector<std::string> browser_result;
  539. EXPECT_TRUE(
  540. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  541. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  542. browser_result));
  543. EXPECT_EQ(browser_result.size(), 6U);
  544. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  545. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  546. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  547. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  548. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  549. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  550. // API client header
  551. std::vector<std::string> api_result;
  552. EXPECT_TRUE(detail::parse_accept_header(
  553. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  554. api_result));
  555. EXPECT_EQ(api_result.size(), 3U);
  556. EXPECT_EQ(api_result[0], "application/json");
  557. EXPECT_EQ(api_result[1], "application/xml");
  558. EXPECT_EQ(api_result[2], "text/plain");
  559. }
  560. TEST(ParseAcceptHeaderTest, SpecialCases) {
  561. // Quality value with 3 decimal places
  562. std::vector<std::string> decimal_result;
  563. EXPECT_TRUE(detail::parse_accept_header(
  564. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  565. EXPECT_EQ(decimal_result.size(), 2U);
  566. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  567. EXPECT_EQ(decimal_result[1], "text/html");
  568. // Zero quality (should still be included but with lowest priority)
  569. std::vector<std::string> zero_q_result;
  570. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  571. zero_q_result));
  572. EXPECT_EQ(zero_q_result.size(), 2U);
  573. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  574. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  575. // No spaces around commas
  576. std::vector<std::string> no_space_result;
  577. EXPECT_TRUE(detail::parse_accept_header(
  578. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  579. no_space_result));
  580. EXPECT_EQ(no_space_result.size(), 3U);
  581. EXPECT_EQ(no_space_result[0], "text/html");
  582. EXPECT_EQ(no_space_result[1], "application/json");
  583. EXPECT_EQ(no_space_result[2], "text/plain");
  584. }
  585. TEST(ParseAcceptHeaderTest, InvalidCases) {
  586. std::vector<std::string> result;
  587. // Invalid quality value (> 1.0)
  588. EXPECT_FALSE(
  589. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  590. // Invalid quality value (< 0.0)
  591. EXPECT_FALSE(
  592. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  593. // Invalid quality value (not a number)
  594. EXPECT_FALSE(detail::parse_accept_header(
  595. "text/html;q=invalid,application/json", result));
  596. // Empty quality value
  597. EXPECT_FALSE(
  598. detail::parse_accept_header("text/html;q=,application/json", result));
  599. // Invalid media type format (no slash and not wildcard)
  600. EXPECT_FALSE(
  601. detail::parse_accept_header("invalidtype,application/json", result));
  602. // Empty media type
  603. result.clear();
  604. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  605. // Only commas
  606. result.clear();
  607. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  608. // Valid cases should still work
  609. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  610. EXPECT_EQ(result.size(), 1U);
  611. EXPECT_EQ(result[0], "*/*");
  612. EXPECT_TRUE(detail::parse_accept_header("*", result));
  613. EXPECT_EQ(result.size(), 1U);
  614. EXPECT_EQ(result[0], "*");
  615. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  616. EXPECT_EQ(result.size(), 1U);
  617. EXPECT_EQ(result[0], "text/*");
  618. }
  619. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  620. Server svr;
  621. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  622. EXPECT_EQ(req.accept_content_types.size(), 3U);
  623. EXPECT_EQ(req.accept_content_types[0], "application/json");
  624. EXPECT_EQ(req.accept_content_types[1], "text/html");
  625. EXPECT_EQ(req.accept_content_types[2], "*/*");
  626. res.set_content("ok", "text/plain");
  627. });
  628. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  629. EXPECT_TRUE(false);
  630. res.set_content("bad request", "text/plain");
  631. });
  632. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  633. auto se = detail::scope_exit([&] {
  634. svr.stop();
  635. listen_thread.join();
  636. ASSERT_FALSE(svr.is_running());
  637. });
  638. svr.wait_until_ready();
  639. Client cli("localhost", PORT);
  640. {
  641. auto res =
  642. cli.Get("/accept_ok",
  643. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  644. ASSERT_TRUE(res);
  645. EXPECT_EQ(StatusCode::OK_200, res->status);
  646. }
  647. {
  648. auto res = cli.Get("/accept_bad_request",
  649. {{"Accept", "text/html;q=abc,application/json"}});
  650. ASSERT_TRUE(res);
  651. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  652. }
  653. }
  654. TEST(DivideTest, DivideStringTests) {
  655. auto divide = [](const std::string &str, char d) {
  656. std::string lhs;
  657. std::string rhs;
  658. detail::divide(str, d,
  659. [&](const char *lhs_data, std::size_t lhs_size,
  660. const char *rhs_data, std::size_t rhs_size) {
  661. lhs.assign(lhs_data, lhs_size);
  662. rhs.assign(rhs_data, rhs_size);
  663. });
  664. return std::make_pair(std::move(lhs), std::move(rhs));
  665. };
  666. {
  667. const auto res = divide("", '=');
  668. EXPECT_EQ(res.first, "");
  669. EXPECT_EQ(res.second, "");
  670. }
  671. {
  672. const auto res = divide("=", '=');
  673. EXPECT_EQ(res.first, "");
  674. EXPECT_EQ(res.second, "");
  675. }
  676. {
  677. const auto res = divide(" ", '=');
  678. EXPECT_EQ(res.first, " ");
  679. EXPECT_EQ(res.second, "");
  680. }
  681. {
  682. const auto res = divide("a", '=');
  683. EXPECT_EQ(res.first, "a");
  684. EXPECT_EQ(res.second, "");
  685. }
  686. {
  687. const auto res = divide("a=", '=');
  688. EXPECT_EQ(res.first, "a");
  689. EXPECT_EQ(res.second, "");
  690. }
  691. {
  692. const auto res = divide("=b", '=');
  693. EXPECT_EQ(res.first, "");
  694. EXPECT_EQ(res.second, "b");
  695. }
  696. {
  697. const auto res = divide("a=b", '=');
  698. EXPECT_EQ(res.first, "a");
  699. EXPECT_EQ(res.second, "b");
  700. }
  701. {
  702. const auto res = divide("a=b=", '=');
  703. EXPECT_EQ(res.first, "a");
  704. EXPECT_EQ(res.second, "b=");
  705. }
  706. {
  707. const auto res = divide("a=b=c", '=');
  708. EXPECT_EQ(res.first, "a");
  709. EXPECT_EQ(res.second, "b=c");
  710. }
  711. }
  712. TEST(SplitTest, ParseQueryString) {
  713. string s = "key1=val1&key2=val2&key3=val3";
  714. Params dic;
  715. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  716. [&](const char *b, const char *e) {
  717. string key, val;
  718. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  719. if (key.empty()) {
  720. key.assign(b2, e2);
  721. } else {
  722. val.assign(b2, e2);
  723. }
  724. });
  725. dic.emplace(key, val);
  726. });
  727. EXPECT_EQ("val1", dic.find("key1")->second);
  728. EXPECT_EQ("val2", dic.find("key2")->second);
  729. EXPECT_EQ("val3", dic.find("key3")->second);
  730. }
  731. TEST(SplitTest, ParseInvalidQueryTests) {
  732. {
  733. string s = " ";
  734. Params dict;
  735. detail::parse_query_text(s, dict);
  736. EXPECT_TRUE(dict.empty());
  737. }
  738. {
  739. string s = " = =";
  740. Params dict;
  741. detail::parse_query_text(s, dict);
  742. EXPECT_TRUE(dict.empty());
  743. }
  744. }
  745. TEST(ParseQueryTest, ParseQueryString) {
  746. {
  747. std::string s = "key1=val1&key2=val2&key3=val3";
  748. Params dic;
  749. detail::parse_query_text(s, dic);
  750. EXPECT_EQ("val1", dic.find("key1")->second);
  751. EXPECT_EQ("val2", dic.find("key2")->second);
  752. EXPECT_EQ("val3", dic.find("key3")->second);
  753. }
  754. {
  755. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  756. Params dic;
  757. detail::parse_query_text(s, dic);
  758. EXPECT_EQ("", dic.find("key1")->second);
  759. EXPECT_EQ("val1", dic.find("key2")->second);
  760. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  761. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  762. }
  763. }
  764. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  765. Params dic;
  766. EXPECT_EQ(detail::params_to_query_str(dic), "");
  767. dic.emplace("key1", "val1");
  768. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  769. dic.emplace("key2", "val2");
  770. dic.emplace("key3", "val3");
  771. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  772. }
  773. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  774. string content_type = "multipart/form-data; boundary=something";
  775. string boundary;
  776. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  777. EXPECT_TRUE(ret);
  778. EXPECT_EQ(boundary, "something");
  779. }
  780. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  781. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  782. string boundary;
  783. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  784. EXPECT_TRUE(ret);
  785. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  786. }
  787. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  788. string content_type =
  789. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  790. string boundary;
  791. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  792. EXPECT_TRUE(ret);
  793. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  794. }
  795. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  796. string content_type =
  797. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  798. string boundary;
  799. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  800. EXPECT_TRUE(ret);
  801. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  802. }
  803. TEST(GetHeaderValueTest, DefaultValue) {
  804. Headers headers = {{"Dummy", "Dummy"}};
  805. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  806. EXPECT_STREQ("text/plain", val);
  807. }
  808. TEST(GetHeaderValueTest, DefaultValueInt) {
  809. Headers headers = {{"Dummy", "Dummy"}};
  810. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  811. EXPECT_EQ(100ull, val);
  812. }
  813. TEST(GetHeaderValueTest, RegularValue) {
  814. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  815. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  816. EXPECT_STREQ("text/html", val);
  817. }
  818. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  819. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  820. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  821. EXPECT_STREQ("text/html", val);
  822. }
  823. TEST(GetHeaderValueTest, SetContent) {
  824. Response res;
  825. res.set_content("html", "text/html");
  826. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  827. res.set_content("text", "text/plain");
  828. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  829. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  830. }
  831. TEST(GetHeaderValueTest, RegularValueInt) {
  832. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  833. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  834. EXPECT_EQ(100ull, val);
  835. }
  836. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  837. Headers headers = {{"Content-Length", "x"}};
  838. auto is_invalid_value = false;
  839. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  840. is_invalid_value);
  841. EXPECT_EQ(0ull, val);
  842. EXPECT_TRUE(is_invalid_value);
  843. }
  844. TEST(GetHeaderValueTest, Range) {
  845. {
  846. Headers headers = {make_range_header({{1, -1}})};
  847. auto val = detail::get_header_value(headers, "Range", 0, 0);
  848. EXPECT_STREQ("bytes=1-", val);
  849. }
  850. {
  851. Headers headers = {make_range_header({{-1, 1}})};
  852. auto val = detail::get_header_value(headers, "Range", 0, 0);
  853. EXPECT_STREQ("bytes=-1", val);
  854. }
  855. {
  856. Headers headers = {make_range_header({{1, 10}})};
  857. auto val = detail::get_header_value(headers, "Range", 0, 0);
  858. EXPECT_STREQ("bytes=1-10", val);
  859. }
  860. {
  861. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  862. auto val = detail::get_header_value(headers, "Range", 0, 0);
  863. EXPECT_STREQ("bytes=1-10, 100-", val);
  864. }
  865. {
  866. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  867. auto val = detail::get_header_value(headers, "Range", 0, 0);
  868. EXPECT_STREQ("bytes=1-10, 100-200", val);
  869. }
  870. {
  871. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  872. auto val = detail::get_header_value(headers, "Range", 0, 0);
  873. EXPECT_STREQ("bytes=0-0, -1", val);
  874. }
  875. }
  876. TEST(ParseHeaderValueTest, Range) {
  877. {
  878. Ranges ranges;
  879. auto ret = detail::parse_range_header("bytes=1-", ranges);
  880. EXPECT_TRUE(ret);
  881. EXPECT_EQ(1u, ranges.size());
  882. EXPECT_EQ(1u, ranges[0].first);
  883. EXPECT_EQ(-1, ranges[0].second);
  884. }
  885. {
  886. Ranges ranges;
  887. auto ret = detail::parse_range_header("bytes=-1", ranges);
  888. EXPECT_TRUE(ret);
  889. EXPECT_EQ(1u, ranges.size());
  890. EXPECT_EQ(-1, ranges[0].first);
  891. EXPECT_EQ(1u, ranges[0].second);
  892. }
  893. {
  894. Ranges ranges;
  895. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  896. EXPECT_TRUE(ret);
  897. EXPECT_EQ(1u, ranges.size());
  898. EXPECT_EQ(1u, ranges[0].first);
  899. EXPECT_EQ(10u, ranges[0].second);
  900. }
  901. {
  902. Ranges ranges;
  903. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  904. EXPECT_FALSE(ret);
  905. }
  906. {
  907. Ranges ranges;
  908. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  909. EXPECT_TRUE(ret);
  910. EXPECT_EQ(2u, ranges.size());
  911. EXPECT_EQ(1u, ranges[0].first);
  912. EXPECT_EQ(10u, ranges[0].second);
  913. EXPECT_EQ(100u, ranges[1].first);
  914. EXPECT_EQ(-1, ranges[1].second);
  915. }
  916. {
  917. Ranges ranges;
  918. auto ret =
  919. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  920. EXPECT_TRUE(ret);
  921. EXPECT_EQ(3u, ranges.size());
  922. EXPECT_EQ(1u, ranges[0].first);
  923. EXPECT_EQ(10u, ranges[0].second);
  924. EXPECT_EQ(100u, ranges[1].first);
  925. EXPECT_EQ(200u, ranges[1].second);
  926. EXPECT_EQ(300u, ranges[2].first);
  927. EXPECT_EQ(400u, ranges[2].second);
  928. }
  929. {
  930. Ranges ranges;
  931. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  932. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  933. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  934. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  935. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  936. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  937. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  938. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  939. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  940. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  941. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  942. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  943. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  944. EXPECT_TRUE(ranges.empty());
  945. }
  946. }
  947. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  948. Request req;
  949. req.set_header("Accept-Encoding", "gzip");
  950. Response res;
  951. res.set_header("Content-Type", "text/plain");
  952. auto ret = detail::encoding_type(req, res);
  953. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  954. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  955. #else
  956. EXPECT_TRUE(ret == detail::EncodingType::None);
  957. #endif
  958. }
  959. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  960. Request req;
  961. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  962. Response res;
  963. res.set_header("Content-Type", "text/plain");
  964. auto ret = detail::encoding_type(req, res);
  965. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  966. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  967. #elif CPPHTTPLIB_ZLIB_SUPPORT
  968. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  969. #elif CPPHTTPLIB_ZSTD_SUPPORT
  970. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  971. #else
  972. EXPECT_TRUE(ret == detail::EncodingType::None);
  973. #endif
  974. }
  975. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  976. Request req;
  977. req.set_header("Accept-Encoding",
  978. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  979. Response res;
  980. res.set_header("Content-Type", "text/plain");
  981. auto ret = detail::encoding_type(req, res);
  982. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  983. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  984. #elif CPPHTTPLIB_ZLIB_SUPPORT
  985. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  986. #elif CPPHTTPLIB_ZSTD_SUPPORT
  987. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  988. #else
  989. EXPECT_TRUE(ret == detail::EncodingType::None);
  990. #endif
  991. }
  992. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  993. // All supported encodings rejected with q=0 should return None
  994. Request req;
  995. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  996. Response res;
  997. res.set_header("Content-Type", "text/plain");
  998. auto ret = detail::encoding_type(req, res);
  999. EXPECT_TRUE(ret == detail::EncodingType::None);
  1000. }
  1001. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1002. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1003. Request req;
  1004. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1005. Response res;
  1006. res.set_header("Content-Type", "text/plain");
  1007. auto ret = detail::encoding_type(req, res);
  1008. EXPECT_TRUE(ret == detail::EncodingType::None);
  1009. }
  1010. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1011. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1012. Request req;
  1013. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1014. Response res;
  1015. res.set_header("Content-Type", "text/plain");
  1016. auto ret = detail::encoding_type(req, res);
  1017. EXPECT_TRUE(ret == detail::EncodingType::None);
  1018. }
  1019. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1020. // RFC 7231: Accept-Encoding values are case-insensitive
  1021. Request req;
  1022. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1023. Response res;
  1024. res.set_header("Content-Type", "text/plain");
  1025. auto ret = detail::encoding_type(req, res);
  1026. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1027. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1028. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1029. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1030. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1031. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1032. #else
  1033. EXPECT_TRUE(ret == detail::EncodingType::None);
  1034. #endif
  1035. }
  1036. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1037. // q value should determine priority, not hardcoded order
  1038. Request req;
  1039. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1040. Response res;
  1041. res.set_header("Content-Type", "text/plain");
  1042. auto ret = detail::encoding_type(req, res);
  1043. // gzip has highest q=1.0, so it should be selected even though
  1044. // br and zstd are also supported
  1045. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1046. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1047. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1048. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1049. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1050. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1051. #else
  1052. EXPECT_TRUE(ret == detail::EncodingType::None);
  1053. #endif
  1054. }
  1055. TEST(BufferStreamTest, read) {
  1056. detail::BufferStream strm1;
  1057. Stream &strm = strm1;
  1058. EXPECT_EQ(5, strm.write("hello"));
  1059. char buf[512];
  1060. EXPECT_EQ(2, strm.read(buf, 2));
  1061. EXPECT_EQ('h', buf[0]);
  1062. EXPECT_EQ('e', buf[1]);
  1063. EXPECT_EQ(2, strm.read(buf, 2));
  1064. EXPECT_EQ('l', buf[0]);
  1065. EXPECT_EQ('l', buf[1]);
  1066. EXPECT_EQ(1, strm.read(buf, 1));
  1067. EXPECT_EQ('o', buf[0]);
  1068. EXPECT_EQ(0, strm.read(buf, 1));
  1069. }
  1070. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1071. auto host = "www.httpwatch.com";
  1072. auto ip = hosted_at(host);
  1073. EXPECT_EQ("23.96.13.243", ip);
  1074. std::vector<std::string> addrs;
  1075. hosted_at(host, addrs);
  1076. EXPECT_EQ(1u, addrs.size());
  1077. }
  1078. #if 0 // It depends on each test environment...
  1079. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1080. auto host = "www.youtube.com";
  1081. std::vector<std::string> addrs;
  1082. hosted_at(host, addrs);
  1083. EXPECT_EQ(20u, addrs.size());
  1084. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1085. EXPECT_TRUE(it != addrs.end());
  1086. }
  1087. #endif
  1088. class ChunkedEncodingTest : public ::testing::Test {
  1089. protected:
  1090. ChunkedEncodingTest()
  1091. : cli_(HOST, PORT)
  1092. #ifdef CPPHTTPLIB_SSL_ENABLED
  1093. ,
  1094. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1095. #endif
  1096. {
  1097. cli_.set_connection_timeout(2);
  1098. #ifdef CPPHTTPLIB_SSL_ENABLED
  1099. cli_.enable_server_certificate_verification(false);
  1100. #endif
  1101. }
  1102. virtual void SetUp() {
  1103. read_file("./image.jpg", image_data_);
  1104. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1105. res.set_content("Hello World!", "text/plain");
  1106. });
  1107. svr_.Get(
  1108. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1109. res.set_chunked_content_provider(
  1110. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1111. size_t remaining = image_data_.size() - offset;
  1112. if (remaining == 0) {
  1113. sink.done();
  1114. } else {
  1115. constexpr size_t CHUNK_SIZE = 1024;
  1116. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1117. sink.write(&image_data_[offset], send_size);
  1118. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1119. }
  1120. return true;
  1121. });
  1122. });
  1123. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1124. svr_.wait_until_ready();
  1125. }
  1126. virtual void TearDown() {
  1127. svr_.stop();
  1128. if (!request_threads_.empty()) {
  1129. std::this_thread::sleep_for(std::chrono::seconds(1));
  1130. for (auto &t : request_threads_) {
  1131. t.join();
  1132. }
  1133. }
  1134. t_.join();
  1135. }
  1136. #ifdef CPPHTTPLIB_SSL_ENABLED
  1137. SSLClient cli_;
  1138. SSLServer svr_;
  1139. #else
  1140. Client cli_;
  1141. Server svr_;
  1142. #endif
  1143. thread t_;
  1144. std::vector<thread> request_threads_;
  1145. std::string image_data_;
  1146. };
  1147. TEST_F(ChunkedEncodingTest, NormalGet) {
  1148. auto res = cli_.Get("/chunked");
  1149. ASSERT_TRUE(res);
  1150. std::string out;
  1151. read_file("./image.jpg", out);
  1152. EXPECT_EQ(StatusCode::OK_200, res->status);
  1153. EXPECT_EQ(out, res->body);
  1154. }
  1155. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1156. std::string body;
  1157. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1158. body.append(data, data_length);
  1159. return true;
  1160. });
  1161. ASSERT_TRUE(res);
  1162. std::string out;
  1163. read_file("./image.jpg", out);
  1164. EXPECT_EQ(StatusCode::OK_200, res->status);
  1165. EXPECT_EQ(out, body);
  1166. }
  1167. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1168. std::string body;
  1169. auto res = cli_.Get(
  1170. "/chunked",
  1171. [&](const Response &response) {
  1172. EXPECT_EQ(StatusCode::OK_200, response.status);
  1173. return true;
  1174. },
  1175. [&](const char *data, size_t data_length) {
  1176. body.append(data, data_length);
  1177. return true;
  1178. });
  1179. ASSERT_TRUE(res);
  1180. std::string out;
  1181. read_file("./image.jpg", out);
  1182. EXPECT_EQ(StatusCode::OK_200, res->status);
  1183. EXPECT_EQ(out, body);
  1184. }
  1185. TEST(RangeTest, FromHTTPBin_Online) {
  1186. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1187. auto host = "httpcan.org";
  1188. auto path = std::string{"/range/32"};
  1189. #else
  1190. auto host = "nghttp2.org";
  1191. auto path = std::string{"/httpbin/range/32"};
  1192. #endif
  1193. #ifdef CPPHTTPLIB_SSL_ENABLED
  1194. auto port = 443;
  1195. SSLClient cli(host, port);
  1196. #else
  1197. auto port = 80;
  1198. Client cli(host, port);
  1199. #endif
  1200. cli.set_connection_timeout(5);
  1201. {
  1202. auto res = cli.Get(path);
  1203. ASSERT_TRUE(res);
  1204. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1205. EXPECT_EQ(StatusCode::OK_200, res->status);
  1206. }
  1207. {
  1208. Headers headers = {make_range_header({{1, -1}})};
  1209. auto res = cli.Get(path, headers);
  1210. ASSERT_TRUE(res);
  1211. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1212. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1213. }
  1214. {
  1215. Headers headers = {make_range_header({{1, 10}})};
  1216. auto res = cli.Get(path, headers);
  1217. ASSERT_TRUE(res);
  1218. EXPECT_EQ("bcdefghijk", res->body);
  1219. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1220. }
  1221. {
  1222. Headers headers = {make_range_header({{0, 31}})};
  1223. auto res = cli.Get(path, headers);
  1224. ASSERT_TRUE(res);
  1225. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1226. EXPECT_EQ(StatusCode::OK_200, res->status);
  1227. }
  1228. {
  1229. Headers headers = {make_range_header({{0, -1}})};
  1230. auto res = cli.Get(path, headers);
  1231. ASSERT_TRUE(res);
  1232. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1233. EXPECT_EQ(StatusCode::OK_200, res->status);
  1234. }
  1235. {
  1236. Headers headers = {make_range_header({{0, 32}})};
  1237. auto res = cli.Get(path, headers);
  1238. ASSERT_TRUE(res);
  1239. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1240. }
  1241. }
  1242. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1243. auto host = "unresolvableaddress.local";
  1244. auto path = std::string{"/"};
  1245. #ifdef CPPHTTPLIB_SSL_ENABLED
  1246. auto port = 443;
  1247. SSLClient cli(host, port);
  1248. #else
  1249. auto port = 80;
  1250. Client cli(host, port);
  1251. #endif
  1252. cli.set_connection_timeout(1);
  1253. {
  1254. auto res = cli.Get(path);
  1255. ASSERT_FALSE(res);
  1256. }
  1257. std::this_thread::sleep_for(std::chrono::seconds(8));
  1258. }
  1259. TEST(ConnectionErrorTest, InvalidHost) {
  1260. auto host = "-abcde.com";
  1261. #ifdef CPPHTTPLIB_SSL_ENABLED
  1262. auto port = 443;
  1263. SSLClient cli(host, port);
  1264. #else
  1265. auto port = 80;
  1266. Client cli(host, port);
  1267. #endif
  1268. cli.set_connection_timeout(std::chrono::seconds(2));
  1269. auto res = cli.Get("/");
  1270. ASSERT_TRUE(!res);
  1271. EXPECT_EQ(Error::Connection, res.error());
  1272. }
  1273. TEST(ConnectionErrorTest, InvalidHost2) {
  1274. auto host = "httpcan.org/";
  1275. #ifdef CPPHTTPLIB_SSL_ENABLED
  1276. SSLClient cli(host);
  1277. #else
  1278. Client cli(host);
  1279. #endif
  1280. cli.set_connection_timeout(std::chrono::seconds(2));
  1281. auto res = cli.Get("/");
  1282. ASSERT_TRUE(!res);
  1283. EXPECT_EQ(Error::Connection, res.error());
  1284. }
  1285. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1286. auto host = "httpcan.org/";
  1287. #ifdef CPPHTTPLIB_SSL_ENABLED
  1288. SSLClient cli(host);
  1289. #else
  1290. Client cli(host);
  1291. #endif
  1292. cli.set_connection_timeout(std::chrono::seconds(2));
  1293. auto res = cli.Get("/");
  1294. ASSERT_TRUE(!res);
  1295. stringstream s;
  1296. s << "error code: " << res.error();
  1297. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1298. }
  1299. TEST(ConnectionErrorTest, InvalidPort) {
  1300. auto host = "localhost";
  1301. auto port = 44380;
  1302. #ifdef CPPHTTPLIB_SSL_ENABLED
  1303. SSLClient cli(host, port);
  1304. #else
  1305. Client cli(host, port);
  1306. #endif
  1307. cli.set_connection_timeout(std::chrono::seconds(2));
  1308. auto res = cli.Get("/");
  1309. ASSERT_TRUE(!res);
  1310. EXPECT_TRUE(Error::Connection == res.error() ||
  1311. Error::ConnectionTimeout == res.error());
  1312. }
  1313. TEST(ConnectionErrorTest, Timeout_Online) {
  1314. auto host = "google.com";
  1315. #ifdef CPPHTTPLIB_SSL_ENABLED
  1316. auto port = 44380;
  1317. SSLClient cli(host, port);
  1318. #else
  1319. auto port = 8080;
  1320. Client cli(host, port);
  1321. #endif
  1322. cli.set_connection_timeout(std::chrono::seconds(2));
  1323. // only probe one address type so that the error reason
  1324. // correlates to the timed-out IPv4, not the unsupported
  1325. // IPv6 connection attempt
  1326. cli.set_address_family(AF_INET);
  1327. auto res = cli.Get("/");
  1328. ASSERT_TRUE(!res);
  1329. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1330. }
  1331. TEST(CancelTest, NoCancel_Online) {
  1332. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1333. auto host = "httpcan.org";
  1334. auto path = std::string{"/range/32"};
  1335. #else
  1336. auto host = "nghttp2.org";
  1337. auto path = std::string{"/httpbin/range/32"};
  1338. #endif
  1339. #ifdef CPPHTTPLIB_SSL_ENABLED
  1340. auto port = 443;
  1341. SSLClient cli(host, port);
  1342. #else
  1343. auto port = 80;
  1344. Client cli(host, port);
  1345. #endif
  1346. cli.set_connection_timeout(std::chrono::seconds(5));
  1347. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1348. ASSERT_TRUE(res);
  1349. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1350. EXPECT_EQ(StatusCode::OK_200, res->status);
  1351. }
  1352. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1353. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1354. auto host = "httpcan.org";
  1355. auto path = std::string{"/range/32"};
  1356. #else
  1357. auto host = "nghttp2.org";
  1358. auto path = std::string{"/httpbin/range/32"};
  1359. #endif
  1360. #ifdef CPPHTTPLIB_SSL_ENABLED
  1361. auto port = 443;
  1362. SSLClient cli(host, port);
  1363. #else
  1364. auto port = 80;
  1365. Client cli(host, port);
  1366. #endif
  1367. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1368. cli.set_connection_timeout(std::chrono::seconds(5));
  1369. ASSERT_TRUE(!res);
  1370. EXPECT_EQ(Error::Canceled, res.error());
  1371. }
  1372. TEST(CancelTest, WithCancelLargePayload_Online) {
  1373. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1374. auto host = "httpcan.org";
  1375. auto path = std::string{"/range/65536"};
  1376. #else
  1377. auto host = "nghttp2.org";
  1378. auto path = std::string{"/httpbin/range/65536"};
  1379. #endif
  1380. #ifdef CPPHTTPLIB_SSL_ENABLED
  1381. auto port = 443;
  1382. SSLClient cli(host, port);
  1383. #else
  1384. auto port = 80;
  1385. Client cli(host, port);
  1386. #endif
  1387. cli.set_connection_timeout(std::chrono::seconds(5));
  1388. uint32_t count = 0;
  1389. auto res =
  1390. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1391. ASSERT_TRUE(!res);
  1392. EXPECT_EQ(Error::Canceled, res.error());
  1393. }
  1394. TEST(CancelTest, NoCancelPost) {
  1395. Server svr;
  1396. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1397. res.set_content("Hello World!", "text/plain");
  1398. });
  1399. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1400. auto se = detail::scope_exit([&] {
  1401. svr.stop();
  1402. thread.join();
  1403. ASSERT_FALSE(svr.is_running());
  1404. });
  1405. svr.wait_until_ready();
  1406. Client cli(HOST, PORT);
  1407. cli.set_connection_timeout(std::chrono::seconds(5));
  1408. auto res =
  1409. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1410. "application/json", [](uint64_t, uint64_t) { return true; });
  1411. ASSERT_TRUE(res);
  1412. EXPECT_EQ("Hello World!", res->body);
  1413. EXPECT_EQ(StatusCode::OK_200, res->status);
  1414. }
  1415. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1416. Server svr;
  1417. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1418. res.set_content("Hello World!", "text/plain");
  1419. });
  1420. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1421. auto se = detail::scope_exit([&] {
  1422. svr.stop();
  1423. thread.join();
  1424. ASSERT_FALSE(svr.is_running());
  1425. });
  1426. svr.wait_until_ready();
  1427. Client cli(HOST, PORT);
  1428. cli.set_connection_timeout(std::chrono::seconds(5));
  1429. auto res =
  1430. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1431. "application/json", [](uint64_t, uint64_t) { return false; });
  1432. ASSERT_TRUE(!res);
  1433. EXPECT_EQ(Error::Canceled, res.error());
  1434. }
  1435. TEST(CancelTest, WithCancelLargePayloadPost) {
  1436. Server svr;
  1437. svr.set_payload_max_length(200 * 1024 * 1024);
  1438. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1439. res.set_content(LARGE_DATA, "text/plain");
  1440. });
  1441. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1442. auto se = detail::scope_exit([&] {
  1443. svr.stop();
  1444. thread.join();
  1445. ASSERT_FALSE(svr.is_running());
  1446. });
  1447. svr.wait_until_ready();
  1448. Client cli(HOST, PORT);
  1449. cli.set_payload_max_length(200 * 1024 * 1024);
  1450. cli.set_connection_timeout(std::chrono::seconds(5));
  1451. auto res =
  1452. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1453. "application/json", [](uint64_t, uint64_t) { return false; });
  1454. ASSERT_TRUE(!res);
  1455. EXPECT_EQ(Error::Canceled, res.error());
  1456. }
  1457. TEST(CancelTest, NoCancelPut) {
  1458. Server svr;
  1459. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1460. res.set_content("Hello World!", "text/plain");
  1461. });
  1462. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1463. auto se = detail::scope_exit([&] {
  1464. svr.stop();
  1465. thread.join();
  1466. ASSERT_FALSE(svr.is_running());
  1467. });
  1468. svr.wait_until_ready();
  1469. Client cli(HOST, PORT);
  1470. cli.set_connection_timeout(std::chrono::seconds(5));
  1471. auto res =
  1472. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1473. "application/json", [](uint64_t, uint64_t) { return true; });
  1474. ASSERT_TRUE(res);
  1475. EXPECT_EQ("Hello World!", res->body);
  1476. EXPECT_EQ(StatusCode::OK_200, res->status);
  1477. }
  1478. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1479. Server svr;
  1480. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1481. res.set_content("Hello World!", "text/plain");
  1482. });
  1483. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1484. auto se = detail::scope_exit([&] {
  1485. svr.stop();
  1486. thread.join();
  1487. ASSERT_FALSE(svr.is_running());
  1488. });
  1489. svr.wait_until_ready();
  1490. Client cli(HOST, PORT);
  1491. cli.set_connection_timeout(std::chrono::seconds(5));
  1492. auto res =
  1493. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1494. "application/json", [](uint64_t, uint64_t) { return false; });
  1495. ASSERT_TRUE(!res);
  1496. EXPECT_EQ(Error::Canceled, res.error());
  1497. }
  1498. TEST(CancelTest, WithCancelLargePayloadPut) {
  1499. Server svr;
  1500. svr.set_payload_max_length(200 * 1024 * 1024);
  1501. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1502. res.set_content(LARGE_DATA, "text/plain");
  1503. });
  1504. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1505. auto se = detail::scope_exit([&] {
  1506. svr.stop();
  1507. thread.join();
  1508. ASSERT_FALSE(svr.is_running());
  1509. });
  1510. svr.wait_until_ready();
  1511. Client cli(HOST, PORT);
  1512. cli.set_payload_max_length(200 * 1024 * 1024);
  1513. cli.set_connection_timeout(std::chrono::seconds(5));
  1514. auto res =
  1515. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1516. "application/json", [](uint64_t, uint64_t) { return false; });
  1517. ASSERT_TRUE(!res);
  1518. EXPECT_EQ(Error::Canceled, res.error());
  1519. }
  1520. TEST(CancelTest, NoCancelPatch) {
  1521. Server svr;
  1522. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1523. res.set_content("Hello World!", "text/plain");
  1524. });
  1525. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1526. auto se = detail::scope_exit([&] {
  1527. svr.stop();
  1528. thread.join();
  1529. ASSERT_FALSE(svr.is_running());
  1530. });
  1531. svr.wait_until_ready();
  1532. Client cli(HOST, PORT);
  1533. cli.set_connection_timeout(std::chrono::seconds(5));
  1534. auto res =
  1535. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1536. "application/json", [](uint64_t, uint64_t) { return true; });
  1537. ASSERT_TRUE(res);
  1538. EXPECT_EQ("Hello World!", res->body);
  1539. EXPECT_EQ(StatusCode::OK_200, res->status);
  1540. }
  1541. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1542. Server svr;
  1543. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1544. res.set_content("Hello World!", "text/plain");
  1545. });
  1546. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1547. auto se = detail::scope_exit([&] {
  1548. svr.stop();
  1549. thread.join();
  1550. ASSERT_FALSE(svr.is_running());
  1551. });
  1552. svr.wait_until_ready();
  1553. Client cli(HOST, PORT);
  1554. cli.set_connection_timeout(std::chrono::seconds(5));
  1555. auto res =
  1556. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1557. "application/json", [](uint64_t, uint64_t) { return false; });
  1558. ASSERT_TRUE(!res);
  1559. EXPECT_EQ(Error::Canceled, res.error());
  1560. }
  1561. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1562. Server svr;
  1563. svr.set_payload_max_length(200 * 1024 * 1024);
  1564. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1565. res.set_content(LARGE_DATA, "text/plain");
  1566. });
  1567. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1568. auto se = detail::scope_exit([&] {
  1569. svr.stop();
  1570. thread.join();
  1571. ASSERT_FALSE(svr.is_running());
  1572. });
  1573. svr.wait_until_ready();
  1574. Client cli(HOST, PORT);
  1575. cli.set_payload_max_length(200 * 1024 * 1024);
  1576. cli.set_connection_timeout(std::chrono::seconds(5));
  1577. auto res =
  1578. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1579. "application/json", [](uint64_t, uint64_t) { return false; });
  1580. ASSERT_TRUE(!res);
  1581. EXPECT_EQ(Error::Canceled, res.error());
  1582. }
  1583. TEST(CancelTest, NoCancelDelete) {
  1584. Server svr;
  1585. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1586. res.set_content("Hello World!", "text/plain");
  1587. });
  1588. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1589. auto se = detail::scope_exit([&] {
  1590. svr.stop();
  1591. thread.join();
  1592. ASSERT_FALSE(svr.is_running());
  1593. });
  1594. svr.wait_until_ready();
  1595. Client cli(HOST, PORT);
  1596. cli.set_connection_timeout(std::chrono::seconds(5));
  1597. auto res =
  1598. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1599. "application/json", [](uint64_t, uint64_t) { return true; });
  1600. ASSERT_TRUE(res);
  1601. EXPECT_EQ("Hello World!", res->body);
  1602. EXPECT_EQ(StatusCode::OK_200, res->status);
  1603. }
  1604. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1605. Server svr;
  1606. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1607. res.set_content("Hello World!", "text/plain");
  1608. });
  1609. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1610. auto se = detail::scope_exit([&] {
  1611. svr.stop();
  1612. thread.join();
  1613. ASSERT_FALSE(svr.is_running());
  1614. });
  1615. svr.wait_until_ready();
  1616. Client cli(HOST, PORT);
  1617. cli.set_connection_timeout(std::chrono::seconds(5));
  1618. auto res =
  1619. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1620. "application/json", [](uint64_t, uint64_t) { return false; });
  1621. ASSERT_TRUE(!res);
  1622. EXPECT_EQ(Error::Canceled, res.error());
  1623. }
  1624. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1625. Server svr;
  1626. svr.set_payload_max_length(200 * 1024 * 1024);
  1627. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1628. res.set_content(LARGE_DATA, "text/plain");
  1629. });
  1630. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1631. auto se = detail::scope_exit([&] {
  1632. svr.stop();
  1633. thread.join();
  1634. ASSERT_FALSE(svr.is_running());
  1635. });
  1636. svr.wait_until_ready();
  1637. Client cli(HOST, PORT);
  1638. cli.set_payload_max_length(200 * 1024 * 1024);
  1639. cli.set_connection_timeout(std::chrono::seconds(5));
  1640. auto res =
  1641. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1642. "application/json", [](uint64_t, uint64_t) { return false; });
  1643. ASSERT_TRUE(!res);
  1644. EXPECT_EQ(Error::Canceled, res.error());
  1645. }
  1646. static std::string remove_whitespace(const std::string &input) {
  1647. std::string output;
  1648. output.reserve(input.size());
  1649. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1650. [](unsigned char c) { return !std::isspace(c); });
  1651. return output;
  1652. }
  1653. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1654. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1655. auto host = "httpcan.org";
  1656. auto path = std::string{"/basic-auth/hello/world"};
  1657. #else
  1658. auto host = "nghttp2.org";
  1659. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1660. #endif
  1661. #ifdef CPPHTTPLIB_SSL_ENABLED
  1662. auto port = 443;
  1663. SSLClient cli(host, port);
  1664. #else
  1665. auto port = 80;
  1666. Client cli(host, port);
  1667. #endif
  1668. {
  1669. auto res = cli.Get(path);
  1670. ASSERT_TRUE(res);
  1671. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1672. }
  1673. {
  1674. auto res =
  1675. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1676. ASSERT_TRUE(res);
  1677. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1678. remove_whitespace(res->body));
  1679. EXPECT_EQ(StatusCode::OK_200, res->status);
  1680. }
  1681. {
  1682. cli.set_basic_auth("hello", "world");
  1683. auto res = cli.Get(path);
  1684. ASSERT_TRUE(res);
  1685. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1686. remove_whitespace(res->body));
  1687. EXPECT_EQ(StatusCode::OK_200, res->status);
  1688. }
  1689. {
  1690. cli.set_basic_auth("hello", "bad");
  1691. auto res = cli.Get(path);
  1692. ASSERT_TRUE(res);
  1693. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1694. }
  1695. {
  1696. cli.set_basic_auth("bad", "world");
  1697. auto res = cli.Get(path);
  1698. ASSERT_TRUE(res);
  1699. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1700. }
  1701. }
  1702. #ifdef CPPHTTPLIB_SSL_ENABLED
  1703. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1704. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1705. auto host = "httpcan.org";
  1706. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1707. auto paths = std::vector<std::string>{
  1708. "/digest-auth/auth/hello/world/MD5",
  1709. "/digest-auth/auth/hello/world/SHA-256",
  1710. "/digest-auth/auth/hello/world/SHA-512",
  1711. };
  1712. #else
  1713. auto host = "nghttp2.org";
  1714. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1715. auto paths = std::vector<std::string>{
  1716. "/httpbin/digest-auth/auth/hello/world/MD5",
  1717. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1718. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1719. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1720. };
  1721. #endif
  1722. auto port = 443;
  1723. SSLClient cli(host, port);
  1724. {
  1725. auto res = cli.Get(unauth_path);
  1726. ASSERT_TRUE(res);
  1727. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1728. }
  1729. {
  1730. cli.set_digest_auth("hello", "world");
  1731. for (const auto &path : paths) {
  1732. auto res = cli.Get(path.c_str());
  1733. ASSERT_TRUE(res);
  1734. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1735. std::string algo(path.substr(path.rfind('/') + 1));
  1736. EXPECT_EQ(
  1737. remove_whitespace("{\"algorithm\":\"" + algo +
  1738. "\",\"authenticated\":true,\"user\":\"hello\"}\n"),
  1739. remove_whitespace(res->body));
  1740. #else
  1741. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1742. remove_whitespace(res->body));
  1743. #endif
  1744. EXPECT_EQ(StatusCode::OK_200, res->status);
  1745. }
  1746. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1747. cli.set_digest_auth("hello", "bad");
  1748. for (const auto &path : paths) {
  1749. auto res = cli.Get(path.c_str());
  1750. ASSERT_TRUE(res);
  1751. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1752. }
  1753. #endif
  1754. }
  1755. }
  1756. #endif
  1757. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1758. auto host = "google.com";
  1759. auto another_host = "example.com";
  1760. auto wrong_ip = "0.0.0.0";
  1761. #ifdef CPPHTTPLIB_SSL_ENABLED
  1762. SSLClient cli(host);
  1763. #else
  1764. Client cli(host);
  1765. #endif
  1766. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1767. auto res = cli.Get("/");
  1768. ASSERT_TRUE(res);
  1769. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1770. }
  1771. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1772. auto host = "google.com";
  1773. auto wrong_ip = "0.0.0.0";
  1774. #ifdef CPPHTTPLIB_SSL_ENABLED
  1775. SSLClient cli(host);
  1776. #else
  1777. Client cli(host);
  1778. #endif
  1779. cli.set_hostname_addr_map({{host, wrong_ip}});
  1780. auto res = cli.Get("/");
  1781. ASSERT_TRUE(!res);
  1782. EXPECT_EQ(Error::Connection, res.error());
  1783. }
  1784. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1785. auto host = "nghttp2.org";
  1786. #ifdef CPPHTTPLIB_SSL_ENABLED
  1787. SSLClient cli(host);
  1788. #else
  1789. Client cli(host);
  1790. #endif
  1791. cli.set_follow_location(true);
  1792. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1793. ASSERT_TRUE(res);
  1794. EXPECT_EQ(StatusCode::OK_200, res->status);
  1795. }
  1796. TEST(RedirectTest, Redirect_Online) {
  1797. auto host = "nghttp2.org";
  1798. #ifdef CPPHTTPLIB_SSL_ENABLED
  1799. SSLClient cli(host);
  1800. #else
  1801. Client cli(host);
  1802. #endif
  1803. cli.set_follow_location(true);
  1804. auto res = cli.Get("/httpbin/redirect/3");
  1805. ASSERT_TRUE(res);
  1806. EXPECT_EQ(StatusCode::OK_200, res->status);
  1807. }
  1808. TEST(RelativeRedirectTest, Redirect_Online) {
  1809. auto host = "nghttp2.org";
  1810. #ifdef CPPHTTPLIB_SSL_ENABLED
  1811. SSLClient cli(host);
  1812. #else
  1813. Client cli(host);
  1814. #endif
  1815. cli.set_follow_location(true);
  1816. auto res = cli.Get("/httpbin/relative-redirect/3");
  1817. ASSERT_TRUE(res);
  1818. EXPECT_EQ(StatusCode::OK_200, res->status);
  1819. }
  1820. TEST(TooManyRedirectTest, Redirect_Online) {
  1821. auto host = "nghttp2.org";
  1822. #ifdef CPPHTTPLIB_SSL_ENABLED
  1823. SSLClient cli(host);
  1824. #else
  1825. Client cli(host);
  1826. #endif
  1827. cli.set_follow_location(true);
  1828. auto res = cli.Get("/httpbin/redirect/21");
  1829. ASSERT_TRUE(!res);
  1830. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1831. }
  1832. #ifdef CPPHTTPLIB_SSL_ENABLED
  1833. TEST(YahooRedirectTest, Redirect_Online) {
  1834. Client cli("yahoo.com");
  1835. auto res = cli.Get("/");
  1836. ASSERT_TRUE(res);
  1837. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1838. cli.set_follow_location(true);
  1839. res = cli.Get("/");
  1840. ASSERT_TRUE(res);
  1841. EXPECT_EQ(StatusCode::OK_200, res->status);
  1842. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1843. }
  1844. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1845. #define REDIR_HOST "httpbingo.org"
  1846. #define REDIR_PATH "/redirect-to"
  1847. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1848. SSLClient cli(REDIR_HOST);
  1849. cli.set_follow_location(true);
  1850. auto res =
  1851. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1852. ASSERT_TRUE(res);
  1853. EXPECT_EQ(StatusCode::OK_200, res->status);
  1854. }
  1855. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1856. SSLClient cli(REDIR_HOST);
  1857. cli.set_follow_location(true);
  1858. Params params;
  1859. params.emplace("url", "http://example.com");
  1860. params.emplace("status_code", "302");
  1861. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1862. ASSERT_TRUE(res);
  1863. EXPECT_EQ(StatusCode::OK_200, res->status);
  1864. }
  1865. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1866. SSLClient cli(REDIR_HOST);
  1867. cli.set_follow_location(true);
  1868. Params params;
  1869. params.emplace("url", "http://example.com");
  1870. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1871. ASSERT_TRUE(res);
  1872. EXPECT_EQ(StatusCode::OK_200, res->status);
  1873. }
  1874. TEST(UrlWithSpace, Redirect_Online) {
  1875. SSLClient cli("edge.forgecdn.net");
  1876. cli.set_follow_location(true);
  1877. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1878. ASSERT_TRUE(res);
  1879. EXPECT_EQ(StatusCode::OK_200, res->status);
  1880. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1881. }
  1882. #endif
  1883. #if !defined(_WIN32) && !defined(_WIN64)
  1884. TEST(ReceiveSignals, Signal) {
  1885. auto setupSignalHandlers = []() {
  1886. struct sigaction act;
  1887. sigemptyset(&act.sa_mask);
  1888. act.sa_flags = SA_SIGINFO;
  1889. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1890. switch (sig) {
  1891. case SIGINT:
  1892. default: break;
  1893. }
  1894. };
  1895. ::sigaction(SIGINT, &act, nullptr);
  1896. };
  1897. Server svr;
  1898. int port = 0;
  1899. auto thread = std::thread([&]() {
  1900. setupSignalHandlers();
  1901. port = svr.bind_to_any_port(HOST);
  1902. svr.listen_after_bind();
  1903. });
  1904. auto se = detail::scope_exit([&] {
  1905. svr.stop();
  1906. thread.join();
  1907. ASSERT_FALSE(svr.is_running());
  1908. });
  1909. svr.wait_until_ready();
  1910. ASSERT_TRUE(svr.is_running());
  1911. pthread_kill(thread.native_handle(), SIGINT);
  1912. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1913. ASSERT_TRUE(svr.is_running());
  1914. }
  1915. #endif
  1916. TEST(RedirectToDifferentPort, Redirect) {
  1917. Server svr1;
  1918. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1919. res.set_content("Hello World!", "text/plain");
  1920. });
  1921. int svr1_port = 0;
  1922. auto thread1 = std::thread([&]() {
  1923. svr1_port = svr1.bind_to_any_port(HOST);
  1924. svr1.listen_after_bind();
  1925. });
  1926. Server svr2;
  1927. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1928. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1929. });
  1930. int svr2_port = 0;
  1931. auto thread2 = std::thread([&]() {
  1932. svr2_port = svr2.bind_to_any_port(HOST);
  1933. svr2.listen_after_bind();
  1934. });
  1935. auto se = detail::scope_exit([&] {
  1936. svr2.stop();
  1937. thread2.join();
  1938. svr1.stop();
  1939. thread1.join();
  1940. ASSERT_FALSE(svr2.is_running());
  1941. ASSERT_FALSE(svr1.is_running());
  1942. });
  1943. svr1.wait_until_ready();
  1944. svr2.wait_until_ready();
  1945. Client cli("localhost", svr2_port);
  1946. cli.set_follow_location(true);
  1947. auto res = cli.Get("/2");
  1948. ASSERT_TRUE(res);
  1949. EXPECT_EQ(StatusCode::OK_200, res->status);
  1950. EXPECT_EQ("Hello World!", res->body);
  1951. }
  1952. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  1953. Server svr;
  1954. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  1955. // Port number that overflows int — should not crash
  1956. res.set_redirect("http://localhost:99999999999999999999/target");
  1957. });
  1958. auto port = svr.bind_to_any_port(HOST);
  1959. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  1960. auto se = detail::scope_exit([&] {
  1961. svr.stop();
  1962. thread.join();
  1963. ASSERT_FALSE(svr.is_running());
  1964. });
  1965. svr.wait_until_ready();
  1966. Client cli(HOST, port);
  1967. cli.set_follow_location(true);
  1968. auto res = cli.Get("/redir");
  1969. // Should fail gracefully, not crash (no valid response due to bad port)
  1970. EXPECT_FALSE(res);
  1971. }
  1972. TEST(RedirectFromPageWithContent, Redirect) {
  1973. Server svr;
  1974. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1975. res.set_content("___", "text/plain");
  1976. res.set_redirect("/2");
  1977. });
  1978. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1979. res.set_content("Hello World!", "text/plain");
  1980. });
  1981. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1982. auto se = detail::scope_exit([&] {
  1983. svr.stop();
  1984. th.join();
  1985. ASSERT_FALSE(svr.is_running());
  1986. });
  1987. svr.wait_until_ready();
  1988. {
  1989. Client cli("localhost", PORT);
  1990. cli.set_follow_location(true);
  1991. std::string body;
  1992. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1993. body.append(data, data_length);
  1994. return true;
  1995. });
  1996. ASSERT_TRUE(res);
  1997. EXPECT_EQ(StatusCode::OK_200, res->status);
  1998. EXPECT_EQ("Hello World!", body);
  1999. }
  2000. {
  2001. Client cli("localhost", PORT);
  2002. std::string body;
  2003. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2004. body.append(data, data_length);
  2005. return true;
  2006. });
  2007. ASSERT_TRUE(res);
  2008. EXPECT_EQ(StatusCode::Found_302, res->status);
  2009. EXPECT_EQ("___", body);
  2010. }
  2011. }
  2012. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2013. Server svr;
  2014. auto port_str = std::to_string(PORT);
  2015. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2016. auto expected_host = "[::1]:" + port_str;
  2017. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2018. res.set_content("___", "text/plain");
  2019. // res.set_redirect("/2");
  2020. res.set_redirect(redirect_url);
  2021. });
  2022. svr.Get("/2", [&](const Request &req, Response &res) {
  2023. auto host_header = req.headers.find("Host");
  2024. ASSERT_TRUE(host_header != req.headers.end());
  2025. EXPECT_EQ(expected_host, host_header->second);
  2026. res.set_content("Hello World!", "text/plain");
  2027. });
  2028. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2029. auto se = detail::scope_exit([&] {
  2030. svr.stop();
  2031. th.join();
  2032. ASSERT_FALSE(svr.is_running());
  2033. });
  2034. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2035. // actually starts anything, so the condition !svr.is_running() will
  2036. // always remain true, and the loop never stops.
  2037. // This basically counts how many milliseconds have passed since the
  2038. // call to svr.listen(), and if after 5 seconds nothing started yet
  2039. // aborts the test.
  2040. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2041. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2042. ASSERT_LT(milliseconds, 5000U);
  2043. }
  2044. {
  2045. Client cli("::1", PORT);
  2046. cli.set_follow_location(true);
  2047. std::string body;
  2048. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2049. body.append(data, data_length);
  2050. return true;
  2051. });
  2052. ASSERT_TRUE(res);
  2053. EXPECT_EQ(StatusCode::OK_200, res->status);
  2054. EXPECT_EQ("Hello World!", body);
  2055. }
  2056. {
  2057. Client cli("::1", PORT);
  2058. std::string body;
  2059. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2060. body.append(data, data_length);
  2061. return true;
  2062. });
  2063. ASSERT_TRUE(res);
  2064. EXPECT_EQ(StatusCode::Found_302, res->status);
  2065. EXPECT_EQ("___", body);
  2066. }
  2067. }
  2068. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2069. Server svr;
  2070. svr.Get("/foo", [](const Request &req, Response &res) {
  2071. auto a = req.params.find("a");
  2072. if (a != req.params.end()) {
  2073. res.set_content((*a).second, "text/plain");
  2074. res.status = StatusCode::OK_200;
  2075. } else {
  2076. res.status = StatusCode::BadRequest_400;
  2077. }
  2078. });
  2079. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2080. auto se = detail::scope_exit([&] {
  2081. svr.stop();
  2082. thread.join();
  2083. ASSERT_FALSE(svr.is_running());
  2084. });
  2085. svr.wait_until_ready();
  2086. {
  2087. Client cli(HOST, PORT);
  2088. cli.set_path_encode(false);
  2089. auto res = cli.Get("/foo?a=explicitly+encoded");
  2090. ASSERT_TRUE(res);
  2091. EXPECT_EQ(StatusCode::OK_200, res->status);
  2092. // This expects it back with a space, as the `+` won't have been
  2093. // url-encoded, and server-side the params get decoded turning `+`
  2094. // into spaces.
  2095. EXPECT_EQ("explicitly encoded", res->body);
  2096. }
  2097. }
  2098. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2099. Server svr;
  2100. svr.Get("/", [](const Request &req, Response &) {
  2101. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2102. });
  2103. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2104. auto se = detail::scope_exit([&] {
  2105. svr.stop();
  2106. thread.join();
  2107. ASSERT_FALSE(svr.is_running());
  2108. });
  2109. svr.wait_until_ready();
  2110. {
  2111. Client cli(HOST, PORT);
  2112. cli.set_path_encode(false);
  2113. auto res = cli.Get("/?something=%0A");
  2114. ASSERT_TRUE(res);
  2115. EXPECT_EQ(StatusCode::OK_200, res->status);
  2116. }
  2117. }
  2118. TEST(BindServerTest, BindDualStack) {
  2119. Server svr;
  2120. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2121. res.set_content("Hello World!", "text/plain");
  2122. });
  2123. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2124. auto se = detail::scope_exit([&] {
  2125. svr.stop();
  2126. thread.join();
  2127. ASSERT_FALSE(svr.is_running());
  2128. });
  2129. svr.wait_until_ready();
  2130. {
  2131. Client cli("127.0.0.1", PORT);
  2132. auto res = cli.Get("/1");
  2133. ASSERT_TRUE(res);
  2134. EXPECT_EQ(StatusCode::OK_200, res->status);
  2135. EXPECT_EQ("Hello World!", res->body);
  2136. }
  2137. {
  2138. Client cli("::1", PORT);
  2139. auto res = cli.Get("/1");
  2140. ASSERT_TRUE(res);
  2141. EXPECT_EQ(StatusCode::OK_200, res->status);
  2142. EXPECT_EQ("Hello World!", res->body);
  2143. }
  2144. }
  2145. TEST(BindServerTest, BindAndListenSeparately) {
  2146. Server svr;
  2147. int port = svr.bind_to_any_port("0.0.0.0");
  2148. ASSERT_TRUE(svr.is_valid());
  2149. ASSERT_TRUE(port > 0);
  2150. svr.stop();
  2151. }
  2152. #ifdef CPPHTTPLIB_SSL_ENABLED
  2153. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2154. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2155. CLIENT_CA_CERT_DIR);
  2156. int port = svr.bind_to_any_port("0.0.0.0");
  2157. ASSERT_TRUE(svr.is_valid());
  2158. ASSERT_TRUE(port > 0);
  2159. svr.stop();
  2160. }
  2161. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2162. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2163. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2164. int port = svr.bind_to_any_port("0.0.0.0");
  2165. ASSERT_TRUE(svr.is_valid());
  2166. ASSERT_TRUE(port > 0);
  2167. svr.stop();
  2168. }
  2169. TEST(BindServerTest, UpdateCertsPem) {
  2170. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2171. int port = svr.bind_to_any_port("0.0.0.0");
  2172. ASSERT_TRUE(svr.is_valid());
  2173. ASSERT_TRUE(port > 0);
  2174. // Read PEM files
  2175. std::string cert_pem, key_pem, ca_pem;
  2176. read_file(SERVER_CERT_FILE, cert_pem);
  2177. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2178. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2179. // Update server certificates using PEM API
  2180. ASSERT_TRUE(
  2181. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2182. ASSERT_TRUE(svr.is_valid());
  2183. svr.stop();
  2184. }
  2185. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2186. // Start server with client CA (enables client auth)
  2187. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2188. ASSERT_TRUE(svr.is_valid());
  2189. bool handler_called = false;
  2190. svr.Get("/test", [&](const Request &req, Response &res) {
  2191. handler_called = true;
  2192. // Verify client certificate is present
  2193. auto cert = req.peer_cert();
  2194. EXPECT_TRUE(static_cast<bool>(cert));
  2195. res.set_content("ok", "text/plain");
  2196. });
  2197. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2198. auto se = detail::scope_exit([&] {
  2199. svr.stop();
  2200. t.join();
  2201. ASSERT_FALSE(svr.is_running());
  2202. });
  2203. svr.wait_until_ready();
  2204. // Read PEM files
  2205. std::string cert_pem, key_pem, ca_pem;
  2206. read_file(SERVER_CERT_FILE, cert_pem);
  2207. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2208. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2209. // Update server certificates and client CA using PEM API while server running
  2210. ASSERT_TRUE(
  2211. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2212. // Connect with client certificate
  2213. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2214. cli.enable_server_certificate_verification(false);
  2215. cli.set_connection_timeout(30);
  2216. auto res = cli.Get("/test");
  2217. ASSERT_TRUE(res);
  2218. ASSERT_EQ(StatusCode::OK_200, res->status);
  2219. ASSERT_TRUE(handler_called);
  2220. EXPECT_EQ("ok", res->body);
  2221. }
  2222. #endif
  2223. TEST(ErrorHandlerTest, ContentLength) {
  2224. Server svr;
  2225. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2226. res.status = StatusCode::OK_200;
  2227. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2228. "text/html"); // <= Content-Length still 13
  2229. });
  2230. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2231. res.set_content("Hello World!\n", "text/plain");
  2232. res.status = 524;
  2233. });
  2234. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2235. auto se = detail::scope_exit([&] {
  2236. svr.stop();
  2237. thread.join();
  2238. ASSERT_FALSE(svr.is_running());
  2239. });
  2240. svr.wait_until_ready();
  2241. {
  2242. Client cli(HOST, PORT);
  2243. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2244. ASSERT_TRUE(res);
  2245. EXPECT_EQ(StatusCode::OK_200, res->status);
  2246. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2247. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2248. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2249. }
  2250. }
  2251. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2252. TEST(ExceptionTest, WithoutExceptionHandler) {
  2253. Server svr;
  2254. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2255. throw std::runtime_error("exception...");
  2256. });
  2257. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2258. throw std::runtime_error("exception\r\n...");
  2259. });
  2260. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2261. auto se = detail::scope_exit([&] {
  2262. svr.stop();
  2263. listen_thread.join();
  2264. ASSERT_FALSE(svr.is_running());
  2265. });
  2266. svr.wait_until_ready();
  2267. Client cli("localhost", PORT);
  2268. {
  2269. auto res = cli.Get("/exception");
  2270. ASSERT_TRUE(res);
  2271. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2272. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2273. }
  2274. {
  2275. auto res = cli.Get("/unknown");
  2276. ASSERT_TRUE(res);
  2277. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2278. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2279. }
  2280. }
  2281. TEST(ExceptionTest, WithExceptionHandler) {
  2282. Server svr;
  2283. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2284. std::exception_ptr ep) {
  2285. EXPECT_FALSE(ep == nullptr);
  2286. try {
  2287. std::rethrow_exception(ep);
  2288. } catch (std::exception &e) {
  2289. EXPECT_EQ("abc", std::string(e.what()));
  2290. } catch (...) {}
  2291. res.status = StatusCode::InternalServerError_500;
  2292. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2293. "text/html"); // <= Content-Length still 13 at this point
  2294. });
  2295. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2296. res.set_content("Hello World!\n", "text/plain");
  2297. throw std::runtime_error("abc");
  2298. });
  2299. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2300. auto se = detail::scope_exit([&] {
  2301. svr.stop();
  2302. thread.join();
  2303. ASSERT_FALSE(svr.is_running());
  2304. });
  2305. svr.wait_until_ready();
  2306. for (size_t i = 0; i < 10; i++) {
  2307. Client cli(HOST, PORT);
  2308. for (size_t j = 0; j < 100; j++) {
  2309. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2310. ASSERT_TRUE(res);
  2311. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2312. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2313. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2314. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2315. }
  2316. cli.set_keep_alive(true);
  2317. for (size_t j = 0; j < 100; j++) {
  2318. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2319. ASSERT_TRUE(res);
  2320. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2321. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2322. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2323. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2324. }
  2325. }
  2326. }
  2327. TEST(ExceptionTest, AndErrorHandler) {
  2328. Server svr;
  2329. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2330. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2331. });
  2332. svr.set_exception_handler(
  2333. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2334. EXPECT_FALSE(ep == nullptr);
  2335. try {
  2336. std::rethrow_exception(ep);
  2337. } catch (std::exception &e) {
  2338. res.set_content(e.what(), "text/html");
  2339. } catch (...) {}
  2340. res.status = StatusCode::InternalServerError_500;
  2341. });
  2342. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2343. throw std::runtime_error("EXCEPTION");
  2344. });
  2345. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2346. res.set_content("ERROR", "text/html");
  2347. res.status = StatusCode::InternalServerError_500;
  2348. });
  2349. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2350. auto se = detail::scope_exit([&] {
  2351. svr.stop();
  2352. thread.join();
  2353. ASSERT_FALSE(svr.is_running());
  2354. });
  2355. svr.wait_until_ready();
  2356. Client cli(HOST, PORT);
  2357. {
  2358. auto res = cli.Get("/exception");
  2359. ASSERT_TRUE(res);
  2360. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2361. EXPECT_EQ("EXCEPTION", res->body);
  2362. }
  2363. {
  2364. auto res = cli.Get("/error");
  2365. ASSERT_TRUE(res);
  2366. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2367. EXPECT_EQ("ERROR", res->body);
  2368. }
  2369. {
  2370. auto res = cli.Get("/invalid");
  2371. ASSERT_TRUE(res);
  2372. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2373. EXPECT_EQ("NOT_FOUND", res->body);
  2374. }
  2375. }
  2376. #endif
  2377. TEST(NoContentTest, ContentLength) {
  2378. Server svr;
  2379. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2380. res.status = StatusCode::NoContent_204;
  2381. });
  2382. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2383. auto se = detail::scope_exit([&] {
  2384. svr.stop();
  2385. thread.join();
  2386. ASSERT_FALSE(svr.is_running());
  2387. });
  2388. svr.wait_until_ready();
  2389. {
  2390. Client cli(HOST, PORT);
  2391. auto res = cli.Get("/hi");
  2392. ASSERT_TRUE(res);
  2393. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2394. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2395. }
  2396. }
  2397. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2398. #ifdef CPPHTTPLIB_SSL_ENABLED
  2399. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2400. ASSERT_TRUE(svr.is_valid());
  2401. #else
  2402. Server svr;
  2403. #endif
  2404. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2405. if (req.path == "/routing_handler") {
  2406. res.set_header("PRE_ROUTING", "on");
  2407. res.set_content("Routing Handler", "text/plain");
  2408. return httplib::Server::HandlerResponse::Handled;
  2409. }
  2410. return httplib::Server::HandlerResponse::Unhandled;
  2411. });
  2412. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2413. res.set_content("Error", "text/html");
  2414. });
  2415. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2416. if (req.path == "/routing_handler") {
  2417. res.set_header("POST_ROUTING", "on");
  2418. }
  2419. });
  2420. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2421. res.set_content("Hello World!\n", "text/plain");
  2422. });
  2423. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2424. auto se = detail::scope_exit([&] {
  2425. svr.stop();
  2426. thread.join();
  2427. ASSERT_FALSE(svr.is_running());
  2428. });
  2429. svr.wait_until_ready();
  2430. {
  2431. #ifdef CPPHTTPLIB_SSL_ENABLED
  2432. SSLClient cli(HOST, PORT);
  2433. cli.enable_server_certificate_verification(false);
  2434. #else
  2435. Client cli(HOST, PORT);
  2436. #endif
  2437. auto res = cli.Get("/routing_handler");
  2438. ASSERT_TRUE(res);
  2439. EXPECT_EQ(StatusCode::OK_200, res->status);
  2440. EXPECT_EQ("Routing Handler", res->body);
  2441. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2442. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2443. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2444. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2445. }
  2446. {
  2447. #ifdef CPPHTTPLIB_SSL_ENABLED
  2448. SSLClient cli(HOST, PORT);
  2449. cli.enable_server_certificate_verification(false);
  2450. #else
  2451. Client cli(HOST, PORT);
  2452. #endif
  2453. auto res = cli.Get("/hi");
  2454. ASSERT_TRUE(res);
  2455. EXPECT_EQ(StatusCode::OK_200, res->status);
  2456. EXPECT_EQ("Hello World!\n", res->body);
  2457. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2458. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2459. }
  2460. {
  2461. #ifdef CPPHTTPLIB_SSL_ENABLED
  2462. SSLClient cli(HOST, PORT);
  2463. cli.enable_server_certificate_verification(false);
  2464. #else
  2465. Client cli(HOST, PORT);
  2466. #endif
  2467. auto res = cli.Get("/aaa");
  2468. ASSERT_TRUE(res);
  2469. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2470. EXPECT_EQ("Error", res->body);
  2471. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2472. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2473. }
  2474. }
  2475. TEST(RequestHandlerTest, PreRequestHandler) {
  2476. auto route_path = "/user/:user";
  2477. Server svr;
  2478. svr.Get("/hi", [](const Request &, Response &res) {
  2479. res.set_content("hi", "text/plain");
  2480. });
  2481. svr.Get(route_path, [](const Request &req, Response &res) {
  2482. res.set_content(req.path_params.at("user"), "text/plain");
  2483. });
  2484. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2485. if (req.matched_route == route_path) {
  2486. auto user = req.path_params.at("user");
  2487. if (user != "john") {
  2488. res.status = StatusCode::Forbidden_403;
  2489. res.set_content("error", "text/html");
  2490. return Server::HandlerResponse::Handled;
  2491. }
  2492. }
  2493. return Server::HandlerResponse::Unhandled;
  2494. });
  2495. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2496. auto se = detail::scope_exit([&] {
  2497. svr.stop();
  2498. thread.join();
  2499. ASSERT_FALSE(svr.is_running());
  2500. });
  2501. svr.wait_until_ready();
  2502. Client cli(HOST, PORT);
  2503. {
  2504. auto res = cli.Get("/hi");
  2505. ASSERT_TRUE(res);
  2506. EXPECT_EQ(StatusCode::OK_200, res->status);
  2507. EXPECT_EQ("hi", res->body);
  2508. }
  2509. {
  2510. auto res = cli.Get("/user/john");
  2511. ASSERT_TRUE(res);
  2512. EXPECT_EQ(StatusCode::OK_200, res->status);
  2513. EXPECT_EQ("john", res->body);
  2514. }
  2515. {
  2516. auto res = cli.Get("/user/invalid-user");
  2517. ASSERT_TRUE(res);
  2518. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2519. EXPECT_EQ("error", res->body);
  2520. }
  2521. }
  2522. TEST(AnyTest, BasicOperations) {
  2523. // Default construction
  2524. httplib::any a;
  2525. EXPECT_FALSE(a.has_value());
  2526. // Value construction and any_cast (pointer form, noexcept)
  2527. httplib::any b(42);
  2528. EXPECT_TRUE(b.has_value());
  2529. auto *p = httplib::any_cast<int>(&b);
  2530. ASSERT_NE(nullptr, p);
  2531. EXPECT_EQ(42, *p);
  2532. // Type mismatch → nullptr
  2533. auto *q = httplib::any_cast<std::string>(&b);
  2534. EXPECT_EQ(nullptr, q);
  2535. // any_cast (value form) succeeds
  2536. EXPECT_EQ(42, httplib::any_cast<int>(b));
  2537. // any_cast (value form) throws on type mismatch
  2538. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2539. EXPECT_THROW(httplib::any_cast<std::string>(b), httplib::bad_any_cast);
  2540. #endif
  2541. // Copy
  2542. httplib::any c = b;
  2543. EXPECT_EQ(42, httplib::any_cast<int>(c));
  2544. // Move
  2545. httplib::any d = std::move(c);
  2546. EXPECT_EQ(42, httplib::any_cast<int>(d));
  2547. // Assignment with different type
  2548. b = std::string("hello");
  2549. EXPECT_EQ("hello", httplib::any_cast<std::string>(b));
  2550. // Reset
  2551. b.reset();
  2552. EXPECT_FALSE(b.has_value());
  2553. }
  2554. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2555. struct AuthCtx {
  2556. std::string user_id;
  2557. };
  2558. Server svr;
  2559. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2560. res.user_data["auth"] = AuthCtx{"alice"};
  2561. return Server::HandlerResponse::Unhandled;
  2562. });
  2563. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2564. auto *ctx = httplib::any_cast<AuthCtx>(&res.user_data["auth"]);
  2565. ASSERT_NE(nullptr, ctx);
  2566. res.set_content("Hello " + ctx->user_id, "text/plain");
  2567. });
  2568. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2569. auto se = detail::scope_exit([&] {
  2570. svr.stop();
  2571. thread.join();
  2572. ASSERT_FALSE(svr.is_running());
  2573. });
  2574. svr.wait_until_ready();
  2575. Client cli(HOST, PORT);
  2576. auto res = cli.Get("/me");
  2577. ASSERT_TRUE(res);
  2578. EXPECT_EQ(StatusCode::OK_200, res->status);
  2579. EXPECT_EQ("Hello alice", res->body);
  2580. }
  2581. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2582. struct RoleCtx {
  2583. std::string role;
  2584. };
  2585. Server svr;
  2586. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2587. res.user_data["role"] = RoleCtx{"admin"};
  2588. return Server::HandlerResponse::Unhandled;
  2589. });
  2590. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2591. auto *ctx = httplib::any_cast<RoleCtx>(&res.user_data["role"]);
  2592. ASSERT_NE(nullptr, ctx);
  2593. res.set_content(ctx->role, "text/plain");
  2594. });
  2595. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2596. auto se = detail::scope_exit([&] {
  2597. svr.stop();
  2598. thread.join();
  2599. ASSERT_FALSE(svr.is_running());
  2600. });
  2601. svr.wait_until_ready();
  2602. Client cli(HOST, PORT);
  2603. auto res = cli.Get("/role");
  2604. ASSERT_TRUE(res);
  2605. EXPECT_EQ(StatusCode::OK_200, res->status);
  2606. EXPECT_EQ("admin", res->body);
  2607. }
  2608. TEST(InvalidFormatTest, StatusCode) {
  2609. Server svr;
  2610. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2611. res.set_content("Hello World!\n", "text/plain");
  2612. res.status = 9999; // Status should be a three-digit code...
  2613. });
  2614. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2615. auto se = detail::scope_exit([&] {
  2616. svr.stop();
  2617. thread.join();
  2618. ASSERT_FALSE(svr.is_running());
  2619. });
  2620. svr.wait_until_ready();
  2621. {
  2622. Client cli(HOST, PORT);
  2623. auto res = cli.Get("/hi");
  2624. ASSERT_FALSE(res);
  2625. }
  2626. }
  2627. TEST(URLFragmentTest, WithFragment) {
  2628. Server svr;
  2629. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2630. EXPECT_TRUE(req.target == "/hi");
  2631. });
  2632. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2633. auto se = detail::scope_exit([&] {
  2634. svr.stop();
  2635. thread.join();
  2636. ASSERT_FALSE(svr.is_running());
  2637. });
  2638. svr.wait_until_ready();
  2639. {
  2640. Client cli(HOST, PORT);
  2641. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2642. EXPECT_TRUE(res);
  2643. EXPECT_EQ(StatusCode::OK_200, res->status);
  2644. res = cli.Get("/hi%23key1=val1=key2=val2");
  2645. EXPECT_TRUE(res);
  2646. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2647. }
  2648. }
  2649. TEST(HeaderWriter, SetHeaderWriter) {
  2650. Server svr;
  2651. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2652. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2653. return detail::write_headers(strm, hdrs);
  2654. });
  2655. svr.Get("/hi", [](const Request &req, Response &res) {
  2656. auto it = req.headers.find("CustomClientHeader");
  2657. EXPECT_TRUE(it != req.headers.end());
  2658. EXPECT_EQ(it->second, "CustomClientValue");
  2659. res.set_content("Hello World!\n", "text/plain");
  2660. });
  2661. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2662. auto se = detail::scope_exit([&] {
  2663. svr.stop();
  2664. thread.join();
  2665. ASSERT_FALSE(svr.is_running());
  2666. });
  2667. svr.wait_until_ready();
  2668. {
  2669. Client cli(HOST, PORT);
  2670. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2671. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2672. return detail::write_headers(strm, hdrs);
  2673. });
  2674. auto res = cli.Get("/hi");
  2675. EXPECT_TRUE(res);
  2676. EXPECT_EQ(StatusCode::OK_200, res->status);
  2677. auto it = res->headers.find("CustomServerHeader");
  2678. EXPECT_TRUE(it != res->headers.end());
  2679. EXPECT_EQ(it->second, "CustomServerValue");
  2680. }
  2681. }
  2682. class ServerTest : public ::testing::Test {
  2683. protected:
  2684. ServerTest()
  2685. : cli_(HOST, PORT)
  2686. #ifdef CPPHTTPLIB_SSL_ENABLED
  2687. ,
  2688. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2689. #endif
  2690. {
  2691. #ifdef CPPHTTPLIB_SSL_ENABLED
  2692. cli_.enable_server_certificate_verification(false);
  2693. #endif
  2694. // Allow LARGE_DATA (100MB) responses
  2695. cli_.set_payload_max_length(200 * 1024 * 1024);
  2696. }
  2697. virtual void SetUp() {
  2698. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2699. svr_.set_payload_max_length(200 * 1024 * 1024);
  2700. svr_.set_mount_point("/", "./www");
  2701. svr_.set_mount_point("/mount", "./www2");
  2702. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2703. svr_.Get("/hi",
  2704. [&](const Request & /*req*/, Response &res) {
  2705. res.set_content("Hello World!", "text/plain");
  2706. })
  2707. .Get("/file_content",
  2708. [&](const Request & /*req*/, Response &res) {
  2709. res.set_file_content("./www/dir/test.html");
  2710. })
  2711. .Get("/file_content_with_content_type",
  2712. [&](const Request & /*req*/, Response &res) {
  2713. res.set_file_content("./www/file", "text/plain");
  2714. })
  2715. .Get("/invalid_file_content",
  2716. [&](const Request & /*req*/, Response &res) {
  2717. res.set_file_content("./www/dir/invalid_file_path");
  2718. })
  2719. .Get("/http_response_splitting",
  2720. [&](const Request & /*req*/, Response &res) {
  2721. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2722. EXPECT_EQ(0U, res.headers.size());
  2723. EXPECT_FALSE(res.has_header("a"));
  2724. res.set_header("a", "1\nSet-Cookie: a=1");
  2725. EXPECT_EQ(0U, res.headers.size());
  2726. EXPECT_FALSE(res.has_header("a"));
  2727. res.set_header("a", "1\rSet-Cookie: a=1");
  2728. EXPECT_EQ(0U, res.headers.size());
  2729. EXPECT_FALSE(res.has_header("a"));
  2730. res.set_header("a\r\nb", "0");
  2731. EXPECT_EQ(0U, res.headers.size());
  2732. EXPECT_FALSE(res.has_header("a"));
  2733. res.set_header("a\rb", "0");
  2734. EXPECT_EQ(0U, res.headers.size());
  2735. EXPECT_FALSE(res.has_header("a"));
  2736. res.set_header("a\nb", "0");
  2737. EXPECT_EQ(0U, res.headers.size());
  2738. EXPECT_FALSE(res.has_header("a"));
  2739. res.set_redirect("1\r\nSet-Cookie: a=1");
  2740. EXPECT_EQ(0U, res.headers.size());
  2741. EXPECT_FALSE(res.has_header("Location"));
  2742. })
  2743. .Get("/slow",
  2744. [&](const Request & /*req*/, Response &res) {
  2745. std::this_thread::sleep_for(std::chrono::seconds(2));
  2746. res.set_content("slow", "text/plain");
  2747. })
  2748. #if 0
  2749. .Post("/slowpost",
  2750. [&](const Request & /*req*/, Response &res) {
  2751. std::this_thread::sleep_for(std::chrono::seconds(2));
  2752. res.set_content("slow", "text/plain");
  2753. })
  2754. #endif
  2755. .Get("/remote_addr",
  2756. [&](const Request &req, Response &res) {
  2757. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2758. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2759. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2760. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2761. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2762. #endif
  2763. res.set_content(req.remote_addr, "text/plain");
  2764. })
  2765. .Get("/local_addr",
  2766. [&](const Request &req, Response &res) {
  2767. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2768. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2769. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2770. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2771. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2772. #endif
  2773. auto local_addr = req.local_addr;
  2774. auto local_port = std::to_string(req.local_port);
  2775. res.set_content(local_addr.append(":").append(local_port),
  2776. "text/plain");
  2777. })
  2778. .Get("/endwith%",
  2779. [&](const Request & /*req*/, Response &res) {
  2780. res.set_content("Hello World!", "text/plain");
  2781. })
  2782. .Get("/a\\+\\+b",
  2783. [&](const Request &req, Response &res) {
  2784. ASSERT_TRUE(req.has_param("a +b"));
  2785. auto val = req.get_param_value("a +b");
  2786. res.set_content(val, "text/plain");
  2787. })
  2788. .Get("/", [&](const Request & /*req*/,
  2789. Response &res) { res.set_redirect("/hi"); })
  2790. .Post("/1",
  2791. [](const Request & /*req*/, Response &res) {
  2792. res.set_redirect("/2", StatusCode::SeeOther_303);
  2793. })
  2794. .Get("/2",
  2795. [](const Request & /*req*/, Response &res) {
  2796. res.set_content("redirected.", "text/plain");
  2797. res.status = StatusCode::OK_200;
  2798. })
  2799. .Post("/person",
  2800. [&](const Request &req, Response &res) {
  2801. if (req.has_param("name") && req.has_param("note")) {
  2802. persons_[req.get_param_value("name")] =
  2803. req.get_param_value("note");
  2804. } else {
  2805. res.status = StatusCode::BadRequest_400;
  2806. }
  2807. })
  2808. .Put("/person",
  2809. [&](const Request &req, Response &res) {
  2810. if (req.has_param("name") && req.has_param("note")) {
  2811. persons_[req.get_param_value("name")] =
  2812. req.get_param_value("note");
  2813. } else {
  2814. res.status = StatusCode::BadRequest_400;
  2815. }
  2816. })
  2817. .Get("/person/(.*)",
  2818. [&](const Request &req, Response &res) {
  2819. string name = req.matches[1];
  2820. if (persons_.find(name) != persons_.end()) {
  2821. auto note = persons_[name];
  2822. res.set_content(note, "text/plain");
  2823. } else {
  2824. res.status = StatusCode::NotFound_404;
  2825. }
  2826. })
  2827. .Delete("/person",
  2828. [&](const Request &req, Response &res) {
  2829. if (req.has_param("name")) {
  2830. string name = req.get_param_value("name");
  2831. if (persons_.find(name) != persons_.end()) {
  2832. persons_.erase(name);
  2833. res.set_content("DELETED", "text/plain");
  2834. } else {
  2835. res.status = StatusCode::NotFound_404;
  2836. }
  2837. } else {
  2838. res.status = StatusCode::BadRequest_400;
  2839. }
  2840. })
  2841. .Post("/x-www-form-urlencoded-json",
  2842. [&](const Request &req, Response &res) {
  2843. auto json = req.get_param_value("json");
  2844. ASSERT_EQ(JSON_DATA, json);
  2845. res.set_content(json, "appliation/json");
  2846. res.status = StatusCode::OK_200;
  2847. })
  2848. .Get("/streamed-chunked",
  2849. [&](const Request & /*req*/, Response &res) {
  2850. res.set_chunked_content_provider(
  2851. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2852. sink.os << "123";
  2853. sink.os << "456";
  2854. sink.os << "789";
  2855. sink.done();
  2856. return true;
  2857. });
  2858. })
  2859. .Get("/streamed-chunked-with-prohibited-trailer",
  2860. [&](const Request & /*req*/, Response &res) {
  2861. auto i = new int(0);
  2862. // Declare both a prohibited trailer (Content-Length) and an
  2863. // allowed one
  2864. res.set_header("Trailer", "Content-Length, X-Allowed");
  2865. res.set_chunked_content_provider(
  2866. "text/plain",
  2867. [i](size_t /*offset*/, DataSink &sink) {
  2868. switch (*i) {
  2869. case 0: sink.os << "123"; break;
  2870. case 1: sink.os << "456"; break;
  2871. case 2: sink.os << "789"; break;
  2872. case 3: {
  2873. sink.done_with_trailer(
  2874. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2875. } break;
  2876. }
  2877. (*i)++;
  2878. return true;
  2879. },
  2880. [i](bool success) {
  2881. EXPECT_TRUE(success);
  2882. delete i;
  2883. });
  2884. })
  2885. .Get("/streamed-chunked2",
  2886. [&](const Request & /*req*/, Response &res) {
  2887. auto i = new int(0);
  2888. res.set_chunked_content_provider(
  2889. "text/plain",
  2890. [i](size_t /*offset*/, DataSink &sink) {
  2891. switch (*i) {
  2892. case 0: sink.os << "123"; break;
  2893. case 1: sink.os << "456"; break;
  2894. case 2: sink.os << "789"; break;
  2895. case 3: sink.done(); break;
  2896. }
  2897. (*i)++;
  2898. return true;
  2899. },
  2900. [i](bool success) {
  2901. EXPECT_TRUE(success);
  2902. delete i;
  2903. });
  2904. })
  2905. .Get("/streamed-chunked-with-trailer",
  2906. [&](const Request & /*req*/, Response &res) {
  2907. auto i = new int(0);
  2908. res.set_header("Trailer", "Dummy1, Dummy2");
  2909. res.set_chunked_content_provider(
  2910. "text/plain",
  2911. [i](size_t /*offset*/, DataSink &sink) {
  2912. switch (*i) {
  2913. case 0: sink.os << "123"; break;
  2914. case 1: sink.os << "456"; break;
  2915. case 2: sink.os << "789"; break;
  2916. case 3: {
  2917. sink.done_with_trailer(
  2918. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2919. } break;
  2920. }
  2921. (*i)++;
  2922. return true;
  2923. },
  2924. [i](bool success) {
  2925. EXPECT_TRUE(success);
  2926. delete i;
  2927. });
  2928. })
  2929. .Get("/streamed",
  2930. [&](const Request & /*req*/, Response &res) {
  2931. res.set_content_provider(
  2932. 6, "text/plain",
  2933. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2934. sink.os << (offset < 3 ? "a" : "b");
  2935. return true;
  2936. });
  2937. })
  2938. .Get("/streamed-with-range",
  2939. [&](const Request &req, Response &res) {
  2940. auto data = new std::string("abcdefg");
  2941. res.set_content_provider(
  2942. data->size(), "text/plain",
  2943. [data](size_t offset, size_t length, DataSink &sink) {
  2944. size_t DATA_CHUNK_SIZE = 4;
  2945. const auto &d = *data;
  2946. auto out_len =
  2947. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2948. auto ret =
  2949. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2950. EXPECT_TRUE(ret);
  2951. return true;
  2952. },
  2953. [data, &req](bool success) {
  2954. EXPECT_EQ(success, !req.has_param("error"));
  2955. delete data;
  2956. });
  2957. })
  2958. .Get("/streamed-cancel",
  2959. [&](const Request & /*req*/, Response &res) {
  2960. res.set_content_provider(
  2961. size_t(-1), "text/plain",
  2962. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2963. sink.os << "data_chunk";
  2964. return true;
  2965. });
  2966. })
  2967. .Get("/regex-with-delimiter",
  2968. [&](const Request &req, Response & /*res*/) {
  2969. ASSERT_TRUE(req.has_param("key"));
  2970. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2971. })
  2972. .Get("/with-range",
  2973. [&](const Request & /*req*/, Response &res) {
  2974. res.set_content("abcdefg", "text/plain");
  2975. })
  2976. .Get("/test-start-time",
  2977. [&](const Request &req, Response & /*res*/) {
  2978. EXPECT_NE(req.start_time_,
  2979. std::chrono::steady_clock::time_point::min());
  2980. })
  2981. .Get("/with-range-customized-response",
  2982. [&](const Request & /*req*/, Response &res) {
  2983. res.status = StatusCode::BadRequest_400;
  2984. res.set_content(JSON_DATA, "application/json");
  2985. })
  2986. .Post("/chunked",
  2987. [&](const Request &req, Response & /*res*/) {
  2988. EXPECT_EQ(req.body, "dechunked post body");
  2989. })
  2990. .Post("/large-chunked",
  2991. [&](const Request &req, Response & /*res*/) {
  2992. std::string expected(6 * 30 * 1024u, 'a');
  2993. EXPECT_EQ(req.body, expected);
  2994. })
  2995. .Post("/multipart",
  2996. [&](const Request &req, Response & /*res*/) {
  2997. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2998. req.form.get_field_count("text2") +
  2999. req.form.get_field_count("file3") +
  3000. req.form.get_field_count("file4"));
  3001. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3002. req.form.get_file_count("file2"));
  3003. ASSERT_TRUE(!req.form.has_file("???"));
  3004. ASSERT_TRUE(!req.form.has_field("???"));
  3005. ASSERT_TRUE(req.body.empty());
  3006. {
  3007. const auto &text = req.form.get_field("text1");
  3008. EXPECT_EQ("text default", text);
  3009. }
  3010. {
  3011. const auto &text = req.form.get_field("text2");
  3012. EXPECT_EQ("aωb", text);
  3013. }
  3014. {
  3015. const auto &file = req.form.get_file("file1");
  3016. EXPECT_EQ("hello.txt", file.filename);
  3017. EXPECT_EQ("text/plain", file.content_type);
  3018. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3019. }
  3020. {
  3021. const auto &file = req.form.get_file("file2");
  3022. EXPECT_EQ("world.json", file.filename);
  3023. EXPECT_EQ("application/json", file.content_type);
  3024. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3025. }
  3026. {
  3027. const auto &text = req.form.get_field("file3");
  3028. EXPECT_EQ(0u, text.size());
  3029. }
  3030. {
  3031. const auto &text = req.form.get_field("file4");
  3032. EXPECT_EQ(0u, text.size());
  3033. }
  3034. })
  3035. .Post("/multipart/multi_file_values",
  3036. [&](const Request &req, Response & /*res*/) {
  3037. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3038. req.form.get_field_count("multi_text1"));
  3039. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3040. ASSERT_TRUE(!req.form.has_file("???"));
  3041. ASSERT_TRUE(!req.form.has_field("???"));
  3042. ASSERT_TRUE(req.body.empty());
  3043. {
  3044. const auto &text = req.form.get_field("text");
  3045. EXPECT_EQ("default text", text);
  3046. }
  3047. {
  3048. const auto &text1_values = req.form.get_fields("multi_text1");
  3049. EXPECT_EQ(2u, text1_values.size());
  3050. EXPECT_EQ("aaaaa", text1_values[0]);
  3051. EXPECT_EQ("bbbbb", text1_values[1]);
  3052. }
  3053. {
  3054. const auto &file1_values = req.form.get_files("multi_file1");
  3055. EXPECT_EQ(2u, file1_values.size());
  3056. auto file1 = file1_values[0];
  3057. EXPECT_EQ(file1.filename, "hello.txt");
  3058. EXPECT_EQ(file1.content_type, "text/plain");
  3059. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3060. auto file2 = file1_values[1];
  3061. EXPECT_EQ(file2.filename, "world.json");
  3062. EXPECT_EQ(file2.content_type, "application/json");
  3063. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3064. }
  3065. })
  3066. .Post("/empty",
  3067. [&](const Request &req, Response &res) {
  3068. EXPECT_EQ(req.body, "");
  3069. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3070. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3071. res.set_content("empty", "text/plain");
  3072. })
  3073. .Post("/empty-no-content-type",
  3074. [&](const Request &req, Response &res) {
  3075. EXPECT_EQ(req.body, "");
  3076. EXPECT_FALSE(req.has_header("Content-Type"));
  3077. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3078. res.set_content("empty-no-content-type", "text/plain");
  3079. })
  3080. .Post("/path-only",
  3081. [&](const Request &req, Response &res) {
  3082. EXPECT_EQ(req.body, "");
  3083. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3084. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3085. res.set_content("path-only", "text/plain");
  3086. })
  3087. .Post("/path-headers-only",
  3088. [&](const Request &req, Response &res) {
  3089. EXPECT_EQ(req.body, "");
  3090. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3091. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3092. EXPECT_EQ("world", req.get_header_value("hello"));
  3093. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3094. res.set_content("path-headers-only", "text/plain");
  3095. })
  3096. .Post("/post-large",
  3097. [&](const Request &req, Response &res) {
  3098. EXPECT_EQ(req.body, LARGE_DATA);
  3099. res.set_content(req.body, "text/plain");
  3100. })
  3101. .Post("/post-loopback",
  3102. [&](const Request &, Response &res,
  3103. ContentReader const &content_reader) {
  3104. std::string body;
  3105. content_reader([&](const char *data, size_t data_length) {
  3106. body.append(data, data_length);
  3107. return true;
  3108. });
  3109. res.set_content(body, "text/plain");
  3110. })
  3111. .Put("/put-loopback",
  3112. [&](const Request &, Response &res,
  3113. ContentReader const &content_reader) {
  3114. std::string body;
  3115. content_reader([&](const char *data, size_t data_length) {
  3116. body.append(data, data_length);
  3117. return true;
  3118. });
  3119. res.set_content(body, "text/plain");
  3120. })
  3121. .Patch("/patch-loopback",
  3122. [&](const Request &, Response &res,
  3123. ContentReader const &content_reader) {
  3124. std::string body;
  3125. content_reader([&](const char *data, size_t data_length) {
  3126. body.append(data, data_length);
  3127. return true;
  3128. });
  3129. res.set_content(body, "text/plain");
  3130. })
  3131. .Put("/empty-no-content-type",
  3132. [&](const Request &req, Response &res) {
  3133. EXPECT_EQ(req.body, "");
  3134. EXPECT_FALSE(req.has_header("Content-Type"));
  3135. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3136. res.set_content("empty-no-content-type", "text/plain");
  3137. })
  3138. .Put("/put",
  3139. [&](const Request &req, Response &res) {
  3140. EXPECT_EQ(req.body, "PUT");
  3141. res.set_content(req.body, "text/plain");
  3142. })
  3143. .Put("/put-large",
  3144. [&](const Request &req, Response &res) {
  3145. EXPECT_EQ(req.body, LARGE_DATA);
  3146. res.set_content(req.body, "text/plain");
  3147. })
  3148. .Patch("/patch",
  3149. [&](const Request &req, Response &res) {
  3150. EXPECT_EQ(req.body, "PATCH");
  3151. res.set_content(req.body, "text/plain");
  3152. })
  3153. .Delete("/delete",
  3154. [&](const Request & /*req*/, Response &res) {
  3155. res.set_content("DELETE", "text/plain");
  3156. })
  3157. .Delete("/delete-body",
  3158. [&](const Request &req, Response &res) {
  3159. EXPECT_EQ(req.body, "content");
  3160. res.set_content(req.body, "text/plain");
  3161. })
  3162. .Options(R"(\*)",
  3163. [&](const Request & /*req*/, Response &res) {
  3164. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3165. })
  3166. .Get("/request-target",
  3167. [&](const Request &req, Response & /*res*/) {
  3168. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3169. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3170. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3171. })
  3172. .Get("/long-query-value",
  3173. [&](const Request &req, Response & /*res*/) {
  3174. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3175. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3176. })
  3177. .Get("/too-long-query-value",
  3178. [&](const Request &req, Response & /*res*/) {
  3179. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3180. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3181. })
  3182. .Get("/array-param",
  3183. [&](const Request &req, Response & /*res*/) {
  3184. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3185. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3186. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3187. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3188. })
  3189. .Post("/validate-no-multiple-headers",
  3190. [&](const Request &req, Response & /*res*/) {
  3191. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3192. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3193. })
  3194. .Post("/content_receiver",
  3195. [&](const Request &req, Response &res,
  3196. const ContentReader &content_reader) {
  3197. if (req.is_multipart_form_data()) {
  3198. std::vector<FormData> items;
  3199. content_reader(
  3200. [&](const FormData &file) {
  3201. items.push_back(file);
  3202. return true;
  3203. },
  3204. [&](const char *data, size_t data_length) {
  3205. items.back().content.append(data, data_length);
  3206. return true;
  3207. });
  3208. EXPECT_EQ(5u, items.size());
  3209. {
  3210. const auto &file = get_file_value(items, "text1");
  3211. EXPECT_TRUE(file.filename.empty());
  3212. EXPECT_EQ("text default", file.content);
  3213. }
  3214. {
  3215. const auto &file = get_file_value(items, "text2");
  3216. EXPECT_TRUE(file.filename.empty());
  3217. EXPECT_EQ("aωb", file.content);
  3218. }
  3219. {
  3220. const auto &file = get_file_value(items, "file1");
  3221. EXPECT_EQ("hello.txt", file.filename);
  3222. EXPECT_EQ("text/plain", file.content_type);
  3223. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3224. }
  3225. {
  3226. const auto &file = get_file_value(items, "file2");
  3227. EXPECT_EQ("world.json", file.filename);
  3228. EXPECT_EQ("application/json", file.content_type);
  3229. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3230. }
  3231. {
  3232. const auto &file = get_file_value(items, "file3");
  3233. EXPECT_TRUE(file.filename.empty());
  3234. EXPECT_EQ("application/octet-stream", file.content_type);
  3235. EXPECT_EQ(0u, file.content.size());
  3236. }
  3237. } else {
  3238. std::string body;
  3239. content_reader([&](const char *data, size_t data_length) {
  3240. EXPECT_EQ(7U, data_length);
  3241. body.append(data, data_length);
  3242. return true;
  3243. });
  3244. EXPECT_EQ(body, "content");
  3245. res.set_content(body, "text/plain");
  3246. }
  3247. })
  3248. .Put("/content_receiver",
  3249. [&](const Request & /*req*/, Response &res,
  3250. const ContentReader &content_reader) {
  3251. std::string body;
  3252. content_reader([&](const char *data, size_t data_length) {
  3253. body.append(data, data_length);
  3254. return true;
  3255. });
  3256. EXPECT_EQ(body, "content");
  3257. res.set_content(body, "text/plain");
  3258. })
  3259. .Patch("/content_receiver",
  3260. [&](const Request & /*req*/, Response &res,
  3261. const ContentReader &content_reader) {
  3262. std::string body;
  3263. content_reader([&](const char *data, size_t data_length) {
  3264. body.append(data, data_length);
  3265. return true;
  3266. });
  3267. EXPECT_EQ(body, "content");
  3268. res.set_content(body, "text/plain");
  3269. })
  3270. .Post("/query-string-and-body",
  3271. [&](const Request &req, Response & /*res*/) {
  3272. ASSERT_TRUE(req.has_param("key"));
  3273. EXPECT_EQ(req.get_param_value("key"), "value");
  3274. EXPECT_EQ(req.body, "content");
  3275. })
  3276. .Get("/last-request",
  3277. [&](const Request &req, Response & /*res*/) {
  3278. EXPECT_EQ("close", req.get_header_value("Connection"));
  3279. })
  3280. .Get(R"(/redirect/(\d+))",
  3281. [&](const Request &req, Response &res) {
  3282. auto num = std::stoi(req.matches[1]) + 1;
  3283. std::string url = "/redirect/" + std::to_string(num);
  3284. res.set_redirect(url);
  3285. })
  3286. .Post("/binary",
  3287. [&](const Request &req, Response &res) {
  3288. EXPECT_EQ(4U, req.body.size());
  3289. EXPECT_EQ("application/octet-stream",
  3290. req.get_header_value("Content-Type"));
  3291. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3292. res.set_content(req.body, "application/octet-stream");
  3293. })
  3294. .Put("/binary",
  3295. [&](const Request &req, Response &res) {
  3296. EXPECT_EQ(4U, req.body.size());
  3297. EXPECT_EQ("application/octet-stream",
  3298. req.get_header_value("Content-Type"));
  3299. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3300. res.set_content(req.body, "application/octet-stream");
  3301. })
  3302. .Patch("/binary",
  3303. [&](const Request &req, Response &res) {
  3304. EXPECT_EQ(4U, req.body.size());
  3305. EXPECT_EQ("application/octet-stream",
  3306. req.get_header_value("Content-Type"));
  3307. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3308. res.set_content(req.body, "application/octet-stream");
  3309. })
  3310. .Delete("/binary",
  3311. [&](const Request &req, Response &res) {
  3312. EXPECT_EQ(4U, req.body.size());
  3313. EXPECT_EQ("application/octet-stream",
  3314. req.get_header_value("Content-Type"));
  3315. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3316. res.set_content(req.body, "application/octet-stream");
  3317. })
  3318. .Get("/issue1772",
  3319. [&](const Request & /*req*/, Response &res) {
  3320. res.status = 401;
  3321. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3322. })
  3323. .Delete("/issue609",
  3324. [](const httplib::Request &, httplib::Response &res,
  3325. const httplib::ContentReader &) {
  3326. res.set_content("ok", "text/plain");
  3327. })
  3328. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3329. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3330. .Get("/compress",
  3331. [&](const Request & /*req*/, Response &res) {
  3332. res.set_content(
  3333. "12345678901234567890123456789012345678901234567890123456789"
  3334. "01234567890123456789012345678901234567890",
  3335. "text/plain");
  3336. })
  3337. .Get("/compress-with-charset",
  3338. [&](const Request & /*req*/, Response &res) {
  3339. res.set_content(
  3340. "12345678901234567890123456789012345678901234567890123456789"
  3341. "01234567890123456789012345678901234567890",
  3342. "application/json; charset=utf-8");
  3343. })
  3344. .Get("/nocompress",
  3345. [&](const Request & /*req*/, Response &res) {
  3346. res.set_content(
  3347. "12345678901234567890123456789012345678901234567890123456789"
  3348. "01234567890123456789012345678901234567890",
  3349. "application/octet-stream");
  3350. })
  3351. .Post("/compress-multipart",
  3352. [&](const Request &req, Response & /*res*/) {
  3353. EXPECT_EQ(2u, req.form.fields.size());
  3354. ASSERT_TRUE(!req.form.has_field("???"));
  3355. {
  3356. const auto &text = req.form.get_field("key1");
  3357. EXPECT_EQ("test", text);
  3358. }
  3359. {
  3360. const auto &text = req.form.get_field("key2");
  3361. EXPECT_EQ("--abcdefg123", text);
  3362. }
  3363. })
  3364. #endif
  3365. ;
  3366. persons_["john"] = "programmer";
  3367. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3368. svr_.wait_until_ready();
  3369. }
  3370. virtual void TearDown() {
  3371. svr_.stop();
  3372. if (!request_threads_.empty()) {
  3373. std::this_thread::sleep_for(std::chrono::seconds(1));
  3374. for (auto &t : request_threads_) {
  3375. t.join();
  3376. }
  3377. }
  3378. t_.join();
  3379. }
  3380. map<string, string> persons_;
  3381. #ifdef CPPHTTPLIB_SSL_ENABLED
  3382. SSLClient cli_;
  3383. SSLServer svr_;
  3384. #else
  3385. Client cli_;
  3386. Server svr_;
  3387. #endif
  3388. thread t_;
  3389. std::vector<thread> request_threads_;
  3390. };
  3391. TEST_F(ServerTest, GetMethod200) {
  3392. auto res = cli_.Get("/hi");
  3393. ASSERT_TRUE(res);
  3394. EXPECT_EQ("HTTP/1.1", res->version);
  3395. EXPECT_EQ(StatusCode::OK_200, res->status);
  3396. EXPECT_EQ("OK", res->reason);
  3397. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3398. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3399. EXPECT_EQ("Hello World!", res->body);
  3400. }
  3401. TEST_F(ServerTest, GetEmptyFile) {
  3402. auto res = cli_.Get("/empty_file");
  3403. ASSERT_TRUE(res);
  3404. EXPECT_EQ(StatusCode::OK_200, res->status);
  3405. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3406. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3407. EXPECT_EQ("", res->body);
  3408. }
  3409. TEST_F(ServerTest, GetFileContent) {
  3410. auto res = cli_.Get("/file_content");
  3411. ASSERT_TRUE(res);
  3412. EXPECT_EQ(StatusCode::OK_200, res->status);
  3413. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3414. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3415. EXPECT_EQ("test.html", res->body);
  3416. }
  3417. TEST_F(ServerTest, GetFileContentWithRange) {
  3418. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3419. ASSERT_TRUE(res);
  3420. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3421. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3422. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3423. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3424. EXPECT_EQ("est", res->body);
  3425. }
  3426. TEST_F(ServerTest, GetFileContentWithContentType) {
  3427. auto res = cli_.Get("/file_content_with_content_type");
  3428. ASSERT_TRUE(res);
  3429. EXPECT_EQ(StatusCode::OK_200, res->status);
  3430. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3431. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3432. EXPECT_EQ("file\n", res->body);
  3433. }
  3434. TEST_F(ServerTest, GetInvalidFileContent) {
  3435. auto res = cli_.Get("/invalid_file_content");
  3436. ASSERT_TRUE(res);
  3437. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3438. }
  3439. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3440. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3441. ASSERT_TRUE(res);
  3442. EXPECT_EQ("HTTP/1.1", res->version);
  3443. EXPECT_EQ(StatusCode::OK_200, res->status);
  3444. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3445. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3446. EXPECT_EQ("Hello World!", res->body);
  3447. }
  3448. TEST_F(ServerTest, GetMethod302) {
  3449. auto res = cli_.Get("/");
  3450. ASSERT_TRUE(res);
  3451. EXPECT_EQ(StatusCode::Found_302, res->status);
  3452. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3453. }
  3454. TEST_F(ServerTest, GetMethod302Redirect) {
  3455. cli_.set_follow_location(true);
  3456. auto res = cli_.Get("/");
  3457. ASSERT_TRUE(res);
  3458. EXPECT_EQ(StatusCode::OK_200, res->status);
  3459. EXPECT_EQ("Hello World!", res->body);
  3460. EXPECT_EQ("/hi", res->location);
  3461. }
  3462. TEST_F(ServerTest, GetMethod404) {
  3463. auto res = cli_.Get("/invalid");
  3464. ASSERT_TRUE(res);
  3465. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3466. }
  3467. TEST_F(ServerTest, HeadMethod200) {
  3468. auto res = cli_.Head("/hi");
  3469. ASSERT_TRUE(res);
  3470. EXPECT_EQ(StatusCode::OK_200, res->status);
  3471. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3472. EXPECT_TRUE(res->body.empty());
  3473. }
  3474. TEST_F(ServerTest, HeadMethod200Static) {
  3475. auto res = cli_.Head("/mount/dir/index.html");
  3476. ASSERT_TRUE(res);
  3477. EXPECT_EQ(StatusCode::OK_200, res->status);
  3478. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3479. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3480. EXPECT_TRUE(res->body.empty());
  3481. }
  3482. TEST_F(ServerTest, HeadMethod404) {
  3483. auto res = cli_.Head("/invalid");
  3484. ASSERT_TRUE(res);
  3485. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3486. EXPECT_TRUE(res->body.empty());
  3487. }
  3488. TEST_F(ServerTest, GetMethodPersonJohn) {
  3489. auto res = cli_.Get("/person/john");
  3490. ASSERT_TRUE(res);
  3491. EXPECT_EQ(StatusCode::OK_200, res->status);
  3492. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3493. EXPECT_EQ("programmer", res->body);
  3494. }
  3495. TEST_F(ServerTest, PostMethod1) {
  3496. auto res = cli_.Get("/person/john1");
  3497. ASSERT_TRUE(res);
  3498. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3499. res = cli_.Post("/person", "name=john1&note=coder",
  3500. "application/x-www-form-urlencoded");
  3501. ASSERT_TRUE(res);
  3502. ASSERT_EQ(StatusCode::OK_200, res->status);
  3503. res = cli_.Get("/person/john1");
  3504. ASSERT_TRUE(res);
  3505. ASSERT_EQ(StatusCode::OK_200, res->status);
  3506. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3507. ASSERT_EQ("coder", res->body);
  3508. }
  3509. TEST_F(ServerTest, PostMethod2) {
  3510. auto res = cli_.Get("/person/john2");
  3511. ASSERT_TRUE(res);
  3512. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3513. Params params;
  3514. params.emplace("name", "john2");
  3515. params.emplace("note", "coder");
  3516. res = cli_.Post("/person", params);
  3517. ASSERT_TRUE(res);
  3518. ASSERT_EQ(StatusCode::OK_200, res->status);
  3519. res = cli_.Get("/person/john2");
  3520. ASSERT_TRUE(res);
  3521. ASSERT_EQ(StatusCode::OK_200, res->status);
  3522. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3523. ASSERT_EQ("coder", res->body);
  3524. }
  3525. TEST_F(ServerTest, PutMethod3) {
  3526. auto res = cli_.Get("/person/john3");
  3527. ASSERT_TRUE(res);
  3528. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3529. Params params;
  3530. params.emplace("name", "john3");
  3531. params.emplace("note", "coder");
  3532. res = cli_.Put("/person", params);
  3533. ASSERT_TRUE(res);
  3534. ASSERT_EQ(StatusCode::OK_200, res->status);
  3535. res = cli_.Get("/person/john3");
  3536. ASSERT_TRUE(res);
  3537. ASSERT_EQ(StatusCode::OK_200, res->status);
  3538. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3539. ASSERT_EQ("coder", res->body);
  3540. }
  3541. TEST_F(ServerTest, DeleteMethod1) {
  3542. auto res = cli_.Get("/person/john4");
  3543. ASSERT_TRUE(res);
  3544. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3545. Params params;
  3546. params.emplace("name", "john4");
  3547. params.emplace("note", "coder");
  3548. res = cli_.Post("/person", params);
  3549. ASSERT_TRUE(res);
  3550. ASSERT_EQ(StatusCode::OK_200, res->status);
  3551. res = cli_.Get("/person/john4");
  3552. ASSERT_TRUE(res);
  3553. ASSERT_EQ(StatusCode::OK_200, res->status);
  3554. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3555. ASSERT_EQ("coder", res->body);
  3556. Params delete_params;
  3557. delete_params.emplace("name", "john4");
  3558. res = cli_.Delete("/person", delete_params);
  3559. ASSERT_TRUE(res);
  3560. ASSERT_EQ(StatusCode::OK_200, res->status);
  3561. ASSERT_EQ("DELETED", res->body);
  3562. res = cli_.Get("/person/john4");
  3563. ASSERT_TRUE(res);
  3564. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3565. }
  3566. TEST_F(ServerTest, DeleteMethod2) {
  3567. auto res = cli_.Get("/person/john5");
  3568. ASSERT_TRUE(res);
  3569. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3570. Params params;
  3571. params.emplace("name", "john5");
  3572. params.emplace("note", "developer");
  3573. res = cli_.Post("/person", params);
  3574. ASSERT_TRUE(res);
  3575. ASSERT_EQ(StatusCode::OK_200, res->status);
  3576. res = cli_.Get("/person/john5");
  3577. ASSERT_TRUE(res);
  3578. ASSERT_EQ(StatusCode::OK_200, res->status);
  3579. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3580. ASSERT_EQ("developer", res->body);
  3581. Params delete_params;
  3582. delete_params.emplace("name", "john5");
  3583. Headers headers;
  3584. headers.emplace("Custom-Header", "test-value");
  3585. res = cli_.Delete("/person", headers, delete_params);
  3586. ASSERT_TRUE(res);
  3587. ASSERT_EQ(StatusCode::OK_200, res->status);
  3588. ASSERT_EQ("DELETED", res->body);
  3589. res = cli_.Get("/person/john5");
  3590. ASSERT_TRUE(res);
  3591. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3592. }
  3593. TEST_F(ServerTest, DeleteMethod3) {
  3594. auto res = cli_.Get("/person/john6");
  3595. ASSERT_TRUE(res);
  3596. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3597. Params params;
  3598. params.emplace("name", "john6");
  3599. params.emplace("note", "tester");
  3600. res = cli_.Post("/person", params);
  3601. ASSERT_TRUE(res);
  3602. ASSERT_EQ(StatusCode::OK_200, res->status);
  3603. res = cli_.Get("/person/john6");
  3604. ASSERT_TRUE(res);
  3605. ASSERT_EQ(StatusCode::OK_200, res->status);
  3606. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3607. ASSERT_EQ("tester", res->body);
  3608. Params delete_params;
  3609. delete_params.emplace("name", "john6");
  3610. Headers headers;
  3611. headers.emplace("Custom-Header", "test-value");
  3612. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3613. ASSERT_TRUE(res);
  3614. ASSERT_EQ(StatusCode::OK_200, res->status);
  3615. ASSERT_EQ("DELETED", res->body);
  3616. res = cli_.Get("/person/john6");
  3617. ASSERT_TRUE(res);
  3618. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3619. }
  3620. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3621. Params params;
  3622. params.emplace("json", JSON_DATA);
  3623. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3624. ASSERT_TRUE(res);
  3625. ASSERT_EQ(StatusCode::OK_200, res->status);
  3626. ASSERT_EQ(JSON_DATA, res->body);
  3627. }
  3628. TEST_F(ServerTest, PostEmptyContent) {
  3629. auto res = cli_.Post("/empty", "", "text/plain");
  3630. ASSERT_TRUE(res);
  3631. ASSERT_EQ(StatusCode::OK_200, res->status);
  3632. ASSERT_EQ("empty", res->body);
  3633. }
  3634. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3635. auto res = cli_.Post("/empty-no-content-type");
  3636. ASSERT_TRUE(res);
  3637. ASSERT_EQ(StatusCode::OK_200, res->status);
  3638. ASSERT_EQ("empty-no-content-type", res->body);
  3639. }
  3640. TEST_F(ServerTest, PostPathOnly) {
  3641. auto res = cli_.Post("/path-only");
  3642. ASSERT_TRUE(res);
  3643. ASSERT_EQ(StatusCode::OK_200, res->status);
  3644. ASSERT_EQ("path-only", res->body);
  3645. }
  3646. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3647. auto res = cli_.Post("/path-headers-only",
  3648. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3649. ASSERT_TRUE(res);
  3650. ASSERT_EQ(StatusCode::OK_200, res->status);
  3651. ASSERT_EQ("path-headers-only", res->body);
  3652. }
  3653. TEST_F(ServerTest, PostLarge) {
  3654. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3655. ASSERT_TRUE(res);
  3656. ASSERT_EQ(StatusCode::OK_200, res->status);
  3657. EXPECT_EQ(LARGE_DATA, res->body);
  3658. }
  3659. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3660. auto res = cli_.Put("/empty-no-content-type");
  3661. ASSERT_TRUE(res);
  3662. ASSERT_EQ(StatusCode::OK_200, res->status);
  3663. ASSERT_EQ("empty-no-content-type", res->body);
  3664. }
  3665. TEST_F(ServerTest, GetMethodDir) {
  3666. auto res = cli_.Get("/dir/");
  3667. ASSERT_TRUE(res);
  3668. EXPECT_EQ(StatusCode::OK_200, res->status);
  3669. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3670. auto body = R"(<html>
  3671. <head>
  3672. </head>
  3673. <body>
  3674. <a href="/dir/test.html">Test</a>
  3675. <a href="/hi">hi</a>
  3676. </body>
  3677. </html>
  3678. )";
  3679. EXPECT_EQ(body, res->body);
  3680. }
  3681. TEST_F(ServerTest, GetMethodDirTest) {
  3682. auto res = cli_.Get("/dir/test.html");
  3683. ASSERT_TRUE(res);
  3684. EXPECT_EQ(StatusCode::OK_200, res->status);
  3685. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3686. EXPECT_EQ("test.html", res->body);
  3687. }
  3688. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3689. auto res = cli_.Get("/dir/../dir/test.html");
  3690. ASSERT_TRUE(res);
  3691. EXPECT_EQ(StatusCode::OK_200, res->status);
  3692. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3693. EXPECT_EQ("test.html", res->body);
  3694. }
  3695. TEST_F(ServerTest, GetMethodInvalidPath) {
  3696. auto res = cli_.Get("/dir/../test.html");
  3697. ASSERT_TRUE(res);
  3698. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3699. }
  3700. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3701. auto res = cli_.Get("/../www/dir/test.html");
  3702. ASSERT_TRUE(res);
  3703. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3704. }
  3705. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3706. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3707. ASSERT_TRUE(res);
  3708. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3709. }
  3710. TEST_F(ServerTest, GetMethodDirMountTest) {
  3711. auto res = cli_.Get("/mount/dir/test.html");
  3712. ASSERT_TRUE(res);
  3713. EXPECT_EQ(StatusCode::OK_200, res->status);
  3714. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3715. EXPECT_EQ("test.html", res->body);
  3716. }
  3717. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3718. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3719. ASSERT_TRUE(res);
  3720. EXPECT_EQ(StatusCode::OK_200, res->status);
  3721. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3722. EXPECT_EQ("test.html", res->body);
  3723. }
  3724. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3725. auto res = cli_.Get("/mount/dir/../test.html");
  3726. ASSERT_TRUE(res);
  3727. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3728. }
  3729. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3730. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3731. ASSERT_TRUE(res);
  3732. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3733. }
  3734. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3735. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3736. ASSERT_TRUE(res);
  3737. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3738. }
  3739. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3740. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3741. ASSERT_TRUE(res);
  3742. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3743. }
  3744. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3745. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3746. ASSERT_TRUE(res);
  3747. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3748. }
  3749. TEST_F(ServerTest, PostMethod303) {
  3750. auto res = cli_.Post("/1", "body", "text/plain");
  3751. ASSERT_TRUE(res);
  3752. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3753. EXPECT_EQ("/2", res->get_header_value("Location"));
  3754. }
  3755. TEST_F(ServerTest, PostMethod303Redirect) {
  3756. cli_.set_follow_location(true);
  3757. auto res = cli_.Post("/1", "body", "text/plain");
  3758. ASSERT_TRUE(res);
  3759. EXPECT_EQ(StatusCode::OK_200, res->status);
  3760. EXPECT_EQ("redirected.", res->body);
  3761. EXPECT_EQ("/2", res->location);
  3762. }
  3763. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3764. auto res = cli_.Get("/dir/test.abcde");
  3765. ASSERT_TRUE(res);
  3766. EXPECT_EQ(StatusCode::OK_200, res->status);
  3767. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3768. EXPECT_EQ("abcde", res->body);
  3769. }
  3770. TEST_F(ServerTest, StaticFileRange) {
  3771. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3772. ASSERT_TRUE(res);
  3773. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3774. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3775. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3776. EXPECT_EQ(true, res->has_header("Content-Range"));
  3777. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3778. EXPECT_EQ(std::string("cd"), res->body);
  3779. }
  3780. TEST_F(ServerTest, StaticFileRanges) {
  3781. auto res =
  3782. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3783. ASSERT_TRUE(res);
  3784. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3785. EXPECT_TRUE(
  3786. res->get_header_value("Content-Type")
  3787. .find(
  3788. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3789. 0);
  3790. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3791. }
  3792. TEST_F(ServerTest, StaticFileRangeHead) {
  3793. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3794. ASSERT_TRUE(res);
  3795. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3796. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3797. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3798. EXPECT_EQ(true, res->has_header("Content-Range"));
  3799. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3800. }
  3801. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3802. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3803. ASSERT_TRUE(res);
  3804. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3805. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3806. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3807. EXPECT_EQ(true, res->has_header("Content-Range"));
  3808. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3809. res->get_header_value("Content-Range"));
  3810. EXPECT_EQ("LAST\n", res->body);
  3811. }
  3812. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3813. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3814. ASSERT_TRUE(res);
  3815. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3816. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3817. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3818. EXPECT_EQ(true, res->has_header("Content-Range"));
  3819. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3820. }
  3821. TEST_F(ServerTest, StaticFileBigFile) {
  3822. auto res = cli_.Get("/dir/1MB.txt");
  3823. ASSERT_TRUE(res);
  3824. EXPECT_EQ(StatusCode::OK_200, res->status);
  3825. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3826. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3827. }
  3828. TEST_F(ServerTest, InvalidBaseDirMount) {
  3829. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3830. }
  3831. TEST_F(ServerTest, Binary) {
  3832. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3833. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3834. "application/octet-stream");
  3835. ASSERT_TRUE(res);
  3836. ASSERT_EQ(StatusCode::OK_200, res->status);
  3837. ASSERT_EQ(4U, res->body.size());
  3838. res = cli_.Put("/binary", binary.data(), binary.size(),
  3839. "application/octet-stream");
  3840. ASSERT_TRUE(res);
  3841. ASSERT_EQ(StatusCode::OK_200, res->status);
  3842. ASSERT_EQ(4U, res->body.size());
  3843. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3844. "application/octet-stream");
  3845. ASSERT_TRUE(res);
  3846. ASSERT_EQ(StatusCode::OK_200, res->status);
  3847. ASSERT_EQ(4U, res->body.size());
  3848. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3849. "application/octet-stream");
  3850. ASSERT_TRUE(res);
  3851. ASSERT_EQ(StatusCode::OK_200, res->status);
  3852. ASSERT_EQ(4U, res->body.size());
  3853. }
  3854. TEST_F(ServerTest, BinaryString) {
  3855. auto binary = std::string("\x00\x01\x02\x03", 4);
  3856. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3857. ASSERT_TRUE(res);
  3858. ASSERT_EQ(StatusCode::OK_200, res->status);
  3859. ASSERT_EQ(4U, res->body.size());
  3860. res = cli_.Put("/binary", binary, "application/octet-stream");
  3861. ASSERT_TRUE(res);
  3862. ASSERT_EQ(StatusCode::OK_200, res->status);
  3863. ASSERT_EQ(4U, res->body.size());
  3864. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3865. ASSERT_TRUE(res);
  3866. ASSERT_EQ(StatusCode::OK_200, res->status);
  3867. ASSERT_EQ(4U, res->body.size());
  3868. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3869. ASSERT_TRUE(res);
  3870. ASSERT_EQ(StatusCode::OK_200, res->status);
  3871. ASSERT_EQ(4U, res->body.size());
  3872. }
  3873. TEST_F(ServerTest, EmptyRequest) {
  3874. auto res = cli_.Get("");
  3875. ASSERT_TRUE(!res);
  3876. EXPECT_EQ(Error::Connection, res.error());
  3877. }
  3878. TEST_F(ServerTest, LongRequest) {
  3879. std::string request;
  3880. for (size_t i = 0; i < 545; i++) {
  3881. request += "/TooLongRequest";
  3882. }
  3883. request += "OK";
  3884. auto res = cli_.Get(request.c_str());
  3885. ASSERT_TRUE(res);
  3886. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3887. }
  3888. TEST_F(ServerTest, TooLongRequest) {
  3889. std::string request;
  3890. for (size_t i = 0; i < 546; i++) {
  3891. request += "/TooLongRequest";
  3892. }
  3893. request += "_NG";
  3894. auto start = std::chrono::high_resolution_clock::now();
  3895. cli_.set_keep_alive(true);
  3896. auto res = cli_.Get(request.c_str());
  3897. auto end = std::chrono::high_resolution_clock::now();
  3898. auto elapsed =
  3899. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3900. .count();
  3901. ASSERT_TRUE(res);
  3902. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3903. EXPECT_LE(elapsed, 1000);
  3904. EXPECT_EQ("close", res->get_header_value("Connection"));
  3905. EXPECT_FALSE(cli_.is_socket_open());
  3906. }
  3907. TEST_F(ServerTest, AlmostTooLongRequest) {
  3908. // test for #2046 - URI length check shouldn't include other content on req
  3909. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3910. // leading /, space, HTTP/1.1)
  3911. std::string request =
  3912. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3913. auto res = cli_.Get(request.c_str());
  3914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3915. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3916. }
  3917. TEST_F(ServerTest, LongHeader) {
  3918. Request req;
  3919. req.method = "GET";
  3920. req.path = "/hi";
  3921. std::string host_and_port;
  3922. host_and_port += HOST;
  3923. host_and_port += ":";
  3924. host_and_port += std::to_string(PORT);
  3925. req.headers.emplace("Host", host_and_port.c_str());
  3926. req.headers.emplace("Accept", "*/*");
  3927. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3928. req.headers.emplace(
  3929. "Header-Name",
  3930. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3931. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3932. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3933. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3934. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3935. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3936. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3937. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3938. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3939. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3940. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3941. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3942. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3943. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3944. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3945. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3946. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3947. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3948. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3949. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3950. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3951. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3952. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3953. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3954. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3955. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3956. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3957. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3958. "@@@@@@@@@@@@@@@@");
  3959. auto res = std::make_shared<Response>();
  3960. auto error = Error::Success;
  3961. auto ret = cli_.send(req, *res, error);
  3962. ASSERT_TRUE(ret);
  3963. EXPECT_EQ(StatusCode::OK_200, res->status);
  3964. }
  3965. TEST_F(ServerTest, LongQueryValue) {
  3966. auto start = std::chrono::high_resolution_clock::now();
  3967. cli_.set_keep_alive(true);
  3968. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3969. auto end = std::chrono::high_resolution_clock::now();
  3970. auto elapsed =
  3971. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3972. .count();
  3973. ASSERT_TRUE(res);
  3974. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3975. EXPECT_LE(elapsed, 1000);
  3976. EXPECT_EQ("close", res->get_header_value("Connection"));
  3977. EXPECT_FALSE(cli_.is_socket_open());
  3978. }
  3979. TEST_F(ServerTest, TooLongQueryValue) {
  3980. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3981. ASSERT_FALSE(res);
  3982. EXPECT_EQ(Error::Read, res.error());
  3983. }
  3984. TEST_F(ServerTest, TooLongHeader) {
  3985. Request req;
  3986. req.method = "GET";
  3987. req.path = "/hi";
  3988. std::string host_and_port;
  3989. host_and_port += HOST;
  3990. host_and_port += ":";
  3991. host_and_port += std::to_string(PORT);
  3992. req.headers.emplace("Host", host_and_port.c_str());
  3993. req.headers.emplace("Accept", "*/*");
  3994. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3995. req.headers.emplace(
  3996. "Header-Name",
  3997. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3998. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3999. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4000. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4001. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4002. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4003. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4004. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4005. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4006. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4007. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4008. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4009. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4010. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4011. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4012. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4013. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4014. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4015. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4016. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4017. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4018. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4019. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4020. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4021. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4022. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4023. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4024. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4025. "@@@@@@@@@@@@@@@@@");
  4026. auto res = std::make_shared<Response>();
  4027. auto error = Error::Success;
  4028. auto ret = cli_.send(req, *res, error);
  4029. ASSERT_TRUE(ret);
  4030. EXPECT_EQ(StatusCode::OK_200, res->status);
  4031. }
  4032. TEST_F(ServerTest, HeaderCountAtLimit) {
  4033. // Test with headers just under the 100 limit
  4034. httplib::Headers headers;
  4035. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4036. // This should keep us just under the 100 header limit
  4037. for (int i = 0; i < 95; i++) {
  4038. std::string name = "X-Test-Header-" + std::to_string(i);
  4039. std::string value = "value" + std::to_string(i);
  4040. headers.emplace(name, value);
  4041. }
  4042. // This should work fine as we're under the limit
  4043. auto res = cli_.Get("/hi", headers);
  4044. EXPECT_TRUE(res);
  4045. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4046. }
  4047. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4048. // Test with many headers to exceed the 100 limit
  4049. httplib::Headers headers;
  4050. // Add 150 headers to definitely exceed the 100 limit
  4051. for (int i = 0; i < 150; i++) {
  4052. std::string name = "X-Test-Header-" + std::to_string(i);
  4053. std::string value = "value" + std::to_string(i);
  4054. headers.emplace(name, value);
  4055. }
  4056. // This should fail due to exceeding header count limit
  4057. cli_.set_keep_alive(true);
  4058. auto res = cli_.Get("/hi", headers);
  4059. // The server should respond with 400 Bad Request
  4060. ASSERT_TRUE(res);
  4061. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4062. EXPECT_EQ("close", res->get_header_value("Connection"));
  4063. EXPECT_FALSE(cli_.is_socket_open());
  4064. }
  4065. TEST_F(ServerTest, PercentEncoding) {
  4066. auto res = cli_.Get("/e%6edwith%");
  4067. ASSERT_TRUE(res);
  4068. EXPECT_EQ(StatusCode::OK_200, res->status);
  4069. }
  4070. TEST_F(ServerTest, PercentEncodingUnicode) {
  4071. auto res = cli_.Get("/e%u006edwith%");
  4072. ASSERT_TRUE(res);
  4073. EXPECT_EQ(StatusCode::OK_200, res->status);
  4074. }
  4075. TEST_F(ServerTest, InvalidPercentEncoding) {
  4076. auto res = cli_.Get("/%endwith%");
  4077. ASSERT_TRUE(res);
  4078. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4079. }
  4080. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4081. auto res = cli_.Get("/%uendwith%");
  4082. ASSERT_TRUE(res);
  4083. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4084. }
  4085. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4086. auto res = cli_.Get("/hello?aaa=bbb%");
  4087. ASSERT_TRUE(res);
  4088. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4089. }
  4090. TEST_F(ServerTest, PlusSignEncoding) {
  4091. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4092. ASSERT_TRUE(res);
  4093. EXPECT_EQ(StatusCode::OK_200, res->status);
  4094. EXPECT_EQ("a +b", res->body);
  4095. }
  4096. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4097. // This test simulates a potential DoS attack using many headers
  4098. // to verify our security fix prevents memory exhaustion
  4099. httplib::Headers attack_headers;
  4100. // Attempt to add many headers like an attacker would (200 headers to far
  4101. // exceed limit)
  4102. for (int i = 0; i < 200; i++) {
  4103. std::string name = "X-Attack-Header-" + std::to_string(i);
  4104. std::string value = "attack_payload_" + std::to_string(i);
  4105. attack_headers.emplace(name, value);
  4106. }
  4107. // Try to POST with excessive headers
  4108. cli_.set_keep_alive(true);
  4109. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4110. // Should either fail or return 400 Bad Request due to security limit
  4111. if (res) {
  4112. // If we get a response, it should be 400 Bad Request
  4113. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4114. EXPECT_EQ("close", res->get_header_value("Connection"));
  4115. }
  4116. EXPECT_FALSE(cli_.is_socket_open());
  4117. }
  4118. TEST_F(ServerTest, MultipartFormData) {
  4119. UploadFormDataItems items = {
  4120. {"text1", "text default", "", ""},
  4121. {"text2", "aωb", "", ""},
  4122. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4123. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4124. {"file3", "", "", "application/octet-stream"},
  4125. {"file4", "", "", " application/json tmp-string "}};
  4126. auto res = cli_.Post("/multipart", items);
  4127. ASSERT_TRUE(res);
  4128. EXPECT_EQ(StatusCode::OK_200, res->status);
  4129. }
  4130. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4131. UploadFormDataItems items = {
  4132. {"text", "default text", "", ""},
  4133. {"multi_text1", "aaaaa", "", ""},
  4134. {"multi_text1", "bbbbb", "", ""},
  4135. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4136. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4137. "application/json"},
  4138. };
  4139. auto res = cli_.Post("/multipart/multi_file_values", items);
  4140. ASSERT_TRUE(res);
  4141. EXPECT_EQ(StatusCode::OK_200, res->status);
  4142. }
  4143. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4144. auto res = cli_.Get("/hi");
  4145. ASSERT_TRUE(res);
  4146. EXPECT_EQ(StatusCode::OK_200, res->status);
  4147. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4148. EXPECT_EQ("Hello World!", res->body);
  4149. }
  4150. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4151. Request req;
  4152. req.method = "POST";
  4153. req.path = "/chunked";
  4154. std::string host_and_port;
  4155. host_and_port += HOST;
  4156. host_and_port += ":";
  4157. host_and_port += std::to_string(PORT);
  4158. req.headers.emplace("Host", host_and_port.c_str());
  4159. req.headers.emplace("Accept", "*/*");
  4160. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4161. req.headers.emplace("Content-Type", "text/plain");
  4162. req.headers.emplace("Content-Length", "0");
  4163. req.headers.emplace(
  4164. "Transfer-Encoding",
  4165. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4166. // Client does not chunk, so make a chunked body manually.
  4167. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4168. auto res = std::make_shared<Response>();
  4169. auto error = Error::Success;
  4170. auto ret = cli_.send(req, *res, error);
  4171. ASSERT_TRUE(ret);
  4172. EXPECT_EQ(StatusCode::OK_200, res->status);
  4173. }
  4174. TEST_F(ServerTest, GetStreamed2) {
  4175. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4176. ASSERT_TRUE(res);
  4177. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4178. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4179. EXPECT_EQ(true, res->has_header("Content-Range"));
  4180. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4181. EXPECT_EQ(std::string("ab"), res->body);
  4182. }
  4183. TEST_F(ServerTest, GetStreamed) {
  4184. auto res = cli_.Get("/streamed");
  4185. ASSERT_TRUE(res);
  4186. EXPECT_EQ(StatusCode::OK_200, res->status);
  4187. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4188. EXPECT_EQ(std::string("aaabbb"), res->body);
  4189. }
  4190. TEST_F(ServerTest, GetStreamedWithRange1) {
  4191. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4192. ASSERT_TRUE(res);
  4193. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4194. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4195. EXPECT_EQ(true, res->has_header("Content-Range"));
  4196. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4197. EXPECT_EQ(std::string("def"), res->body);
  4198. }
  4199. TEST_F(ServerTest, GetStreamedWithRange2) {
  4200. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4201. ASSERT_TRUE(res);
  4202. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4203. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4204. EXPECT_EQ(true, res->has_header("Content-Range"));
  4205. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4206. EXPECT_EQ(std::string("bcdefg"), res->body);
  4207. }
  4208. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4209. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4210. ASSERT_TRUE(res);
  4211. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4212. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4213. EXPECT_EQ(true, res->has_header("Content-Range"));
  4214. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4215. EXPECT_EQ(std::string("efg"), res->body);
  4216. }
  4217. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4218. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4219. ASSERT_TRUE(res);
  4220. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4221. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4222. EXPECT_EQ(false, res->has_header("Content-Range"));
  4223. EXPECT_EQ(0U, res->body.size());
  4224. }
  4225. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4226. auto res = cli_.Get("/streamed-with-range",
  4227. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4228. "92233720368547758079223372036854775807"}});
  4229. ASSERT_TRUE(res);
  4230. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4231. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4232. EXPECT_EQ(false, res->has_header("Content-Range"));
  4233. EXPECT_EQ(0U, res->body.size());
  4234. }
  4235. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4236. auto res = cli_.Get(
  4237. "/with-range",
  4238. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4239. {"Accept-Encoding", ""}});
  4240. ASSERT_TRUE(res);
  4241. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4242. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4243. EXPECT_EQ(true, res->has_header("Content-Range"));
  4244. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4245. EXPECT_EQ(std::string("abcdefg"), res->body);
  4246. }
  4247. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4248. auto res = cli_.Get("/with-range", {
  4249. {"Range", "bytes=0-"},
  4250. {"Accept-Encoding", ""},
  4251. });
  4252. ASSERT_TRUE(res);
  4253. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4254. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4255. EXPECT_EQ(true, res->has_header("Content-Range"));
  4256. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4257. EXPECT_EQ(std::string("abcdefg"), res->body);
  4258. }
  4259. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4260. auto res =
  4261. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4262. ASSERT_TRUE(res);
  4263. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4264. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4265. EXPECT_EQ(false, res->has_header("Content-Range"));
  4266. EXPECT_EQ(267U, res->body.size());
  4267. // Check that both range contents are present
  4268. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4269. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4270. // Check that Content-Range headers are present for both ranges
  4271. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4272. std::string::npos);
  4273. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4274. std::string::npos);
  4275. }
  4276. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4277. Ranges ranges;
  4278. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4279. ranges.emplace_back(0, -1);
  4280. }
  4281. auto res =
  4282. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4283. ASSERT_TRUE(res);
  4284. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4285. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4286. EXPECT_EQ(false, res->has_header("Content-Range"));
  4287. EXPECT_EQ(0U, res->body.size());
  4288. }
  4289. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4290. auto res =
  4291. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4292. ASSERT_TRUE(res);
  4293. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4294. EXPECT_EQ(5U, res->body.size());
  4295. // Check that overlapping ranges are coalesced into a single range
  4296. EXPECT_EQ("bcdef", res->body);
  4297. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4298. // Should be single range, not multipart
  4299. EXPECT_TRUE(res->has_header("Content-Range"));
  4300. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4301. }
  4302. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4303. auto res =
  4304. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4305. ASSERT_TRUE(res);
  4306. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4307. EXPECT_EQ(268U, res->body.size());
  4308. // Check that both range contents are present
  4309. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4310. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4311. // Check that Content-Range headers are present for both ranges
  4312. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4313. std::string::npos);
  4314. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4315. std::string::npos);
  4316. }
  4317. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4318. auto res =
  4319. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4320. ASSERT_TRUE(res);
  4321. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4322. EXPECT_EQ(269U, res->body.size());
  4323. // Check that both duplicate range contents are present
  4324. size_t first_abc = res->body.find("abc\r\n");
  4325. EXPECT_TRUE(first_abc != std::string::npos);
  4326. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4327. EXPECT_TRUE(second_abc != std::string::npos);
  4328. // Check that Content-Range headers are present for both ranges
  4329. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4330. EXPECT_TRUE(first_range != std::string::npos);
  4331. size_t second_range =
  4332. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4333. EXPECT_TRUE(second_range != std::string::npos);
  4334. }
  4335. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4336. auto res = cli_.Get("/streamed-with-range?error",
  4337. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4338. ASSERT_TRUE(res);
  4339. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4340. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4341. EXPECT_EQ(false, res->has_header("Content-Range"));
  4342. EXPECT_EQ(0U, res->body.size());
  4343. }
  4344. TEST_F(ServerTest, GetStreamedEndless) {
  4345. uint64_t offset = 0;
  4346. auto res = cli_.Get("/streamed-cancel",
  4347. [&](const char * /*data*/, uint64_t data_length) {
  4348. if (offset < 100) {
  4349. offset += data_length;
  4350. return true;
  4351. }
  4352. return false;
  4353. });
  4354. ASSERT_TRUE(!res);
  4355. EXPECT_EQ(Error::Canceled, res.error());
  4356. }
  4357. TEST_F(ServerTest, ClientStop) {
  4358. std::atomic_size_t count{4};
  4359. std::vector<std::thread> threads;
  4360. for (auto i = count.load(); i != 0; --i) {
  4361. threads.emplace_back([&]() {
  4362. auto res = cli_.Get("/streamed-cancel",
  4363. [&](const char *, uint64_t) { return true; });
  4364. --count;
  4365. ASSERT_TRUE(!res);
  4366. EXPECT_TRUE(res.error() == Error::Canceled ||
  4367. res.error() == Error::Read || res.error() == Error::Write);
  4368. });
  4369. }
  4370. std::this_thread::sleep_for(std::chrono::seconds(2));
  4371. while (count != 0) {
  4372. cli_.stop();
  4373. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4374. }
  4375. for (auto &t : threads) {
  4376. t.join();
  4377. }
  4378. }
  4379. TEST_F(ServerTest, GetWithRange1) {
  4380. auto res = cli_.Get("/with-range", {
  4381. make_range_header({{3, 5}}),
  4382. {"Accept-Encoding", ""},
  4383. });
  4384. ASSERT_TRUE(res);
  4385. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4386. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4387. EXPECT_EQ(true, res->has_header("Content-Range"));
  4388. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4389. EXPECT_EQ(std::string("def"), res->body);
  4390. }
  4391. TEST_F(ServerTest, GetWithRange2) {
  4392. auto res = cli_.Get("/with-range", {
  4393. make_range_header({{1, -1}}),
  4394. {"Accept-Encoding", ""},
  4395. });
  4396. ASSERT_TRUE(res);
  4397. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4398. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4399. EXPECT_EQ(true, res->has_header("Content-Range"));
  4400. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4401. EXPECT_EQ(std::string("bcdefg"), res->body);
  4402. }
  4403. TEST_F(ServerTest, GetWithRange3) {
  4404. auto res = cli_.Get("/with-range", {
  4405. make_range_header({{0, 0}}),
  4406. {"Accept-Encoding", ""},
  4407. });
  4408. ASSERT_TRUE(res);
  4409. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4410. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4411. EXPECT_EQ(true, res->has_header("Content-Range"));
  4412. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4413. EXPECT_EQ(std::string("a"), res->body);
  4414. }
  4415. TEST_F(ServerTest, GetWithRange4) {
  4416. auto res = cli_.Get("/with-range", {
  4417. make_range_header({{-1, 2}}),
  4418. {"Accept-Encoding", ""},
  4419. });
  4420. ASSERT_TRUE(res);
  4421. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4422. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4423. EXPECT_EQ(true, res->has_header("Content-Range"));
  4424. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4425. EXPECT_EQ(std::string("fg"), res->body);
  4426. }
  4427. TEST_F(ServerTest, GetWithRange5) {
  4428. auto res = cli_.Get("/with-range", {
  4429. make_range_header({{0, 5}}),
  4430. {"Accept-Encoding", ""},
  4431. });
  4432. ASSERT_TRUE(res);
  4433. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4434. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4435. EXPECT_EQ(true, res->has_header("Content-Range"));
  4436. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4437. EXPECT_EQ(std::string("abcdef"), res->body);
  4438. }
  4439. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4440. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4441. ASSERT_TRUE(res);
  4442. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4443. }
  4444. TEST_F(ServerTest, GetWithRangeMultipart) {
  4445. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4446. ASSERT_TRUE(res);
  4447. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4448. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4449. EXPECT_EQ(false, res->has_header("Content-Range"));
  4450. EXPECT_EQ(267U, res->body.size());
  4451. }
  4452. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4453. auto res =
  4454. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4455. ASSERT_TRUE(res);
  4456. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4457. }
  4458. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4459. auto res = cli_.Get("/with-range-customized-response",
  4460. {{make_range_header({{1, 2}})}});
  4461. ASSERT_TRUE(res);
  4462. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4463. EXPECT_EQ(true, res->has_header("Content-Length"));
  4464. EXPECT_EQ(false, res->has_header("Content-Range"));
  4465. EXPECT_EQ(JSON_DATA, res->body);
  4466. }
  4467. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4468. auto res = cli_.Get("/with-range-customized-response",
  4469. {{make_range_header({{1, 2}, {4, 5}})}});
  4470. ASSERT_TRUE(res);
  4471. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4472. EXPECT_EQ(true, res->has_header("Content-Length"));
  4473. EXPECT_EQ(false, res->has_header("Content-Range"));
  4474. EXPECT_EQ(JSON_DATA, res->body);
  4475. }
  4476. TEST_F(ServerTest, Issue1772) {
  4477. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4478. ASSERT_TRUE(res);
  4479. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4480. }
  4481. TEST_F(ServerTest, Issue609) {
  4482. auto res = cli_.Delete("/issue609");
  4483. ASSERT_TRUE(res);
  4484. EXPECT_EQ(StatusCode::OK_200, res->status);
  4485. EXPECT_EQ(std::string("ok"), res->body);
  4486. }
  4487. TEST_F(ServerTest, GetStreamedChunked) {
  4488. auto res = cli_.Get("/streamed-chunked");
  4489. ASSERT_TRUE(res);
  4490. EXPECT_EQ(StatusCode::OK_200, res->status);
  4491. EXPECT_EQ(std::string("123456789"), res->body);
  4492. }
  4493. TEST_F(ServerTest, GetStreamedChunked2) {
  4494. auto res = cli_.Get("/streamed-chunked2");
  4495. ASSERT_TRUE(res);
  4496. EXPECT_EQ(StatusCode::OK_200, res->status);
  4497. EXPECT_EQ(std::string("123456789"), res->body);
  4498. }
  4499. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4500. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4501. ASSERT_TRUE(res);
  4502. EXPECT_EQ(StatusCode::OK_200, res->status);
  4503. EXPECT_EQ(std::string("123456789"), res->body);
  4504. EXPECT_TRUE(res->has_header("Trailer"));
  4505. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4506. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4507. // Trailers are now stored separately from headers (security fix)
  4508. EXPECT_EQ(2U, res->trailers.size());
  4509. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4510. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4511. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4512. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4513. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4514. // Verify trailers are NOT in headers (security verification)
  4515. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4516. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4517. }
  4518. TEST_F(ServerTest, LargeChunkedPost) {
  4519. Request req;
  4520. req.method = "POST";
  4521. req.path = "/large-chunked";
  4522. std::string host_and_port;
  4523. host_and_port += HOST;
  4524. host_and_port += ":";
  4525. host_and_port += std::to_string(PORT);
  4526. req.headers.emplace("Host", host_and_port.c_str());
  4527. req.headers.emplace("Accept", "*/*");
  4528. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4529. req.headers.emplace("Content-Type", "text/plain");
  4530. req.headers.emplace("Content-Length", "0");
  4531. req.headers.emplace("Transfer-Encoding", "chunked");
  4532. std::string long_string(30 * 1024u, 'a');
  4533. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4534. // Attempt to make a large enough post to exceed OS buffers, to test that
  4535. // the server handles short reads if the full chunk data isn't available.
  4536. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4537. auto res = std::make_shared<Response>();
  4538. auto error = Error::Success;
  4539. auto ret = cli_.send(req, *res, error);
  4540. ASSERT_TRUE(ret);
  4541. EXPECT_EQ(StatusCode::OK_200, res->status);
  4542. }
  4543. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4544. auto res = cli_.Get("/remote_addr");
  4545. ASSERT_TRUE(res);
  4546. EXPECT_EQ(StatusCode::OK_200, res->status);
  4547. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4548. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4549. }
  4550. TEST_F(ServerTest, GetMethodLocalAddr) {
  4551. auto res = cli_.Get("/local_addr");
  4552. ASSERT_TRUE(res);
  4553. EXPECT_EQ(StatusCode::OK_200, res->status);
  4554. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4555. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4556. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4557. }
  4558. TEST_F(ServerTest, HTTPResponseSplitting) {
  4559. auto res = cli_.Get("/http_response_splitting");
  4560. ASSERT_TRUE(res);
  4561. EXPECT_EQ(StatusCode::OK_200, res->status);
  4562. }
  4563. TEST_F(ServerTest, SlowRequest) {
  4564. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4565. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4566. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4567. }
  4568. #if 0
  4569. TEST_F(ServerTest, SlowPost) {
  4570. char buffer[64 * 1024];
  4571. memset(buffer, 0x42, sizeof(buffer));
  4572. auto res = cli_.Post(
  4573. "/slowpost", 64 * 1024 * 1024,
  4574. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4575. auto ret = sink.write(buffer, sizeof(buffer));
  4576. EXPECT_TRUE(ret);
  4577. return true;
  4578. },
  4579. "text/plain");
  4580. ASSERT_TRUE(res);
  4581. EXPECT_EQ(StatusCode::OK_200, res->status);
  4582. }
  4583. TEST_F(ServerTest, SlowPostFail) {
  4584. char buffer[64 * 1024];
  4585. memset(buffer, 0x42, sizeof(buffer));
  4586. cli_.set_write_timeout(std::chrono::seconds(0));
  4587. auto res = cli_.Post(
  4588. "/slowpost", 64 * 1024 * 1024,
  4589. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4590. sink.write(buffer, sizeof(buffer));
  4591. return true;
  4592. },
  4593. "text/plain");
  4594. ASSERT_TRUE(!res);
  4595. EXPECT_EQ(Error::Write, res.error());
  4596. }
  4597. #endif
  4598. TEST_F(ServerTest, Put) {
  4599. auto res = cli_.Put("/put", "PUT", "text/plain");
  4600. ASSERT_TRUE(res);
  4601. EXPECT_EQ(StatusCode::OK_200, res->status);
  4602. EXPECT_EQ("PUT", res->body);
  4603. }
  4604. TEST_F(ServerTest, PutWithContentProvider) {
  4605. auto res = cli_.Put(
  4606. "/put", 3,
  4607. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4608. sink.os << "PUT";
  4609. return true;
  4610. },
  4611. "text/plain");
  4612. ASSERT_TRUE(res);
  4613. EXPECT_EQ(StatusCode::OK_200, res->status);
  4614. EXPECT_EQ("PUT", res->body);
  4615. }
  4616. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4617. auto res = cli_.Post(
  4618. "/post", 42,
  4619. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4620. return false;
  4621. },
  4622. "text/plain");
  4623. ASSERT_TRUE(!res);
  4624. EXPECT_EQ(Error::Canceled, res.error());
  4625. }
  4626. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4627. auto res = cli_.Put(
  4628. "/put",
  4629. [](size_t /*offset*/, DataSink &sink) {
  4630. sink.os << "PUT";
  4631. sink.done();
  4632. return true;
  4633. },
  4634. "text/plain");
  4635. ASSERT_TRUE(res);
  4636. EXPECT_EQ(StatusCode::OK_200, res->status);
  4637. EXPECT_EQ("PUT", res->body);
  4638. }
  4639. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4640. auto res = cli_.Post(
  4641. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4642. "text/plain");
  4643. ASSERT_TRUE(!res);
  4644. EXPECT_EQ(Error::Canceled, res.error());
  4645. }
  4646. TEST_F(ServerTest, PostLoopBack) {
  4647. std::string body;
  4648. auto res = cli_.Post(
  4649. "/post-loopback", 9,
  4650. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4651. EXPECT_EQ(9u, length);
  4652. sink.write("123", 3);
  4653. sink.write("456", 3);
  4654. sink.write("789", 3);
  4655. return true;
  4656. },
  4657. "text/plain",
  4658. [&body](const char *data, size_t data_length) {
  4659. body.append(data, data_length);
  4660. return true;
  4661. });
  4662. ASSERT_TRUE(res);
  4663. EXPECT_EQ(StatusCode::OK_200, res->status);
  4664. EXPECT_EQ("123456789", body);
  4665. }
  4666. TEST_F(ServerTest, PutLoopBack) {
  4667. std::string body;
  4668. auto res = cli_.Put(
  4669. "/put-loopback", 9,
  4670. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4671. EXPECT_EQ(9u, length);
  4672. sink.write("123", 3);
  4673. sink.write("456", 3);
  4674. sink.write("789", 3);
  4675. return true;
  4676. },
  4677. "text/plain",
  4678. [&body](const char *data, size_t data_length) {
  4679. body.append(data, data_length);
  4680. return true;
  4681. });
  4682. ASSERT_TRUE(res);
  4683. EXPECT_EQ(StatusCode::OK_200, res->status);
  4684. EXPECT_EQ("123456789", body);
  4685. }
  4686. TEST_F(ServerTest, PatchLoopBack) {
  4687. std::string body;
  4688. auto res = cli_.Patch(
  4689. "/patch-loopback", 9,
  4690. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4691. EXPECT_EQ(9u, length);
  4692. sink.write("123", 3);
  4693. sink.write("456", 3);
  4694. sink.write("789", 3);
  4695. return true;
  4696. },
  4697. "text/plain",
  4698. [&body](const char *data, size_t data_length) {
  4699. body.append(data, data_length);
  4700. return true;
  4701. });
  4702. ASSERT_TRUE(res);
  4703. EXPECT_EQ(StatusCode::OK_200, res->status);
  4704. EXPECT_EQ("123456789", body);
  4705. }
  4706. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4707. std::string body;
  4708. auto res = cli_.Post(
  4709. "/post-loopback",
  4710. [](size_t /*offset*/, DataSink &sink) {
  4711. sink.write("123", 3);
  4712. sink.write("456", 3);
  4713. sink.write("789", 3);
  4714. sink.done();
  4715. return true;
  4716. },
  4717. "text/plain",
  4718. [&body](const char *data, size_t data_length) {
  4719. body.append(data, data_length);
  4720. return true;
  4721. });
  4722. ASSERT_TRUE(res);
  4723. EXPECT_EQ(StatusCode::OK_200, res->status);
  4724. EXPECT_EQ("123456789", body);
  4725. }
  4726. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4727. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4728. cli_.set_compress(true);
  4729. auto res = cli_.Put(
  4730. "/put", 3,
  4731. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4732. sink.os << "PUT";
  4733. return true;
  4734. },
  4735. "text/plain");
  4736. ASSERT_TRUE(res);
  4737. EXPECT_EQ(StatusCode::OK_200, res->status);
  4738. EXPECT_EQ("PUT", res->body);
  4739. }
  4740. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4741. cli_.set_compress(true);
  4742. auto res = cli_.Post(
  4743. "/post", 42,
  4744. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4745. return false;
  4746. },
  4747. "text/plain");
  4748. ASSERT_TRUE(!res);
  4749. EXPECT_EQ(Error::Canceled, res.error());
  4750. }
  4751. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4752. cli_.set_compress(true);
  4753. auto res = cli_.Put(
  4754. "/put",
  4755. [](size_t /*offset*/, DataSink &sink) {
  4756. sink.os << "PUT";
  4757. sink.done();
  4758. return true;
  4759. },
  4760. "text/plain");
  4761. ASSERT_TRUE(res);
  4762. EXPECT_EQ(StatusCode::OK_200, res->status);
  4763. EXPECT_EQ("PUT", res->body);
  4764. }
  4765. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4766. cli_.set_compress(true);
  4767. auto res = cli_.Post(
  4768. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4769. "text/plain");
  4770. ASSERT_TRUE(!res);
  4771. EXPECT_EQ(Error::Canceled, res.error());
  4772. }
  4773. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4774. cli_.set_compress(true);
  4775. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4776. ASSERT_TRUE(res);
  4777. EXPECT_EQ(StatusCode::OK_200, res->status);
  4778. EXPECT_EQ(LARGE_DATA, res->body);
  4779. }
  4780. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4781. #ifdef CPPHTTPLIB_SSL_ENABLED
  4782. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4783. Client cli(s.c_str());
  4784. cli.enable_server_certificate_verification(false);
  4785. #else
  4786. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4787. Client cli(s.c_str());
  4788. #endif
  4789. cli.set_compress(true);
  4790. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4791. ASSERT_TRUE(res);
  4792. EXPECT_EQ(StatusCode::OK_200, res->status);
  4793. EXPECT_EQ(LARGE_DATA, res->body);
  4794. // The compressed size should be less than a 10th of the original. May vary
  4795. // depending on the zlib library.
  4796. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4797. static_cast<uint64_t>(10 * 1024 * 1024));
  4798. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4799. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  4800. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  4801. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4802. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4803. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  4804. #endif
  4805. }
  4806. TEST_F(ServerTest, PutContentWithDeflate) {
  4807. cli_.set_compress(false);
  4808. Headers headers;
  4809. headers.emplace("Content-Encoding", "deflate");
  4810. // PUT in deflate format:
  4811. auto res = cli_.Put("/put", headers,
  4812. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4813. ASSERT_TRUE(res);
  4814. EXPECT_EQ(StatusCode::OK_200, res->status);
  4815. EXPECT_EQ("PUT", res->body);
  4816. }
  4817. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4818. Headers headers;
  4819. headers.emplace("Accept-Encoding", "gzip, deflate");
  4820. auto res = cli_.Get("/streamed-chunked", headers);
  4821. ASSERT_TRUE(res);
  4822. EXPECT_EQ(StatusCode::OK_200, res->status);
  4823. EXPECT_EQ(std::string("123456789"), res->body);
  4824. }
  4825. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4826. Headers headers;
  4827. headers.emplace("Accept-Encoding", "gzip, deflate");
  4828. auto res = cli_.Get("/streamed-chunked2", headers);
  4829. ASSERT_TRUE(res);
  4830. EXPECT_EQ(StatusCode::OK_200, res->status);
  4831. EXPECT_EQ(std::string("123456789"), res->body);
  4832. }
  4833. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4834. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4835. ASSERT_TRUE(res);
  4836. EXPECT_EQ(StatusCode::OK_200, res->status);
  4837. }
  4838. TEST(GzipDecompressor, ChunkedDecompression) {
  4839. std::string data;
  4840. for (size_t i = 0; i < 32 * 1024; ++i) {
  4841. data.push_back(static_cast<char>('a' + i % 26));
  4842. }
  4843. std::string compressed_data;
  4844. {
  4845. httplib::detail::gzip_compressor compressor;
  4846. bool result = compressor.compress(
  4847. data.data(), data.size(),
  4848. /*last=*/true,
  4849. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4850. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4851. compressed_data_size);
  4852. return true;
  4853. });
  4854. ASSERT_TRUE(result);
  4855. }
  4856. std::string decompressed_data;
  4857. {
  4858. httplib::detail::gzip_decompressor decompressor;
  4859. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4860. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4861. size_t chunk_size = 130;
  4862. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4863. chunk_begin += chunk_size) {
  4864. size_t current_chunk_size =
  4865. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4866. bool result = decompressor.decompress(
  4867. compressed_data.data() + chunk_begin, current_chunk_size,
  4868. [&](const char *decompressed_data_chunk,
  4869. size_t decompressed_data_chunk_size) {
  4870. decompressed_data.insert(decompressed_data.size(),
  4871. decompressed_data_chunk,
  4872. decompressed_data_chunk_size);
  4873. return true;
  4874. });
  4875. ASSERT_TRUE(result);
  4876. }
  4877. }
  4878. ASSERT_EQ(data, decompressed_data);
  4879. }
  4880. TEST(GzipDecompressor, DeflateDecompression) {
  4881. std::string original_text = "Raw deflate without gzip";
  4882. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4883. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4884. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4885. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4886. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4887. std::string decompressed_data;
  4888. {
  4889. httplib::detail::gzip_decompressor decompressor;
  4890. bool result = decompressor.decompress(
  4891. compressed_data.data(), compressed_data.size(),
  4892. [&](const char *decompressed_data_chunk,
  4893. size_t decompressed_data_chunk_size) {
  4894. decompressed_data.insert(decompressed_data.size(),
  4895. decompressed_data_chunk,
  4896. decompressed_data_chunk_size);
  4897. return true;
  4898. });
  4899. ASSERT_TRUE(result);
  4900. }
  4901. ASSERT_EQ(original_text, decompressed_data);
  4902. }
  4903. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4904. std::string original_text = "Raw deflate without gzip";
  4905. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4906. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4907. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4908. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4909. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4910. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4911. std::string decompressed_data;
  4912. {
  4913. httplib::detail::gzip_decompressor decompressor;
  4914. bool result = decompressor.decompress(
  4915. compressed_data.data(), compressed_data.size(),
  4916. [&](const char *decompressed_data_chunk,
  4917. size_t decompressed_data_chunk_size) {
  4918. decompressed_data.insert(decompressed_data.size(),
  4919. decompressed_data_chunk,
  4920. decompressed_data_chunk_size);
  4921. return true;
  4922. });
  4923. ASSERT_TRUE(result);
  4924. }
  4925. ASSERT_EQ(original_text, decompressed_data);
  4926. }
  4927. #endif
  4928. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4929. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4930. Headers headers;
  4931. headers.emplace("Accept-Encoding", "br");
  4932. auto res = cli_.Get("/streamed-chunked", headers);
  4933. ASSERT_TRUE(res);
  4934. EXPECT_EQ(StatusCode::OK_200, res->status);
  4935. EXPECT_EQ(std::string("123456789"), res->body);
  4936. }
  4937. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4938. Headers headers;
  4939. headers.emplace("Accept-Encoding", "br");
  4940. auto res = cli_.Get("/streamed-chunked2", headers);
  4941. ASSERT_TRUE(res);
  4942. EXPECT_EQ(StatusCode::OK_200, res->status);
  4943. EXPECT_EQ(std::string("123456789"), res->body);
  4944. }
  4945. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  4946. cli_.set_compress(true);
  4947. auto res = cli_.Put(
  4948. "/put", 3,
  4949. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4950. sink.os << "PUT";
  4951. return true;
  4952. },
  4953. "text/plain");
  4954. ASSERT_TRUE(res);
  4955. EXPECT_EQ(StatusCode::OK_200, res->status);
  4956. EXPECT_EQ("PUT", res->body);
  4957. }
  4958. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  4959. cli_.set_compress(true);
  4960. auto res = cli_.Put(
  4961. "/put",
  4962. [](size_t /*offset*/, DataSink &sink) {
  4963. sink.os << "PUT";
  4964. sink.done();
  4965. return true;
  4966. },
  4967. "text/plain");
  4968. ASSERT_TRUE(res);
  4969. EXPECT_EQ(StatusCode::OK_200, res->status);
  4970. EXPECT_EQ("PUT", res->body);
  4971. }
  4972. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  4973. cli_.set_compress(true);
  4974. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4975. ASSERT_TRUE(res);
  4976. EXPECT_EQ(StatusCode::OK_200, res->status);
  4977. EXPECT_EQ(LARGE_DATA, res->body);
  4978. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  4979. }
  4980. #endif
  4981. TEST_F(ServerTest, Patch) {
  4982. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4983. ASSERT_TRUE(res);
  4984. EXPECT_EQ(StatusCode::OK_200, res->status);
  4985. EXPECT_EQ("PATCH", res->body);
  4986. }
  4987. TEST_F(ServerTest, Delete) {
  4988. auto res = cli_.Delete("/delete");
  4989. ASSERT_TRUE(res);
  4990. EXPECT_EQ(StatusCode::OK_200, res->status);
  4991. EXPECT_EQ("DELETE", res->body);
  4992. }
  4993. TEST_F(ServerTest, DeleteContentReceiver) {
  4994. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4995. ASSERT_TRUE(res);
  4996. EXPECT_EQ(StatusCode::OK_200, res->status);
  4997. EXPECT_EQ("content", res->body);
  4998. }
  4999. TEST_F(ServerTest, Options) {
  5000. auto res = cli_.Options("*");
  5001. ASSERT_TRUE(res);
  5002. EXPECT_EQ(StatusCode::OK_200, res->status);
  5003. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5004. EXPECT_TRUE(res->body.empty());
  5005. }
  5006. TEST_F(ServerTest, URL) {
  5007. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5008. ASSERT_TRUE(res);
  5009. EXPECT_EQ(StatusCode::OK_200, res->status);
  5010. }
  5011. TEST_F(ServerTest, ArrayParam) {
  5012. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5013. ASSERT_TRUE(res);
  5014. EXPECT_EQ(StatusCode::OK_200, res->status);
  5015. }
  5016. TEST_F(ServerTest, NoMultipleHeaders) {
  5017. Headers headers = {{"Content-Length", "5"}};
  5018. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5019. "text/plain");
  5020. ASSERT_TRUE(res);
  5021. EXPECT_EQ(StatusCode::OK_200, res->status);
  5022. }
  5023. TEST_F(ServerTest, PostContentReceiver) {
  5024. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5025. ASSERT_TRUE(res);
  5026. ASSERT_EQ(StatusCode::OK_200, res->status);
  5027. ASSERT_EQ("content", res->body);
  5028. }
  5029. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5030. UploadFormDataItems items = {
  5031. {"text1", "text default", "", ""},
  5032. {"text2", "aωb", "", ""},
  5033. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5034. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5035. {"file3", "", "", "application/octet-stream"},
  5036. };
  5037. auto res = cli_.Post("/content_receiver", items);
  5038. ASSERT_TRUE(res);
  5039. EXPECT_EQ(StatusCode::OK_200, res->status);
  5040. }
  5041. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5042. UploadFormDataItems items = {
  5043. {"text1", "text default", "", ""},
  5044. {"text2", "aωb", "", ""},
  5045. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5046. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5047. {"file3", "", "", "application/octet-stream"},
  5048. };
  5049. auto boundary = std::string("+++++");
  5050. std::string body;
  5051. for (const auto &item : items) {
  5052. body += "--" + boundary + "\r\n";
  5053. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5054. if (!item.filename.empty()) {
  5055. body += "; filename=\"" + item.filename + "\"";
  5056. }
  5057. body += "\r\n";
  5058. if (!item.content_type.empty()) {
  5059. body += "Content-Type: " + item.content_type + "\r\n";
  5060. }
  5061. body += "\r\n";
  5062. body += item.content + "\r\n";
  5063. }
  5064. body += "--" + boundary + "--\r\n";
  5065. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5066. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5067. ASSERT_TRUE(res);
  5068. EXPECT_EQ(StatusCode::OK_200, res->status);
  5069. }
  5070. TEST_F(ServerTest, PostContentReceiverGzip) {
  5071. cli_.set_compress(true);
  5072. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5073. ASSERT_TRUE(res);
  5074. ASSERT_EQ(StatusCode::OK_200, res->status);
  5075. ASSERT_EQ("content", res->body);
  5076. }
  5077. TEST_F(ServerTest, PutContentReceiver) {
  5078. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5079. ASSERT_TRUE(res);
  5080. ASSERT_EQ(StatusCode::OK_200, res->status);
  5081. ASSERT_EQ("content", res->body);
  5082. }
  5083. TEST_F(ServerTest, PatchContentReceiver) {
  5084. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5085. ASSERT_TRUE(res);
  5086. ASSERT_EQ(StatusCode::OK_200, res->status);
  5087. ASSERT_EQ("content", res->body);
  5088. }
  5089. template <typename ClientType>
  5090. void TestWithHeadersAndContentReceiver(
  5091. ClientType &cli,
  5092. std::function<Result(ClientType &, const std::string &, const Headers &,
  5093. const std::string &, const std::string &,
  5094. ContentReceiver, DownloadProgress)>
  5095. request_func) {
  5096. Headers headers;
  5097. headers.emplace("X-Custom-Header", "test-value");
  5098. std::string received_body;
  5099. auto res = request_func(
  5100. cli, "/content_receiver", headers, "content", "application/json",
  5101. [&](const char *data, size_t data_length) {
  5102. received_body.append(data, data_length);
  5103. return true;
  5104. },
  5105. nullptr);
  5106. ASSERT_TRUE(res);
  5107. EXPECT_EQ(StatusCode::OK_200, res->status);
  5108. EXPECT_EQ("content", received_body);
  5109. }
  5110. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5111. #ifdef CPPHTTPLIB_SSL_ENABLED
  5112. using ClientT = SSLClient;
  5113. #else
  5114. using ClientT = Client;
  5115. #endif
  5116. TestWithHeadersAndContentReceiver<ClientT>(
  5117. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5118. const std::string &body, const std::string &content_type,
  5119. ContentReceiver receiver, DownloadProgress progress) {
  5120. return cli.Post(path, headers, body, content_type, receiver, progress);
  5121. });
  5122. }
  5123. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5124. #ifdef CPPHTTPLIB_SSL_ENABLED
  5125. using ClientT = SSLClient;
  5126. #else
  5127. using ClientT = Client;
  5128. #endif
  5129. TestWithHeadersAndContentReceiver<ClientT>(
  5130. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5131. const std::string &body, const std::string &content_type,
  5132. ContentReceiver receiver, DownloadProgress progress) {
  5133. return cli.Put(path, headers, body, content_type, receiver, progress);
  5134. });
  5135. }
  5136. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5137. #ifdef CPPHTTPLIB_SSL_ENABLED
  5138. using ClientT = SSLClient;
  5139. #else
  5140. using ClientT = Client;
  5141. #endif
  5142. TestWithHeadersAndContentReceiver<ClientT>(
  5143. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5144. const std::string &body, const std::string &content_type,
  5145. ContentReceiver receiver, DownloadProgress progress) {
  5146. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5147. });
  5148. }
  5149. template <typename ClientType>
  5150. void TestWithHeadersAndContentReceiverWithProgress(
  5151. ClientType &cli,
  5152. std::function<Result(ClientType &, const std::string &, const Headers &,
  5153. const std::string &, const std::string &,
  5154. ContentReceiver, DownloadProgress)>
  5155. request_func) {
  5156. Headers headers;
  5157. headers.emplace("X-Test-Header", "progress-test");
  5158. std::string received_body;
  5159. auto progress_called = false;
  5160. auto res = request_func(
  5161. cli, "/content_receiver", headers, "content", "text/plain",
  5162. [&](const char *data, size_t data_length) {
  5163. received_body.append(data, data_length);
  5164. return true;
  5165. },
  5166. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5167. progress_called = true;
  5168. return true;
  5169. });
  5170. ASSERT_TRUE(res);
  5171. EXPECT_EQ(StatusCode::OK_200, res->status);
  5172. EXPECT_EQ("content", received_body);
  5173. EXPECT_TRUE(progress_called);
  5174. }
  5175. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5176. #ifdef CPPHTTPLIB_SSL_ENABLED
  5177. using ClientT = SSLClient;
  5178. #else
  5179. using ClientT = Client;
  5180. #endif
  5181. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5182. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5183. const std::string &body, const std::string &content_type,
  5184. ContentReceiver receiver, DownloadProgress progress) {
  5185. return cli.Post(path, headers, body, content_type, receiver, progress);
  5186. });
  5187. }
  5188. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5189. #ifdef CPPHTTPLIB_SSL_ENABLED
  5190. using ClientT = SSLClient;
  5191. #else
  5192. using ClientT = Client;
  5193. #endif
  5194. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5195. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5196. const std::string &body, const std::string &content_type,
  5197. ContentReceiver receiver, DownloadProgress progress) {
  5198. return cli.Put(path, headers, body, content_type, receiver, progress);
  5199. });
  5200. }
  5201. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5202. #ifdef CPPHTTPLIB_SSL_ENABLED
  5203. using ClientT = SSLClient;
  5204. #else
  5205. using ClientT = Client;
  5206. #endif
  5207. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5208. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5209. const std::string &body, const std::string &content_type,
  5210. ContentReceiver receiver, DownloadProgress progress) {
  5211. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5212. });
  5213. }
  5214. template <typename ClientType>
  5215. void TestWithHeadersAndContentReceiverError(
  5216. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5217. const Headers &, const std::string &,
  5218. const std::string &, ContentReceiver)>
  5219. request_func) {
  5220. Headers headers;
  5221. headers.emplace("X-Error-Test", "true");
  5222. std::string received_body;
  5223. auto receiver_failed = false;
  5224. auto res =
  5225. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5226. [&](const char *data, size_t data_length) {
  5227. received_body.append(data, data_length);
  5228. receiver_failed = true;
  5229. return false;
  5230. });
  5231. ASSERT_FALSE(res);
  5232. EXPECT_TRUE(receiver_failed);
  5233. }
  5234. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5235. #ifdef CPPHTTPLIB_SSL_ENABLED
  5236. using ClientT = SSLClient;
  5237. #else
  5238. using ClientT = Client;
  5239. #endif
  5240. TestWithHeadersAndContentReceiverError<ClientT>(
  5241. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5242. const std::string &body, const std::string &content_type,
  5243. ContentReceiver receiver) {
  5244. return cli.Post(path, headers, body, content_type, receiver);
  5245. });
  5246. }
  5247. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5248. #ifdef CPPHTTPLIB_SSL_ENABLED
  5249. using ClientT = SSLClient;
  5250. #else
  5251. using ClientT = Client;
  5252. #endif
  5253. TestWithHeadersAndContentReceiverError<ClientT>(
  5254. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5255. const std::string &body, const std::string &content_type,
  5256. ContentReceiver receiver) {
  5257. return cli.Put(path, headers, body, content_type, receiver);
  5258. });
  5259. }
  5260. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5261. #ifdef CPPHTTPLIB_SSL_ENABLED
  5262. using ClientT = SSLClient;
  5263. #else
  5264. using ClientT = Client;
  5265. #endif
  5266. TestWithHeadersAndContentReceiverError<ClientT>(
  5267. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5268. const std::string &body, const std::string &content_type,
  5269. ContentReceiver receiver) {
  5270. return cli.Patch(path, headers, body, content_type, receiver);
  5271. });
  5272. }
  5273. TEST_F(ServerTest, PostQueryStringAndBody) {
  5274. auto res =
  5275. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5276. ASSERT_TRUE(res);
  5277. ASSERT_EQ(StatusCode::OK_200, res->status);
  5278. }
  5279. TEST_F(ServerTest, HTTP2Magic) {
  5280. Request req;
  5281. req.method = "PRI";
  5282. req.path = "*";
  5283. req.body = "SM";
  5284. auto res = std::make_shared<Response>();
  5285. auto error = Error::Success;
  5286. auto ret = cli_.send(req, *res, error);
  5287. ASSERT_TRUE(ret);
  5288. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5289. }
  5290. TEST_F(ServerTest, KeepAlive) {
  5291. auto res = cli_.Get("/hi");
  5292. ASSERT_TRUE(res);
  5293. EXPECT_EQ(StatusCode::OK_200, res->status);
  5294. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5295. EXPECT_EQ("Hello World!", res->body);
  5296. res = cli_.Get("/hi");
  5297. ASSERT_TRUE(res);
  5298. EXPECT_EQ(StatusCode::OK_200, res->status);
  5299. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5300. EXPECT_EQ("Hello World!", res->body);
  5301. res = cli_.Get("/hi");
  5302. ASSERT_TRUE(res);
  5303. EXPECT_EQ(StatusCode::OK_200, res->status);
  5304. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5305. EXPECT_EQ("Hello World!", res->body);
  5306. res = cli_.Get("/not-exist");
  5307. ASSERT_TRUE(res);
  5308. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5309. res = cli_.Post("/empty", "", "text/plain");
  5310. ASSERT_TRUE(res);
  5311. EXPECT_EQ(StatusCode::OK_200, res->status);
  5312. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5313. EXPECT_EQ("empty", res->body);
  5314. EXPECT_EQ("close", res->get_header_value("Connection"));
  5315. res = cli_.Post(
  5316. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5317. "text/plain");
  5318. ASSERT_TRUE(res);
  5319. EXPECT_EQ(StatusCode::OK_200, res->status);
  5320. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5321. EXPECT_EQ("empty", res->body);
  5322. cli_.set_keep_alive(false);
  5323. res = cli_.Get("/last-request");
  5324. ASSERT_TRUE(res);
  5325. EXPECT_EQ(StatusCode::OK_200, res->status);
  5326. EXPECT_EQ("close", res->get_header_value("Connection"));
  5327. }
  5328. TEST_F(ServerTest, TooManyRedirect) {
  5329. cli_.set_follow_location(true);
  5330. auto res = cli_.Get("/redirect/0");
  5331. ASSERT_TRUE(!res);
  5332. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5333. }
  5334. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5335. Request req;
  5336. req.method = "FOOBAR";
  5337. req.path = "/hi";
  5338. cli_.set_keep_alive(true);
  5339. auto res = cli_.send(req);
  5340. ASSERT_TRUE(res);
  5341. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5342. EXPECT_EQ("close", res->get_header_value("Connection"));
  5343. EXPECT_FALSE(cli_.is_socket_open());
  5344. }
  5345. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5346. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5347. TEST_F(ServerTest, Gzip) {
  5348. Headers headers;
  5349. headers.emplace("Accept-Encoding", "gzip, deflate");
  5350. auto res = cli_.Get("/compress", headers);
  5351. ASSERT_TRUE(res);
  5352. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5353. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5354. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5355. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5356. "7890123456789012345678901234567890",
  5357. res->body);
  5358. EXPECT_EQ(StatusCode::OK_200, res->status);
  5359. }
  5360. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5361. Headers headers;
  5362. headers.emplace("Accept-Encoding", "gzip, deflate");
  5363. auto res = cli_.Get("/compress-with-charset", headers);
  5364. ASSERT_TRUE(res);
  5365. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5366. EXPECT_EQ("application/json; charset=utf-8",
  5367. res->get_header_value("Content-Type"));
  5368. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5369. "7890123456789012345678901234567890",
  5370. res->body);
  5371. EXPECT_EQ(StatusCode::OK_200, res->status);
  5372. }
  5373. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5374. Headers headers;
  5375. headers.emplace("Accept-Encoding", "");
  5376. auto res = cli_.Get("/compress", headers);
  5377. ASSERT_TRUE(res);
  5378. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5379. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5380. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5381. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5382. "7890123456789012345678901234567890",
  5383. res->body);
  5384. EXPECT_EQ(StatusCode::OK_200, res->status);
  5385. }
  5386. TEST_F(ServerTest, GzipWithContentReceiver) {
  5387. Headers headers;
  5388. headers.emplace("Accept-Encoding", "gzip, deflate");
  5389. std::string body;
  5390. auto res = cli_.Get("/compress", headers,
  5391. [&](const char *data, uint64_t data_length) {
  5392. EXPECT_EQ(100U, data_length);
  5393. body.append(data, data_length);
  5394. return true;
  5395. });
  5396. ASSERT_TRUE(res);
  5397. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5398. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5399. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5400. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5401. "7890123456789012345678901234567890",
  5402. body);
  5403. EXPECT_EQ(StatusCode::OK_200, res->status);
  5404. }
  5405. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5406. Headers headers;
  5407. headers.emplace("Accept-Encoding", "gzip, deflate");
  5408. cli_.set_decompress(false);
  5409. auto res = cli_.Get("/compress", headers);
  5410. ASSERT_TRUE(res);
  5411. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5412. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5413. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5414. EXPECT_EQ(33U, res->body.size());
  5415. EXPECT_EQ(StatusCode::OK_200, res->status);
  5416. }
  5417. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5418. Headers headers;
  5419. headers.emplace("Accept-Encoding", "");
  5420. std::string body;
  5421. auto res = cli_.Get("/compress", headers,
  5422. [&](const char *data, uint64_t data_length) {
  5423. EXPECT_EQ(100U, data_length);
  5424. body.append(data, data_length);
  5425. return true;
  5426. });
  5427. ASSERT_TRUE(res);
  5428. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5429. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5430. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5431. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5432. "7890123456789012345678901234567890",
  5433. body);
  5434. EXPECT_EQ(StatusCode::OK_200, res->status);
  5435. }
  5436. TEST_F(ServerTest, NoGzip) {
  5437. Headers headers;
  5438. headers.emplace("Accept-Encoding", "gzip, deflate");
  5439. auto res = cli_.Get("/nocompress", headers);
  5440. ASSERT_TRUE(res);
  5441. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5442. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5443. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5444. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5445. "7890123456789012345678901234567890",
  5446. res->body);
  5447. EXPECT_EQ(StatusCode::OK_200, res->status);
  5448. }
  5449. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5450. Headers headers;
  5451. headers.emplace("Accept-Encoding", "gzip, deflate");
  5452. std::string body;
  5453. auto res = cli_.Get("/nocompress", headers,
  5454. [&](const char *data, uint64_t data_length) {
  5455. EXPECT_EQ(100U, data_length);
  5456. body.append(data, data_length);
  5457. return true;
  5458. });
  5459. ASSERT_TRUE(res);
  5460. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5461. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5462. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5463. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5464. "7890123456789012345678901234567890",
  5465. body);
  5466. EXPECT_EQ(StatusCode::OK_200, res->status);
  5467. }
  5468. TEST_F(ServerTest, MultipartFormDataGzip) {
  5469. UploadFormDataItems items = {
  5470. {"key1", "test", "", ""},
  5471. {"key2", "--abcdefg123", "", ""},
  5472. };
  5473. cli_.set_compress(true);
  5474. auto res = cli_.Post("/compress-multipart", items);
  5475. ASSERT_TRUE(res);
  5476. EXPECT_EQ(StatusCode::OK_200, res->status);
  5477. }
  5478. #endif
  5479. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5480. TEST_F(ServerTest, Brotli) {
  5481. Headers headers;
  5482. headers.emplace("Accept-Encoding", "br");
  5483. auto res = cli_.Get("/compress", headers);
  5484. ASSERT_TRUE(res);
  5485. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5486. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5487. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5488. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5489. "7890123456789012345678901234567890",
  5490. res->body);
  5491. EXPECT_EQ(StatusCode::OK_200, res->status);
  5492. }
  5493. #endif
  5494. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5495. TEST_F(ServerTest, Zstd) {
  5496. Headers headers;
  5497. headers.emplace("Accept-Encoding", "zstd");
  5498. auto res = cli_.Get("/compress", headers);
  5499. ASSERT_TRUE(res);
  5500. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5501. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5502. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5503. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5504. "7890123456789012345678901234567890",
  5505. res->body);
  5506. EXPECT_EQ(StatusCode::OK_200, res->status);
  5507. }
  5508. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5509. Headers headers;
  5510. headers.emplace("Accept-Encoding", "");
  5511. auto res = cli_.Get("/compress", headers);
  5512. ASSERT_TRUE(res);
  5513. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5514. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5515. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5516. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5517. "7890123456789012345678901234567890",
  5518. res->body);
  5519. EXPECT_EQ(StatusCode::OK_200, res->status);
  5520. }
  5521. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5522. Headers headers;
  5523. headers.emplace("Accept-Encoding", "zstd");
  5524. std::string body;
  5525. auto res = cli_.Get("/compress", headers,
  5526. [&](const char *data, uint64_t data_length) {
  5527. EXPECT_EQ(100U, data_length);
  5528. body.append(data, data_length);
  5529. return true;
  5530. });
  5531. ASSERT_TRUE(res);
  5532. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5533. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5534. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5535. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5536. "7890123456789012345678901234567890",
  5537. body);
  5538. EXPECT_EQ(StatusCode::OK_200, res->status);
  5539. }
  5540. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5541. Headers headers;
  5542. headers.emplace("Accept-Encoding", "zstd");
  5543. cli_.set_decompress(false);
  5544. auto res = cli_.Get("/compress", headers);
  5545. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5546. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5547. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5548. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5549. ASSERT_TRUE(res);
  5550. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5551. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5552. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5553. EXPECT_EQ(StatusCode::OK_200, res->status);
  5554. ASSERT_EQ(26U, res->body.size());
  5555. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5556. 0);
  5557. }
  5558. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5559. Headers headers;
  5560. headers.emplace("Accept-Encoding", "");
  5561. std::string body;
  5562. auto res = cli_.Get("/compress", headers,
  5563. [&](const char *data, uint64_t data_length) {
  5564. EXPECT_EQ(100U, data_length);
  5565. body.append(data, data_length);
  5566. return true;
  5567. });
  5568. ASSERT_TRUE(res);
  5569. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5570. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5571. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5572. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5573. "7890123456789012345678901234567890",
  5574. body);
  5575. EXPECT_EQ(StatusCode::OK_200, res->status);
  5576. }
  5577. TEST_F(ServerTest, NoZstd) {
  5578. Headers headers;
  5579. headers.emplace("Accept-Encoding", "zstd");
  5580. auto res = cli_.Get("/nocompress", headers);
  5581. ASSERT_TRUE(res);
  5582. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5583. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5584. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5585. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5586. "7890123456789012345678901234567890",
  5587. res->body);
  5588. EXPECT_EQ(StatusCode::OK_200, res->status);
  5589. }
  5590. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5591. Headers headers;
  5592. headers.emplace("Accept-Encoding", "zstd");
  5593. std::string body;
  5594. auto res = cli_.Get("/nocompress", headers,
  5595. [&](const char *data, uint64_t data_length) {
  5596. EXPECT_EQ(100U, data_length);
  5597. body.append(data, data_length);
  5598. return true;
  5599. });
  5600. ASSERT_TRUE(res);
  5601. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5602. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5603. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5604. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5605. "7890123456789012345678901234567890",
  5606. body);
  5607. EXPECT_EQ(StatusCode::OK_200, res->status);
  5608. }
  5609. // TODO: How to enable zstd ??
  5610. TEST_F(ServerTest, MultipartFormDataZstd) {
  5611. UploadFormDataItems items = {
  5612. {"key1", "test", "", ""},
  5613. {"key2", "--abcdefg123", "", ""},
  5614. };
  5615. Headers headers;
  5616. headers.emplace("Accept-Encoding", "zstd");
  5617. cli_.set_compress(true);
  5618. auto res = cli_.Post("/compress-multipart", headers, items);
  5619. ASSERT_TRUE(res);
  5620. EXPECT_EQ(StatusCode::OK_200, res->status);
  5621. }
  5622. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5623. Headers headers;
  5624. headers.emplace("Accept-Encoding", "zstd");
  5625. cli_.set_compress(true);
  5626. auto res = cli_.Put(
  5627. "/put", headers, 3,
  5628. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5629. sink.os << "PUT";
  5630. return true;
  5631. },
  5632. "text/plain");
  5633. ASSERT_TRUE(res);
  5634. EXPECT_EQ(StatusCode::OK_200, res->status);
  5635. EXPECT_EQ("PUT", res->body);
  5636. }
  5637. // Pre-compression logging tests
  5638. TEST_F(ServerTest, PreCompressionLogging) {
  5639. // Test data for compression (matches the actual /compress endpoint content)
  5640. const std::string test_content =
  5641. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5642. "3456789012345678901234567890";
  5643. // Variables to capture logging data
  5644. std::string pre_compression_body;
  5645. std::string pre_compression_content_type;
  5646. std::string pre_compression_content_encoding;
  5647. std::string post_compression_body;
  5648. std::string post_compression_content_type;
  5649. std::string post_compression_content_encoding;
  5650. // Set up pre-compression logger
  5651. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5652. const Response &res) {
  5653. pre_compression_body = res.body;
  5654. pre_compression_content_type = res.get_header_value("Content-Type");
  5655. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5656. });
  5657. // Set up post-compression logger
  5658. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5659. post_compression_body = res.body;
  5660. post_compression_content_type = res.get_header_value("Content-Type");
  5661. post_compression_content_encoding =
  5662. res.get_header_value("Content-Encoding");
  5663. });
  5664. // Test with gzip compression
  5665. Headers headers;
  5666. headers.emplace("Accept-Encoding", "gzip");
  5667. auto res = cli_.Get("/compress", headers);
  5668. // Verify response was compressed
  5669. ASSERT_TRUE(res);
  5670. EXPECT_EQ(StatusCode::OK_200, res->status);
  5671. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5672. // Verify pre-compression logger captured uncompressed content
  5673. EXPECT_EQ(test_content, pre_compression_body);
  5674. EXPECT_EQ("text/plain", pre_compression_content_type);
  5675. EXPECT_TRUE(pre_compression_content_encoding
  5676. .empty()); // No encoding header before compression
  5677. // Verify post-compression logger captured compressed content
  5678. EXPECT_NE(test_content,
  5679. post_compression_body); // Should be different after compression
  5680. EXPECT_EQ("text/plain", post_compression_content_type);
  5681. EXPECT_EQ("gzip", post_compression_content_encoding);
  5682. // Verify compressed content is smaller
  5683. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5684. }
  5685. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5686. const std::string test_content =
  5687. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5688. "3456789012345678901234567890";
  5689. std::string pre_compression_body;
  5690. std::string post_compression_body;
  5691. svr_.set_pre_compression_logger(
  5692. [&](const Request & /*req*/, const Response &res) {
  5693. pre_compression_body = res.body;
  5694. });
  5695. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5696. post_compression_body = res.body;
  5697. });
  5698. Headers headers;
  5699. headers.emplace("Accept-Encoding", "br");
  5700. auto res = cli_.Get("/compress", headers);
  5701. ASSERT_TRUE(res);
  5702. EXPECT_EQ(StatusCode::OK_200, res->status);
  5703. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5704. // Verify pre-compression content is uncompressed
  5705. EXPECT_EQ(test_content, pre_compression_body);
  5706. // Verify post-compression content is compressed
  5707. EXPECT_NE(test_content, post_compression_body);
  5708. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5709. }
  5710. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5711. const std::string test_content =
  5712. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5713. "3456789012345678901234567890";
  5714. std::string pre_compression_body;
  5715. std::string post_compression_body;
  5716. svr_.set_pre_compression_logger(
  5717. [&](const Request & /*req*/, const Response &res) {
  5718. pre_compression_body = res.body;
  5719. });
  5720. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5721. post_compression_body = res.body;
  5722. });
  5723. // Request without compression (use /nocompress endpoint)
  5724. Headers headers;
  5725. auto res = cli_.Get("/nocompress", headers);
  5726. ASSERT_TRUE(res);
  5727. EXPECT_EQ(StatusCode::OK_200, res->status);
  5728. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5729. // Pre-compression logger should not be called when no compression is applied
  5730. EXPECT_TRUE(
  5731. pre_compression_body.empty()); // Pre-compression logger not called
  5732. EXPECT_EQ(
  5733. test_content,
  5734. post_compression_body); // Post-compression logger captures final content
  5735. }
  5736. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5737. const std::string test_content =
  5738. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5739. "3456789012345678901234567890";
  5740. std::string pre_compression_body;
  5741. bool pre_logger_called = false;
  5742. // Set only pre-compression logger
  5743. svr_.set_pre_compression_logger(
  5744. [&](const Request & /*req*/, const Response &res) {
  5745. pre_compression_body = res.body;
  5746. pre_logger_called = true;
  5747. });
  5748. Headers headers;
  5749. headers.emplace("Accept-Encoding", "gzip");
  5750. auto res = cli_.Get("/compress", headers);
  5751. ASSERT_TRUE(res);
  5752. EXPECT_EQ(StatusCode::OK_200, res->status);
  5753. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5754. // Verify pre-compression logger was called
  5755. EXPECT_TRUE(pre_logger_called);
  5756. EXPECT_EQ(test_content, pre_compression_body);
  5757. }
  5758. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5759. {
  5760. // Test with Expect: 100-continue header - success case
  5761. // Server returns 100 Continue, client sends body, server returns 200 OK
  5762. Request req;
  5763. req.method = "POST";
  5764. req.path = "/post-large";
  5765. req.set_header("Expect", "100-continue");
  5766. req.body = LARGE_DATA;
  5767. Response res;
  5768. auto error = Error::Success;
  5769. cli_.set_keep_alive(true);
  5770. auto ret = cli_.send(req, res, error);
  5771. EXPECT_TRUE(ret);
  5772. EXPECT_EQ(StatusCode::OK_200, res.status);
  5773. EXPECT_EQ(LARGE_DATA, res.body);
  5774. }
  5775. {
  5776. // Test with Expect: 100-continue header - error case
  5777. // Client should not send the body when server returns an error
  5778. Request req;
  5779. req.method = "POST";
  5780. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5781. req.set_header("Expect", "100-continue");
  5782. req.body = LARGE_DATA;
  5783. Response res;
  5784. auto error = Error::Success;
  5785. auto start = std::chrono::high_resolution_clock::now();
  5786. cli_.set_keep_alive(true);
  5787. auto ret = cli_.send(req, res, error);
  5788. auto end = std::chrono::high_resolution_clock::now();
  5789. auto elapsed =
  5790. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5791. .count();
  5792. // With Expect: 100-continue, request completes successfully but with error
  5793. EXPECT_TRUE(ret);
  5794. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5795. EXPECT_EQ("close", res.get_header_value("Connection"));
  5796. EXPECT_FALSE(cli_.is_socket_open());
  5797. EXPECT_LE(elapsed, 200);
  5798. }
  5799. {
  5800. // Send an extra GET request to ensure error recovery without hanging
  5801. Request req;
  5802. req.method = "GET";
  5803. req.path = "/hi";
  5804. auto start = std::chrono::high_resolution_clock::now();
  5805. auto res = cli_.send(req);
  5806. auto end = std::chrono::high_resolution_clock::now();
  5807. auto elapsed =
  5808. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5809. .count();
  5810. ASSERT_TRUE(res);
  5811. EXPECT_EQ(StatusCode::OK_200, res->status);
  5812. EXPECT_EQ("Hello World!", res->body);
  5813. EXPECT_LE(elapsed, 500);
  5814. }
  5815. }
  5816. TEST(ZstdDecompressor, ChunkedDecompression) {
  5817. std::string data;
  5818. for (size_t i = 0; i < 32 * 1024; ++i) {
  5819. data.push_back(static_cast<char>('a' + i % 26));
  5820. }
  5821. std::string compressed_data;
  5822. {
  5823. httplib::detail::zstd_compressor compressor;
  5824. bool result = compressor.compress(
  5825. data.data(), data.size(),
  5826. /*last=*/true,
  5827. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5828. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5829. compressed_data_size);
  5830. return true;
  5831. });
  5832. ASSERT_TRUE(result);
  5833. }
  5834. std::string decompressed_data;
  5835. {
  5836. httplib::detail::zstd_decompressor decompressor;
  5837. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5838. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5839. size_t chunk_size = 130;
  5840. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5841. chunk_begin += chunk_size) {
  5842. size_t current_chunk_size =
  5843. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5844. bool result = decompressor.decompress(
  5845. compressed_data.data() + chunk_begin, current_chunk_size,
  5846. [&](const char *decompressed_data_chunk,
  5847. size_t decompressed_data_chunk_size) {
  5848. decompressed_data.insert(decompressed_data.size(),
  5849. decompressed_data_chunk,
  5850. decompressed_data_chunk_size);
  5851. return true;
  5852. });
  5853. ASSERT_TRUE(result);
  5854. }
  5855. }
  5856. ASSERT_EQ(data, decompressed_data);
  5857. }
  5858. TEST(ZstdDecompressor, Decompress) {
  5859. std::string original_text = "Compressed with ZSTD";
  5860. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5861. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5862. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5863. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5864. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5865. std::string decompressed_data;
  5866. {
  5867. httplib::detail::zstd_decompressor decompressor;
  5868. bool result = decompressor.decompress(
  5869. compressed_data.data(), compressed_data.size(),
  5870. [&](const char *decompressed_data_chunk,
  5871. size_t decompressed_data_chunk_size) {
  5872. decompressed_data.insert(decompressed_data.size(),
  5873. decompressed_data_chunk,
  5874. decompressed_data_chunk_size);
  5875. return true;
  5876. });
  5877. ASSERT_TRUE(result);
  5878. }
  5879. ASSERT_EQ(original_text, decompressed_data);
  5880. }
  5881. #endif
  5882. // Sends a raw request to a server listening at HOST:PORT.
  5883. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5884. std::string *resp = nullptr) {
  5885. auto error = Error::Success;
  5886. auto client_sock = detail::create_client_socket(
  5887. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5888. /*connection_timeout_sec=*/5, 0,
  5889. /*read_timeout_sec=*/5, 0,
  5890. /*write_timeout_sec=*/5, 0, std::string(), error);
  5891. if (client_sock == INVALID_SOCKET) { return false; }
  5892. auto ret = detail::process_client_socket(
  5893. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5894. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5895. if (req.size() !=
  5896. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5897. return false;
  5898. }
  5899. char buf[512];
  5900. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5901. while (line_reader.getline()) {
  5902. if (resp) { *resp += line_reader.ptr(); }
  5903. }
  5904. return true;
  5905. });
  5906. detail::close_socket(client_sock);
  5907. return ret;
  5908. }
  5909. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5910. Server svr;
  5911. std::string header_value;
  5912. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5913. header_value = req.get_header_value("foo");
  5914. res.set_content("ok", "text/plain");
  5915. });
  5916. thread t = thread([&] { svr.listen(HOST, PORT); });
  5917. auto se = detail::scope_exit([&] {
  5918. svr.stop();
  5919. t.join();
  5920. ASSERT_FALSE(svr.is_running());
  5921. });
  5922. svr.wait_until_ready();
  5923. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5924. // like characters are not treated the same - use vertical tab and escape.
  5925. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5926. "foo: \t \v bar \x1B\t \r\n"
  5927. "Connection: close\r\n"
  5928. "\r\n";
  5929. std::string res;
  5930. ASSERT_TRUE(send_request(5, req, &res));
  5931. EXPECT_EQ(header_value, "");
  5932. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5933. }
  5934. // Sends a raw request and verifies that there isn't a crash or exception.
  5935. static void test_raw_request(const std::string &req,
  5936. std::string *out = nullptr) {
  5937. Server svr;
  5938. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5939. res.set_content("ok", "text/plain");
  5940. });
  5941. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5942. res.set_content("ok", "text/plain");
  5943. });
  5944. svr.Get("/header_field_value_check",
  5945. [&](const Request & /*req*/, Response &res) {
  5946. res.set_content("ok", "text/plain");
  5947. });
  5948. // Server read timeout must be longer than the client read timeout for the
  5949. // bug to reproduce, probably to force the server to process a request
  5950. // without a trailing blank line.
  5951. const time_t client_read_timeout_sec = 1;
  5952. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5953. bool listen_thread_ok = false;
  5954. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5955. auto se = detail::scope_exit([&] {
  5956. svr.stop();
  5957. t.join();
  5958. ASSERT_FALSE(svr.is_running());
  5959. EXPECT_TRUE(listen_thread_ok);
  5960. });
  5961. svr.wait_until_ready();
  5962. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5963. }
  5964. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5965. // A certain header line causes an exception if the header property is parsed
  5966. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5967. test_raw_request(
  5968. "GET /hi HTTP/1.1\r\n"
  5969. " : "
  5970. " "
  5971. " ");
  5972. }
  5973. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5974. // A certain header line causes an exception if the header property *name* is
  5975. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5976. // greedy matcher and requires backtracking when there are a lot of ":"
  5977. // characters.
  5978. // This occurs with libc++ but not libstdc++.
  5979. test_raw_request(
  5980. "GET /hi HTTP/1.1\r\n"
  5981. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5982. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5983. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5984. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5985. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5986. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5987. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5988. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5989. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5990. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5991. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5992. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5993. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5994. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5995. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5996. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5997. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5998. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5999. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6000. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6001. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6002. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6003. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6004. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6005. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6006. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6007. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6008. "&&&%%%");
  6009. }
  6010. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6011. // Make sure this doesn't crash the server.
  6012. // In a previous version of the header line regex, the "\r" rendered the line
  6013. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6014. // a new position where the leading white space ended and the field value
  6015. // began.
  6016. // The crash occurs with libc++ but not libstdc++.
  6017. test_raw_request("GET /hi HTTP/1.1\r\n"
  6018. "a:" +
  6019. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6020. "\r\n"
  6021. "\r\n");
  6022. }
  6023. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6024. std::string out;
  6025. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6026. "Content-Type: text/plain\r\n"
  6027. "Transfer-Encoding: chunked\r\n"
  6028. "\r\n"
  6029. "nothex\r\n",
  6030. &out);
  6031. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6032. }
  6033. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6034. std::string out;
  6035. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6036. "Content-Type: text/plain\r\n"
  6037. "Transfer-Encoding: chunked\r\n"
  6038. "\r\n"
  6039. "3\r\n"
  6040. "xyz\r\n"
  6041. "NaN\r\n",
  6042. &out);
  6043. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6044. }
  6045. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6046. std::string out;
  6047. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6048. "Content-Type: text/plain\r\n"
  6049. "Transfer-Encoding: chunked\r\n"
  6050. "\r\n"
  6051. // Length is too large for 64 bits.
  6052. "1ffffffffffffffff\r\n"
  6053. "xyz\r\n",
  6054. &out);
  6055. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6056. }
  6057. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6058. test_raw_request("GET /hi HTTP/1.1\r\n"
  6059. "Content-Type: text/plain\r\n\r");
  6060. }
  6061. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6062. std::string out;
  6063. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6064. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6065. }
  6066. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6067. Server svr;
  6068. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6069. EXPECT_TRUE(!req.remote_addr.empty());
  6070. });
  6071. thread t = thread([&] { svr.listen(HOST, PORT); });
  6072. auto se = detail::scope_exit([&] {
  6073. svr.stop();
  6074. t.join();
  6075. ASSERT_FALSE(svr.is_running());
  6076. });
  6077. svr.wait_until_ready();
  6078. // Send an invalid request line to trigger Bad Request
  6079. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6080. std::string out;
  6081. ASSERT_TRUE(send_request(5, bad_req, &out));
  6082. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6083. }
  6084. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6085. std::string out;
  6086. std::string request(
  6087. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6088. test_raw_request(request, &out);
  6089. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6090. }
  6091. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6092. std::string out;
  6093. std::string request(
  6094. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6095. test_raw_request(request, &out);
  6096. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6097. }
  6098. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6099. std::string out;
  6100. std::string request(
  6101. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6102. test_raw_request(request, &out);
  6103. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6104. }
  6105. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6106. std::string out;
  6107. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6108. "Test: \r\n\r\n",
  6109. &out);
  6110. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6111. }
  6112. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6113. Server svr;
  6114. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6115. res.set_header("Cache-Control", "no-cache");
  6116. res.set_chunked_content_provider(
  6117. "text/event-stream", [](size_t offset, DataSink &sink) {
  6118. std::string s = "data:";
  6119. s += std::to_string(offset);
  6120. s += "\n\n";
  6121. auto ret = sink.write(s.data(), s.size());
  6122. EXPECT_TRUE(ret);
  6123. std::this_thread::sleep_for(std::chrono::seconds(1));
  6124. return true;
  6125. });
  6126. });
  6127. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6128. svr.wait_until_ready();
  6129. Client client(HOST, PORT);
  6130. const Headers headers = {{"Accept", "text/event-stream"}};
  6131. auto get_thread = std::thread([&client, &headers]() {
  6132. auto res = client.Get(
  6133. "/events", headers,
  6134. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6135. });
  6136. auto se = detail::scope_exit([&] {
  6137. svr.stop();
  6138. get_thread.join();
  6139. listen_thread.join();
  6140. ASSERT_FALSE(svr.is_running());
  6141. });
  6142. // Give GET time to get a few messages.
  6143. std::this_thread::sleep_for(std::chrono::seconds(2));
  6144. }
  6145. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6146. httplib::Server svr;
  6147. svr.Post("/hi",
  6148. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6149. res.status = StatusCode::OK_200;
  6150. });
  6151. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6152. svr.wait_until_ready();
  6153. Client cli(HOST, PORT);
  6154. auto res = cli.Post("/hi", "data", "text/plain");
  6155. ASSERT_TRUE(res);
  6156. EXPECT_EQ(StatusCode::OK_200, res->status);
  6157. svr.stop();
  6158. thread.join();
  6159. ASSERT_FALSE(svr.is_running());
  6160. res = cli.Post("/hi", "data", "text/plain");
  6161. ASSERT_FALSE(res);
  6162. }
  6163. TEST(ServerStopTest, ListenFailure) {
  6164. Server svr;
  6165. auto t = thread([&]() {
  6166. auto ret = svr.listen("????", PORT);
  6167. EXPECT_FALSE(ret);
  6168. });
  6169. svr.wait_until_ready();
  6170. svr.stop();
  6171. t.join();
  6172. }
  6173. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6174. TEST(ServerStopTest, Decommision) {
  6175. Server svr;
  6176. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6177. for (int i = 0; i < 4; i++) {
  6178. auto is_even = !(i % 2);
  6179. std::thread t{[&] {
  6180. try {
  6181. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6182. if (is_even) {
  6183. throw std::runtime_error("Some thing that happens to go wrong.");
  6184. }
  6185. svr.listen(HOST, PORT);
  6186. } catch (...) { svr.decommission(); }
  6187. }};
  6188. svr.wait_until_ready();
  6189. // Server is up
  6190. {
  6191. Client cli(HOST, PORT);
  6192. auto res = cli.Get("/hi");
  6193. if (is_even) {
  6194. EXPECT_FALSE(res);
  6195. } else {
  6196. EXPECT_TRUE(res);
  6197. EXPECT_EQ("hi...", res->body);
  6198. }
  6199. }
  6200. svr.stop();
  6201. t.join();
  6202. // Server is down...
  6203. {
  6204. Client cli(HOST, PORT);
  6205. auto res = cli.Get("/hi");
  6206. EXPECT_FALSE(res);
  6207. }
  6208. }
  6209. }
  6210. #endif
  6211. // Helper function for string body upload progress tests
  6212. template <typename SetupHandler, typename ClientCall>
  6213. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6214. ClientCall &&client_call,
  6215. const string &body) {
  6216. Server svr;
  6217. setup_handler(svr);
  6218. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6219. auto se = detail::scope_exit([&] {
  6220. svr.stop();
  6221. t.join();
  6222. });
  6223. svr.wait_until_ready();
  6224. Client cli(HOST, PORT);
  6225. vector<uint64_t> progress_values;
  6226. bool progress_called = false;
  6227. auto res =
  6228. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6229. progress_values.push_back(current);
  6230. progress_called = true;
  6231. return true;
  6232. });
  6233. ASSERT_TRUE(res);
  6234. EXPECT_EQ(200, res->status);
  6235. EXPECT_TRUE(progress_called);
  6236. }
  6237. TEST(UploadProgressTest, PostStringBodyBasic) {
  6238. TestStringBodyUploadProgress(
  6239. [](Server &svr) {
  6240. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6241. res.set_content("received", "text/plain");
  6242. });
  6243. },
  6244. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6245. return cli.Post("/test", body, "text/plain", progress_callback);
  6246. },
  6247. "test data for upload progress");
  6248. }
  6249. TEST(UploadProgressTest, PutStringBodyBasic) {
  6250. TestStringBodyUploadProgress(
  6251. [](Server &svr) {
  6252. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6253. res.set_content("put received", "text/plain");
  6254. });
  6255. },
  6256. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6257. return cli.Put("/test", body, "text/plain", progress_callback);
  6258. },
  6259. "put test data for upload progress");
  6260. }
  6261. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6262. TestStringBodyUploadProgress(
  6263. [](Server &svr) {
  6264. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6265. res.set_content("patch received", "text/plain");
  6266. });
  6267. },
  6268. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6269. return cli.Patch("/test", body, "text/plain", progress_callback);
  6270. },
  6271. "patch test data for upload progress");
  6272. }
  6273. // Helper function for content provider upload progress tests
  6274. template <typename SetupHandler, typename ClientCall>
  6275. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6276. ClientCall &&client_call) {
  6277. Server svr;
  6278. setup_handler(svr);
  6279. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6280. auto se = detail::scope_exit([&] {
  6281. svr.stop();
  6282. t.join();
  6283. });
  6284. svr.wait_until_ready();
  6285. Client cli(HOST, PORT);
  6286. vector<uint64_t> progress_values;
  6287. auto res =
  6288. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6289. progress_values.push_back(current);
  6290. return true;
  6291. });
  6292. ASSERT_TRUE(res);
  6293. EXPECT_EQ(200, res->status);
  6294. EXPECT_FALSE(progress_values.empty());
  6295. }
  6296. TEST(UploadProgressTest, PostContentProviderProgress) {
  6297. TestContentProviderUploadProgress(
  6298. [](Server &svr) {
  6299. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6300. res.set_content("provider received", "text/plain");
  6301. });
  6302. },
  6303. [](Client &cli, UploadProgress progress_callback) {
  6304. return cli.Post(
  6305. "/test", 10,
  6306. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6307. sink.os << "test data";
  6308. return true;
  6309. },
  6310. "text/plain", progress_callback);
  6311. });
  6312. }
  6313. // Helper function for multipart upload progress tests
  6314. template <typename SetupHandler, typename ClientCall>
  6315. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6316. ClientCall &&client_call,
  6317. const string &endpoint) {
  6318. Server svr;
  6319. setup_handler(svr);
  6320. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6321. auto se = detail::scope_exit([&] {
  6322. svr.stop();
  6323. t.join();
  6324. });
  6325. svr.wait_until_ready();
  6326. Client cli(HOST, PORT);
  6327. vector<uint64_t> progress_values;
  6328. UploadFormDataItems items = {
  6329. {"field1", "value1", "", ""},
  6330. {"field2", "longer value for progress tracking test", "", ""},
  6331. {"file1", "file content data for upload progress", "test.txt",
  6332. "text/plain"}};
  6333. auto res = client_call(cli, endpoint, items,
  6334. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6335. progress_values.push_back(current);
  6336. return true;
  6337. });
  6338. ASSERT_TRUE(res);
  6339. EXPECT_EQ(200, res->status);
  6340. EXPECT_FALSE(progress_values.empty());
  6341. }
  6342. TEST(UploadProgressTest, PostMultipartProgress) {
  6343. TestMultipartUploadProgress(
  6344. [](Server &svr) {
  6345. svr.Post("/multipart", [](const Request &req, Response &res) {
  6346. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6347. res.set_content("multipart received", "text/plain");
  6348. });
  6349. },
  6350. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6351. UploadProgress progress_callback) {
  6352. return cli.Post(endpoint, items, progress_callback);
  6353. },
  6354. "/multipart");
  6355. }
  6356. // Helper function for basic download progress tests
  6357. template <typename SetupHandler, typename ClientCall>
  6358. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6359. ClientCall &&client_call, const string &endpoint,
  6360. size_t expected_content_size) {
  6361. Server svr;
  6362. setup_handler(svr);
  6363. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6364. auto se = detail::scope_exit([&] {
  6365. svr.stop();
  6366. t.join();
  6367. });
  6368. svr.wait_until_ready();
  6369. Client cli(HOST, PORT);
  6370. vector<uint64_t> progress_values;
  6371. auto res = client_call(cli, endpoint,
  6372. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6373. progress_values.push_back(current);
  6374. return true;
  6375. });
  6376. ASSERT_TRUE(res);
  6377. EXPECT_EQ(200, res->status);
  6378. EXPECT_FALSE(progress_values.empty());
  6379. EXPECT_EQ(expected_content_size, res->body.size());
  6380. }
  6381. TEST(DownloadProgressTest, GetBasic) {
  6382. TestBasicDownloadProgress(
  6383. [](Server &svr) {
  6384. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6385. string content(1000, 'D');
  6386. res.set_content(content, "text/plain");
  6387. });
  6388. },
  6389. [](Client &cli, const string &endpoint,
  6390. DownloadProgress progress_callback) {
  6391. return cli.Get(endpoint, progress_callback);
  6392. },
  6393. "/download", 1000u);
  6394. }
  6395. // Helper function for content receiver download progress tests
  6396. template <typename SetupHandler, typename ClientCall>
  6397. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6398. ClientCall &&client_call,
  6399. const string &endpoint,
  6400. size_t expected_content_size) {
  6401. Server svr;
  6402. setup_handler(svr);
  6403. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6404. auto se = detail::scope_exit([&] {
  6405. svr.stop();
  6406. t.join();
  6407. });
  6408. svr.wait_until_ready();
  6409. Client cli(HOST, PORT);
  6410. vector<uint64_t> progress_values;
  6411. string received_body;
  6412. auto res = client_call(
  6413. cli, endpoint,
  6414. [&](const char *data, size_t data_length) -> bool {
  6415. received_body.append(data, data_length);
  6416. return true;
  6417. },
  6418. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6419. progress_values.push_back(current);
  6420. return true;
  6421. });
  6422. ASSERT_TRUE(res);
  6423. EXPECT_EQ(200, res->status);
  6424. EXPECT_FALSE(progress_values.empty());
  6425. EXPECT_EQ(expected_content_size, received_body.size());
  6426. EXPECT_TRUE(res->body.empty());
  6427. }
  6428. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6429. TestContentReceiverDownloadProgress(
  6430. [](Server &svr) {
  6431. svr.Get("/download-receiver",
  6432. [](const Request & /*req*/, Response &res) {
  6433. string content(2000, 'R');
  6434. res.set_content(content, "text/plain");
  6435. });
  6436. },
  6437. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6438. DownloadProgress progress_callback) {
  6439. return cli.Get(endpoint, content_receiver, progress_callback);
  6440. },
  6441. "/download-receiver", 2000u);
  6442. }
  6443. TEST(StreamingTest, NoContentLengthStreaming) {
  6444. Server svr;
  6445. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6446. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6447. if (offset < 6) {
  6448. sink.os << (offset < 3 ? "a" : "b");
  6449. } else {
  6450. sink.done();
  6451. }
  6452. return true;
  6453. });
  6454. });
  6455. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6456. auto listen_se = detail::scope_exit([&] {
  6457. svr.stop();
  6458. listen_thread.join();
  6459. ASSERT_FALSE(svr.is_running());
  6460. });
  6461. svr.wait_until_ready();
  6462. Client client(HOST, PORT);
  6463. auto get_thread = std::thread([&client]() {
  6464. std::string s;
  6465. auto res =
  6466. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6467. s += std::string(data, len);
  6468. return true;
  6469. });
  6470. ASSERT_TRUE(res);
  6471. EXPECT_EQ(StatusCode::OK_200, res->status);
  6472. EXPECT_EQ("aaabbb", s);
  6473. });
  6474. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6475. // Give GET time to get a few messages.
  6476. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6477. }
  6478. TEST(MountTest, Unmount) {
  6479. Server svr;
  6480. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6481. auto se = detail::scope_exit([&] {
  6482. svr.stop();
  6483. listen_thread.join();
  6484. ASSERT_FALSE(svr.is_running());
  6485. });
  6486. svr.wait_until_ready();
  6487. Client cli("localhost", PORT);
  6488. svr.set_mount_point("/mount2", "./www2");
  6489. auto res = cli.Get("/");
  6490. ASSERT_TRUE(res);
  6491. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6492. res = cli.Get("/mount2/dir/test.html");
  6493. ASSERT_TRUE(res);
  6494. EXPECT_EQ(StatusCode::OK_200, res->status);
  6495. svr.set_mount_point("/", "./www");
  6496. res = cli.Get("/dir/");
  6497. ASSERT_TRUE(res);
  6498. EXPECT_EQ(StatusCode::OK_200, res->status);
  6499. svr.remove_mount_point("/");
  6500. res = cli.Get("/dir/");
  6501. ASSERT_TRUE(res);
  6502. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6503. svr.remove_mount_point("/mount2");
  6504. res = cli.Get("/mount2/dir/test.html");
  6505. ASSERT_TRUE(res);
  6506. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6507. }
  6508. TEST(MountTest, Redicect) {
  6509. Server svr;
  6510. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6511. auto se = detail::scope_exit([&] {
  6512. svr.stop();
  6513. listen_thread.join();
  6514. ASSERT_FALSE(svr.is_running());
  6515. });
  6516. svr.set_mount_point("/", "./www");
  6517. svr.wait_until_ready();
  6518. Client cli("localhost", PORT);
  6519. auto res = cli.Get("/dir/");
  6520. ASSERT_TRUE(res);
  6521. EXPECT_EQ(StatusCode::OK_200, res->status);
  6522. res = cli.Get("/dir");
  6523. ASSERT_TRUE(res);
  6524. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6525. res = cli.Get("/file");
  6526. ASSERT_TRUE(res);
  6527. EXPECT_EQ(StatusCode::OK_200, res->status);
  6528. res = cli.Get("/file/");
  6529. ASSERT_TRUE(res);
  6530. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6531. cli.set_follow_location(true);
  6532. res = cli.Get("/dir");
  6533. ASSERT_TRUE(res);
  6534. EXPECT_EQ(StatusCode::OK_200, res->status);
  6535. }
  6536. TEST(MountTest, MultibytesPathName) {
  6537. Server svr;
  6538. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6539. auto se = detail::scope_exit([&] {
  6540. svr.stop();
  6541. listen_thread.join();
  6542. ASSERT_FALSE(svr.is_running());
  6543. });
  6544. svr.set_mount_point("/", "./www");
  6545. svr.wait_until_ready();
  6546. Client cli("localhost", PORT);
  6547. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6548. ASSERT_TRUE(res);
  6549. EXPECT_EQ(StatusCode::OK_200, res->status);
  6550. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6551. }
  6552. TEST(KeepAliveTest, ReadTimeout) {
  6553. Server svr;
  6554. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6555. std::this_thread::sleep_for(std::chrono::seconds(2));
  6556. res.set_content("a", "text/plain");
  6557. });
  6558. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6559. res.set_content("b", "text/plain");
  6560. });
  6561. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6562. auto se = detail::scope_exit([&] {
  6563. svr.stop();
  6564. listen_thread.join();
  6565. ASSERT_FALSE(svr.is_running());
  6566. });
  6567. svr.wait_until_ready();
  6568. Client cli("localhost", PORT);
  6569. cli.set_keep_alive(true);
  6570. cli.set_read_timeout(std::chrono::seconds(1));
  6571. auto resa = cli.Get("/a");
  6572. ASSERT_FALSE(resa);
  6573. EXPECT_EQ(Error::Read, resa.error());
  6574. auto resb = cli.Get("/b");
  6575. ASSERT_TRUE(resb);
  6576. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6577. EXPECT_EQ("b", resb->body);
  6578. }
  6579. TEST(KeepAliveTest, MaxCount) {
  6580. size_t keep_alive_max_count = 3;
  6581. Server svr;
  6582. svr.set_keep_alive_max_count(keep_alive_max_count);
  6583. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6584. res.set_content("Hello World!", "text/plain");
  6585. });
  6586. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6587. auto se = detail::scope_exit([&] {
  6588. svr.stop();
  6589. listen_thread.join();
  6590. ASSERT_FALSE(svr.is_running());
  6591. });
  6592. svr.wait_until_ready();
  6593. Client cli(HOST, PORT);
  6594. cli.set_keep_alive(true);
  6595. for (size_t i = 0; i < 5; i++) {
  6596. auto result = cli.Get("/hi");
  6597. ASSERT_TRUE(result);
  6598. EXPECT_EQ(StatusCode::OK_200, result->status);
  6599. if (i == keep_alive_max_count - 1) {
  6600. EXPECT_EQ("close", result->get_header_value("Connection"));
  6601. } else {
  6602. EXPECT_FALSE(result->has_header("Connection"));
  6603. }
  6604. }
  6605. }
  6606. TEST(KeepAliveTest, Issue1041) {
  6607. Server svr;
  6608. svr.set_keep_alive_timeout(3);
  6609. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6610. res.set_content("Hello World!", "text/plain");
  6611. });
  6612. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6613. auto se = detail::scope_exit([&] {
  6614. svr.stop();
  6615. listen_thread.join();
  6616. ASSERT_FALSE(svr.is_running());
  6617. });
  6618. svr.wait_until_ready();
  6619. Client cli(HOST, PORT);
  6620. cli.set_keep_alive(true);
  6621. auto result = cli.Get("/hi");
  6622. ASSERT_TRUE(result);
  6623. EXPECT_EQ(StatusCode::OK_200, result->status);
  6624. std::this_thread::sleep_for(std::chrono::seconds(5));
  6625. result = cli.Get("/hi");
  6626. ASSERT_TRUE(result);
  6627. EXPECT_EQ(StatusCode::OK_200, result->status);
  6628. }
  6629. TEST(KeepAliveTest, Issue1959) {
  6630. Server svr;
  6631. svr.set_keep_alive_timeout(5);
  6632. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6633. res.set_content("a", "text/plain");
  6634. });
  6635. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6636. auto se = detail::scope_exit([&] {
  6637. if (!svr.is_running()) return;
  6638. svr.stop();
  6639. listen_thread.join();
  6640. ASSERT_FALSE(svr.is_running());
  6641. });
  6642. svr.wait_until_ready();
  6643. Client cli("localhost", PORT);
  6644. cli.set_keep_alive(true);
  6645. using namespace std::chrono;
  6646. auto start = steady_clock::now();
  6647. cli.Get("/a");
  6648. svr.stop();
  6649. listen_thread.join();
  6650. auto end = steady_clock::now();
  6651. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6652. EXPECT_LT(elapsed, 5000);
  6653. }
  6654. #ifdef CPPHTTPLIB_SSL_ENABLED
  6655. TEST(KeepAliveTest, SSLClientReconnection) {
  6656. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6657. ASSERT_TRUE(svr.is_valid());
  6658. svr.set_keep_alive_timeout(1);
  6659. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6660. res.set_content("Hello World!", "text/plain");
  6661. });
  6662. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6663. auto se = detail::scope_exit([&] {
  6664. svr.stop();
  6665. listen_thread.join();
  6666. ASSERT_FALSE(svr.is_running());
  6667. });
  6668. svr.wait_until_ready();
  6669. SSLClient cli(HOST, PORT);
  6670. cli.enable_server_certificate_verification(false);
  6671. cli.set_keep_alive(true);
  6672. auto result = cli.Get("/hi");
  6673. ASSERT_TRUE(result);
  6674. EXPECT_EQ(StatusCode::OK_200, result->status);
  6675. result = cli.Get("/hi");
  6676. ASSERT_TRUE(result);
  6677. EXPECT_EQ(StatusCode::OK_200, result->status);
  6678. std::this_thread::sleep_for(std::chrono::seconds(2));
  6679. // Recoonect
  6680. result = cli.Get("/hi");
  6681. ASSERT_TRUE(result);
  6682. EXPECT_EQ(StatusCode::OK_200, result->status);
  6683. result = cli.Get("/hi");
  6684. ASSERT_TRUE(result);
  6685. EXPECT_EQ(StatusCode::OK_200, result->status);
  6686. }
  6687. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6688. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6689. ASSERT_TRUE(svr.is_valid());
  6690. svr.set_keep_alive_timeout(1);
  6691. std::string content = "reconnect";
  6692. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6693. res.set_content("Hello World!", "text/plain");
  6694. });
  6695. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6696. auto se = detail::scope_exit([&] {
  6697. svr.stop();
  6698. listen_thread.join();
  6699. ASSERT_FALSE(svr.is_running());
  6700. });
  6701. svr.wait_until_ready();
  6702. SSLClient cli(HOST, PORT);
  6703. cli.enable_server_certificate_verification(false);
  6704. cli.set_keep_alive(true);
  6705. auto result = cli.Post(
  6706. "/hi", content.size(),
  6707. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6708. sink.write(content.c_str(), content.size());
  6709. return true;
  6710. },
  6711. "text/plain");
  6712. ASSERT_TRUE(result);
  6713. EXPECT_EQ(200, result->status);
  6714. std::this_thread::sleep_for(std::chrono::seconds(2));
  6715. // Recoonect
  6716. result = cli.Post(
  6717. "/hi", content.size(),
  6718. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6719. sink.write(content.c_str(), content.size());
  6720. return true;
  6721. },
  6722. "text/plain");
  6723. ASSERT_TRUE(result);
  6724. EXPECT_EQ(200, result->status);
  6725. result = cli.Post(
  6726. "/hi", content.size(),
  6727. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6728. sink.write(content.c_str(), content.size());
  6729. return true;
  6730. },
  6731. "text/plain");
  6732. ASSERT_TRUE(result);
  6733. EXPECT_EQ(200, result->status);
  6734. }
  6735. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6736. using namespace httplib::tls;
  6737. {
  6738. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6739. ASSERT_TRUE(svr.is_valid());
  6740. svr.Get("/sni", [&](const Request &req, Response &res) {
  6741. std::string expected = req.sni();
  6742. EXPECT_EQ(expected, req.get_param_value("expected"));
  6743. res.set_content("ok", "text/plain");
  6744. });
  6745. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6746. auto se = detail::scope_exit([&] {
  6747. svr.stop();
  6748. listen_thread.join();
  6749. ASSERT_FALSE(svr.is_running());
  6750. });
  6751. svr.wait_until_ready();
  6752. {
  6753. SSLClient cli("localhost", PORT);
  6754. cli.enable_server_certificate_verification(false);
  6755. auto res = cli.Get("/sni?expected=localhost");
  6756. ASSERT_TRUE(res);
  6757. }
  6758. {
  6759. SSLClient cli("::1", PORT);
  6760. cli.enable_server_certificate_verification(false);
  6761. auto res = cli.Get("/sni?expected=");
  6762. // NOTE: This may fail if the server is listening on IPv4 only
  6763. // (e.g., when localhost resolves to 127.0.0.1 only)
  6764. if (res) {
  6765. EXPECT_EQ(StatusCode::OK_200, res->status);
  6766. } else {
  6767. EXPECT_EQ(Error::Connection, res.error());
  6768. }
  6769. }
  6770. }
  6771. }
  6772. #endif
  6773. TEST(ClientProblemDetectionTest, ContentProvider) {
  6774. Server svr;
  6775. size_t content_length = 1024 * 1024;
  6776. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6777. res.set_content_provider(
  6778. content_length, "text/plain",
  6779. [&](size_t offset, size_t length, DataSink &sink) {
  6780. auto out_len = std::min(length, static_cast<size_t>(1024));
  6781. std::string out(out_len, '@');
  6782. sink.write(out.data(), out_len);
  6783. return offset < 4096;
  6784. },
  6785. [](bool success) { ASSERT_FALSE(success); });
  6786. });
  6787. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6788. res.set_content_provider(
  6789. 0, "text/plain",
  6790. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6791. EXPECT_TRUE(false);
  6792. return true;
  6793. },
  6794. [](bool success) { ASSERT_FALSE(success); });
  6795. });
  6796. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6797. auto se = detail::scope_exit([&] {
  6798. svr.stop();
  6799. listen_thread.join();
  6800. ASSERT_FALSE(svr.is_running());
  6801. });
  6802. svr.wait_until_ready();
  6803. Client cli("localhost", PORT);
  6804. {
  6805. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6806. size_t /*data_length*/) { return false; });
  6807. ASSERT_FALSE(res);
  6808. }
  6809. {
  6810. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6811. size_t /*data_length*/) { return false; });
  6812. ASSERT_TRUE(res);
  6813. }
  6814. }
  6815. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6816. Server svr;
  6817. svr.set_error_handler([](Request const &, Response &res) -> void {
  6818. res.set_chunked_content_provider(
  6819. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6820. sink.os << "hello";
  6821. sink.os << "world";
  6822. sink.done();
  6823. return true;
  6824. });
  6825. });
  6826. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6827. auto se = detail::scope_exit([&] {
  6828. svr.stop();
  6829. listen_thread.join();
  6830. ASSERT_FALSE(svr.is_running());
  6831. });
  6832. svr.wait_until_ready();
  6833. Client cli("localhost", PORT);
  6834. auto res = cli.Get("/");
  6835. ASSERT_TRUE(res);
  6836. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6837. EXPECT_EQ("helloworld", res->body);
  6838. }
  6839. TEST(LongPollingTest, ClientCloseDetection) {
  6840. Server svr;
  6841. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6842. res.set_chunked_content_provider(
  6843. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6844. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6845. sink.os << "hello";
  6846. auto count = 10;
  6847. while (count > 0 && sink.is_writable()) {
  6848. this_thread::sleep_for(chrono::milliseconds(10));
  6849. count--;
  6850. }
  6851. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6852. return true;
  6853. });
  6854. });
  6855. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6856. auto se = detail::scope_exit([&] {
  6857. svr.stop();
  6858. listen_thread.join();
  6859. ASSERT_FALSE(svr.is_running());
  6860. });
  6861. svr.wait_until_ready();
  6862. Client cli("localhost", PORT);
  6863. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6864. EXPECT_EQ("hello", string(data, data_length));
  6865. return false; // close the socket immediately.
  6866. });
  6867. ASSERT_FALSE(res);
  6868. }
  6869. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  6870. Server svr;
  6871. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6872. res.set_chunked_content_provider(
  6873. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6874. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6875. sink.os << "hello";
  6876. EXPECT_TRUE(sink.os.good());
  6877. // Wait for the client to close the connection
  6878. auto count = 10;
  6879. while (count > 0 && sink.is_writable()) {
  6880. this_thread::sleep_for(chrono::milliseconds(10));
  6881. count--;
  6882. }
  6883. // After client disconnect, write repeatedly until the socket
  6884. // write actually fails (small writes may be absorbed by the
  6885. // kernel buffer)
  6886. std::string chunk(1024, 'x');
  6887. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  6888. sink.os << chunk;
  6889. }
  6890. EXPECT_TRUE(sink.os.fail());
  6891. return true;
  6892. });
  6893. });
  6894. auto port = svr.bind_to_any_port("localhost");
  6895. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  6896. auto se = detail::scope_exit([&] {
  6897. svr.stop();
  6898. listen_thread.join();
  6899. ASSERT_FALSE(svr.is_running());
  6900. });
  6901. svr.wait_until_ready();
  6902. Client cli("localhost", port);
  6903. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6904. EXPECT_EQ("hello", string(data, data_length));
  6905. return false; // close the socket immediately.
  6906. });
  6907. ASSERT_FALSE(res);
  6908. }
  6909. TEST(GetWithParametersTest, GetWithParameters) {
  6910. Server svr;
  6911. svr.Get("/", [&](const Request &req, Response &) {
  6912. EXPECT_EQ("world", req.get_param_value("hello"));
  6913. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6914. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6915. });
  6916. svr.Get("/params", [&](const Request &req, Response &) {
  6917. EXPECT_EQ("world", req.get_param_value("hello"));
  6918. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6919. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6920. });
  6921. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6922. EXPECT_EQ("resource-id", req.matches[1]);
  6923. EXPECT_EQ("foo", req.get_param_value("param1"));
  6924. EXPECT_EQ("bar", req.get_param_value("param2"));
  6925. });
  6926. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6927. EXPECT_EQ("user-id", req.path_params.at("id"));
  6928. EXPECT_EQ("foo", req.get_param_value("param1"));
  6929. EXPECT_EQ("bar", req.get_param_value("param2"));
  6930. });
  6931. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6932. auto se = detail::scope_exit([&] {
  6933. svr.stop();
  6934. listen_thread.join();
  6935. ASSERT_FALSE(svr.is_running());
  6936. });
  6937. svr.wait_until_ready();
  6938. {
  6939. Client cli(HOST, PORT);
  6940. Params params;
  6941. params.emplace("hello", "world");
  6942. params.emplace("hello2", "world2");
  6943. params.emplace("hello3", "world3");
  6944. auto res = cli.Get("/", params, Headers{});
  6945. ASSERT_TRUE(res);
  6946. EXPECT_EQ(StatusCode::OK_200, res->status);
  6947. }
  6948. {
  6949. Client cli(HOST, PORT);
  6950. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6951. ASSERT_TRUE(res);
  6952. EXPECT_EQ(StatusCode::OK_200, res->status);
  6953. }
  6954. {
  6955. Client cli(HOST, PORT);
  6956. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6957. ASSERT_TRUE(res);
  6958. EXPECT_EQ(StatusCode::OK_200, res->status);
  6959. }
  6960. {
  6961. Client cli(HOST, PORT);
  6962. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6963. ASSERT_TRUE(res);
  6964. EXPECT_EQ(StatusCode::OK_200, res->status);
  6965. }
  6966. }
  6967. TEST(GetWithParametersTest, GetWithParameters2) {
  6968. Server svr;
  6969. svr.Get("/", [&](const Request &req, Response &res) {
  6970. auto text = req.get_param_value("hello");
  6971. res.set_content(text, "text/plain");
  6972. });
  6973. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6974. auto se = detail::scope_exit([&] {
  6975. svr.stop();
  6976. listen_thread.join();
  6977. ASSERT_FALSE(svr.is_running());
  6978. });
  6979. svr.wait_until_ready();
  6980. Client cli("localhost", PORT);
  6981. Params params;
  6982. params.emplace("hello", "world");
  6983. std::string body;
  6984. auto res = cli.Get("/", params, Headers{},
  6985. [&](const char *data, size_t data_length) {
  6986. body.append(data, data_length);
  6987. return true;
  6988. });
  6989. ASSERT_TRUE(res);
  6990. EXPECT_EQ(StatusCode::OK_200, res->status);
  6991. EXPECT_EQ("world", body);
  6992. }
  6993. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6994. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6995. auto host = "httpcan.org";
  6996. auto path = std::string{"/range/32"};
  6997. #else
  6998. auto host = "nghttp2.org";
  6999. auto path = std::string{"/httpbin/range/32"};
  7000. #endif
  7001. #ifdef CPPHTTPLIB_SSL_ENABLED
  7002. SSLClient cli(host);
  7003. #else
  7004. Client cli(host);
  7005. #endif
  7006. cli.set_default_headers({make_range_header({{1, 10}})});
  7007. cli.set_connection_timeout(5);
  7008. {
  7009. auto res = cli.Get(path);
  7010. ASSERT_TRUE(res);
  7011. EXPECT_EQ("bcdefghijk", res->body);
  7012. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7013. }
  7014. {
  7015. auto res = cli.Get(path);
  7016. ASSERT_TRUE(res);
  7017. EXPECT_EQ("bcdefghijk", res->body);
  7018. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7019. }
  7020. }
  7021. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7022. Server svr;
  7023. svr.set_default_headers({{"Hello", "World"}});
  7024. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7025. res.set_content("ok", "text/plain");
  7026. });
  7027. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7028. auto se = detail::scope_exit([&] {
  7029. svr.stop();
  7030. listen_thread.join();
  7031. ASSERT_FALSE(svr.is_running());
  7032. });
  7033. svr.wait_until_ready();
  7034. Client cli("localhost", PORT);
  7035. auto res = cli.Get("/");
  7036. ASSERT_TRUE(res);
  7037. EXPECT_EQ(StatusCode::OK_200, res->status);
  7038. EXPECT_EQ("ok", res->body);
  7039. EXPECT_EQ("World", res->get_header_value("Hello"));
  7040. }
  7041. #ifdef CPPHTTPLIB_SSL_ENABLED
  7042. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7043. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7044. ASSERT_TRUE(svr.is_valid());
  7045. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7046. std::this_thread::sleep_for(std::chrono::seconds(2));
  7047. res.set_content("a", "text/plain");
  7048. });
  7049. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7050. res.set_content("b", "text/plain");
  7051. });
  7052. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7053. auto se = detail::scope_exit([&] {
  7054. svr.stop();
  7055. listen_thread.join();
  7056. ASSERT_FALSE(svr.is_running());
  7057. });
  7058. svr.wait_until_ready();
  7059. SSLClient cli("localhost", PORT);
  7060. cli.enable_server_certificate_verification(false);
  7061. cli.set_keep_alive(true);
  7062. cli.set_read_timeout(std::chrono::seconds(1));
  7063. auto resa = cli.Get("/a");
  7064. ASSERT_TRUE(!resa);
  7065. EXPECT_EQ(Error::Read, resa.error());
  7066. auto resb = cli.Get("/b");
  7067. ASSERT_TRUE(resb);
  7068. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7069. EXPECT_EQ("b", resb->body);
  7070. }
  7071. #endif
  7072. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7073. protected:
  7074. ServerTestWithAI_PASSIVE()
  7075. : cli_(HOST, PORT)
  7076. #ifdef CPPHTTPLIB_SSL_ENABLED
  7077. ,
  7078. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7079. #endif
  7080. {
  7081. #ifdef CPPHTTPLIB_SSL_ENABLED
  7082. cli_.enable_server_certificate_verification(false);
  7083. #endif
  7084. }
  7085. virtual void SetUp() {
  7086. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7087. res.set_content("Hello World!", "text/plain");
  7088. });
  7089. t_ = thread(
  7090. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7091. svr_.wait_until_ready();
  7092. }
  7093. virtual void TearDown() {
  7094. svr_.stop();
  7095. t_.join();
  7096. }
  7097. #ifdef CPPHTTPLIB_SSL_ENABLED
  7098. SSLClient cli_;
  7099. SSLServer svr_;
  7100. #else
  7101. Client cli_;
  7102. Server svr_;
  7103. #endif
  7104. thread t_;
  7105. };
  7106. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7107. auto res = cli_.Get("/hi");
  7108. ASSERT_TRUE(res);
  7109. EXPECT_EQ(StatusCode::OK_200, res->status);
  7110. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7111. EXPECT_EQ("Hello World!", res->body);
  7112. }
  7113. class ServerUpDownTest : public ::testing::Test {
  7114. protected:
  7115. ServerUpDownTest() : cli_(HOST, PORT) {}
  7116. virtual void SetUp() {
  7117. t_ = thread([&]() {
  7118. svr_.bind_to_any_port(HOST);
  7119. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7120. ASSERT_TRUE(svr_.listen_after_bind());
  7121. });
  7122. svr_.wait_until_ready();
  7123. }
  7124. virtual void TearDown() {
  7125. svr_.stop();
  7126. t_.join();
  7127. }
  7128. Client cli_;
  7129. Server svr_;
  7130. thread t_;
  7131. };
  7132. TEST_F(ServerUpDownTest, QuickStartStop) {
  7133. // Should not crash, especially when run with
  7134. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7135. }
  7136. class PayloadMaxLengthTest : public ::testing::Test {
  7137. protected:
  7138. PayloadMaxLengthTest()
  7139. : cli_(HOST, PORT)
  7140. #ifdef CPPHTTPLIB_SSL_ENABLED
  7141. ,
  7142. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7143. #endif
  7144. {
  7145. #ifdef CPPHTTPLIB_SSL_ENABLED
  7146. cli_.enable_server_certificate_verification(false);
  7147. #endif
  7148. }
  7149. virtual void SetUp() {
  7150. svr_.set_payload_max_length(8);
  7151. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7152. res.set_content("test", "text/plain");
  7153. });
  7154. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7155. svr_.wait_until_ready();
  7156. }
  7157. virtual void TearDown() {
  7158. svr_.stop();
  7159. t_.join();
  7160. }
  7161. #ifdef CPPHTTPLIB_SSL_ENABLED
  7162. SSLClient cli_;
  7163. SSLServer svr_;
  7164. #else
  7165. Client cli_;
  7166. Server svr_;
  7167. #endif
  7168. thread t_;
  7169. };
  7170. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7171. auto res = cli_.Post("/test", "123456789", "text/plain");
  7172. ASSERT_TRUE(res);
  7173. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7174. res = cli_.Post("/test", "12345678", "text/plain");
  7175. ASSERT_TRUE(res);
  7176. EXPECT_EQ(StatusCode::OK_200, res->status);
  7177. }
  7178. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7179. // Test chunked encoding with payload exceeding the 8-byte limit
  7180. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7181. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7182. ASSERT_TRUE(res);
  7183. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7184. }
  7185. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7186. // Test chunked encoding with payload within the 8-byte limit
  7187. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7188. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7189. ASSERT_TRUE(res);
  7190. EXPECT_EQ(StatusCode::OK_200, res->status);
  7191. }
  7192. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7193. // Test using send_request to send chunked data exceeding payload limit
  7194. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7195. "Host: " +
  7196. std::string(HOST) + ":" + std::to_string(PORT) +
  7197. "\r\n"
  7198. "Transfer-Encoding: chunked\r\n"
  7199. "Connection: close\r\n"
  7200. "\r\n"
  7201. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7202. "0123456789\r\n"
  7203. "0\r\n" // End chunk
  7204. "\r\n";
  7205. std::string response;
  7206. bool result = send_request(1, chunked_request, &response);
  7207. if (!result) {
  7208. // If send_request fails, it might be because the server closed the
  7209. // connection due to payload limit enforcement, which is acceptable
  7210. SUCCEED()
  7211. << "Server rejected oversized chunked request (connection closed)";
  7212. } else {
  7213. // If we got a response, check if it's an error response or connection was
  7214. // closed early Short response length indicates connection was closed due to
  7215. // payload limit
  7216. if (response.length() <= 10) {
  7217. SUCCEED() << "Server closed connection for oversized chunked request";
  7218. } else {
  7219. // Check for error status codes
  7220. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7221. response.find("Payload Too Large") != std::string::npos ||
  7222. response.find("400") != std::string::npos);
  7223. }
  7224. }
  7225. }
  7226. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7227. // Test request without Content-Length header exceeding payload limit
  7228. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7229. "Host: " +
  7230. std::string(HOST) + ":" +
  7231. std::to_string(PORT) +
  7232. "\r\n"
  7233. "Connection: close\r\n"
  7234. "\r\n";
  7235. // Add payload exceeding the 8-byte limit
  7236. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7237. request_without_content_length += large_payload;
  7238. std::string response;
  7239. bool result = send_request(1, request_without_content_length, &response);
  7240. if (!result) {
  7241. // If send_request fails, server likely closed connection due to payload
  7242. // limit
  7243. SUCCEED() << "Server rejected oversized request without Content-Length "
  7244. "(connection closed)";
  7245. } else {
  7246. // Check if server responded with error or closed connection early
  7247. if (response.length() <= 10) {
  7248. SUCCEED() << "Server closed connection for oversized request without "
  7249. "Content-Length";
  7250. } else {
  7251. // Check for error status codes
  7252. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7253. response.find("Payload Too Large") != std::string::npos ||
  7254. response.find("400") != std::string::npos);
  7255. }
  7256. }
  7257. }
  7258. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7259. // Test request without Content-Length header within payload limit
  7260. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7261. "Host: " +
  7262. std::string(HOST) + ":" +
  7263. std::to_string(PORT) +
  7264. "\r\n"
  7265. "Connection: close\r\n"
  7266. "\r\n";
  7267. // Add payload within the 8-byte limit
  7268. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7269. request_without_content_length += small_payload;
  7270. std::string response;
  7271. bool result = send_request(1, request_without_content_length, &response);
  7272. // For requests without Content-Length, the server may have different behavior
  7273. // The key is that it should not reject due to payload limit for small
  7274. // payloads
  7275. if (result) {
  7276. // Check for any HTTP response (success or error, but not connection closed)
  7277. if (response.length() > 10) {
  7278. SUCCEED()
  7279. << "Server processed request without Content-Length within limit";
  7280. } else {
  7281. // Short response might indicate connection closed, which is acceptable
  7282. SUCCEED() << "Server closed connection for request without "
  7283. "Content-Length (acceptable behavior)";
  7284. }
  7285. } else {
  7286. // Connection failure might be due to protocol requirements
  7287. SUCCEED() << "Connection issue with request without Content-Length "
  7288. "(environment-specific)";
  7289. }
  7290. }
  7291. class LargePayloadMaxLengthTest : public ::testing::Test {
  7292. protected:
  7293. LargePayloadMaxLengthTest()
  7294. : cli_(HOST, PORT)
  7295. #ifdef CPPHTTPLIB_SSL_ENABLED
  7296. ,
  7297. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7298. #endif
  7299. {
  7300. #ifdef CPPHTTPLIB_SSL_ENABLED
  7301. cli_.enable_server_certificate_verification(false);
  7302. #endif
  7303. }
  7304. virtual void SetUp() {
  7305. // Set 10MB payload limit
  7306. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7307. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7308. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7309. res.set_content("Large payload test", "text/plain");
  7310. });
  7311. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7312. svr_.wait_until_ready();
  7313. }
  7314. virtual void TearDown() {
  7315. svr_.stop();
  7316. t_.join();
  7317. }
  7318. #ifdef CPPHTTPLIB_SSL_ENABLED
  7319. SSLClient cli_;
  7320. SSLServer svr_;
  7321. #else
  7322. Client cli_;
  7323. Server svr_;
  7324. #endif
  7325. thread t_;
  7326. };
  7327. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7328. // Test chunked encoding with payload within 10MB limit
  7329. std::string medium_payload(5 * 1024 * 1024,
  7330. 'A'); // 5MB payload, within 10MB limit
  7331. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7332. ASSERT_TRUE(res);
  7333. EXPECT_EQ(StatusCode::OK_200, res->status);
  7334. }
  7335. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7336. // Test chunked encoding with payload exceeding 10MB limit
  7337. std::string large_payload(12 * 1024 * 1024,
  7338. 'B'); // 12MB payload, exceeds 10MB limit
  7339. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7340. // Server may either return 413 or close the connection
  7341. if (res) {
  7342. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7343. } else {
  7344. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7345. }
  7346. }
  7347. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7348. // Test request without Content-Length header within 10MB limit
  7349. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7350. "Host: " +
  7351. std::string(HOST) + ":" +
  7352. std::to_string(PORT) +
  7353. "\r\n"
  7354. "Connection: close\r\n"
  7355. "\r\n";
  7356. // Add 1MB payload (within 10MB limit)
  7357. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7358. request_without_content_length += medium_payload;
  7359. std::string response;
  7360. bool result = send_request(5, request_without_content_length, &response);
  7361. if (result) {
  7362. // Should get a proper HTTP response for payloads within limit
  7363. if (response.length() > 10) {
  7364. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7365. "10MB limit";
  7366. } else {
  7367. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7368. "Content-Length)";
  7369. }
  7370. } else {
  7371. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7372. }
  7373. }
  7374. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7375. // Test request without Content-Length header exceeding 10MB limit
  7376. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7377. "Host: " +
  7378. std::string(HOST) + ":" +
  7379. std::to_string(PORT) +
  7380. "\r\n"
  7381. "Connection: close\r\n"
  7382. "\r\n";
  7383. // Add 12MB payload (exceeds 10MB limit)
  7384. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7385. request_without_content_length += large_payload;
  7386. std::string response;
  7387. bool result = send_request(10, request_without_content_length, &response);
  7388. if (!result) {
  7389. // Server should close connection due to payload limit
  7390. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7391. "(connection closed)";
  7392. } else {
  7393. // Check for error response
  7394. if (response.length() <= 10) {
  7395. SUCCEED()
  7396. << "Server closed connection for 12MB request exceeding 10MB limit";
  7397. } else {
  7398. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7399. response.find("Payload Too Large") != std::string::npos ||
  7400. response.find("400") != std::string::npos);
  7401. }
  7402. }
  7403. }
  7404. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7405. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7406. // path.
  7407. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7408. Server svr;
  7409. const size_t LIMIT = 64 * 1024; // 64KB
  7410. svr.set_payload_max_length(LIMIT);
  7411. size_t total = 0;
  7412. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7413. const ContentReader &content_reader) {
  7414. content_reader([&](const char * /*data*/, size_t len) {
  7415. total += len;
  7416. return true;
  7417. });
  7418. res.status = 200;
  7419. res.set_content("stream_ok", "text/plain");
  7420. });
  7421. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7422. auto se = detail::scope_exit([&] {
  7423. svr.stop();
  7424. thread.join();
  7425. ASSERT_FALSE(svr.is_running());
  7426. });
  7427. svr.wait_until_ready();
  7428. // Prepare 256KB raw data and gzip-compress it
  7429. std::string raw(256 * 1024, 'A');
  7430. std::string gz;
  7431. {
  7432. z_stream zs{};
  7433. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7434. Z_DEFAULT_STRATEGY);
  7435. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7436. zs.avail_in = static_cast<uInt>(raw.size());
  7437. char outbuf[4096];
  7438. int ret;
  7439. do {
  7440. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7441. zs.avail_out = sizeof(outbuf);
  7442. ret = deflate(&zs, Z_FINISH);
  7443. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7444. } while (ret != Z_STREAM_END);
  7445. deflateEnd(&zs);
  7446. }
  7447. Client cli(HOST, PORT);
  7448. cli.set_connection_timeout(std::chrono::seconds(5));
  7449. Headers headers = {{"Content-Encoding", "gzip"}};
  7450. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7451. "application/octet-stream");
  7452. ASSERT_TRUE(res);
  7453. // Server must reject oversized decompressed payloads with 413.
  7454. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7455. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7456. EXPECT_LE(total, LIMIT);
  7457. }
  7458. #endif
  7459. // Regression test for DoS vulnerability: a malicious server sending a response
  7460. // without Content-Length header must not cause unbounded memory consumption on
  7461. // the client side. The client should stop reading after a reasonable limit,
  7462. // similar to the server-side set_payload_max_length protection.
  7463. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7464. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7465. #ifndef _WIN32
  7466. signal(SIGPIPE, SIG_IGN);
  7467. #endif
  7468. auto server_thread = std::thread([] {
  7469. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7470. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7471. default_socket_options(srv);
  7472. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7473. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7474. sockaddr_in addr{};
  7475. addr.sin_family = AF_INET;
  7476. addr.sin_port = htons(PORT + 2);
  7477. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7478. int opt = 1;
  7479. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7480. #ifdef _WIN32
  7481. reinterpret_cast<const char *>(&opt),
  7482. #else
  7483. &opt,
  7484. #endif
  7485. sizeof(opt));
  7486. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7487. ::listen(srv, 1);
  7488. sockaddr_in cli_addr{};
  7489. socklen_t cli_len = sizeof(cli_addr);
  7490. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7491. if (cli != INVALID_SOCKET) {
  7492. char buf[4096];
  7493. ::recv(cli, buf, sizeof(buf), 0);
  7494. // Malicious response: no Content-Length, no chunked encoding
  7495. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7496. "Connection: close\r\n"
  7497. "\r\n";
  7498. ::send(cli,
  7499. #ifdef _WIN32
  7500. static_cast<const char *>(response_header.c_str()),
  7501. static_cast<int>(response_header.size()),
  7502. #else
  7503. response_header.c_str(), response_header.size(),
  7504. #endif
  7505. 0);
  7506. // Send 10MB of data
  7507. std::string chunk(64 * 1024, 'A');
  7508. size_t total_sent = 0;
  7509. while (total_sent < MALICIOUS_DATA_SIZE) {
  7510. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7511. auto sent = ::send(cli,
  7512. #ifdef _WIN32
  7513. static_cast<const char *>(chunk.c_str()),
  7514. static_cast<int>(to_send),
  7515. #else
  7516. chunk.c_str(), to_send,
  7517. #endif
  7518. 0);
  7519. if (sent <= 0) break;
  7520. total_sent += static_cast<size_t>(sent);
  7521. }
  7522. detail::close_socket(cli);
  7523. }
  7524. detail::close_socket(srv);
  7525. });
  7526. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7527. size_t total_read = 0;
  7528. {
  7529. Client cli("127.0.0.1", PORT + 2);
  7530. cli.set_read_timeout(5, 0);
  7531. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7532. auto stream = cli.open_stream("GET", "/malicious");
  7533. ASSERT_TRUE(stream.is_valid());
  7534. char buffer[64 * 1024];
  7535. ssize_t n;
  7536. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7537. total_read += static_cast<size_t>(n);
  7538. }
  7539. } // StreamHandle and Client destroyed here, closing the socket
  7540. server_thread.join();
  7541. // With set_payload_max_length, the client must stop reading before consuming
  7542. // all 10MB. The read loop should be cut off at or near the configured limit.
  7543. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7544. << "Client read " << total_read << " bytes, exceeding the configured "
  7545. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7546. }
  7547. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7548. // the entire response body without truncation.
  7549. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7550. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7551. #ifndef _WIN32
  7552. signal(SIGPIPE, SIG_IGN);
  7553. #endif
  7554. auto server_thread = std::thread([] {
  7555. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7556. default_socket_options(srv);
  7557. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7558. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7559. sockaddr_in addr{};
  7560. addr.sin_family = AF_INET;
  7561. addr.sin_port = htons(PORT + 2);
  7562. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7563. int opt = 1;
  7564. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7565. #ifdef _WIN32
  7566. reinterpret_cast<const char *>(&opt),
  7567. #else
  7568. &opt,
  7569. #endif
  7570. sizeof(opt));
  7571. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7572. ::listen(srv, 1);
  7573. sockaddr_in cli_addr{};
  7574. socklen_t cli_len = sizeof(cli_addr);
  7575. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7576. if (cli != INVALID_SOCKET) {
  7577. char buf[4096];
  7578. ::recv(cli, buf, sizeof(buf), 0);
  7579. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7580. "Connection: close\r\n"
  7581. "\r\n";
  7582. ::send(cli,
  7583. #ifdef _WIN32
  7584. static_cast<const char *>(response_header.c_str()),
  7585. static_cast<int>(response_header.size()),
  7586. #else
  7587. response_header.c_str(), response_header.size(),
  7588. #endif
  7589. 0);
  7590. std::string chunk(64 * 1024, 'A');
  7591. size_t total_sent = 0;
  7592. while (total_sent < DATA_SIZE) {
  7593. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7594. auto sent = ::send(cli,
  7595. #ifdef _WIN32
  7596. static_cast<const char *>(chunk.c_str()),
  7597. static_cast<int>(to_send),
  7598. #else
  7599. chunk.c_str(), to_send,
  7600. #endif
  7601. 0);
  7602. if (sent <= 0) break;
  7603. total_sent += static_cast<size_t>(sent);
  7604. }
  7605. #ifdef _WIN32
  7606. ::shutdown(cli, SD_SEND);
  7607. #else
  7608. ::shutdown(cli, SHUT_WR);
  7609. #endif
  7610. // Drain until the client closes its end, ensuring all data is delivered
  7611. char drain[1024];
  7612. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7613. detail::close_socket(cli);
  7614. }
  7615. detail::close_socket(srv);
  7616. });
  7617. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7618. size_t total_read = 0;
  7619. {
  7620. Client cli("127.0.0.1", PORT + 2);
  7621. cli.set_read_timeout(5, 0);
  7622. cli.set_payload_max_length(0); // 0 means no limit
  7623. auto stream = cli.open_stream("GET", "/data");
  7624. ASSERT_TRUE(stream.is_valid());
  7625. char buffer[64 * 1024];
  7626. ssize_t n;
  7627. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7628. total_read += static_cast<size_t>(n);
  7629. }
  7630. }
  7631. server_thread.join();
  7632. EXPECT_EQ(total_read, DATA_SIZE)
  7633. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7634. << " bytes without truncation, but only read " << total_read << " bytes.";
  7635. }
  7636. // Verify that content_receiver bypasses the default payload_max_length,
  7637. // allowing streaming downloads larger than 100MB without requiring an explicit
  7638. // set_payload_max_length call.
  7639. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  7640. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7641. #ifndef _WIN32
  7642. signal(SIGPIPE, SIG_IGN);
  7643. #endif
  7644. auto server_thread = std::thread([] {
  7645. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7646. default_socket_options(srv);
  7647. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7648. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7649. sockaddr_in addr{};
  7650. addr.sin_family = AF_INET;
  7651. addr.sin_port = htons(PORT + 2);
  7652. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7653. int opt = 1;
  7654. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7655. #ifdef _WIN32
  7656. reinterpret_cast<const char *>(&opt),
  7657. #else
  7658. &opt,
  7659. #endif
  7660. sizeof(opt));
  7661. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7662. ::listen(srv, 1);
  7663. sockaddr_in cli_addr{};
  7664. socklen_t cli_len = sizeof(cli_addr);
  7665. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7666. if (cli != INVALID_SOCKET) {
  7667. char buf[4096];
  7668. ::recv(cli, buf, sizeof(buf), 0);
  7669. // Response with Content-Length larger than default 100MB limit
  7670. auto content_length = std::to_string(DATA_SIZE);
  7671. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7672. "Content-Length: " +
  7673. content_length +
  7674. "\r\n"
  7675. "Connection: close\r\n"
  7676. "\r\n";
  7677. ::send(cli,
  7678. #ifdef _WIN32
  7679. static_cast<const char *>(response_header.c_str()),
  7680. static_cast<int>(response_header.size()),
  7681. #else
  7682. response_header.c_str(), response_header.size(),
  7683. #endif
  7684. 0);
  7685. std::string chunk(64 * 1024, 'A');
  7686. size_t total_sent = 0;
  7687. while (total_sent < DATA_SIZE) {
  7688. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7689. auto sent = ::send(cli,
  7690. #ifdef _WIN32
  7691. static_cast<const char *>(chunk.c_str()),
  7692. static_cast<int>(to_send),
  7693. #else
  7694. chunk.c_str(), to_send,
  7695. #endif
  7696. 0);
  7697. if (sent <= 0) break;
  7698. total_sent += static_cast<size_t>(sent);
  7699. }
  7700. detail::close_socket(cli);
  7701. }
  7702. detail::close_socket(srv);
  7703. });
  7704. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7705. size_t total_received = 0;
  7706. {
  7707. Client cli("127.0.0.1", PORT + 2);
  7708. cli.set_read_timeout(10, 0);
  7709. // Do NOT call set_payload_max_length — use the default 100MB limit
  7710. auto res =
  7711. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7712. total_received += data_length;
  7713. return true;
  7714. });
  7715. ASSERT_TRUE(res);
  7716. EXPECT_EQ(StatusCode::OK_200, res->status);
  7717. }
  7718. server_thread.join();
  7719. EXPECT_EQ(total_received, DATA_SIZE)
  7720. << "With content_receiver, the client should read all " << DATA_SIZE
  7721. << " bytes despite the default 100MB payload_max_length, but only read "
  7722. << total_received << " bytes.";
  7723. }
  7724. // Verify that an explicit set_payload_max_length smaller than the response is
  7725. // enforced even when a content_receiver is used.
  7726. TEST(ClientVulnerabilityTest,
  7727. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  7728. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7729. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  7730. #ifndef _WIN32
  7731. signal(SIGPIPE, SIG_IGN);
  7732. #endif
  7733. auto server_thread = std::thread([] {
  7734. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7735. default_socket_options(srv);
  7736. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7737. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7738. sockaddr_in addr{};
  7739. addr.sin_family = AF_INET;
  7740. addr.sin_port = htons(PORT + 2);
  7741. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7742. int opt = 1;
  7743. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7744. #ifdef _WIN32
  7745. reinterpret_cast<const char *>(&opt),
  7746. #else
  7747. &opt,
  7748. #endif
  7749. sizeof(opt));
  7750. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7751. ::listen(srv, 1);
  7752. sockaddr_in cli_addr{};
  7753. socklen_t cli_len = sizeof(cli_addr);
  7754. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7755. if (cli != INVALID_SOCKET) {
  7756. char buf[4096];
  7757. ::recv(cli, buf, sizeof(buf), 0);
  7758. auto content_length = std::to_string(DATA_SIZE);
  7759. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7760. "Content-Length: " +
  7761. content_length +
  7762. "\r\n"
  7763. "Connection: close\r\n"
  7764. "\r\n";
  7765. ::send(cli,
  7766. #ifdef _WIN32
  7767. static_cast<const char *>(response_header.c_str()),
  7768. static_cast<int>(response_header.size()),
  7769. #else
  7770. response_header.c_str(), response_header.size(),
  7771. #endif
  7772. 0);
  7773. std::string chunk(64 * 1024, 'A');
  7774. size_t total_sent = 0;
  7775. while (total_sent < DATA_SIZE) {
  7776. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7777. auto sent = ::send(cli,
  7778. #ifdef _WIN32
  7779. static_cast<const char *>(chunk.c_str()),
  7780. static_cast<int>(to_send),
  7781. #else
  7782. chunk.c_str(), to_send,
  7783. #endif
  7784. 0);
  7785. if (sent <= 0) break;
  7786. total_sent += static_cast<size_t>(sent);
  7787. }
  7788. detail::close_socket(cli);
  7789. }
  7790. detail::close_socket(srv);
  7791. });
  7792. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7793. size_t total_received = 0;
  7794. {
  7795. Client cli("127.0.0.1", PORT + 2);
  7796. cli.set_read_timeout(10, 0);
  7797. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  7798. auto res =
  7799. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7800. total_received += data_length;
  7801. return true;
  7802. });
  7803. // Should fail because 200MB exceeds the explicit 150MB limit
  7804. EXPECT_FALSE(res);
  7805. }
  7806. server_thread.join();
  7807. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  7808. << "Client with content_receiver should respect the explicit "
  7809. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  7810. << total_received << " bytes.";
  7811. }
  7812. // Verify that an explicit set_payload_max_length larger than the response
  7813. // allows the content_receiver to read all data successfully.
  7814. TEST(ClientVulnerabilityTest,
  7815. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  7816. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7817. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  7818. #ifndef _WIN32
  7819. signal(SIGPIPE, SIG_IGN);
  7820. #endif
  7821. auto server_thread = std::thread([] {
  7822. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7823. default_socket_options(srv);
  7824. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7825. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7826. sockaddr_in addr{};
  7827. addr.sin_family = AF_INET;
  7828. addr.sin_port = htons(PORT + 2);
  7829. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7830. int opt = 1;
  7831. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7832. #ifdef _WIN32
  7833. reinterpret_cast<const char *>(&opt),
  7834. #else
  7835. &opt,
  7836. #endif
  7837. sizeof(opt));
  7838. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7839. ::listen(srv, 1);
  7840. sockaddr_in cli_addr{};
  7841. socklen_t cli_len = sizeof(cli_addr);
  7842. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7843. if (cli != INVALID_SOCKET) {
  7844. char buf[4096];
  7845. ::recv(cli, buf, sizeof(buf), 0);
  7846. auto content_length = std::to_string(DATA_SIZE);
  7847. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7848. "Content-Length: " +
  7849. content_length +
  7850. "\r\n"
  7851. "Connection: close\r\n"
  7852. "\r\n";
  7853. ::send(cli,
  7854. #ifdef _WIN32
  7855. static_cast<const char *>(response_header.c_str()),
  7856. static_cast<int>(response_header.size()),
  7857. #else
  7858. response_header.c_str(), response_header.size(),
  7859. #endif
  7860. 0);
  7861. std::string chunk(64 * 1024, 'A');
  7862. size_t total_sent = 0;
  7863. while (total_sent < DATA_SIZE) {
  7864. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7865. auto sent = ::send(cli,
  7866. #ifdef _WIN32
  7867. static_cast<const char *>(chunk.c_str()),
  7868. static_cast<int>(to_send),
  7869. #else
  7870. chunk.c_str(), to_send,
  7871. #endif
  7872. 0);
  7873. if (sent <= 0) break;
  7874. total_sent += static_cast<size_t>(sent);
  7875. }
  7876. #ifdef _WIN32
  7877. ::shutdown(cli, SD_SEND);
  7878. #else
  7879. ::shutdown(cli, SHUT_WR);
  7880. #endif
  7881. char drain[1024];
  7882. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7883. detail::close_socket(cli);
  7884. }
  7885. detail::close_socket(srv);
  7886. });
  7887. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7888. size_t total_received = 0;
  7889. {
  7890. Client cli("127.0.0.1", PORT + 2);
  7891. cli.set_read_timeout(10, 0);
  7892. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  7893. auto res =
  7894. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7895. total_received += data_length;
  7896. return true;
  7897. });
  7898. ASSERT_TRUE(res);
  7899. EXPECT_EQ(StatusCode::OK_200, res->status);
  7900. }
  7901. server_thread.join();
  7902. EXPECT_EQ(total_received, DATA_SIZE)
  7903. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  7904. << " bytes (larger than " << DATA_SIZE
  7905. << " bytes response), content_receiver should read all data, but only "
  7906. "read "
  7907. << total_received << " bytes.";
  7908. }
  7909. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  7910. // Regression test for "zip bomb" attack on the client side: a malicious server
  7911. // sends a small gzip-compressed response that decompresses to a huge payload.
  7912. // The client must enforce payload_max_length on the decompressed size.
  7913. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  7914. constexpr size_t DECOMPRESSED_SIZE =
  7915. 10 * 1024 * 1024; // 10MB after decompression
  7916. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7917. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  7918. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  7919. std::string compressed;
  7920. {
  7921. httplib::detail::gzip_compressor compressor;
  7922. bool ok =
  7923. compressor.compress(uncompressed.data(), uncompressed.size(),
  7924. /*last=*/true, [&](const char *buf, size_t len) {
  7925. compressed.append(buf, len);
  7926. return true;
  7927. });
  7928. ASSERT_TRUE(ok);
  7929. }
  7930. // Sanity: compressed data should be much smaller than the decompressed size
  7931. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  7932. #ifndef _WIN32
  7933. signal(SIGPIPE, SIG_IGN);
  7934. #endif
  7935. // Set up the listening socket in the main thread so the server is guaranteed
  7936. // to be ready before the client connects (eliminates race condition).
  7937. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7938. default_socket_options(srv);
  7939. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7940. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7941. sockaddr_in addr{};
  7942. addr.sin_family = AF_INET;
  7943. addr.sin_port = htons(PORT + 3);
  7944. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7945. int opt = 1;
  7946. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7947. #ifdef _WIN32
  7948. reinterpret_cast<const char *>(&opt),
  7949. #else
  7950. &opt,
  7951. #endif
  7952. sizeof(opt));
  7953. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  7954. ASSERT_EQ(0, ::listen(srv, 1));
  7955. auto server_thread = std::thread([&compressed, srv] {
  7956. sockaddr_in cli_addr{};
  7957. socklen_t cli_len = sizeof(cli_addr);
  7958. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7959. if (cli != INVALID_SOCKET) {
  7960. // Read the full HTTP request (until \r\n\r\n)
  7961. char buf[4096];
  7962. size_t total = 0;
  7963. while (total < sizeof(buf)) {
  7964. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  7965. if (n <= 0) break;
  7966. total += static_cast<size_t>(n);
  7967. // Check for end of headers
  7968. if (total >= 4) {
  7969. std::string req(buf, total);
  7970. if (req.find("\r\n\r\n") != std::string::npos) break;
  7971. }
  7972. }
  7973. // Malicious response: gzip-compressed body, no Content-Length
  7974. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7975. "Content-Encoding: gzip\r\n"
  7976. "Connection: close\r\n"
  7977. "\r\n";
  7978. ::send(cli,
  7979. #ifdef _WIN32
  7980. static_cast<const char *>(response_header.c_str()),
  7981. static_cast<int>(response_header.size()),
  7982. #else
  7983. response_header.c_str(), response_header.size(),
  7984. #endif
  7985. 0);
  7986. // Send the compressed payload (small on the wire, huge when decompressed)
  7987. size_t total_sent = 0;
  7988. while (total_sent < compressed.size()) {
  7989. auto to_send = std::min(compressed.size() - total_sent,
  7990. static_cast<size_t>(64 * 1024));
  7991. auto sent =
  7992. ::send(cli,
  7993. #ifdef _WIN32
  7994. static_cast<const char *>(compressed.c_str() + total_sent),
  7995. static_cast<int>(to_send),
  7996. #else
  7997. compressed.c_str() + total_sent, to_send,
  7998. #endif
  7999. 0);
  8000. if (sent <= 0) break;
  8001. total_sent += static_cast<size_t>(sent);
  8002. }
  8003. detail::close_socket(cli);
  8004. }
  8005. });
  8006. auto se = detail::scope_exit([&] {
  8007. detail::close_socket(srv);
  8008. server_thread.join();
  8009. });
  8010. size_t total_decompressed = 0;
  8011. {
  8012. Client cli("127.0.0.1", PORT + 3);
  8013. cli.set_read_timeout(5, 0);
  8014. cli.set_decompress(true);
  8015. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8016. auto stream = cli.open_stream("GET", "/zipbomb");
  8017. ASSERT_TRUE(stream.is_valid());
  8018. char buffer[64 * 1024];
  8019. ssize_t n;
  8020. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8021. total_decompressed += static_cast<size_t>(n);
  8022. }
  8023. }
  8024. // The decompressed size must be capped by payload_max_length. Without
  8025. // protection, the client would decompress the full 10MB from a tiny
  8026. // compressed payload, enabling a zip bomb DoS attack.
  8027. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8028. << "Client decompressed " << total_decompressed
  8029. << " bytes from a gzip response. The decompressed size should be "
  8030. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8031. }
  8032. #endif
  8033. TEST(HostAndPortPropertiesTest, NoSSL) {
  8034. httplib::Client cli("www.google.com", 1234);
  8035. ASSERT_EQ("www.google.com", cli.host());
  8036. ASSERT_EQ(1234, cli.port());
  8037. }
  8038. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8039. httplib::Client cli("www.google.com:1234");
  8040. ASSERT_EQ("www.google.com", cli.host());
  8041. ASSERT_EQ(1234, cli.port());
  8042. }
  8043. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8044. // Port number that overflows int — should not crash, client becomes invalid
  8045. httplib::Client cli("http://www.google.com:99999999999999999999");
  8046. ASSERT_FALSE(cli.is_valid());
  8047. }
  8048. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8049. // Port 99999 exceeds valid range (1-65535) — should not crash
  8050. httplib::Client cli("http://www.google.com:99999");
  8051. ASSERT_FALSE(cli.is_valid());
  8052. }
  8053. #ifdef CPPHTTPLIB_SSL_ENABLED
  8054. TEST(HostAndPortPropertiesTest, SSL) {
  8055. httplib::SSLClient cli("www.google.com");
  8056. ASSERT_EQ("www.google.com", cli.host());
  8057. ASSERT_EQ(443, cli.port());
  8058. }
  8059. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8060. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8061. std::string cert;
  8062. read_file(CA_CERT_FILE, cert);
  8063. httplib::SSLClient httplib_client("www.google.com");
  8064. // Load CA store first time
  8065. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8066. // Load CA store second time (update)
  8067. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8068. // Verify client is still valid and can make connections
  8069. httplib_client.enable_server_certificate_verification(true);
  8070. auto res = httplib_client.Get("/");
  8071. ASSERT_TRUE(res);
  8072. // Google may return 200 or 301 depending on various factors
  8073. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8074. res->status == StatusCode::MovedPermanently_301);
  8075. }
  8076. TEST(SSLClientTest, ServerNameIndication_Online) {
  8077. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  8078. auto host = "httpcan.org";
  8079. auto path = std::string{"/get"};
  8080. #else
  8081. auto host = "nghttp2.org";
  8082. auto path = std::string{"/httpbin/get"};
  8083. #endif
  8084. SSLClient cli(host, 443);
  8085. auto res = cli.Get(path);
  8086. ASSERT_TRUE(res);
  8087. ASSERT_EQ(StatusCode::OK_200, res->status);
  8088. }
  8089. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8090. // Use a site that will cause SSL verification failure due to self-signed cert
  8091. SSLClient cli("self-signed.badssl.com", 443);
  8092. cli.enable_server_certificate_verification(true);
  8093. auto res = cli.Get("/");
  8094. ASSERT_TRUE(!res);
  8095. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8096. // Verify backend error is captured for SSLServerVerification
  8097. // This occurs when certificate verification fails
  8098. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8099. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8100. EXPECT_NE(0UL, res.ssl_backend_error());
  8101. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8102. // For OpenSSL, ssl_error is 0 for verification errors
  8103. EXPECT_EQ(0, res.ssl_error());
  8104. #if !defined(_WIN32) || \
  8105. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8106. // On non-Windows or when Windows Schannel is disabled, the error comes
  8107. // from OpenSSL's verification
  8108. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8109. res.ssl_backend_error());
  8110. #endif
  8111. #endif
  8112. }
  8113. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8114. // Use a site where hostname doesn't match the certificate
  8115. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8116. SSLClient cli("wrong.host.badssl.com", 443);
  8117. cli.enable_server_certificate_verification(true);
  8118. cli.enable_server_hostname_verification(true);
  8119. auto res = cli.Get("/");
  8120. ASSERT_TRUE(!res);
  8121. // The error type depends on when hostname verification occurs:
  8122. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8123. // - Mbed TLS: SSLServerVerification (during handshake)
  8124. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8125. res.error() == Error::SSLServerVerification);
  8126. // Verify backend error is captured for hostname verification failure
  8127. EXPECT_NE(0UL, res.ssl_backend_error());
  8128. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8129. // For OpenSSL, ssl_error is 0 for verification errors
  8130. EXPECT_EQ(0, res.ssl_error());
  8131. #if !defined(_WIN32) || \
  8132. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8133. // On non-Windows or when Windows Schannel is disabled, the error comes
  8134. // from OpenSSL's hostname verification
  8135. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8136. res.ssl_backend_error());
  8137. #endif
  8138. #endif
  8139. }
  8140. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8141. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8142. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8143. SSLClient cli("www.google.com", 443);
  8144. cli.enable_server_certificate_verification(true);
  8145. auto res = cli.Get("/");
  8146. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8147. }
  8148. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8149. SSLClient cli("www.google.com", 443);
  8150. cli.enable_server_certificate_verification(true);
  8151. cli.enable_windows_certificate_verification(false);
  8152. auto res = cli.Get("/");
  8153. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8154. }
  8155. #endif
  8156. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8157. Client cli("https://google.com");
  8158. auto res = cli.Get("/");
  8159. ASSERT_TRUE(res);
  8160. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8161. }
  8162. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8163. SSLClient cli("google.com");
  8164. cli.set_ca_cert_path(CA_CERT_FILE);
  8165. auto res = cli.Get("/");
  8166. ASSERT_TRUE(res);
  8167. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8168. }
  8169. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8170. SSLClient cli("google.com");
  8171. cli.enable_server_certificate_verification(true);
  8172. cli.set_ca_cert_path("hello");
  8173. auto res = cli.Get("/");
  8174. ASSERT_TRUE(!res);
  8175. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8176. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8177. // should be set
  8178. EXPECT_EQ(0, res.ssl_error());
  8179. // Verify backend error is captured for SSLLoadingCerts
  8180. // This error occurs when loading CA certificates fails
  8181. EXPECT_NE(0UL, res.ssl_backend_error());
  8182. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8183. // OpenSSL specific error codes:
  8184. // > openssl errstr 0x80000002
  8185. // error:80000002:system library::No such file or directory
  8186. // > openssl errstr 0xA000126
  8187. // error:0A000126:SSL routines::unexpected eof while reading
  8188. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8189. res.ssl_backend_error() == 0xA000126);
  8190. #endif
  8191. }
  8192. TEST(SSLClientTest, ServerCertificateVerification4) {
  8193. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8194. ASSERT_TRUE(svr.is_valid());
  8195. svr.Get("/test", [&](const Request &, Response &res) {
  8196. res.set_content("test", "text/plain");
  8197. svr.stop();
  8198. ASSERT_TRUE(true);
  8199. });
  8200. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8201. auto se = detail::scope_exit([&] {
  8202. t.join();
  8203. ASSERT_FALSE(svr.is_running());
  8204. });
  8205. svr.wait_until_ready();
  8206. SSLClient cli("127.0.0.1", PORT);
  8207. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8208. cli.enable_server_certificate_verification(true);
  8209. cli.set_connection_timeout(30);
  8210. auto res = cli.Get("/test");
  8211. ASSERT_TRUE(res);
  8212. ASSERT_EQ(StatusCode::OK_200, res->status);
  8213. }
  8214. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8215. std::string cert;
  8216. read_file(CA_CERT_FILE, cert);
  8217. SSLClient cli("google.com");
  8218. cli.load_ca_cert_store(cert.data(), cert.size());
  8219. const auto res = cli.Get("/");
  8220. ASSERT_TRUE(res);
  8221. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8222. }
  8223. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8224. // clang-format off
  8225. static constexpr char cert[] =
  8226. "GlobalSign Root CA\n"
  8227. "==================\n"
  8228. "-----BEGIN CERTIFICATE-----\n"
  8229. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8230. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8231. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8232. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8233. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8234. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8235. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8236. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8237. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8238. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8239. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8240. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8241. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8242. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8243. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8244. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8245. "-----END CERTIFICATE-----\n";
  8246. // clang-format on
  8247. SSLClient cli("google.com");
  8248. cli.load_ca_cert_store(cert, sizeof(cert));
  8249. const auto res = cli.Get("/");
  8250. ASSERT_TRUE(res);
  8251. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8252. }
  8253. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8254. SSLClient cli("www.youtube.com");
  8255. cli.set_ca_cert_path(CA_CERT_FILE);
  8256. cli.enable_server_certificate_verification(true);
  8257. cli.set_follow_location(true);
  8258. auto res = cli.Get("/");
  8259. ASSERT_TRUE(res);
  8260. ASSERT_EQ(StatusCode::OK_200, res->status);
  8261. }
  8262. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8263. SSLClient cli("wWw.YouTube.Com");
  8264. cli.set_ca_cert_path(CA_CERT_FILE);
  8265. cli.enable_server_certificate_verification(true);
  8266. cli.enable_server_hostname_verification(true);
  8267. cli.set_follow_location(true);
  8268. auto res = cli.Get("/");
  8269. ASSERT_TRUE(res);
  8270. ASSERT_EQ(StatusCode::OK_200, res->status);
  8271. }
  8272. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8273. SSLClient cli("gOoGlE.COm");
  8274. cli.enable_server_certificate_verification(true);
  8275. cli.enable_server_hostname_verification(true);
  8276. cli.set_follow_location(true);
  8277. auto res = cli.Get("/");
  8278. ASSERT_TRUE(res);
  8279. ASSERT_EQ(StatusCode::OK_200, res->status);
  8280. }
  8281. TEST(SSLClientTest, Issue2004_Online) {
  8282. Client client("https://google.com");
  8283. client.set_follow_location(true);
  8284. auto res = client.Get("/");
  8285. ASSERT_TRUE(res);
  8286. ASSERT_EQ(StatusCode::OK_200, res->status);
  8287. auto body = res->body;
  8288. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8289. }
  8290. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8291. // Create SSLClient with invalid cert/key to make is_valid() return false
  8292. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8293. "nonexistent_key.pem");
  8294. // is_valid() should be false due to cert loading failure
  8295. ASSERT_FALSE(cli.is_valid());
  8296. auto res = cli.Get("/");
  8297. ASSERT_FALSE(res);
  8298. EXPECT_EQ(Error::SSLConnection, res.error());
  8299. }
  8300. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8301. // Test for Issue #2251: SSL error not properly reported when client cert
  8302. // and key paths are swapped or mismatched
  8303. // This simulates the scenario where user accidentally swaps the cert and key
  8304. // files
  8305. // Using client cert file as private key and vice versa (completely wrong)
  8306. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8307. // Should fail validation due to cert/key mismatch
  8308. ASSERT_FALSE(cli.is_valid());
  8309. // Attempt to make a request should fail with proper error
  8310. auto res = cli.Get("/");
  8311. ASSERT_FALSE(res);
  8312. EXPECT_EQ(Error::SSLConnection, res.error());
  8313. // SSL error should be recorded in the Result object (this is the key fix for
  8314. // Issue #2251)
  8315. auto backend_error = res.ssl_backend_error();
  8316. EXPECT_NE(0u, backend_error);
  8317. }
  8318. // Tests cert/key mismatch detection at the TLS context level
  8319. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8320. // Test that using mismatched cert/key causes connection failure.
  8321. // We verify this at the SSLClient level rather than through internal
  8322. // TLS API functions.
  8323. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8324. cli.enable_server_certificate_verification(false);
  8325. cli.set_connection_timeout(2);
  8326. // The mismatch should cause a connection or handshake error
  8327. auto res = cli.Get("/test");
  8328. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8329. // Either way, the request should fail
  8330. EXPECT_FALSE(res);
  8331. }
  8332. #endif
  8333. #if 0
  8334. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8335. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8336. ASSERT_TRUE(cli != nullptr);
  8337. cli->set_address_family(AF_INET6);
  8338. cli->set_interface("en0");
  8339. auto res = cli->Get("/get");
  8340. ASSERT_TRUE(res);
  8341. ASSERT_EQ(StatusCode::OK_200, res->status);
  8342. }
  8343. #endif
  8344. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8345. #ifdef CPPHTTPLIB_SSL_ENABLED
  8346. void ClientCertPresent(
  8347. const std::string &client_cert_file,
  8348. const std::string &client_private_key_file,
  8349. const std::string &client_encrypted_private_key_pass = std::string()) {
  8350. using namespace httplib::tls;
  8351. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8352. CLIENT_CA_CERT_DIR);
  8353. ASSERT_TRUE(svr.is_valid());
  8354. svr.Get("/test", [&](const Request &req, Response &res) {
  8355. res.set_content("test", "text/plain");
  8356. auto cert = req.peer_cert();
  8357. ASSERT_TRUE(static_cast<bool>(cert));
  8358. std::string common_name = cert.subject_cn();
  8359. EXPECT_EQ("Common Name", common_name);
  8360. });
  8361. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8362. auto se = detail::scope_exit([&] {
  8363. svr.stop();
  8364. t.join();
  8365. ASSERT_FALSE(svr.is_running());
  8366. });
  8367. svr.wait_until_ready();
  8368. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8369. client_encrypted_private_key_pass);
  8370. cli.enable_server_certificate_verification(false);
  8371. cli.set_connection_timeout(30);
  8372. auto res = cli.Get("/test");
  8373. ASSERT_TRUE(res);
  8374. ASSERT_EQ(StatusCode::OK_200, res->status);
  8375. }
  8376. TEST(SSLClientServerTest, ClientCertPresent) {
  8377. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8378. }
  8379. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8380. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8381. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8382. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8383. }
  8384. // PEM memory-based constructor tests (works with all TLS backends)
  8385. void PemMemoryClientCertPresent(
  8386. const std::string &client_cert_file,
  8387. const std::string &client_private_key_file,
  8388. const std::string &client_encrypted_private_key_pass = std::string()) {
  8389. // Read PEM files into memory
  8390. std::string server_cert_pem, server_key_pem;
  8391. std::string client_ca_pem;
  8392. std::string client_cert_pem, client_key_pem;
  8393. read_file(SERVER_CERT_FILE, server_cert_pem);
  8394. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8395. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8396. read_file(client_cert_file, client_cert_pem);
  8397. read_file(client_private_key_file, client_key_pem);
  8398. // Create server with PEM memory
  8399. SSLServer::PemMemory server_pem = {
  8400. server_cert_pem.c_str(),
  8401. server_cert_pem.size(),
  8402. server_key_pem.c_str(),
  8403. server_key_pem.size(),
  8404. client_ca_pem.c_str(),
  8405. client_ca_pem.size(),
  8406. nullptr // no password for server key
  8407. };
  8408. SSLServer svr(server_pem);
  8409. ASSERT_TRUE(svr.is_valid());
  8410. svr.Get("/test", [&](const Request &, Response &res) {
  8411. res.set_content("test", "text/plain");
  8412. });
  8413. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8414. auto se = detail::scope_exit([&] {
  8415. svr.stop();
  8416. t.join();
  8417. ASSERT_FALSE(svr.is_running());
  8418. });
  8419. svr.wait_until_ready();
  8420. // Create client with PEM memory
  8421. const char *password = client_encrypted_private_key_pass.empty()
  8422. ? nullptr
  8423. : client_encrypted_private_key_pass.c_str();
  8424. SSLClient::PemMemory client_pem = {
  8425. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8426. client_key_pem.size(), password};
  8427. SSLClient cli(HOST, PORT, client_pem);
  8428. cli.enable_server_certificate_verification(false);
  8429. cli.set_connection_timeout(30);
  8430. auto res = cli.Get("/test");
  8431. ASSERT_TRUE(res);
  8432. ASSERT_EQ(StatusCode::OK_200, res->status);
  8433. }
  8434. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8435. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8436. }
  8437. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8438. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8439. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8440. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8441. }
  8442. TEST(SSLClientServerTest, ClientCertMissing) {
  8443. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8444. CLIENT_CA_CERT_DIR);
  8445. ASSERT_TRUE(svr.is_valid());
  8446. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8447. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8448. auto se = detail::scope_exit([&] {
  8449. svr.stop();
  8450. t.join();
  8451. ASSERT_FALSE(svr.is_running());
  8452. });
  8453. svr.wait_until_ready();
  8454. SSLClient cli(HOST, PORT);
  8455. cli.set_connection_timeout(30);
  8456. auto res = cli.Get("/test");
  8457. ASSERT_TRUE(!res);
  8458. // When client cert is missing and server requires it, connection fails
  8459. // Error type depends on backend implementation
  8460. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8461. res.error() == Error::SSLConnection);
  8462. // Verify backend error is captured
  8463. // Note: This test may have different error codes depending on the exact
  8464. // verification failure
  8465. EXPECT_NE(0UL, res.ssl_backend_error());
  8466. }
  8467. TEST(SSLClientServerTest, TrustDirOptional) {
  8468. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8469. ASSERT_TRUE(svr.is_valid());
  8470. svr.Get("/test", [&](const Request &, Response &res) {
  8471. res.set_content("test", "text/plain");
  8472. });
  8473. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8474. auto se = detail::scope_exit([&] {
  8475. svr.stop();
  8476. t.join();
  8477. ASSERT_FALSE(svr.is_running());
  8478. });
  8479. svr.wait_until_ready();
  8480. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8481. cli.enable_server_certificate_verification(false);
  8482. cli.set_connection_timeout(30);
  8483. auto res = cli.Get("/test");
  8484. ASSERT_TRUE(res);
  8485. ASSERT_EQ(StatusCode::OK_200, res->status);
  8486. }
  8487. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8488. class NoListenSSLServer : public SSLServer {
  8489. public:
  8490. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8491. const char *client_ca_cert_file_path,
  8492. const char *client_ca_cert_dir_path = nullptr)
  8493. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8494. client_ca_cert_dir_path),
  8495. stop_(false) {}
  8496. std::atomic_bool stop_;
  8497. private:
  8498. bool process_and_close_socket(socket_t /*sock*/) override {
  8499. // Don't create SSL context
  8500. while (!stop_.load()) {
  8501. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8502. }
  8503. return true;
  8504. }
  8505. };
  8506. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8507. CLIENT_CA_CERT_FILE);
  8508. ASSERT_TRUE(svr.is_valid());
  8509. svr.Get("/test", [&](const Request &, Response &res) {
  8510. res.set_content("test", "text/plain");
  8511. });
  8512. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8513. auto se = detail::scope_exit([&] {
  8514. svr.stop_ = true;
  8515. svr.stop();
  8516. t.join();
  8517. ASSERT_FALSE(svr.is_running());
  8518. });
  8519. svr.wait_until_ready();
  8520. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8521. cli.enable_server_certificate_verification(false);
  8522. cli.set_connection_timeout(1);
  8523. auto res = cli.Get("/test");
  8524. ASSERT_TRUE(!res);
  8525. EXPECT_EQ(Error::SSLConnection, res.error());
  8526. // Timeout results in WantRead error code (maps to backend-specific value)
  8527. EXPECT_NE(0, res.ssl_error());
  8528. }
  8529. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8530. // Test SSLServer with client certificate verification using the standard
  8531. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8532. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8533. CLIENT_CA_CERT_DIR);
  8534. ASSERT_TRUE(svr.is_valid());
  8535. svr.Get("/test", [&](const Request &req, Response &res) {
  8536. res.set_content("test", "text/plain");
  8537. auto cert = req.peer_cert();
  8538. ASSERT_TRUE(static_cast<bool>(cert));
  8539. auto common_name = cert.subject_cn();
  8540. EXPECT_EQ("Common Name", common_name);
  8541. });
  8542. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8543. auto se = detail::scope_exit([&] {
  8544. svr.stop();
  8545. t.join();
  8546. ASSERT_FALSE(svr.is_running());
  8547. });
  8548. svr.wait_until_ready();
  8549. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8550. cli.enable_server_certificate_verification(false);
  8551. cli.set_connection_timeout(30);
  8552. auto res = cli.Get("/test");
  8553. ASSERT_TRUE(res);
  8554. ASSERT_EQ(StatusCode::OK_200, res->status);
  8555. }
  8556. // Test verify_hostname for both OpenSSL and MbedTLS backends
  8557. // Verifies that wildcard matching and exact matching work consistently
  8558. TEST(SSLClientServerTest, TlsVerifyHostname) {
  8559. using namespace httplib::tls;
  8560. // We need a running server to test against
  8561. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8562. ASSERT_TRUE(svr.is_valid());
  8563. svr.Get("/test", [](const Request &, Response &res) {
  8564. res.set_content("ok", "text/plain");
  8565. });
  8566. thread t([&]() { svr.listen(HOST, PORT); });
  8567. auto se = detail::scope_exit([&] {
  8568. svr.stop();
  8569. t.join();
  8570. });
  8571. svr.wait_until_ready();
  8572. bool verify_callback_called = false;
  8573. bool verify_result_wrong = false;
  8574. SSLClient cli(HOST, PORT);
  8575. cli.enable_server_certificate_verification(true);
  8576. cli.set_ca_cert_path(CA_CERT_FILE);
  8577. cli.set_connection_timeout(5);
  8578. // Note: Test certificate has CN="Common Name", not "localhost"
  8579. bool verify_result_cn = false;
  8580. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8581. verify_callback_called = true;
  8582. if (!ctx.cert) return false;
  8583. // Test 1: "Common Name" should match (our test server cert CN)
  8584. verify_result_cn = ctx.check_hostname("Common Name");
  8585. // Test 2: wrong hostname should not match
  8586. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  8587. return true; // Accept for the purpose of this test
  8588. });
  8589. auto res = cli.Get("/test");
  8590. // The request may succeed or fail depending on cert configuration
  8591. // but the callback should have been called
  8592. ASSERT_TRUE(verify_callback_called)
  8593. << "Verify callback should have been called";
  8594. // CN="Common Name" should match our test certificate
  8595. EXPECT_TRUE(verify_result_cn)
  8596. << "verify_hostname should match 'Common Name' (certificate CN)";
  8597. // Wrong hostname should not match
  8598. EXPECT_FALSE(verify_result_wrong)
  8599. << "verify_hostname should not match 'wronghost.example.com'";
  8600. }
  8601. #endif
  8602. // mbedTLS-specific callback constructor test
  8603. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8604. #ifdef CPPHTTPLIB_SSL_ENABLED
  8605. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8606. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8607. ASSERT_TRUE(svr.is_valid());
  8608. // Set up a handler to verify client certificate is present
  8609. bool client_cert_verified = false;
  8610. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8611. // Verify that client certificate was provided
  8612. client_cert_verified = true;
  8613. res.set_content("success", "text/plain");
  8614. });
  8615. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8616. auto se = detail::scope_exit([&] {
  8617. svr.stop();
  8618. t.join();
  8619. ASSERT_FALSE(svr.is_running());
  8620. });
  8621. svr.wait_until_ready();
  8622. // Client with certificate
  8623. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8624. cli.enable_server_certificate_verification(false);
  8625. cli.set_connection_timeout(30);
  8626. auto res = cli.Get("/test");
  8627. ASSERT_TRUE(res);
  8628. ASSERT_EQ(StatusCode::OK_200, res->status);
  8629. ASSERT_TRUE(client_cert_verified);
  8630. EXPECT_EQ("success", res->body);
  8631. }
  8632. #endif
  8633. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  8634. // backends
  8635. #ifdef CPPHTTPLIB_SSL_ENABLED
  8636. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  8637. using namespace httplib::tls;
  8638. // Test that when client CA cert file is provided,
  8639. // the server properly requests and validates client certificates
  8640. // Create a server with client authentication
  8641. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8642. ASSERT_TRUE(svr.is_valid());
  8643. bool handler_called = false;
  8644. svr.Get("/test", [&](const Request &req, Response &res) {
  8645. handler_called = true;
  8646. // Verify that a client certificate was provided
  8647. auto cert = req.peer_cert();
  8648. ASSERT_TRUE(static_cast<bool>(cert));
  8649. // Get the issuer name
  8650. std::string issuer_str = cert.issuer_name();
  8651. ASSERT_FALSE(issuer_str.empty());
  8652. // The client certificate should be issued by our test CA
  8653. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  8654. res.set_content("authenticated", "text/plain");
  8655. });
  8656. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8657. auto se = detail::scope_exit([&] {
  8658. svr.stop();
  8659. t.join();
  8660. ASSERT_FALSE(svr.is_running());
  8661. });
  8662. svr.wait_until_ready();
  8663. // Connect with a client certificate issued by the CA
  8664. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8665. cli.enable_server_certificate_verification(false);
  8666. cli.set_connection_timeout(30);
  8667. auto res = cli.Get("/test");
  8668. ASSERT_TRUE(res);
  8669. ASSERT_EQ(StatusCode::OK_200, res->status);
  8670. ASSERT_TRUE(handler_called);
  8671. EXPECT_EQ("authenticated", res->body);
  8672. }
  8673. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  8674. using namespace httplib::tls;
  8675. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8676. ASSERT_TRUE(svr.is_valid());
  8677. svr.Get("/test", [](const Request &, Response &res) {
  8678. res.set_content("ok", "text/plain");
  8679. });
  8680. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8681. auto se = detail::scope_exit([&] {
  8682. svr.stop();
  8683. t.join();
  8684. });
  8685. svr.wait_until_ready();
  8686. SSLClient cli(HOST, PORT);
  8687. cli.enable_server_certificate_verification(false);
  8688. cli.set_connection_timeout(30);
  8689. bool cert_checked = false;
  8690. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8691. if (ctx.cert) {
  8692. auto sans = ctx.sans();
  8693. // Test certificate may or may not have SANs - just verify the API
  8694. // works If SANs exist, verify the types are valid
  8695. for (const auto &san : sans) {
  8696. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  8697. san.type == SanType::EMAIL || san.type == SanType::URI ||
  8698. san.type == SanType::OTHER);
  8699. EXPECT_FALSE(san.value.empty());
  8700. }
  8701. cert_checked = true;
  8702. }
  8703. return true;
  8704. });
  8705. auto res = cli.Get("/test");
  8706. ASSERT_TRUE(res);
  8707. EXPECT_TRUE(cert_checked);
  8708. }
  8709. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  8710. using namespace httplib::tls;
  8711. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8712. ASSERT_TRUE(svr.is_valid());
  8713. svr.Get("/test", [](const Request &, Response &res) {
  8714. res.set_content("ok", "text/plain");
  8715. });
  8716. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8717. auto se = detail::scope_exit([&] {
  8718. svr.stop();
  8719. t.join();
  8720. });
  8721. svr.wait_until_ready();
  8722. SSLClient cli(HOST, PORT);
  8723. cli.enable_server_certificate_verification(false);
  8724. cli.set_connection_timeout(30);
  8725. bool validity_checked = false;
  8726. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8727. if (ctx.cert) {
  8728. time_t not_before = 0, not_after = 0;
  8729. bool result = ctx.validity(not_before, not_after);
  8730. EXPECT_TRUE(result);
  8731. // Verify that not_before < now < not_after for a valid cert
  8732. time_t now = time(nullptr);
  8733. EXPECT_LT(not_before, now);
  8734. EXPECT_GT(not_after, now);
  8735. validity_checked = true;
  8736. }
  8737. return true;
  8738. });
  8739. auto res = cli.Get("/test");
  8740. ASSERT_TRUE(res);
  8741. EXPECT_TRUE(validity_checked);
  8742. }
  8743. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  8744. using namespace httplib::tls;
  8745. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8746. ASSERT_TRUE(svr.is_valid());
  8747. svr.Get("/test", [](const Request &, Response &res) {
  8748. res.set_content("ok", "text/plain");
  8749. });
  8750. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8751. auto se = detail::scope_exit([&] {
  8752. svr.stop();
  8753. t.join();
  8754. });
  8755. svr.wait_until_ready();
  8756. SSLClient cli(HOST, PORT);
  8757. cli.enable_server_certificate_verification(false);
  8758. cli.set_connection_timeout(30);
  8759. bool serial_checked = false;
  8760. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8761. if (ctx.cert) {
  8762. std::string serial = ctx.serial();
  8763. EXPECT_FALSE(serial.empty());
  8764. // Serial should be a hex string
  8765. for (char c : serial) {
  8766. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  8767. (c >= 'a' && c <= 'f'));
  8768. }
  8769. serial_checked = true;
  8770. }
  8771. return true;
  8772. });
  8773. auto res = cli.Get("/test");
  8774. ASSERT_TRUE(res);
  8775. EXPECT_TRUE(serial_checked);
  8776. }
  8777. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  8778. // Test 1: Valid CA file - no error should be recorded
  8779. {
  8780. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8781. CLIENT_CA_CERT_FILE);
  8782. ASSERT_TRUE(svr.is_valid());
  8783. // With valid setup, last_ssl_error should be 0
  8784. EXPECT_EQ(0, svr.ssl_last_error());
  8785. }
  8786. // Test 2: Invalid CA file content
  8787. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  8788. {
  8789. // Create a temporary file with completely invalid content
  8790. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  8791. {
  8792. std::ofstream ofs(temp_invalid_ca);
  8793. ofs << "This is not a certificate file at all\n";
  8794. ofs << "Just plain text content\n";
  8795. }
  8796. // Create server with invalid CA file
  8797. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  8798. // Clean up temporary file
  8799. std::remove(temp_invalid_ca);
  8800. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  8801. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  8802. // Note: SSL_CTX_load_verify_locations typically fails first,
  8803. // but our error handling code path is still exercised
  8804. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  8805. }
  8806. }
  8807. TEST(VerifyCallbackTest, VerifyContextFields) {
  8808. using namespace httplib::tls;
  8809. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8810. ASSERT_TRUE(svr.is_valid());
  8811. svr.Get("/test", [](const Request &, Response &res) {
  8812. res.set_content("ok", "text/plain");
  8813. });
  8814. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8815. auto se = detail::scope_exit([&] {
  8816. svr.stop();
  8817. t.join();
  8818. });
  8819. svr.wait_until_ready();
  8820. SSLClient cli(HOST, PORT);
  8821. cli.enable_server_certificate_verification(false);
  8822. cli.set_connection_timeout(30);
  8823. int callback_count = 0;
  8824. bool saw_leaf_cert = false;
  8825. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8826. if (ctx.cert) {
  8827. callback_count++;
  8828. // We should see at least one certificate (the leaf)
  8829. std::string cn = ctx.subject_cn();
  8830. if (!cn.empty()) { saw_leaf_cert = true; }
  8831. // Verify context fields are populated
  8832. EXPECT_NE(ctx.session, nullptr);
  8833. EXPECT_GE(ctx.depth, 0);
  8834. }
  8835. return true;
  8836. });
  8837. auto res = cli.Get("/test");
  8838. ASSERT_TRUE(res);
  8839. EXPECT_GT(callback_count, 0);
  8840. EXPECT_TRUE(saw_leaf_cert);
  8841. }
  8842. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  8843. using httplib::tls::TlsError;
  8844. // Test that verify_error_to_string returns empty for success
  8845. std::string success_str = TlsError::verify_error_to_string(0);
  8846. EXPECT_TRUE(success_str.empty());
  8847. // Test that verify_error_to_string returns non-empty for error codes
  8848. // Using a common error code (certificate expired)
  8849. std::string error_str =
  8850. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  8851. EXPECT_FALSE(error_str.empty());
  8852. }
  8853. TEST(SessionVerifierTest, CertificateAccepted) {
  8854. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8855. ASSERT_TRUE(svr.is_valid());
  8856. svr.Get("/test", [](const Request &, Response &res) {
  8857. res.set_content("ok", "text/plain");
  8858. });
  8859. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8860. auto se = detail::scope_exit([&] {
  8861. svr.stop();
  8862. t.join();
  8863. });
  8864. svr.wait_until_ready();
  8865. SSLClient cli(HOST, PORT);
  8866. cli.enable_server_certificate_verification(false);
  8867. cli.set_connection_timeout(30);
  8868. bool callback_called = false;
  8869. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8870. EXPECT_NE(session, nullptr);
  8871. callback_called = true;
  8872. return SSLVerifierResponse::CertificateAccepted;
  8873. });
  8874. auto res = cli.Get("/test");
  8875. ASSERT_TRUE(res);
  8876. EXPECT_EQ(200, res->status);
  8877. EXPECT_TRUE(callback_called);
  8878. }
  8879. TEST(SessionVerifierTest, CertificateRejected) {
  8880. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8881. ASSERT_TRUE(svr.is_valid());
  8882. svr.Get("/test", [](const Request &, Response &res) {
  8883. res.set_content("ok", "text/plain");
  8884. });
  8885. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8886. auto se = detail::scope_exit([&] {
  8887. svr.stop();
  8888. t.join();
  8889. });
  8890. svr.wait_until_ready();
  8891. SSLClient cli(HOST, PORT);
  8892. cli.enable_server_certificate_verification(false);
  8893. cli.set_connection_timeout(30);
  8894. bool callback_called = false;
  8895. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8896. EXPECT_NE(session, nullptr);
  8897. callback_called = true;
  8898. return SSLVerifierResponse::CertificateRejected;
  8899. });
  8900. auto res = cli.Get("/test");
  8901. EXPECT_FALSE(res);
  8902. EXPECT_TRUE(callback_called);
  8903. }
  8904. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  8905. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8906. ASSERT_TRUE(svr.is_valid());
  8907. svr.Get("/test", [](const Request &, Response &res) {
  8908. res.set_content("ok", "text/plain");
  8909. });
  8910. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8911. auto se = detail::scope_exit([&] {
  8912. svr.stop();
  8913. t.join();
  8914. });
  8915. svr.wait_until_ready();
  8916. // NoDecisionMade with verification disabled should succeed (no default check)
  8917. SSLClient cli(HOST, PORT);
  8918. cli.enable_server_certificate_verification(false);
  8919. cli.set_connection_timeout(30);
  8920. bool callback_called = false;
  8921. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8922. EXPECT_NE(session, nullptr);
  8923. callback_called = true;
  8924. return SSLVerifierResponse::NoDecisionMade;
  8925. });
  8926. auto res = cli.Get("/test");
  8927. ASSERT_TRUE(res);
  8928. EXPECT_EQ(200, res->status);
  8929. EXPECT_TRUE(callback_called);
  8930. }
  8931. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  8932. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8933. ASSERT_TRUE(svr.is_valid());
  8934. svr.Get("/test", [](const Request &, Response &res) {
  8935. res.set_content("ok", "text/plain");
  8936. });
  8937. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8938. auto se = detail::scope_exit([&] {
  8939. svr.stop();
  8940. t.join();
  8941. });
  8942. svr.wait_until_ready();
  8943. // NoDecisionMade with verification enabled should fail (self-signed cert).
  8944. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  8945. // so we only check that the request fails, not whether the callback was
  8946. // called.
  8947. SSLClient cli(HOST, PORT);
  8948. cli.enable_server_certificate_verification(true);
  8949. cli.set_connection_timeout(30);
  8950. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8951. EXPECT_NE(session, nullptr);
  8952. return SSLVerifierResponse::NoDecisionMade;
  8953. });
  8954. auto res = cli.Get("/test");
  8955. EXPECT_FALSE(res);
  8956. }
  8957. TEST(SSLClientServerTest, ClientCAListFromPem) {
  8958. // Test SSL server using PemMemory constructor with client CA certificates
  8959. // Read PEM files
  8960. std::string server_cert_pem, server_key_pem, client_ca_pem;
  8961. read_file(SERVER_CERT_FILE, server_cert_pem);
  8962. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8963. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8964. // Create SSLServer with PemMemory constructor including client CA
  8965. SSLServer::PemMemory server_pem = {
  8966. server_cert_pem.c_str(),
  8967. server_cert_pem.size(),
  8968. server_key_pem.c_str(),
  8969. server_key_pem.size(),
  8970. client_ca_pem.c_str(),
  8971. client_ca_pem.size(),
  8972. nullptr // no password for server key
  8973. };
  8974. SSLServer svr(server_pem);
  8975. ASSERT_TRUE(svr.is_valid());
  8976. // No SSL error should be recorded for valid setup
  8977. EXPECT_EQ(0, svr.ssl_last_error());
  8978. // Set up server endpoints
  8979. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  8980. res.set_content("ok", "text/plain");
  8981. });
  8982. // Start server in a thread
  8983. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  8984. svr.wait_until_ready();
  8985. // Connect with client certificate (using constructor with paths)
  8986. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8987. cli.enable_server_certificate_verification(false);
  8988. auto res = cli.Get("/test-pem-ca");
  8989. ASSERT_TRUE(res);
  8990. EXPECT_EQ(200, res->status);
  8991. EXPECT_EQ("ok", res->body);
  8992. svr.stop();
  8993. server_thread.join();
  8994. }
  8995. #endif
  8996. #ifdef _WIN32
  8997. TEST(CleanupTest, WSACleanup) {
  8998. int ret = WSACleanup();
  8999. ASSERT_EQ(0, ret);
  9000. }
  9001. #endif
  9002. #ifndef CPPHTTPLIB_SSL_ENABLED
  9003. TEST(NoSSLSupport, SimpleInterface) {
  9004. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  9005. }
  9006. #endif
  9007. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9008. TEST(InvalidScheme, SimpleInterface) {
  9009. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  9010. }
  9011. #endif
  9012. TEST(NoScheme, SimpleInterface) {
  9013. Client cli("yahoo.com:80");
  9014. ASSERT_TRUE(cli.is_valid());
  9015. }
  9016. TEST(SendAPI, SimpleInterface_Online) {
  9017. Client cli("http://yahoo.com");
  9018. Request req;
  9019. req.method = "GET";
  9020. req.path = "/";
  9021. auto res = cli.send(req);
  9022. ASSERT_TRUE(res);
  9023. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9024. }
  9025. TEST(SendAPI, WithParamsInRequest) {
  9026. Server svr;
  9027. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  9028. EXPECT_TRUE(req.has_param("test"));
  9029. EXPECT_EQ("test_value", req.get_param_value("test"));
  9030. });
  9031. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  9032. auto se = detail::scope_exit([&] {
  9033. svr.stop();
  9034. t.join();
  9035. ASSERT_FALSE(svr.is_running());
  9036. });
  9037. svr.wait_until_ready();
  9038. Client cli(HOST, PORT);
  9039. {
  9040. Request req;
  9041. req.method = "GET";
  9042. req.path = "/";
  9043. req.params.emplace("test", "test_value");
  9044. auto res = cli.send(req);
  9045. ASSERT_TRUE(res);
  9046. }
  9047. {
  9048. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  9049. ASSERT_TRUE(res);
  9050. }
  9051. }
  9052. TEST(ClientImplMethods, GetSocketTest) {
  9053. httplib::Server svr;
  9054. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9055. res.status = StatusCode::OK_200;
  9056. });
  9057. auto port = svr.bind_to_any_port("127.0.0.1");
  9058. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9059. auto se = detail::scope_exit([&] {
  9060. svr.stop();
  9061. thread.join();
  9062. ASSERT_FALSE(svr.is_running());
  9063. });
  9064. svr.wait_until_ready();
  9065. {
  9066. httplib::Client cli("127.0.0.1", port);
  9067. cli.set_keep_alive(true);
  9068. // Use the behavior of cpp-httplib of opening the connection
  9069. // only when the first request happens. If that changes,
  9070. // this test would be obsolete.
  9071. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9072. // This also implicitly tests the server. But other tests would fail much
  9073. // earlier than this one to be considered.
  9074. auto res = cli.Get("/");
  9075. ASSERT_TRUE(res);
  9076. EXPECT_EQ(StatusCode::OK_200, res->status);
  9077. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9078. }
  9079. }
  9080. #ifdef CPPHTTPLIB_SSL_ENABLED
  9081. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9082. Client cli("http://yahoo.com");
  9083. auto res = cli.Get("/");
  9084. ASSERT_TRUE(res);
  9085. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9086. cli.set_follow_location(true);
  9087. res = cli.Get("/");
  9088. ASSERT_TRUE(res);
  9089. EXPECT_EQ(StatusCode::OK_200, res->status);
  9090. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9091. }
  9092. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9093. Client cli("https://yahoo.com");
  9094. auto res = cli.Get("/");
  9095. ASSERT_TRUE(res);
  9096. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9097. cli.set_follow_location(true);
  9098. res = cli.Get("/");
  9099. ASSERT_TRUE(res);
  9100. EXPECT_EQ(StatusCode::OK_200, res->status);
  9101. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9102. }
  9103. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9104. Client cli("https://yahoo.com");
  9105. auto res = cli.Get("/");
  9106. ASSERT_TRUE(res);
  9107. ASSERT_FALSE(!res);
  9108. ASSERT_TRUE(res);
  9109. ASSERT_FALSE(res == nullptr);
  9110. ASSERT_TRUE(res != nullptr);
  9111. EXPECT_EQ(Error::Success, res.error());
  9112. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9113. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9114. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9115. cli.set_follow_location(true);
  9116. res = cli.Get("/");
  9117. ASSERT_TRUE(res);
  9118. EXPECT_EQ(Error::Success, res.error());
  9119. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9120. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9121. EXPECT_EQ(StatusCode::OK_200, res->status);
  9122. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9123. }
  9124. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9125. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9126. Client cli("https://cdnjs.cloudflare.com");
  9127. auto res =
  9128. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9129. ASSERT_TRUE(res);
  9130. EXPECT_EQ(StatusCode::OK_200, res->status);
  9131. EXPECT_EQ(287630U, res->body.size());
  9132. EXPECT_EQ("application/javascript; charset=utf-8",
  9133. res->get_header_value("Content-Type"));
  9134. }
  9135. #endif
  9136. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9137. #undef REDIR_HOST // Silence compiler warning
  9138. #define REDIR_HOST "https://httpbingo.org"
  9139. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9140. Client cli(REDIR_HOST);
  9141. cli.set_follow_location(true);
  9142. auto res =
  9143. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9144. ASSERT_TRUE(res);
  9145. EXPECT_EQ(StatusCode::OK_200, res->status);
  9146. }
  9147. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9148. Client cli(REDIR_HOST);
  9149. cli.set_follow_location(true);
  9150. Params params;
  9151. params.emplace("url", "http://example.com");
  9152. params.emplace("status_code", "302");
  9153. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9154. ASSERT_TRUE(res);
  9155. EXPECT_EQ(StatusCode::OK_200, res->status);
  9156. }
  9157. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9158. Client cli(REDIR_HOST);
  9159. cli.set_follow_location(true);
  9160. Params params;
  9161. params.emplace("url", "http://example.com");
  9162. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9163. ASSERT_TRUE(res);
  9164. EXPECT_EQ(StatusCode::OK_200, res->status);
  9165. }
  9166. TEST(HttpToHttpsRedirectTest, CertFile) {
  9167. auto ssl_port = PORT + 1;
  9168. Server svr;
  9169. ASSERT_TRUE(svr.is_valid());
  9170. svr.Get("/index", [&](const Request &, Response &res) {
  9171. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9172. "/index");
  9173. svr.stop();
  9174. });
  9175. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9176. ASSERT_TRUE(ssl_svr.is_valid());
  9177. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9178. res.set_content("test", "text/plain");
  9179. ssl_svr.stop();
  9180. });
  9181. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9182. thread t2 =
  9183. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9184. auto se = detail::scope_exit([&] {
  9185. t2.join();
  9186. t.join();
  9187. ASSERT_FALSE(svr.is_running());
  9188. });
  9189. svr.wait_until_ready();
  9190. ssl_svr.wait_until_ready();
  9191. Client cli("127.0.0.1", PORT);
  9192. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9193. cli.enable_server_certificate_verification(true);
  9194. cli.set_follow_location(true);
  9195. cli.set_connection_timeout(30);
  9196. auto res = cli.Get("/index");
  9197. ASSERT_TRUE(res);
  9198. ASSERT_EQ(StatusCode::OK_200, res->status);
  9199. }
  9200. TEST(SSLClientRedirectTest, CertFile) {
  9201. auto ssl_port = PORT + 1;
  9202. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9203. ASSERT_TRUE(ssl_svr1.is_valid());
  9204. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9205. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9206. "/index");
  9207. ssl_svr1.stop();
  9208. });
  9209. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9210. ASSERT_TRUE(ssl_svr2.is_valid());
  9211. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9212. res.set_content("test", "text/plain");
  9213. ssl_svr2.stop();
  9214. });
  9215. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9216. thread t2 =
  9217. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9218. auto se = detail::scope_exit([&] {
  9219. t2.join();
  9220. t.join();
  9221. ASSERT_FALSE(ssl_svr1.is_running());
  9222. });
  9223. ssl_svr1.wait_until_ready();
  9224. ssl_svr2.wait_until_ready();
  9225. SSLClient cli("127.0.0.1", PORT);
  9226. std::string cert;
  9227. read_file(SERVER_CERT2_FILE, cert);
  9228. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9229. cli.enable_server_certificate_verification(true);
  9230. cli.set_follow_location(true);
  9231. cli.set_connection_timeout(30);
  9232. auto res = cli.Get("/index");
  9233. ASSERT_TRUE(res);
  9234. ASSERT_EQ(StatusCode::OK_200, res->status);
  9235. }
  9236. #endif
  9237. #ifdef CPPHTTPLIB_SSL_ENABLED
  9238. // Test that set_ca_cert_store() skips system certs (consistent with
  9239. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9240. // should be trusted - system certs should NOT be loaded.
  9241. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9242. // Load a specific cert that is NOT a system CA cert
  9243. std::string cert;
  9244. read_file(SERVER_CERT2_FILE, cert);
  9245. SSLClient cli("google.com");
  9246. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9247. cli.enable_server_certificate_verification(true);
  9248. // This should FAIL because:
  9249. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9250. // 2. System certs should NOT be loaded when custom store is set
  9251. // If system certs WERE loaded, this would succeed
  9252. auto res = cli.Get("/");
  9253. ASSERT_FALSE(res);
  9254. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9255. }
  9256. TEST(MultipartFormDataTest, LargeData) {
  9257. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9258. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9259. const ContentReader &content_reader) {
  9260. if (req.is_multipart_form_data()) {
  9261. std::vector<FormData> items;
  9262. content_reader(
  9263. [&](const FormData &file) {
  9264. items.push_back(file);
  9265. return true;
  9266. },
  9267. [&](const char *data, size_t data_length) {
  9268. items.back().content.append(data, data_length);
  9269. return true;
  9270. });
  9271. EXPECT_TRUE(std::string(items[0].name) == "document");
  9272. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9273. EXPECT_TRUE(items[0].filename == "2MB_data");
  9274. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9275. EXPECT_TRUE(items[1].name == "hello");
  9276. EXPECT_TRUE(items[1].content == "world");
  9277. EXPECT_TRUE(items[1].filename == "");
  9278. EXPECT_TRUE(items[1].content_type == "");
  9279. } else {
  9280. std::string body;
  9281. content_reader([&](const char *data, size_t data_length) {
  9282. body.append(data, data_length);
  9283. return true;
  9284. });
  9285. }
  9286. });
  9287. auto port = svr.bind_to_any_port(HOST);
  9288. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9289. auto se = detail::scope_exit([&] {
  9290. svr.stop();
  9291. t.join();
  9292. ASSERT_FALSE(svr.is_running());
  9293. });
  9294. svr.wait_until_ready();
  9295. {
  9296. std::string data(1024 * 1024 * 2, '.');
  9297. std::stringstream buffer;
  9298. buffer << data;
  9299. SSLClient cli(HOST, port);
  9300. cli.enable_server_certificate_verification(false);
  9301. UploadFormDataItems items{
  9302. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9303. {"hello", "world", "", ""},
  9304. };
  9305. auto res = cli.Post("/post", items);
  9306. ASSERT_TRUE(res);
  9307. ASSERT_EQ(StatusCode::OK_200, res->status);
  9308. }
  9309. }
  9310. TEST(MultipartFormDataTest, DataProviderItems) {
  9311. std::random_device seed_gen;
  9312. std::mt19937 random(seed_gen());
  9313. std::string rand1;
  9314. rand1.resize(1000);
  9315. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9316. std::string rand2;
  9317. rand2.resize(3000);
  9318. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9319. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9320. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9321. const ContentReader &content_reader) {
  9322. ASSERT_FALSE(req.is_multipart_form_data());
  9323. std::string body;
  9324. content_reader([&](const char *data, size_t data_length) {
  9325. body.append(data, data_length);
  9326. return true;
  9327. });
  9328. EXPECT_EQ(body, "");
  9329. });
  9330. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9331. const ContentReader &content_reader) {
  9332. ASSERT_TRUE(req.is_multipart_form_data());
  9333. std::vector<FormData> items;
  9334. content_reader(
  9335. [&](const FormData &file) {
  9336. items.push_back(file);
  9337. return true;
  9338. },
  9339. [&](const char *data, size_t data_length) {
  9340. items.back().content.append(data, data_length);
  9341. return true;
  9342. });
  9343. ASSERT_TRUE(items.size() == 2);
  9344. EXPECT_EQ(std::string(items[0].name), "name1");
  9345. EXPECT_EQ(items[0].content, "Testing123");
  9346. EXPECT_EQ(items[0].filename, "filename1");
  9347. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9348. EXPECT_EQ(items[1].name, "name2");
  9349. EXPECT_EQ(items[1].content, "Testing456");
  9350. EXPECT_EQ(items[1].filename, "");
  9351. EXPECT_EQ(items[1].content_type, "");
  9352. });
  9353. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9354. const ContentReader &content_reader) {
  9355. ASSERT_TRUE(req.is_multipart_form_data());
  9356. std::vector<FormData> items;
  9357. content_reader(
  9358. [&](const FormData &file) {
  9359. items.push_back(file);
  9360. return true;
  9361. },
  9362. [&](const char *data, size_t data_length) {
  9363. items.back().content.append(data, data_length);
  9364. return true;
  9365. });
  9366. ASSERT_TRUE(items.size() == 2);
  9367. EXPECT_EQ(items[0].name, "name3");
  9368. EXPECT_EQ(items[0].content, rand1);
  9369. EXPECT_EQ(items[0].filename, "filename3");
  9370. EXPECT_EQ(items[0].content_type, "");
  9371. EXPECT_EQ(items[1].name, "name4");
  9372. EXPECT_EQ(items[1].content, rand2);
  9373. EXPECT_EQ(items[1].filename, "filename4");
  9374. EXPECT_EQ(items[1].content_type, "");
  9375. });
  9376. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9377. const ContentReader &content_reader) {
  9378. ASSERT_TRUE(req.is_multipart_form_data());
  9379. std::vector<FormData> items;
  9380. content_reader(
  9381. [&](const FormData &file) {
  9382. items.push_back(file);
  9383. return true;
  9384. },
  9385. [&](const char *data, size_t data_length) {
  9386. items.back().content.append(data, data_length);
  9387. return true;
  9388. });
  9389. ASSERT_TRUE(items.size() == 4);
  9390. EXPECT_EQ(std::string(items[0].name), "name1");
  9391. EXPECT_EQ(items[0].content, "Testing123");
  9392. EXPECT_EQ(items[0].filename, "filename1");
  9393. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9394. EXPECT_EQ(items[1].name, "name2");
  9395. EXPECT_EQ(items[1].content, "Testing456");
  9396. EXPECT_EQ(items[1].filename, "");
  9397. EXPECT_EQ(items[1].content_type, "");
  9398. EXPECT_EQ(items[2].name, "name3");
  9399. EXPECT_EQ(items[2].content, rand1);
  9400. EXPECT_EQ(items[2].filename, "filename3");
  9401. EXPECT_EQ(items[2].content_type, "");
  9402. EXPECT_EQ(items[3].name, "name4");
  9403. EXPECT_EQ(items[3].content, rand2);
  9404. EXPECT_EQ(items[3].filename, "filename4");
  9405. EXPECT_EQ(items[3].content_type, "");
  9406. });
  9407. auto port = svr.bind_to_any_port("localhost");
  9408. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9409. auto se = detail::scope_exit([&] {
  9410. svr.stop();
  9411. t.join();
  9412. ASSERT_FALSE(svr.is_running());
  9413. });
  9414. svr.wait_until_ready();
  9415. {
  9416. SSLClient cli("localhost", port);
  9417. cli.enable_server_certificate_verification(false);
  9418. UploadFormDataItems items{
  9419. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9420. {"name2", "Testing456", "", ""}, // not a file
  9421. };
  9422. {
  9423. auto res = cli.Post("/post-none", {}, {}, {});
  9424. ASSERT_TRUE(res);
  9425. ASSERT_EQ(StatusCode::OK_200, res->status);
  9426. }
  9427. FormDataProviderItems providers;
  9428. {
  9429. auto res =
  9430. cli.Post("/post-items", {}, items, providers); // empty providers
  9431. ASSERT_TRUE(res);
  9432. ASSERT_EQ(StatusCode::OK_200, res->status);
  9433. }
  9434. providers.push_back({"name3",
  9435. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9436. // test the offset is given correctly at each step
  9437. if (!offset)
  9438. sink.os.write(rand1.data(), 30);
  9439. else if (offset == 30)
  9440. sink.os.write(rand1.data() + 30, 300);
  9441. else if (offset == 330)
  9442. sink.os.write(rand1.data() + 330, 670);
  9443. else if (offset == rand1.size())
  9444. sink.done();
  9445. return true;
  9446. },
  9447. "filename3",
  9448. {}});
  9449. providers.push_back({"name4",
  9450. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9451. // test the offset is given correctly at each step
  9452. if (!offset)
  9453. sink.os.write(rand2.data(), 2000);
  9454. else if (offset == 2000)
  9455. sink.os.write(rand2.data() + 2000, 1);
  9456. else if (offset == 2001)
  9457. sink.os.write(rand2.data() + 2001, 999);
  9458. else if (offset == rand2.size())
  9459. sink.done();
  9460. return true;
  9461. },
  9462. "filename4",
  9463. {}});
  9464. {
  9465. auto res = cli.Post("/post-providers", {}, {}, providers);
  9466. ASSERT_TRUE(res);
  9467. ASSERT_EQ(StatusCode::OK_200, res->status);
  9468. }
  9469. {
  9470. auto res = cli.Post("/post-both", {}, items, providers);
  9471. ASSERT_TRUE(res);
  9472. ASSERT_EQ(StatusCode::OK_200, res->status);
  9473. }
  9474. }
  9475. }
  9476. TEST(MultipartFormDataTest, BadHeader) {
  9477. Server svr;
  9478. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9479. res.set_content("ok", "text/plain");
  9480. });
  9481. thread t = thread([&] { svr.listen(HOST, PORT); });
  9482. auto se = detail::scope_exit([&] {
  9483. svr.stop();
  9484. t.join();
  9485. ASSERT_FALSE(svr.is_running());
  9486. });
  9487. svr.wait_until_ready();
  9488. const std::string body =
  9489. "This is the preamble. It is to be ignored, though it\r\n"
  9490. "is a handy place for composition agents to include an\r\n"
  9491. "explanatory note to non-MIME conformant readers.\r\n"
  9492. "\r\n"
  9493. "\r\n"
  9494. "--simple boundary\r\n"
  9495. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9496. ": BAD...\r\n"
  9497. "\r\n"
  9498. "value1\r\n"
  9499. "--simple boundary\r\n"
  9500. "Content-Disposition: form-data; name=\"field2\"; "
  9501. "filename=\"example.txt\"\r\n"
  9502. "\r\n"
  9503. "value2\r\n"
  9504. "--simple boundary--\r\n"
  9505. "This is the epilogue. It is also to be ignored.\r\n";
  9506. std::string content_type =
  9507. R"(multipart/form-data; boundary="simple boundary")";
  9508. Client cli(HOST, PORT);
  9509. auto res = cli.Post("/post", body, content_type.c_str());
  9510. ASSERT_TRUE(res);
  9511. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9512. }
  9513. TEST(MultipartFormDataTest, WithPreamble) {
  9514. Server svr;
  9515. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9516. res.set_content("ok", "text/plain");
  9517. });
  9518. thread t = thread([&] { svr.listen(HOST, PORT); });
  9519. auto se = detail::scope_exit([&] {
  9520. svr.stop();
  9521. t.join();
  9522. ASSERT_FALSE(svr.is_running());
  9523. });
  9524. svr.wait_until_ready();
  9525. const std::string body =
  9526. "This is the preamble. It is to be ignored, though it\r\n"
  9527. "is a handy place for composition agents to include an\r\n"
  9528. "explanatory note to non-MIME conformant readers.\r\n"
  9529. "\r\n"
  9530. "\r\n"
  9531. "--simple boundary\r\n"
  9532. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9533. "\r\n"
  9534. "value1\r\n"
  9535. "--simple boundary\r\n"
  9536. "Content-Disposition: form-data; name=\"field2\"; "
  9537. "filename=\"example.txt\"\r\n"
  9538. "\r\n"
  9539. "value2\r\n"
  9540. "--simple boundary--\r\n"
  9541. "This is the epilogue. It is also to be ignored.\r\n";
  9542. std::string content_type =
  9543. R"(multipart/form-data; boundary="simple boundary")";
  9544. Client cli(HOST, PORT);
  9545. auto res = cli.Post("/post", body, content_type.c_str());
  9546. ASSERT_TRUE(res);
  9547. EXPECT_EQ(StatusCode::OK_200, res->status);
  9548. }
  9549. TEST(MultipartFormDataTest, PostCustomBoundary) {
  9550. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9551. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  9552. const ContentReader &content_reader) {
  9553. if (req.is_multipart_form_data()) {
  9554. std::vector<FormData> items;
  9555. content_reader(
  9556. [&](const FormData &file) {
  9557. items.push_back(file);
  9558. return true;
  9559. },
  9560. [&](const char *data, size_t data_length) {
  9561. items.back().content.append(data, data_length);
  9562. return true;
  9563. });
  9564. EXPECT_TRUE(std::string(items[0].name) == "document");
  9565. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9566. EXPECT_TRUE(items[0].filename == "2MB_data");
  9567. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9568. EXPECT_TRUE(items[1].name == "hello");
  9569. EXPECT_TRUE(items[1].content == "world");
  9570. EXPECT_TRUE(items[1].filename == "");
  9571. EXPECT_TRUE(items[1].content_type == "");
  9572. } else {
  9573. std::string body;
  9574. content_reader([&](const char *data, size_t data_length) {
  9575. body.append(data, data_length);
  9576. return true;
  9577. });
  9578. }
  9579. });
  9580. auto port = svr.bind_to_any_port("localhost");
  9581. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9582. auto se = detail::scope_exit([&] {
  9583. svr.stop();
  9584. t.join();
  9585. ASSERT_FALSE(svr.is_running());
  9586. });
  9587. svr.wait_until_ready();
  9588. {
  9589. std::string data(1024 * 1024 * 2, '.');
  9590. std::stringstream buffer;
  9591. buffer << data;
  9592. SSLClient cli("localhost", port);
  9593. cli.enable_server_certificate_verification(false);
  9594. UploadFormDataItems items{
  9595. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9596. {"hello", "world", "", ""},
  9597. };
  9598. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9599. ASSERT_TRUE(res);
  9600. ASSERT_EQ(StatusCode::OK_200, res->status);
  9601. }
  9602. }
  9603. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9604. std::string data(1024 * 1024 * 2, '&');
  9605. std::stringstream buffer;
  9606. buffer << data;
  9607. Client cli("https://localhost:8080");
  9608. UploadFormDataItems items{
  9609. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9610. {"hello", "world", "", ""},
  9611. };
  9612. for (const char &c : " \t\r\n") {
  9613. auto res =
  9614. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9615. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9616. ASSERT_FALSE(res);
  9617. }
  9618. }
  9619. TEST(MultipartFormDataTest, PutFormData) {
  9620. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9621. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9622. const ContentReader &content_reader) {
  9623. if (req.is_multipart_form_data()) {
  9624. std::vector<FormData> items;
  9625. content_reader(
  9626. [&](const FormData &file) {
  9627. items.push_back(file);
  9628. return true;
  9629. },
  9630. [&](const char *data, size_t data_length) {
  9631. items.back().content.append(data, data_length);
  9632. return true;
  9633. });
  9634. EXPECT_TRUE(std::string(items[0].name) == "document");
  9635. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9636. EXPECT_TRUE(items[0].filename == "2MB_data");
  9637. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9638. EXPECT_TRUE(items[1].name == "hello");
  9639. EXPECT_TRUE(items[1].content == "world");
  9640. EXPECT_TRUE(items[1].filename == "");
  9641. EXPECT_TRUE(items[1].content_type == "");
  9642. } else {
  9643. std::string body;
  9644. content_reader([&](const char *data, size_t data_length) {
  9645. body.append(data, data_length);
  9646. return true;
  9647. });
  9648. }
  9649. });
  9650. auto port = svr.bind_to_any_port("localhost");
  9651. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9652. auto se = detail::scope_exit([&] {
  9653. svr.stop();
  9654. t.join();
  9655. ASSERT_FALSE(svr.is_running());
  9656. });
  9657. svr.wait_until_ready();
  9658. {
  9659. std::string data(1024 * 1024 * 2, '&');
  9660. std::stringstream buffer;
  9661. buffer << data;
  9662. SSLClient cli("localhost", port);
  9663. cli.enable_server_certificate_verification(false);
  9664. UploadFormDataItems items{
  9665. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9666. {"hello", "world", "", ""},
  9667. };
  9668. auto res = cli.Put("/put", items);
  9669. ASSERT_TRUE(res);
  9670. ASSERT_EQ(StatusCode::OK_200, res->status);
  9671. }
  9672. }
  9673. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  9674. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9675. svr.Put("/put_customboundary",
  9676. [&](const Request &req, const Response & /*res*/,
  9677. const ContentReader &content_reader) {
  9678. if (req.is_multipart_form_data()) {
  9679. std::vector<FormData> items;
  9680. content_reader(
  9681. [&](const FormData &file) {
  9682. items.push_back(file);
  9683. return true;
  9684. },
  9685. [&](const char *data, size_t data_length) {
  9686. items.back().content.append(data, data_length);
  9687. return true;
  9688. });
  9689. EXPECT_TRUE(std::string(items[0].name) == "document");
  9690. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9691. EXPECT_TRUE(items[0].filename == "2MB_data");
  9692. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9693. EXPECT_TRUE(items[1].name == "hello");
  9694. EXPECT_TRUE(items[1].content == "world");
  9695. EXPECT_TRUE(items[1].filename == "");
  9696. EXPECT_TRUE(items[1].content_type == "");
  9697. } else {
  9698. std::string body;
  9699. content_reader([&](const char *data, size_t data_length) {
  9700. body.append(data, data_length);
  9701. return true;
  9702. });
  9703. }
  9704. });
  9705. auto port = svr.bind_to_any_port("localhost");
  9706. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9707. auto se = detail::scope_exit([&] {
  9708. svr.stop();
  9709. t.join();
  9710. ASSERT_FALSE(svr.is_running());
  9711. });
  9712. svr.wait_until_ready();
  9713. {
  9714. std::string data(1024 * 1024 * 2, '&');
  9715. std::stringstream buffer;
  9716. buffer << data;
  9717. SSLClient cli("localhost", port);
  9718. cli.enable_server_certificate_verification(false);
  9719. UploadFormDataItems items{
  9720. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9721. {"hello", "world", "", ""},
  9722. };
  9723. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  9724. ASSERT_TRUE(res);
  9725. ASSERT_EQ(StatusCode::OK_200, res->status);
  9726. }
  9727. }
  9728. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  9729. std::string data(1024 * 1024 * 2, '&');
  9730. std::stringstream buffer;
  9731. buffer << data;
  9732. Client cli("https://localhost:8080");
  9733. cli.enable_server_certificate_verification(false);
  9734. UploadFormDataItems items{
  9735. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9736. {"hello", "world", "", ""},
  9737. };
  9738. for (const char &c : " \t\r\n") {
  9739. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  9740. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9741. ASSERT_FALSE(res);
  9742. }
  9743. }
  9744. TEST(MultipartFormDataTest, AlternateFilename) {
  9745. auto handled = false;
  9746. Server svr;
  9747. svr.Post("/test", [&](const Request &req, Response &res) {
  9748. ASSERT_EQ(2u, req.form.files.size());
  9749. ASSERT_EQ(1u, req.form.fields.size());
  9750. // Test files
  9751. const auto &file1 = req.form.get_file("file1");
  9752. ASSERT_EQ("file1", file1.name);
  9753. ASSERT_EQ("A.txt", file1.filename);
  9754. ASSERT_EQ("text/plain", file1.content_type);
  9755. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  9756. const auto &file2 = req.form.get_file("file2");
  9757. ASSERT_EQ("file2", file2.name);
  9758. ASSERT_EQ("a.html", file2.filename);
  9759. ASSERT_EQ("text/html", file2.content_type);
  9760. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  9761. file2.content);
  9762. // Test text field
  9763. const auto &text = req.form.get_field("text");
  9764. ASSERT_EQ("text default", text);
  9765. res.set_content("ok", "text/plain");
  9766. handled = true;
  9767. });
  9768. thread t = thread([&] { svr.listen(HOST, PORT); });
  9769. auto se = detail::scope_exit([&] {
  9770. svr.stop();
  9771. t.join();
  9772. ASSERT_FALSE(svr.is_running());
  9773. ASSERT_TRUE(handled);
  9774. });
  9775. svr.wait_until_ready();
  9776. auto req = "POST /test HTTP/1.1\r\n"
  9777. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9778. "Content-Length: 399\r\n"
  9779. "\r\n"
  9780. "----------\r\n"
  9781. "Content-Disposition: form-data; name=\"text\"\r\n"
  9782. "\r\n"
  9783. "text default\r\n"
  9784. "----------\r\n"
  9785. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  9786. "filename=\"a.txt\"; name=\"file1\"\r\n"
  9787. "Content-Type: text/plain\r\n"
  9788. "\r\n"
  9789. "Content of a.txt.\r\n"
  9790. "\r\n"
  9791. "----------\r\n"
  9792. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  9793. "\"a.html\"\r\n"
  9794. "Content-Type: text/html\r\n"
  9795. "\r\n"
  9796. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  9797. "\r\n"
  9798. "------------\r\n";
  9799. ASSERT_TRUE(send_request(1, req));
  9800. }
  9801. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  9802. auto handled = false;
  9803. Server svr;
  9804. svr.Post("/test", [&](const Request &req, Response &res) {
  9805. // Case-insensitive "utf-8''" prefix with a long value
  9806. const auto &file = req.form.get_file("file1");
  9807. ASSERT_EQ("file1", file.name);
  9808. // 8000 chars exercises both the Content-Disposition parser and the
  9809. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  9810. // Prior to the fix, std::regex_match on this header would cause O(N)
  9811. // stack recursion in libstdc++, leading to SIGSEGV.
  9812. std::string expected_filename(8000, 'A');
  9813. ASSERT_EQ(expected_filename, file.filename);
  9814. res.set_content("ok", "text/plain");
  9815. handled = true;
  9816. });
  9817. thread t = thread([&] { svr.listen(HOST, PORT); });
  9818. auto se = detail::scope_exit([&] {
  9819. svr.stop();
  9820. t.join();
  9821. ASSERT_FALSE(svr.is_running());
  9822. ASSERT_TRUE(handled);
  9823. });
  9824. svr.wait_until_ready();
  9825. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  9826. // Regression test for GHSA-qq6v-r583-3h69
  9827. std::string long_filename(8000, 'A');
  9828. std::string body = "----------\r\n"
  9829. "Content-Disposition: form-data; name=\"file1\"; "
  9830. "filename*=\"Utf-8''" +
  9831. long_filename +
  9832. "\"\r\n"
  9833. "\r\n"
  9834. "hello\r\n"
  9835. "------------\r\n";
  9836. auto req = "POST /test HTTP/1.1\r\n"
  9837. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9838. "Content-Length: " +
  9839. std::to_string(body.size()) + "\r\n\r\n" + body;
  9840. ASSERT_TRUE(send_request(1, req));
  9841. }
  9842. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  9843. auto handled = false;
  9844. Server svr;
  9845. svr.Post("/test", [&](const Request &req, Response &) {
  9846. ASSERT_EQ(2u, req.form.fields.size());
  9847. const auto &text1 = req.form.get_field("text1");
  9848. ASSERT_EQ("text1", text1);
  9849. const auto &text2 = req.form.get_field("text2");
  9850. ASSERT_EQ("text2", text2);
  9851. handled = true;
  9852. });
  9853. thread t = thread([&] { svr.listen(HOST, PORT); });
  9854. auto se = detail::scope_exit([&] {
  9855. svr.stop();
  9856. t.join();
  9857. ASSERT_FALSE(svr.is_running());
  9858. ASSERT_TRUE(handled);
  9859. });
  9860. svr.wait_until_ready();
  9861. auto req = "POST /test HTTP/1.1\r\n"
  9862. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9863. "Content-Length: 146\r\n"
  9864. "\r\n----------\r\n"
  9865. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9866. "\r\n"
  9867. "text1"
  9868. "\r\n----------\r\n"
  9869. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9870. "\r\n"
  9871. "text2"
  9872. "\r\n------------";
  9873. std::string response;
  9874. ASSERT_TRUE(send_request(1, req, &response));
  9875. ASSERT_EQ("200", response.substr(9, 3));
  9876. }
  9877. TEST(MultipartFormDataTest, ContentLength) {
  9878. auto handled = false;
  9879. Server svr;
  9880. svr.Post("/test", [&](const Request &req, Response &) {
  9881. ASSERT_EQ(2u, req.form.fields.size());
  9882. const auto &text1 = req.form.get_field("text1");
  9883. ASSERT_EQ("text1", text1);
  9884. const auto &text2 = req.form.get_field("text2");
  9885. ASSERT_EQ("text2", text2);
  9886. handled = true;
  9887. });
  9888. thread t = thread([&] { svr.listen(HOST, PORT); });
  9889. auto se = detail::scope_exit([&] {
  9890. svr.stop();
  9891. t.join();
  9892. ASSERT_FALSE(svr.is_running());
  9893. ASSERT_TRUE(handled);
  9894. });
  9895. svr.wait_until_ready();
  9896. auto req = "POST /test HTTP/1.1\r\n"
  9897. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9898. "Content-Length: 167\r\n"
  9899. "\r\n----------\r\n"
  9900. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9901. "Content-Length: 5\r\n"
  9902. "\r\n"
  9903. "text1"
  9904. "\r\n----------\r\n"
  9905. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9906. "\r\n"
  9907. "text2"
  9908. "\r\n------------\r\n";
  9909. std::string response;
  9910. ASSERT_TRUE(send_request(1, req, &response));
  9911. ASSERT_EQ("200", response.substr(9, 3));
  9912. }
  9913. TEST(MultipartFormDataTest, AccessPartHeaders) {
  9914. auto handled = false;
  9915. Server svr;
  9916. svr.Post("/test", [&](const Request &req, Response &) {
  9917. ASSERT_EQ(2u, req.form.fields.size());
  9918. const auto &text1 = req.form.get_field("text1");
  9919. ASSERT_EQ("text1", text1);
  9920. // TODO: Add header access for text fields if needed
  9921. const auto &text2 = req.form.get_field("text2");
  9922. ASSERT_EQ("text2", text2);
  9923. // TODO: Header access for text fields needs to be implemented
  9924. // auto &headers = it->second.headers;
  9925. // ASSERT_EQ(3U, headers.size());
  9926. // auto custom_header = headers.find("x-whatever");
  9927. // ASSERT_TRUE(custom_header != headers.end());
  9928. // ASSERT_NE("customvalue", custom_header->second);
  9929. // ASSERT_EQ("CustomValue", custom_header->second);
  9930. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  9931. handled = true;
  9932. });
  9933. thread t = thread([&] { svr.listen(HOST, PORT); });
  9934. auto se = detail::scope_exit([&] {
  9935. svr.stop();
  9936. t.join();
  9937. ASSERT_FALSE(svr.is_running());
  9938. ASSERT_TRUE(handled);
  9939. });
  9940. svr.wait_until_ready();
  9941. auto req = "POST /test HTTP/1.1\r\n"
  9942. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9943. "Content-Length: 232\r\n"
  9944. "\r\n----------\r\n"
  9945. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9946. "Content-Length: 5\r\n"
  9947. "X-Test: 1\r\n"
  9948. "\r\n"
  9949. "text1"
  9950. "\r\n----------\r\n"
  9951. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9952. "Content-Type: text/plain\r\n"
  9953. "X-Whatever: CustomValue\r\n"
  9954. "\r\n"
  9955. "text2"
  9956. "\r\n------------\r\n"
  9957. "That should be disregarded. Not even read";
  9958. std::string response;
  9959. ASSERT_TRUE(send_request(1, req, &response));
  9960. ASSERT_EQ("200", response.substr(9, 3));
  9961. }
  9962. TEST(MultipartFormDataTest, LargeHeader) {
  9963. auto handled = false;
  9964. Server svr;
  9965. svr.Post("/test", [&](const Request &req, Response &) {
  9966. ASSERT_EQ(1u, req.form.fields.size());
  9967. const auto &text = req.form.get_field("name1");
  9968. ASSERT_EQ("text1", text);
  9969. handled = true;
  9970. });
  9971. thread t = thread([&] { svr.listen(HOST, PORT); });
  9972. auto se = detail::scope_exit([&] {
  9973. svr.stop();
  9974. t.join();
  9975. ASSERT_FALSE(svr.is_running());
  9976. ASSERT_TRUE(handled);
  9977. });
  9978. svr.wait_until_ready();
  9979. auto boundary = std::string("cpp-httplib-multipart-data");
  9980. std::string content = "--" + boundary +
  9981. "\r\n"
  9982. "Content-Disposition: form-data; name=\"name1\"\r\n"
  9983. "\r\n"
  9984. "text1\r\n"
  9985. "--" +
  9986. boundary + "--\r\n";
  9987. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  9988. "Content-Type: multipart/form-data;boundary=" +
  9989. boundary +
  9990. "\r\n"
  9991. "Content-Length: " +
  9992. std::to_string(content.size()) +
  9993. "\r\n"
  9994. "Dummy-Header: ";
  9995. std::string header_suffix = "\r\n"
  9996. "\r\n";
  9997. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  9998. size_t header_dummy_size =
  9999. read_buff_size -
  10000. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  10001. auto header_dummy = std::string(header_dummy_size, '@');
  10002. auto req = header_prefix + header_dummy + header_suffix + content;
  10003. std::string response;
  10004. ASSERT_TRUE(send_request(1, req, &response));
  10005. ASSERT_EQ("200", response.substr(9, 3));
  10006. }
  10007. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  10008. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  10009. // (not chunked Transfer-Encoding) after the streaming refactor.
  10010. auto handled = false;
  10011. Server svr;
  10012. svr.Post("/upload", [&](const Request &req, Response &res) {
  10013. auto cl_it = req.headers.find("Content-Length");
  10014. EXPECT_TRUE(cl_it != req.headers.end());
  10015. auto te_it = req.headers.find("Transfer-Encoding");
  10016. EXPECT_TRUE(te_it == req.headers.end());
  10017. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  10018. res.set_content("ok", "text/plain");
  10019. handled = true;
  10020. });
  10021. auto port = svr.bind_to_any_port(HOST);
  10022. auto t = thread([&] { svr.listen_after_bind(); });
  10023. auto se = detail::scope_exit([&] {
  10024. svr.stop();
  10025. t.join();
  10026. ASSERT_FALSE(svr.is_running());
  10027. ASSERT_TRUE(handled);
  10028. });
  10029. svr.wait_until_ready();
  10030. UploadFormDataItems items = {
  10031. {"field1", "hello", "", "text/plain"},
  10032. {"file1", "world", "test.txt", "application/octet-stream"},
  10033. };
  10034. Client cli(HOST, port);
  10035. auto res = cli.Post("/upload", {}, items);
  10036. ASSERT_TRUE(res);
  10037. EXPECT_EQ(StatusCode::OK_200, res->status);
  10038. }
  10039. TEST(MultipartFormDataTest, MakeFileProvider) {
  10040. // Verify make_file_provider sends a file's contents correctly.
  10041. const std::string file_content(4096, 'Z');
  10042. const std::string tmp_path = "/tmp/httplib_test_make_file_provider.bin";
  10043. {
  10044. std::ofstream ofs(tmp_path, std::ios::binary);
  10045. ofs.write(file_content.data(),
  10046. static_cast<std::streamsize>(file_content.size()));
  10047. }
  10048. auto handled = false;
  10049. Server svr;
  10050. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  10051. const ContentReader &content_reader) {
  10052. ASSERT_TRUE(req.is_multipart_form_data());
  10053. std::vector<FormData> items;
  10054. content_reader(
  10055. [&](const FormData &file) {
  10056. items.push_back(file);
  10057. return true;
  10058. },
  10059. [&](const char *data, size_t data_length) {
  10060. items.back().content.append(data, data_length);
  10061. return true;
  10062. });
  10063. ASSERT_EQ(1u, items.size());
  10064. EXPECT_EQ("myfile", items[0].name);
  10065. EXPECT_EQ("data.bin", items[0].filename);
  10066. EXPECT_EQ("application/octet-stream", items[0].content_type);
  10067. EXPECT_EQ(file_content, items[0].content);
  10068. handled = true;
  10069. });
  10070. auto port = svr.bind_to_any_port(HOST);
  10071. auto t = thread([&] { svr.listen_after_bind(); });
  10072. auto se = detail::scope_exit([&] {
  10073. svr.stop();
  10074. t.join();
  10075. ASSERT_FALSE(svr.is_running());
  10076. ASSERT_TRUE(handled);
  10077. std::remove(tmp_path.c_str());
  10078. });
  10079. svr.wait_until_ready();
  10080. FormDataProviderItems providers;
  10081. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  10082. "application/octet-stream"));
  10083. Client cli(HOST, port);
  10084. auto res = cli.Post("/upload", {}, {}, providers);
  10085. ASSERT_TRUE(res);
  10086. EXPECT_EQ(StatusCode::OK_200, res->status);
  10087. }
  10088. TEST(MakeFileBodyTest, Basic) {
  10089. const std::string file_content(4096, 'Z');
  10090. const std::string tmp_path = "/tmp/httplib_test_make_file_body.bin";
  10091. {
  10092. std::ofstream ofs(tmp_path, std::ios::binary);
  10093. ofs.write(file_content.data(),
  10094. static_cast<std::streamsize>(file_content.size()));
  10095. }
  10096. auto handled = false;
  10097. Server svr;
  10098. svr.Post("/upload", [&](const Request &req, Response &res) {
  10099. EXPECT_EQ(file_content, req.body);
  10100. handled = true;
  10101. res.status = StatusCode::OK_200;
  10102. });
  10103. auto port = svr.bind_to_any_port(HOST);
  10104. auto t = thread([&] { svr.listen_after_bind(); });
  10105. auto se = detail::scope_exit([&] {
  10106. svr.stop();
  10107. t.join();
  10108. ASSERT_FALSE(svr.is_running());
  10109. ASSERT_TRUE(handled);
  10110. std::remove(tmp_path.c_str());
  10111. });
  10112. svr.wait_until_ready();
  10113. auto fb = make_file_body(tmp_path);
  10114. ASSERT_GT(fb.first, 0u);
  10115. Client cli(HOST, port);
  10116. auto res =
  10117. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  10118. ASSERT_TRUE(res);
  10119. EXPECT_EQ(StatusCode::OK_200, res->status);
  10120. }
  10121. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  10122. static constexpr unsigned int number_of_tasks{1000000};
  10123. std::atomic_uint count{0};
  10124. std::unique_ptr<TaskQueue> task_queue{
  10125. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  10126. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10127. auto queued = task_queue->enqueue(
  10128. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  10129. EXPECT_TRUE(queued);
  10130. }
  10131. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10132. task_queue->shutdown();
  10133. #else
  10134. EXPECT_NO_THROW(task_queue->shutdown());
  10135. #endif
  10136. EXPECT_EQ(number_of_tasks, count.load());
  10137. }
  10138. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  10139. static constexpr unsigned int number_of_tasks{1000000};
  10140. static constexpr unsigned int qlimit{2};
  10141. unsigned int queued_count{0};
  10142. std::atomic_uint count{0};
  10143. std::unique_ptr<TaskQueue> task_queue{
  10144. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  10145. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10146. if (task_queue->enqueue(
  10147. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  10148. queued_count++;
  10149. }
  10150. }
  10151. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10152. task_queue->shutdown();
  10153. #else
  10154. EXPECT_NO_THROW(task_queue->shutdown());
  10155. #endif
  10156. EXPECT_EQ(queued_count, count.load());
  10157. EXPECT_TRUE(queued_count <= number_of_tasks);
  10158. EXPECT_TRUE(queued_count >= qlimit);
  10159. }
  10160. TEST(TaskQueueTest, MaxQueuedRequests) {
  10161. static constexpr unsigned int qlimit{3};
  10162. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  10163. std::condition_variable sem_cv;
  10164. std::mutex sem_mtx;
  10165. int credits = 0;
  10166. bool queued;
  10167. /* Fill up the queue with tasks that will block until we give them credits to
  10168. * complete. */
  10169. for (unsigned int n = 0; n <= qlimit;) {
  10170. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  10171. std::unique_lock<std::mutex> lock(sem_mtx);
  10172. while (credits <= 0) {
  10173. sem_cv.wait(lock);
  10174. }
  10175. /* Consume the credit and signal the test code if they are all gone. */
  10176. if (--credits == 0) { sem_cv.notify_one(); }
  10177. });
  10178. if (n < qlimit) {
  10179. /* The first qlimit enqueues must succeed. */
  10180. EXPECT_TRUE(queued);
  10181. } else {
  10182. /* The last one will succeed only when the worker thread
  10183. * starts and dequeues the first blocking task. Although
  10184. * not necessary for the correctness of this test, we sleep for
  10185. * a short while to avoid busy waiting. */
  10186. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10187. }
  10188. if (queued) { n++; }
  10189. }
  10190. /* Further enqueues must fail since the queue is full. */
  10191. for (auto i = 0; i < 4; i++) {
  10192. queued = task_queue->enqueue([] {});
  10193. EXPECT_FALSE(queued);
  10194. }
  10195. /* Give the credits to allow the previous tasks to complete. */
  10196. {
  10197. std::unique_lock<std::mutex> lock(sem_mtx);
  10198. credits += qlimit + 1;
  10199. }
  10200. sem_cv.notify_all();
  10201. /* Wait for all the credits to be consumed. */
  10202. {
  10203. std::unique_lock<std::mutex> lock(sem_mtx);
  10204. while (credits > 0) {
  10205. sem_cv.wait(lock);
  10206. }
  10207. }
  10208. /* Check that we are able again to enqueue at least qlimit tasks. */
  10209. for (unsigned int i = 0; i < qlimit; i++) {
  10210. queued = task_queue->enqueue([] {});
  10211. EXPECT_TRUE(queued);
  10212. }
  10213. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10214. task_queue->shutdown();
  10215. #else
  10216. EXPECT_NO_THROW(task_queue->shutdown());
  10217. #endif
  10218. }
  10219. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  10220. Server svr;
  10221. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10222. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  10223. });
  10224. svr.Get("/hello", [](const Request &req, Response &res) {
  10225. res.set_content(req.get_param_value("key"), "text/plain");
  10226. });
  10227. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10228. auto se = detail::scope_exit([&] {
  10229. svr.stop();
  10230. thread.join();
  10231. ASSERT_FALSE(svr.is_running());
  10232. });
  10233. svr.wait_until_ready();
  10234. {
  10235. Client cli(HOST, PORT);
  10236. cli.set_follow_location(true);
  10237. auto res = cli.Get("/");
  10238. ASSERT_TRUE(res);
  10239. EXPECT_EQ(StatusCode::OK_200, res->status);
  10240. EXPECT_EQ("val&key2=val2", res->body);
  10241. }
  10242. }
  10243. #endif
  10244. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  10245. Server svr;
  10246. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10247. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  10248. });
  10249. svr.Get("/hello", [](const Request &req, Response &res) {
  10250. res.set_content(req.get_param_value("key"), "text/plain");
  10251. });
  10252. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10253. auto se = detail::scope_exit([&] {
  10254. svr.stop();
  10255. thread.join();
  10256. ASSERT_FALSE(svr.is_running());
  10257. });
  10258. svr.wait_until_ready();
  10259. {
  10260. Client cli(HOST, PORT);
  10261. cli.set_follow_location(true);
  10262. auto res = cli.Get("/");
  10263. ASSERT_TRUE(res);
  10264. EXPECT_EQ(StatusCode::OK_200, res->status);
  10265. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  10266. }
  10267. }
  10268. #ifdef CPPHTTPLIB_SSL_ENABLED
  10269. TEST(RedirectTest, Issue2185_Online) {
  10270. SSLClient client("github.com");
  10271. client.set_follow_location(true);
  10272. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  10273. "Coollab-Windows.zip");
  10274. ASSERT_TRUE(res);
  10275. EXPECT_EQ(StatusCode::OK_200, res->status);
  10276. EXPECT_EQ(9920427U, res->body.size());
  10277. }
  10278. #endif
  10279. TEST(VulnerabilityTest, CRLFInjection) {
  10280. Server svr;
  10281. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  10282. res.set_content("Hello 1", "text/plain");
  10283. });
  10284. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  10285. res.set_content("Hello 2", "text/plain");
  10286. });
  10287. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  10288. res.set_content("Hello 3", "text/plain");
  10289. });
  10290. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  10291. res.set_content("Hello 4", "text/plain");
  10292. });
  10293. svr.set_logger([](const Request &req, const Response & /*res*/) {
  10294. for (const auto &x : req.headers) {
  10295. auto key = x.first;
  10296. EXPECT_STRNE("evil", key.c_str());
  10297. }
  10298. });
  10299. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10300. auto se = detail::scope_exit([&] {
  10301. svr.stop();
  10302. thread.join();
  10303. ASSERT_FALSE(svr.is_running());
  10304. });
  10305. svr.wait_until_ready();
  10306. {
  10307. Client cli(HOST, PORT);
  10308. cli.Post("/test1", "A=B",
  10309. "application/x-www-form-urlencoded\r\nevil: hello1");
  10310. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  10311. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  10312. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  10313. }
  10314. }
  10315. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  10316. auto server_thread = std::thread([] {
  10317. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10318. default_socket_options(srv);
  10319. sockaddr_in addr{};
  10320. addr.sin_family = AF_INET;
  10321. addr.sin_port = htons(PORT + 1);
  10322. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10323. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10324. ::listen(srv, 1);
  10325. sockaddr_in cli_addr{};
  10326. socklen_t cli_len = sizeof(cli_addr);
  10327. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10328. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  10329. std::string buf_all;
  10330. char buf[2048];
  10331. ssize_t n;
  10332. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  10333. buf_all.append(buf, static_cast<size_t>(n));
  10334. size_t pos;
  10335. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  10336. auto request_block = buf_all.substr(0, pos + 4); // include separator
  10337. auto e = request_block.find("\r\n");
  10338. if (e != std::string::npos) {
  10339. auto request_line = request_block.substr(0, e);
  10340. std::string msg =
  10341. "CRLF injection detected in request line: '" + request_line + "'";
  10342. EXPECT_FALSE(true) << msg;
  10343. }
  10344. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  10345. ::send(cli,
  10346. #ifdef _WIN32
  10347. static_cast<const char *>(resp.c_str()),
  10348. static_cast<int>(resp.size()),
  10349. #else
  10350. resp.c_str(), resp.size(),
  10351. #endif
  10352. 0);
  10353. buf_all.erase(0, pos + 4);
  10354. }
  10355. }
  10356. detail::close_socket(cli);
  10357. detail::close_socket(srv);
  10358. });
  10359. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10360. auto cli = Client("127.0.0.1", PORT + 1);
  10361. auto headers = Headers{
  10362. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  10363. {"Connection", "keep-alive"}};
  10364. auto res = cli.Get("/hi", headers);
  10365. EXPECT_FALSE(res);
  10366. EXPECT_EQ(Error::InvalidHeaders, res.error());
  10367. server_thread.join();
  10368. }
  10369. TEST(PathParamsTest, StaticMatch) {
  10370. const auto pattern = "/users/all";
  10371. detail::PathParamsMatcher matcher(pattern);
  10372. Request request;
  10373. request.path = "/users/all";
  10374. ASSERT_TRUE(matcher.match(request));
  10375. std::unordered_map<std::string, std::string> expected_params = {};
  10376. EXPECT_EQ(request.path_params, expected_params);
  10377. }
  10378. TEST(PathParamsTest, StaticMismatch) {
  10379. const auto pattern = "/users/all";
  10380. detail::PathParamsMatcher matcher(pattern);
  10381. Request request;
  10382. request.path = "/users/1";
  10383. ASSERT_FALSE(matcher.match(request));
  10384. }
  10385. TEST(PathParamsTest, SingleParamInTheMiddle) {
  10386. const auto pattern = "/users/:id/subscriptions";
  10387. detail::PathParamsMatcher matcher(pattern);
  10388. Request request;
  10389. request.path = "/users/42/subscriptions";
  10390. ASSERT_TRUE(matcher.match(request));
  10391. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10392. EXPECT_EQ(request.path_params, expected_params);
  10393. }
  10394. TEST(PathParamsTest, SingleParamInTheEnd) {
  10395. const auto pattern = "/users/:id";
  10396. detail::PathParamsMatcher matcher(pattern);
  10397. Request request;
  10398. request.path = "/users/24";
  10399. ASSERT_TRUE(matcher.match(request));
  10400. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  10401. EXPECT_EQ(request.path_params, expected_params);
  10402. }
  10403. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  10404. const auto pattern = "/users/:id/";
  10405. detail::PathParamsMatcher matcher(pattern);
  10406. Request request;
  10407. request.path = "/users/42/";
  10408. ASSERT_TRUE(matcher.match(request));
  10409. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10410. EXPECT_EQ(request.path_params, expected_params);
  10411. }
  10412. TEST(PathParamsTest, EmptyParam) {
  10413. const auto pattern = "/users/:id/";
  10414. detail::PathParamsMatcher matcher(pattern);
  10415. Request request;
  10416. request.path = "/users//";
  10417. ASSERT_TRUE(matcher.match(request));
  10418. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10419. EXPECT_EQ(request.path_params, expected_params);
  10420. }
  10421. TEST(PathParamsTest, FragmentMismatch) {
  10422. const auto pattern = "/users/:id/";
  10423. detail::PathParamsMatcher matcher(pattern);
  10424. Request request;
  10425. request.path = "/admins/24/";
  10426. ASSERT_FALSE(matcher.match(request));
  10427. }
  10428. TEST(PathParamsTest, ExtraFragments) {
  10429. const auto pattern = "/users/:id";
  10430. detail::PathParamsMatcher matcher(pattern);
  10431. Request request;
  10432. request.path = "/users/42/subscriptions";
  10433. ASSERT_FALSE(matcher.match(request));
  10434. }
  10435. TEST(PathParamsTest, MissingTrailingParam) {
  10436. const auto pattern = "/users/:id";
  10437. detail::PathParamsMatcher matcher(pattern);
  10438. Request request;
  10439. request.path = "/users";
  10440. ASSERT_FALSE(matcher.match(request));
  10441. }
  10442. TEST(PathParamsTest, MissingParamInTheMiddle) {
  10443. const auto pattern = "/users/:id/subscriptions";
  10444. detail::PathParamsMatcher matcher(pattern);
  10445. Request request;
  10446. request.path = "/users/subscriptions";
  10447. ASSERT_FALSE(matcher.match(request));
  10448. }
  10449. TEST(PathParamsTest, MultipleParams) {
  10450. const auto pattern = "/users/:userid/subscriptions/:subid";
  10451. detail::PathParamsMatcher matcher(pattern);
  10452. Request request;
  10453. request.path = "/users/42/subscriptions/2";
  10454. ASSERT_TRUE(matcher.match(request));
  10455. std::unordered_map<std::string, std::string> expected_params = {
  10456. {"userid", "42"}, {"subid", "2"}};
  10457. EXPECT_EQ(request.path_params, expected_params);
  10458. }
  10459. TEST(PathParamsTest, SequenceOfParams) {
  10460. const auto pattern = "/values/:x/:y/:z";
  10461. detail::PathParamsMatcher matcher(pattern);
  10462. Request request;
  10463. request.path = "/values/1/2/3";
  10464. ASSERT_TRUE(matcher.match(request));
  10465. std::unordered_map<std::string, std::string> expected_params = {
  10466. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  10467. EXPECT_EQ(request.path_params, expected_params);
  10468. }
  10469. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  10470. const auto pattern = "/prefix:suffix";
  10471. detail::PathParamsMatcher matcher(pattern);
  10472. Request request;
  10473. request.path = "/prefix:suffix";
  10474. ASSERT_TRUE(matcher.match(request));
  10475. const std::unordered_map<std::string, std::string> expected_params = {};
  10476. EXPECT_EQ(request.path_params, expected_params);
  10477. }
  10478. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  10479. // If ipv6 regex working, regex match codepath is taken.
  10480. // else port will default to 80 in Client impl
  10481. int clientImplMagicPort = 80;
  10482. int port = 4321;
  10483. // above ports must be different to avoid false negative
  10484. EXPECT_NE(clientImplMagicPort, port);
  10485. std::string ipV6TestURL = "http://[ff06::c3]";
  10486. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  10487. CLIENT_PRIVATE_KEY_FILE);
  10488. EXPECT_EQ(cli.port(), port);
  10489. }
  10490. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  10491. auto file_path = "./www/dir/index.html";
  10492. auto dir_path = "./www/dir";
  10493. detail::FileStat stat_file(file_path);
  10494. EXPECT_TRUE(stat_file.is_file());
  10495. EXPECT_FALSE(stat_file.is_dir());
  10496. detail::FileStat stat_dir(dir_path);
  10497. EXPECT_FALSE(stat_dir.is_file());
  10498. EXPECT_TRUE(stat_dir.is_dir());
  10499. }
  10500. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  10501. // IPv4 with default HTTP port (80)
  10502. EXPECT_EQ("example.com",
  10503. detail::make_host_and_port_string("example.com", 80, false));
  10504. // IPv4 with default HTTPS port (443)
  10505. EXPECT_EQ("example.com",
  10506. detail::make_host_and_port_string("example.com", 443, true));
  10507. // IPv4 with non-default HTTP port
  10508. EXPECT_EQ("example.com:8080",
  10509. detail::make_host_and_port_string("example.com", 8080, false));
  10510. // IPv4 with non-default HTTPS port
  10511. EXPECT_EQ("example.com:8443",
  10512. detail::make_host_and_port_string("example.com", 8443, true));
  10513. // IPv6 with default HTTP port (80)
  10514. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  10515. // IPv6 with default HTTPS port (443)
  10516. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  10517. // IPv6 with non-default HTTP port
  10518. EXPECT_EQ("[::1]:8080",
  10519. detail::make_host_and_port_string("::1", 8080, false));
  10520. // IPv6 with non-default HTTPS port
  10521. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  10522. // IPv6 full address with default port
  10523. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  10524. detail::make_host_and_port_string(
  10525. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  10526. // IPv6 full address with non-default port
  10527. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  10528. detail::make_host_and_port_string(
  10529. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  10530. // IPv6 localhost with non-default port
  10531. EXPECT_EQ("[::1]:3000",
  10532. detail::make_host_and_port_string("::1", 3000, false));
  10533. // IPv6 with zone ID (link-local address) with default port
  10534. EXPECT_EQ("[fe80::1%eth0]",
  10535. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  10536. // IPv6 with zone ID (link-local address) with non-default port
  10537. EXPECT_EQ("[fe80::1%eth0]:8080",
  10538. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  10539. // Edge case: Port 443 with is_ssl=false (should add port)
  10540. EXPECT_EQ("example.com:443",
  10541. detail::make_host_and_port_string("example.com", 443, false));
  10542. // Edge case: Port 80 with is_ssl=true (should add port)
  10543. EXPECT_EQ("example.com:80",
  10544. detail::make_host_and_port_string("example.com", 80, true));
  10545. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  10546. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  10547. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  10548. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  10549. // Security fix: Already bracketed IPv6 should not get double brackets
  10550. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  10551. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  10552. EXPECT_EQ("[::1]:8080",
  10553. detail::make_host_and_port_string("[::1]", 8080, false));
  10554. EXPECT_EQ("[2001:db8::1]:8080",
  10555. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  10556. EXPECT_EQ("[fe80::1%eth0]",
  10557. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  10558. EXPECT_EQ("[fe80::1%eth0]:8080",
  10559. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  10560. // Edge case: Empty host (should return as-is)
  10561. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  10562. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  10563. // This is a known limitation but shouldn't crash
  10564. EXPECT_EQ("[host:name]",
  10565. detail::make_host_and_port_string("host:name", 80, false));
  10566. // Port number edge cases (no validation, but should not crash)
  10567. EXPECT_EQ("example.com:0",
  10568. detail::make_host_and_port_string("example.com", 0, false));
  10569. EXPECT_EQ("example.com:-1",
  10570. detail::make_host_and_port_string("example.com", -1, false));
  10571. EXPECT_EQ("example.com:65535",
  10572. detail::make_host_and_port_string("example.com", 65535, false));
  10573. EXPECT_EQ("example.com:65536",
  10574. detail::make_host_and_port_string("example.com", 65536, false));
  10575. }
  10576. #ifdef CPPHTTPLIB_SSL_ENABLED
  10577. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  10578. httplib::SSLClient cli("roblox.com", 443);
  10579. cli.set_follow_location(true);
  10580. auto res = cli.Get("/");
  10581. ASSERT_TRUE(res);
  10582. EXPECT_EQ(StatusCode::OK_200, res->status);
  10583. }
  10584. #endif
  10585. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  10586. Server svr;
  10587. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10588. EXPECT_EQ(res.status, 400);
  10589. });
  10590. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10591. auto se = detail::scope_exit([&] {
  10592. svr.stop();
  10593. thread.join();
  10594. ASSERT_FALSE(svr.is_running());
  10595. });
  10596. svr.wait_until_ready();
  10597. Client cli(HOST, PORT);
  10598. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  10599. }
  10600. TEST(InvalidHeaderCharsTest, is_field_name) {
  10601. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  10602. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  10603. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  10604. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  10605. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  10606. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  10607. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  10608. EXPECT_FALSE(detail::fields::is_field_name(""));
  10609. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  10610. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  10611. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  10612. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  10613. }
  10614. TEST(InvalidHeaderCharsTest, is_field_value) {
  10615. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  10616. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  10617. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  10618. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  10619. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  10620. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  10621. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  10622. EXPECT_TRUE(detail::fields::is_field_value(""));
  10623. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  10624. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  10625. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  10626. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  10627. EXPECT_TRUE(detail::fields::is_field_value("0"));
  10628. }
  10629. TEST(InvalidHeaderCharsTest, OnServer) {
  10630. Server svr;
  10631. svr.Get("/test_name", [&](const Request &req, Response &res) {
  10632. std::string header = "Not Set";
  10633. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10634. res.set_header(header, "value");
  10635. res.set_content("Page Content Page Content", "text/plain");
  10636. });
  10637. svr.Get("/test_value", [&](const Request &req, Response &res) {
  10638. std::string header = "Not Set";
  10639. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10640. res.set_header("X-Test", header);
  10641. res.set_content("Page Content Page Content", "text/plain");
  10642. });
  10643. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10644. auto se = detail::scope_exit([&] {
  10645. svr.stop();
  10646. thread.join();
  10647. ASSERT_FALSE(svr.is_running());
  10648. });
  10649. svr.wait_until_ready();
  10650. Client cli(HOST, PORT);
  10651. {
  10652. auto res = cli.Get(
  10653. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10654. ASSERT_TRUE(res);
  10655. EXPECT_EQ("Page Content Page Content", res->body);
  10656. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10657. }
  10658. {
  10659. auto res = cli.Get(
  10660. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10661. ASSERT_TRUE(res);
  10662. EXPECT_EQ("Page Content Page Content", res->body);
  10663. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10664. }
  10665. }
  10666. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  10667. auto handled = false;
  10668. Server svr;
  10669. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10670. thread t = thread([&] { svr.listen(HOST, PORT); });
  10671. auto se = detail::scope_exit([&] {
  10672. svr.stop();
  10673. t.join();
  10674. ASSERT_FALSE(svr.is_running());
  10675. ASSERT_FALSE(handled);
  10676. });
  10677. svr.wait_until_ready();
  10678. auto req = "POST /test HTTP/1.1\r\n"
  10679. "Content-Length: x\r\n"
  10680. "\r\n";
  10681. std::string response;
  10682. ASSERT_TRUE(send_request(1, req, &response));
  10683. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10684. response.substr(0, response.find("\r\n")));
  10685. }
  10686. #ifndef _WIN32
  10687. TEST(Expect100ContinueTest, ServerClosesConnection) {
  10688. static constexpr char reject[] = "Unauthorized";
  10689. static constexpr char accept[] = "Upload accepted";
  10690. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  10691. Server svr;
  10692. svr.set_expect_100_continue_handler(
  10693. [](const Request & /*req*/, Response &res) {
  10694. res.status = StatusCode::Unauthorized_401;
  10695. res.set_content(reject, "text/plain");
  10696. return res.status;
  10697. });
  10698. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  10699. res.set_content(accept, "text/plain");
  10700. });
  10701. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10702. auto se = detail::scope_exit([&] {
  10703. svr.stop();
  10704. thread.join();
  10705. ASSERT_FALSE(svr.is_running());
  10706. });
  10707. svr.wait_until_ready();
  10708. {
  10709. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  10710. curl_easy_init(), &curl_easy_cleanup};
  10711. ASSERT_NE(curl, nullptr);
  10712. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  10713. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  10714. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  10715. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  10716. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  10717. &curl_slist_free_all};
  10718. ASSERT_NE(list, nullptr);
  10719. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  10720. struct read_data {
  10721. size_t read_size;
  10722. size_t total_size;
  10723. } data = {0, total_size};
  10724. using read_callback_t =
  10725. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10726. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  10727. void *userdata) -> size_t {
  10728. read_data *data = (read_data *)userdata;
  10729. if (!userdata || data->read_size >= data->total_size) { return 0; }
  10730. std::fill_n(ptr, size * nmemb, 'A');
  10731. data->read_size += size * nmemb;
  10732. return size * nmemb;
  10733. };
  10734. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  10735. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  10736. std::vector<char> buffer;
  10737. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  10738. using write_callback_t =
  10739. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10740. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  10741. void *userdata) -> size_t {
  10742. std::vector<char> *buffer = (std::vector<char> *)userdata;
  10743. buffer->reserve(buffer->size() + size * nmemb + 1);
  10744. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  10745. return size * nmemb;
  10746. };
  10747. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  10748. {
  10749. const auto res = curl_easy_perform(curl.get());
  10750. ASSERT_EQ(res, CURLE_OK);
  10751. }
  10752. {
  10753. auto response_code = long{};
  10754. const auto res =
  10755. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  10756. ASSERT_EQ(res, CURLE_OK);
  10757. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  10758. }
  10759. {
  10760. auto dl = curl_off_t{};
  10761. const auto res =
  10762. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  10763. ASSERT_EQ(res, CURLE_OK);
  10764. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  10765. }
  10766. {
  10767. buffer.push_back('\0');
  10768. ASSERT_STRCASEEQ(buffer.data(), reject);
  10769. }
  10770. }
  10771. }
  10772. #endif
  10773. template <typename S, typename C>
  10774. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  10775. svr.Get("/stream", [&](const Request &, Response &res) {
  10776. auto data = new std::string("01234567890123456789");
  10777. res.set_content_provider(
  10778. data->size(), "text/plain",
  10779. [&, data](size_t offset, size_t length, DataSink &sink) {
  10780. const size_t DATA_CHUNK_SIZE = 4;
  10781. const auto &d = *data;
  10782. std::this_thread::sleep_for(std::chrono::seconds(1));
  10783. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  10784. return true;
  10785. },
  10786. [data](bool success) {
  10787. EXPECT_FALSE(success);
  10788. delete data;
  10789. });
  10790. });
  10791. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  10792. auto i = new size_t(0);
  10793. res.set_content_provider(
  10794. "text/plain",
  10795. [i](size_t, DataSink &sink) {
  10796. if (*i < 5) {
  10797. std::this_thread::sleep_for(std::chrono::seconds(1));
  10798. sink.write("abcd", 4);
  10799. (*i)++;
  10800. } else {
  10801. sink.done();
  10802. }
  10803. return true;
  10804. },
  10805. [i](bool success) {
  10806. EXPECT_FALSE(success);
  10807. delete i;
  10808. });
  10809. });
  10810. svr.Get("/chunked", [&](const Request &, Response &res) {
  10811. auto i = new size_t(0);
  10812. res.set_chunked_content_provider(
  10813. "text/plain",
  10814. [i](size_t, DataSink &sink) {
  10815. if (*i < 5) {
  10816. std::this_thread::sleep_for(std::chrono::seconds(1));
  10817. sink.os << "abcd";
  10818. (*i)++;
  10819. } else {
  10820. sink.done();
  10821. }
  10822. return true;
  10823. },
  10824. [i](bool success) {
  10825. EXPECT_FALSE(success);
  10826. delete i;
  10827. });
  10828. });
  10829. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10830. auto se = detail::scope_exit([&] {
  10831. svr.stop();
  10832. listen_thread.join();
  10833. ASSERT_FALSE(svr.is_running());
  10834. });
  10835. svr.wait_until_ready();
  10836. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  10837. {
  10838. auto start = std::chrono::steady_clock::now();
  10839. auto res = cli.Get("/stream");
  10840. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10841. std::chrono::steady_clock::now() - start)
  10842. .count();
  10843. ASSERT_FALSE(res);
  10844. EXPECT_EQ(Error::Read, res.error());
  10845. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10846. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10847. }
  10848. {
  10849. auto start = std::chrono::steady_clock::now();
  10850. auto res = cli.Get("/stream_without_length");
  10851. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10852. std::chrono::steady_clock::now() - start)
  10853. .count();
  10854. ASSERT_FALSE(res);
  10855. EXPECT_EQ(Error::Read, res.error());
  10856. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10857. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10858. }
  10859. {
  10860. auto start = std::chrono::steady_clock::now();
  10861. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  10862. EXPECT_EQ("abcd", string(data, data_length));
  10863. return true;
  10864. });
  10865. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10866. std::chrono::steady_clock::now() - start)
  10867. .count();
  10868. ASSERT_FALSE(res);
  10869. EXPECT_EQ(Error::Read, res.error());
  10870. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10871. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10872. }
  10873. }
  10874. TEST(MaxTimeoutTest, ContentStream) {
  10875. time_t timeout = 2000;
  10876. time_t threshold = 200;
  10877. Server svr;
  10878. Client cli("localhost", PORT);
  10879. max_timeout_test(svr, cli, timeout, threshold);
  10880. }
  10881. #ifdef CPPHTTPLIB_SSL_ENABLED
  10882. TEST(MaxTimeoutTest, ContentStreamSSL) {
  10883. time_t timeout = 2000;
  10884. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  10885. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10886. SSLClient cli("localhost", PORT);
  10887. cli.enable_server_certificate_verification(false);
  10888. max_timeout_test(svr, cli, timeout, threshold);
  10889. }
  10890. #endif
  10891. class EventDispatcher {
  10892. public:
  10893. EventDispatcher() {}
  10894. bool wait_event(DataSink *sink) {
  10895. unique_lock<mutex> lk(m_);
  10896. int id = id_;
  10897. // Wait with timeout to prevent hanging if client disconnects
  10898. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  10899. [&] { return cid_ == id; })) {
  10900. return false; // Timeout occurred
  10901. }
  10902. sink->write(message_.data(), message_.size());
  10903. return true;
  10904. }
  10905. void send_event(const string &message) {
  10906. lock_guard<mutex> lk(m_);
  10907. cid_ = id_++;
  10908. message_ = message;
  10909. cv_.notify_all();
  10910. }
  10911. private:
  10912. mutex m_;
  10913. condition_variable cv_;
  10914. atomic_int id_{0};
  10915. atomic_int cid_{-1};
  10916. string message_;
  10917. };
  10918. TEST(ClientInThreadTest, Issue2068) {
  10919. EventDispatcher ed;
  10920. Server svr;
  10921. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  10922. res.set_chunked_content_provider("text/event-stream",
  10923. [&](size_t /*offset*/, DataSink &sink) {
  10924. return ed.wait_event(&sink);
  10925. });
  10926. });
  10927. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10928. svr.wait_until_ready();
  10929. thread event_thread([&] {
  10930. int id = 0;
  10931. while (svr.is_running()) {
  10932. this_thread::sleep_for(chrono::milliseconds(500));
  10933. std::stringstream ss;
  10934. ss << "data: " << id << "\n\n";
  10935. ed.send_event(ss.str());
  10936. id++;
  10937. }
  10938. });
  10939. auto se = detail::scope_exit([&] {
  10940. svr.stop();
  10941. listen_thread.join();
  10942. event_thread.join();
  10943. ASSERT_FALSE(svr.is_running());
  10944. });
  10945. {
  10946. auto client = detail::make_unique<Client>(HOST, PORT);
  10947. client->set_read_timeout(std::chrono::minutes(10));
  10948. std::atomic<bool> stop{false};
  10949. std::thread t([&] {
  10950. client->Get("/event1",
  10951. [&](const char *, size_t) -> bool { return !stop; });
  10952. });
  10953. std::this_thread::sleep_for(std::chrono::seconds(2));
  10954. stop = true;
  10955. client->stop();
  10956. t.join();
  10957. // Reset client after thread has finished
  10958. client.reset();
  10959. }
  10960. }
  10961. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  10962. auto handled = false;
  10963. Server svr;
  10964. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10965. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10966. auto se = detail::scope_exit([&] {
  10967. svr.stop();
  10968. t.join();
  10969. ASSERT_FALSE(svr.is_running());
  10970. ASSERT_FALSE(handled);
  10971. });
  10972. svr.wait_until_ready();
  10973. // Two Content-Length headers with different values — must be rejected
  10974. auto req = "POST /test HTTP/1.1\r\n"
  10975. "Content-Length: 5\r\n"
  10976. "Content-Length: 10\r\n"
  10977. "\r\n"
  10978. "hello";
  10979. std::string response;
  10980. ASSERT_TRUE(send_request(1, req, &response));
  10981. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10982. response.substr(0, response.find("\r\n")));
  10983. }
  10984. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  10985. auto handled = false;
  10986. Server svr;
  10987. svr.Post("/test", [&](const Request &, Response &res) {
  10988. handled = true;
  10989. res.set_content("ok", "text/plain");
  10990. });
  10991. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10992. auto se = detail::scope_exit([&] {
  10993. svr.stop();
  10994. t.join();
  10995. ASSERT_FALSE(svr.is_running());
  10996. ASSERT_TRUE(handled);
  10997. });
  10998. svr.wait_until_ready();
  10999. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  11000. auto req = "POST /test HTTP/1.1\r\n"
  11001. "Content-Length: 5\r\n"
  11002. "Content-Length: 5\r\n"
  11003. "\r\n"
  11004. "hello";
  11005. std::string response;
  11006. ASSERT_TRUE(send_request(1, req, &response));
  11007. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  11008. }
  11009. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  11010. Server svr;
  11011. svr.Get("/", [](const Request &req, Response &res) {
  11012. EXPECT_EQ(2U, req.trailers.size());
  11013. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  11014. // Denied
  11015. EXPECT_FALSE(req.has_trailer("Content-Length"));
  11016. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  11017. // Accepted
  11018. EXPECT_TRUE(req.has_trailer("X-Hello"));
  11019. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  11020. EXPECT_TRUE(req.has_trailer("X-World"));
  11021. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  11022. res.set_content("ok", "text/plain");
  11023. });
  11024. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11025. auto se = detail::scope_exit([&] {
  11026. svr.stop();
  11027. t.join();
  11028. ASSERT_FALSE(svr.is_running());
  11029. });
  11030. svr.wait_until_ready();
  11031. const std::string req = "GET / HTTP/1.1\r\n"
  11032. "Transfer-Encoding: chunked\r\n"
  11033. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  11034. "\r\n"
  11035. "0\r\n"
  11036. "Content-Length: 10\r\n"
  11037. "Host: internal.local\r\n"
  11038. "Content-Type: malicious/content\r\n"
  11039. "Cookie: any\r\n"
  11040. "Set-Cookie: any\r\n"
  11041. "X-Forwarded-For: attacker.com\r\n"
  11042. "X-Real-Ip: 1.1.1.1\r\n"
  11043. "X-Hello: hello\r\n"
  11044. "X-World: world\r\n"
  11045. "\r\n";
  11046. std::string res;
  11047. ASSERT_TRUE(send_request(1, req, &res));
  11048. }
  11049. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  11050. Server svr;
  11051. std::string observed_remote_addr;
  11052. std::string observed_xff;
  11053. svr.Get("/ip", [&](const Request &req, Response &res) {
  11054. observed_remote_addr = req.remote_addr;
  11055. observed_xff = req.get_header_value("X-Forwarded-For");
  11056. res.set_content("ok", "text/plain");
  11057. });
  11058. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11059. auto se = detail::scope_exit([&] {
  11060. svr.stop();
  11061. t.join();
  11062. ASSERT_FALSE(svr.is_running());
  11063. });
  11064. svr.wait_until_ready();
  11065. Client cli(HOST, PORT);
  11066. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  11067. ASSERT_TRUE(res);
  11068. EXPECT_EQ(StatusCode::OK_200, res->status);
  11069. EXPECT_EQ(observed_xff, "203.0.113.66");
  11070. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11071. observed_remote_addr == "127.0.0.1");
  11072. }
  11073. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  11074. Server svr;
  11075. svr.set_trusted_proxies({"203.0.113.66"});
  11076. std::string observed_remote_addr;
  11077. std::string observed_xff;
  11078. svr.Get("/ip", [&](const Request &req, Response &res) {
  11079. observed_remote_addr = req.remote_addr;
  11080. observed_xff = req.get_header_value("X-Forwarded-For");
  11081. res.set_content("ok", "text/plain");
  11082. });
  11083. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11084. auto se = detail::scope_exit([&] {
  11085. svr.stop();
  11086. t.join();
  11087. ASSERT_FALSE(svr.is_running());
  11088. });
  11089. svr.wait_until_ready();
  11090. Client cli(HOST, PORT);
  11091. auto res = cli.Get("/ip");
  11092. ASSERT_TRUE(res);
  11093. EXPECT_EQ(StatusCode::OK_200, res->status);
  11094. EXPECT_EQ(observed_xff, "");
  11095. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11096. observed_remote_addr == "127.0.0.1");
  11097. }
  11098. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  11099. Server svr;
  11100. svr.set_trusted_proxies({"203.0.113.66"});
  11101. std::string observed_remote_addr;
  11102. std::string observed_xff;
  11103. svr.Get("/ip", [&](const Request &req, Response &res) {
  11104. observed_remote_addr = req.remote_addr;
  11105. observed_xff = req.get_header_value("X-Forwarded-For");
  11106. res.set_content("ok", "text/plain");
  11107. });
  11108. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11109. auto se = detail::scope_exit([&] {
  11110. svr.stop();
  11111. t.join();
  11112. ASSERT_FALSE(svr.is_running());
  11113. });
  11114. svr.wait_until_ready();
  11115. Client cli(HOST, PORT);
  11116. auto res =
  11117. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  11118. ASSERT_TRUE(res);
  11119. EXPECT_EQ(StatusCode::OK_200, res->status);
  11120. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  11121. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11122. }
  11123. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  11124. Server svr;
  11125. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  11126. std::string observed_remote_addr;
  11127. std::string observed_xff;
  11128. svr.Get("/ip", [&](const Request &req, Response &res) {
  11129. observed_remote_addr = req.remote_addr;
  11130. observed_xff = req.get_header_value("X-Forwarded-For");
  11131. res.set_content("ok", "text/plain");
  11132. });
  11133. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11134. auto se = detail::scope_exit([&] {
  11135. svr.stop();
  11136. t.join();
  11137. ASSERT_FALSE(svr.is_running());
  11138. });
  11139. svr.wait_until_ready();
  11140. Client cli(HOST, PORT);
  11141. auto res = cli.Get(
  11142. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11143. ASSERT_TRUE(res);
  11144. EXPECT_EQ(StatusCode::OK_200, res->status);
  11145. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11146. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11147. }
  11148. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  11149. Server svr;
  11150. svr.set_trusted_proxies({"192.0.2.45"});
  11151. std::string observed_remote_addr;
  11152. std::string observed_xff;
  11153. svr.Get("/ip", [&](const Request &req, Response &res) {
  11154. observed_remote_addr = req.remote_addr;
  11155. observed_xff = req.get_header_value("X-Forwarded-For");
  11156. res.set_content("ok", "text/plain");
  11157. });
  11158. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11159. auto se = detail::scope_exit([&] {
  11160. svr.stop();
  11161. t.join();
  11162. ASSERT_FALSE(svr.is_running());
  11163. });
  11164. svr.wait_until_ready();
  11165. Client cli(HOST, PORT);
  11166. auto res =
  11167. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  11168. ASSERT_TRUE(res);
  11169. EXPECT_EQ(StatusCode::OK_200, res->status);
  11170. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  11171. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11172. }
  11173. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  11174. Server svr;
  11175. svr.set_trusted_proxies({"192.0.2.45"});
  11176. std::string observed_remote_addr;
  11177. std::string observed_xff;
  11178. svr.Get("/ip", [&](const Request &req, Response &res) {
  11179. observed_remote_addr = req.remote_addr;
  11180. observed_xff = req.get_header_value("X-Forwarded-For");
  11181. res.set_content("ok", "text/plain");
  11182. });
  11183. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11184. auto se = detail::scope_exit([&] {
  11185. svr.stop();
  11186. t.join();
  11187. ASSERT_FALSE(svr.is_running());
  11188. });
  11189. svr.wait_until_ready();
  11190. Client cli(HOST, PORT);
  11191. auto res = cli.Get(
  11192. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11193. ASSERT_TRUE(res);
  11194. EXPECT_EQ(StatusCode::OK_200, res->status);
  11195. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11196. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11197. }
  11198. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  11199. Server svr;
  11200. svr.set_trusted_proxies({"192.0.2.45"});
  11201. std::string observed_remote_addr;
  11202. std::string observed_xff;
  11203. svr.Get("/ip", [&](const Request &req, Response &res) {
  11204. observed_remote_addr = req.remote_addr;
  11205. observed_xff = req.get_header_value("X-Forwarded-For");
  11206. res.set_content("ok", "text/plain");
  11207. });
  11208. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11209. auto se = detail::scope_exit([&] {
  11210. svr.stop();
  11211. t.join();
  11212. ASSERT_FALSE(svr.is_running());
  11213. });
  11214. svr.wait_until_ready();
  11215. std::string raw_req =
  11216. "GET /ip HTTP/1.1\r\n"
  11217. "Host: localhost\r\n"
  11218. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  11219. "Connection: close\r\n"
  11220. "\r\n";
  11221. std::string out;
  11222. ASSERT_TRUE(send_request(5, raw_req, &out));
  11223. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11224. // Header parser trims surrounding whitespace of the header value
  11225. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  11226. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11227. }
  11228. #ifndef _WIN32
  11229. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  11230. Server svr;
  11231. svr.Post("/post", [&](const Request &req, Response &res) {
  11232. res.set_content(req.body, "text/plain");
  11233. });
  11234. svr.Put("/put", [&](const Request &req, Response &res) {
  11235. res.set_content(req.body, "text/plain");
  11236. });
  11237. svr.Patch("/patch", [&](const Request &req, Response &res) {
  11238. res.set_content(req.body, "text/plain");
  11239. });
  11240. svr.Delete("/delete", [&](const Request &req, Response &res) {
  11241. res.set_content(req.body, "text/plain");
  11242. });
  11243. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11244. auto se = detail::scope_exit([&] {
  11245. svr.stop();
  11246. t.join();
  11247. ASSERT_FALSE(svr.is_running());
  11248. });
  11249. svr.wait_until_ready();
  11250. std::string resp;
  11251. // POST without Content-Length
  11252. ASSERT_TRUE(send_request(5,
  11253. "POST /post HTTP/1.1\r\n"
  11254. "Host: localhost\r\n"
  11255. "Connection: close\r\n"
  11256. "\r\n",
  11257. &resp));
  11258. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11259. // PUT without Content-Length
  11260. resp.clear();
  11261. ASSERT_TRUE(send_request(5,
  11262. "PUT /put HTTP/1.1\r\n"
  11263. "Host: localhost\r\n"
  11264. "Connection: close\r\n"
  11265. "\r\n",
  11266. &resp));
  11267. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11268. // PATCH without Content-Length
  11269. resp.clear();
  11270. ASSERT_TRUE(send_request(5,
  11271. "PATCH /patch HTTP/1.1\r\n"
  11272. "Host: localhost\r\n"
  11273. "Connection: close\r\n"
  11274. "\r\n",
  11275. &resp));
  11276. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11277. // DELETE without Content-Length
  11278. resp.clear();
  11279. ASSERT_TRUE(send_request(5,
  11280. "DELETE /delete HTTP/1.1\r\n"
  11281. "Host: localhost\r\n"
  11282. "Connection: close\r\n"
  11283. "\r\n",
  11284. &resp));
  11285. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11286. }
  11287. #endif
  11288. //==============================================================================
  11289. // open_stream() Tests
  11290. //==============================================================================
  11291. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  11292. std::string result;
  11293. char buf[8192];
  11294. ssize_t n;
  11295. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11296. result.append(buf, static_cast<size_t>(n));
  11297. }
  11298. return result;
  11299. }
  11300. // Mock stream for unit tests
  11301. class MockStream : public Stream {
  11302. public:
  11303. std::string data;
  11304. size_t pos = 0;
  11305. ssize_t error_after = -1; // -1 = no error
  11306. explicit MockStream(const std::string &d, ssize_t err = -1)
  11307. : data(d), error_after(err) {}
  11308. bool is_readable() const override { return true; }
  11309. bool wait_readable() const override { return true; }
  11310. bool wait_writable() const override { return true; }
  11311. ssize_t read(char *ptr, size_t size) override {
  11312. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  11313. if (pos >= data.size()) return 0;
  11314. size_t limit =
  11315. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  11316. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  11317. std::memcpy(ptr, data.data() + pos, to_read);
  11318. pos += to_read;
  11319. return static_cast<ssize_t>(to_read);
  11320. }
  11321. ssize_t write(const char *, size_t) override { return -1; }
  11322. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  11323. ip = "127.0.0.1";
  11324. port = 0;
  11325. }
  11326. void get_local_ip_and_port(std::string &ip, int &port) const override {
  11327. ip = "127.0.0.1";
  11328. port = 0;
  11329. }
  11330. socket_t socket() const override { return INVALID_SOCKET; }
  11331. time_t duration() const override { return 0; }
  11332. };
  11333. TEST(StreamHandleTest, Basic) {
  11334. ClientImpl::StreamHandle handle;
  11335. EXPECT_FALSE(handle.is_valid());
  11336. handle.response = detail::make_unique<Response>();
  11337. handle.error = Error::Connection;
  11338. EXPECT_FALSE(handle.is_valid());
  11339. handle.error = Error::Success;
  11340. EXPECT_TRUE(handle.is_valid());
  11341. }
  11342. TEST(BodyReaderTest, Basic) {
  11343. MockStream stream("Hello, World!");
  11344. detail::BodyReader reader;
  11345. reader.stream = &stream;
  11346. reader.content_length = 13;
  11347. char buf[32];
  11348. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  11349. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  11350. EXPECT_TRUE(reader.eof);
  11351. }
  11352. TEST(BodyReaderTest, NoStream) {
  11353. detail::BodyReader reader;
  11354. char buf[32];
  11355. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11356. EXPECT_EQ(Error::Connection, reader.last_error);
  11357. }
  11358. TEST(BodyReaderTest, Error) {
  11359. MockStream stream("Hello, World!", 5);
  11360. detail::BodyReader reader;
  11361. reader.stream = &stream;
  11362. reader.content_length = 13;
  11363. char buf[32];
  11364. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  11365. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11366. EXPECT_EQ(Error::Read, reader.last_error);
  11367. }
  11368. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  11369. // Mock-based StreamHandle tests relying on private internals are removed.
  11370. class OpenStreamTest : public ::testing::Test {
  11371. protected:
  11372. void SetUp() override {
  11373. svr_.Get("/hello", [](const Request &, Response &res) {
  11374. res.set_content("Hello World!", "text/plain");
  11375. });
  11376. svr_.Get("/large", [](const Request &, Response &res) {
  11377. res.set_content(std::string(10000, 'X'), "text/plain");
  11378. });
  11379. svr_.Get("/chunked", [](const Request &, Response &res) {
  11380. res.set_chunked_content_provider("text/plain",
  11381. [](size_t offset, DataSink &sink) {
  11382. if (offset < 15) {
  11383. sink.write("chunk", 5);
  11384. return true;
  11385. }
  11386. sink.done();
  11387. return true;
  11388. });
  11389. });
  11390. svr_.Get("/compressible", [](const Request &, Response &res) {
  11391. res.set_chunked_content_provider("text/plain", [](size_t offset,
  11392. DataSink &sink) {
  11393. if (offset < 100 * 1024) {
  11394. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  11395. sink.write(chunk.data(), chunk.size());
  11396. return true;
  11397. }
  11398. sink.done();
  11399. return true;
  11400. });
  11401. });
  11402. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  11403. [](const Request & /*req*/, Response &res) {
  11404. auto i = new int(0);
  11405. res.set_header("Trailer", "Content-Length, X-Allowed");
  11406. res.set_chunked_content_provider(
  11407. "text/plain",
  11408. [i](size_t /*offset*/, DataSink &sink) {
  11409. switch (*i) {
  11410. case 0: sink.os << "123"; break;
  11411. case 1: sink.os << "456"; break;
  11412. case 2: sink.os << "789"; break;
  11413. case 3: {
  11414. sink.done_with_trailer(
  11415. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  11416. } break;
  11417. }
  11418. (*i)++;
  11419. return true;
  11420. },
  11421. [i](bool success) {
  11422. EXPECT_TRUE(success);
  11423. delete i;
  11424. });
  11425. });
  11426. // Echo headers endpoint for header-related tests
  11427. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  11428. std::string body;
  11429. for (const auto &h : req.headers) {
  11430. body.append(h.first);
  11431. body.push_back(':');
  11432. body.append(h.second);
  11433. body.push_back('\n');
  11434. }
  11435. res.set_content(body, "text/plain");
  11436. });
  11437. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  11438. std::string body;
  11439. for (const auto &h : req.headers) {
  11440. body.append(h.first);
  11441. body.push_back(':');
  11442. body.append(h.second);
  11443. body.push_back('\n');
  11444. }
  11445. res.set_content(body, "text/plain");
  11446. });
  11447. port_ = svr_.bind_to_any_port("127.0.0.1");
  11448. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11449. svr_.wait_until_ready();
  11450. }
  11451. void TearDown() override {
  11452. svr_.stop();
  11453. if (thread_.joinable()) thread_.join();
  11454. }
  11455. Server svr_;
  11456. std::thread thread_;
  11457. int port_ = 0;
  11458. };
  11459. TEST_F(OpenStreamTest, Basic) {
  11460. Client cli("127.0.0.1", port_);
  11461. auto handle = cli.open_stream("GET", "/hello");
  11462. EXPECT_TRUE(handle.is_valid());
  11463. EXPECT_EQ("Hello World!", read_all(handle));
  11464. }
  11465. TEST_F(OpenStreamTest, SmallBuffer) {
  11466. Client cli("127.0.0.1", port_);
  11467. auto handle = cli.open_stream("GET", "/hello");
  11468. std::string result;
  11469. char buf[4];
  11470. ssize_t n;
  11471. while ((n = handle.read(buf, sizeof(buf))) > 0)
  11472. result.append(buf, static_cast<size_t>(n));
  11473. EXPECT_EQ("Hello World!", result);
  11474. }
  11475. TEST_F(OpenStreamTest, DefaultHeaders) {
  11476. Client cli("127.0.0.1", port_);
  11477. // open_stream GET should include Host, User-Agent and Accept-Encoding
  11478. {
  11479. auto handle = cli.open_stream("GET", "/echo-headers");
  11480. ASSERT_TRUE(handle.is_valid());
  11481. auto body = read_all(handle);
  11482. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  11483. std::string::npos);
  11484. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  11485. std::string::npos);
  11486. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  11487. }
  11488. // open_stream POST with body and no explicit content_type should NOT add
  11489. // text/plain Content-Type (behavior differs from non-streaming path), but
  11490. // should include Content-Length
  11491. {
  11492. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  11493. ASSERT_TRUE(handle.is_valid());
  11494. auto body = read_all(handle);
  11495. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  11496. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  11497. }
  11498. // open_stream POST with explicit Content-Type should preserve it
  11499. {
  11500. auto handle = cli.open_stream("POST", "/echo-headers", {},
  11501. {{"Content-Type", "application/custom"}},
  11502. "{}", "application/custom");
  11503. ASSERT_TRUE(handle.is_valid());
  11504. auto body = read_all(handle);
  11505. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  11506. }
  11507. // User-specified User-Agent must not be overwritten for stream API
  11508. {
  11509. auto handle = cli.open_stream("GET", "/echo-headers", {},
  11510. {{"User-Agent", "MyAgent/1.2"}});
  11511. ASSERT_TRUE(handle.is_valid());
  11512. auto body = read_all(handle);
  11513. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  11514. }
  11515. }
  11516. TEST_F(OpenStreamTest, Large) {
  11517. Client cli("127.0.0.1", port_);
  11518. auto handle = cli.open_stream("GET", "/large");
  11519. EXPECT_EQ(10000u, read_all(handle).size());
  11520. }
  11521. TEST_F(OpenStreamTest, ConnectionError) {
  11522. Client cli("127.0.0.1", 9999);
  11523. auto handle = cli.open_stream("GET", "/hello");
  11524. EXPECT_FALSE(handle.is_valid());
  11525. }
  11526. TEST_F(OpenStreamTest, Chunked) {
  11527. Client cli("127.0.0.1", port_);
  11528. auto handle = cli.open_stream("GET", "/chunked");
  11529. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11530. "Transfer-Encoding") == "chunked");
  11531. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  11532. }
  11533. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  11534. Client cli("127.0.0.1", port_);
  11535. auto handle =
  11536. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  11537. ASSERT_TRUE(handle.is_valid());
  11538. // Consume body to allow trailers to be received/parsed
  11539. auto body = read_all(handle);
  11540. // Explicitly parse trailers (ensure trailers are available for assertion)
  11541. handle.parse_trailers_if_needed();
  11542. EXPECT_EQ(std::string("123456789"), body);
  11543. // The response should include a Trailer header declaring both names
  11544. ASSERT_TRUE(handle.response);
  11545. EXPECT_TRUE(handle.response->has_header("Trailer"));
  11546. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  11547. handle.response->get_header_value("Trailer"));
  11548. // Prohibited trailer must not be present
  11549. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  11550. // Allowed trailer should be present
  11551. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  11552. EXPECT_EQ(std::string("yes"),
  11553. handle.response->get_trailer_value("X-Allowed"));
  11554. // Verify trailers are NOT present as regular headers
  11555. EXPECT_EQ(std::string(""),
  11556. handle.response->get_header_value("Content-Length"));
  11557. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  11558. }
  11559. static std::thread serve_single_response(std::promise<int> &port_promise,
  11560. const std::string &response) {
  11561. return std::thread([&port_promise, response] {
  11562. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11563. default_socket_options(srv);
  11564. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11565. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11566. sockaddr_in addr{};
  11567. addr.sin_family = AF_INET;
  11568. addr.sin_port = htons(0); // Let OS assign a free port
  11569. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11570. int opt = 1;
  11571. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11572. #ifdef _WIN32
  11573. reinterpret_cast<const char *>(&opt),
  11574. #else
  11575. &opt,
  11576. #endif
  11577. sizeof(opt));
  11578. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  11579. ::listen(srv, 1) != 0) {
  11580. port_promise.set_value(-1);
  11581. detail::close_socket(srv);
  11582. return;
  11583. }
  11584. socklen_t addr_len = sizeof(addr);
  11585. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  11586. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  11587. sockaddr_in cli_addr{};
  11588. socklen_t cli_len = sizeof(cli_addr);
  11589. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11590. if (cli != INVALID_SOCKET) {
  11591. char buf[4096];
  11592. ::recv(cli, buf, sizeof(buf), 0);
  11593. ::send(cli,
  11594. #ifdef _WIN32
  11595. static_cast<const char *>(response.c_str()),
  11596. static_cast<int>(response.size()),
  11597. #else
  11598. response.c_str(), response.size(),
  11599. #endif
  11600. 0);
  11601. detail::close_socket(cli);
  11602. }
  11603. detail::close_socket(srv);
  11604. });
  11605. }
  11606. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  11607. #ifndef _WIN32
  11608. signal(SIGPIPE, SIG_IGN);
  11609. #endif
  11610. std::promise<int> port_promise;
  11611. auto port_future = port_promise.get_future();
  11612. auto server_thread =
  11613. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  11614. "Content-Type: text/plain\r\n"
  11615. "Content-Length: not-a-number\r\n"
  11616. "Connection: close\r\n"
  11617. "\r\n"
  11618. "hello");
  11619. auto port = port_future.get();
  11620. ASSERT_GT(port, 0);
  11621. Client cli("127.0.0.1", port);
  11622. auto handle = cli.open_stream("GET", "/");
  11623. EXPECT_FALSE(handle.is_valid());
  11624. server_thread.join();
  11625. }
  11626. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  11627. #ifndef _WIN32
  11628. signal(SIGPIPE, SIG_IGN);
  11629. #endif
  11630. std::promise<int> port_promise;
  11631. auto port_future = port_promise.get_future();
  11632. auto server_thread = serve_single_response(
  11633. port_promise, "HTTP/1.1 200 OK\r\n"
  11634. "Content-Type: text/plain\r\n"
  11635. "Content-Length: 99999999999999999999999999\r\n"
  11636. "Connection: close\r\n"
  11637. "\r\n"
  11638. "hello");
  11639. auto port = port_future.get();
  11640. ASSERT_GT(port, 0);
  11641. // Before the fix, std::stoull would throw std::out_of_range here and
  11642. // crash the process. After the fix, strtoull silently clamps to
  11643. // ULLONG_MAX so the stream opens without crashing. The important thing
  11644. // is that the process does NOT terminate.
  11645. Client cli("127.0.0.1", port);
  11646. auto handle = cli.open_stream("GET", "/");
  11647. EXPECT_TRUE(handle.is_valid());
  11648. server_thread.join();
  11649. }
  11650. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11651. TEST_F(OpenStreamTest, Gzip) {
  11652. Client cli("127.0.0.1", port_);
  11653. auto handle = cli.open_stream("GET", "/compressible", {},
  11654. {{"Accept-Encoding", "gzip"}});
  11655. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  11656. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11657. }
  11658. #endif
  11659. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11660. TEST_F(OpenStreamTest, Brotli) {
  11661. Client cli("127.0.0.1", port_);
  11662. auto handle =
  11663. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  11664. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  11665. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11666. }
  11667. #endif
  11668. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11669. TEST_F(OpenStreamTest, Zstd) {
  11670. Client cli("127.0.0.1", port_);
  11671. auto handle = cli.open_stream("GET", "/compressible", {},
  11672. {{"Accept-Encoding", "zstd"}});
  11673. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  11674. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11675. }
  11676. #endif
  11677. #ifdef CPPHTTPLIB_SSL_ENABLED
  11678. class SSLOpenStreamTest : public ::testing::Test {
  11679. protected:
  11680. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  11681. void SetUp() override {
  11682. svr_.Get("/hello", [](const Request &, Response &res) {
  11683. res.set_content("Hello SSL World!", "text/plain");
  11684. });
  11685. svr_.Get("/chunked", [](const Request &, Response &res) {
  11686. res.set_chunked_content_provider("text/plain",
  11687. [](size_t offset, DataSink &sink) {
  11688. if (offset < 15) {
  11689. sink.write("chunk", 5);
  11690. return true;
  11691. }
  11692. sink.done();
  11693. return true;
  11694. });
  11695. });
  11696. svr_.Post("/echo", [](const Request &req, Response &res) {
  11697. res.set_content(req.body, req.get_header_value("Content-Type"));
  11698. });
  11699. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  11700. std::string body = req.body;
  11701. res.set_chunked_content_provider(
  11702. "text/plain", [body](size_t offset, DataSink &sink) {
  11703. if (offset < body.size()) {
  11704. sink.write(body.data() + offset, body.size() - offset);
  11705. }
  11706. sink.done();
  11707. return true;
  11708. });
  11709. });
  11710. port_ = svr_.bind_to_any_port("127.0.0.1");
  11711. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11712. svr_.wait_until_ready();
  11713. }
  11714. void TearDown() override {
  11715. svr_.stop();
  11716. if (thread_.joinable()) thread_.join();
  11717. }
  11718. SSLServer svr_;
  11719. std::thread thread_;
  11720. int port_ = 0;
  11721. };
  11722. TEST_F(SSLOpenStreamTest, Basic) {
  11723. SSLClient cli("127.0.0.1", port_);
  11724. cli.enable_server_certificate_verification(false);
  11725. auto handle = cli.open_stream("GET", "/hello");
  11726. ASSERT_TRUE(handle.is_valid());
  11727. EXPECT_EQ("Hello SSL World!", read_all(handle));
  11728. }
  11729. TEST_F(SSLOpenStreamTest, Chunked) {
  11730. SSLClient cli("127.0.0.1", port_);
  11731. cli.enable_server_certificate_verification(false);
  11732. auto handle = cli.open_stream("GET", "/chunked");
  11733. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11734. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11735. "Transfer-Encoding") == "chunked");
  11736. auto body = read_all(handle);
  11737. EXPECT_EQ("chunkchunkchunk", body);
  11738. }
  11739. TEST_F(SSLOpenStreamTest, Post) {
  11740. SSLClient cli("127.0.0.1", port_);
  11741. cli.enable_server_certificate_verification(false);
  11742. auto handle =
  11743. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  11744. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11745. EXPECT_EQ(200, handle.response->status);
  11746. auto body = read_all(handle);
  11747. EXPECT_EQ("Hello SSL POST", body);
  11748. }
  11749. TEST_F(SSLOpenStreamTest, PostChunked) {
  11750. SSLClient cli("127.0.0.1", port_);
  11751. cli.enable_server_certificate_verification(false);
  11752. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  11753. "Chunked SSL Data", "text/plain");
  11754. ASSERT_TRUE(handle.is_valid());
  11755. EXPECT_EQ(200, handle.response->status);
  11756. auto body = read_all(handle);
  11757. EXPECT_EQ("Chunked SSL Data", body);
  11758. }
  11759. #endif // CPPHTTPLIB_SSL_ENABLED
  11760. //==============================================================================
  11761. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  11762. // results for various scenarios.
  11763. //==============================================================================
  11764. TEST(ParityTest, GetVsOpenStream) {
  11765. Server svr;
  11766. const std::string path = "/parity";
  11767. const std::string content = "Parity test content: hello world";
  11768. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11769. res.set_content(content, "text/plain");
  11770. });
  11771. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11772. auto se = detail::scope_exit([&] {
  11773. svr.stop();
  11774. t.join();
  11775. ASSERT_FALSE(svr.is_running());
  11776. });
  11777. svr.wait_until_ready();
  11778. Client cli(HOST, PORT);
  11779. // Non-stream path
  11780. auto r1 = cli.Get(path);
  11781. ASSERT_TRUE(r1);
  11782. EXPECT_EQ(StatusCode::OK_200, r1->status);
  11783. // Stream path
  11784. auto h = cli.open_stream("GET", path);
  11785. ASSERT_TRUE(h.is_valid());
  11786. EXPECT_EQ(r1->body, read_all(h));
  11787. }
  11788. // Helper to compress data with provided compressor type T
  11789. template <typename Compressor>
  11790. static std::string compress_payload_for_parity(const std::string &in) {
  11791. std::string out;
  11792. Compressor compressor;
  11793. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  11794. [&](const char *data, size_t n) {
  11795. out.append(data, n);
  11796. return true;
  11797. });
  11798. EXPECT_TRUE(ok);
  11799. return out;
  11800. }
  11801. // Helper function for compression parity tests
  11802. template <typename Compressor>
  11803. static void test_compression_parity(const std::string &original,
  11804. const std::string &path,
  11805. const std::string &encoding) {
  11806. const std::string compressed =
  11807. compress_payload_for_parity<Compressor>(original);
  11808. Server svr;
  11809. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11810. res.set_content(compressed, "application/octet-stream");
  11811. res.set_header("Content-Encoding", encoding);
  11812. });
  11813. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  11814. auto se = detail::scope_exit([&] {
  11815. svr.stop();
  11816. t.join();
  11817. ASSERT_FALSE(svr.is_running());
  11818. });
  11819. svr.wait_until_ready();
  11820. Client cli(HOST, PORT);
  11821. // Non-streaming
  11822. {
  11823. auto res = cli.Get(path);
  11824. ASSERT_TRUE(res);
  11825. EXPECT_EQ(StatusCode::OK_200, res->status);
  11826. EXPECT_EQ(original, res->body);
  11827. }
  11828. // Streaming
  11829. {
  11830. auto h = cli.open_stream("GET", path);
  11831. ASSERT_TRUE(h.is_valid());
  11832. EXPECT_EQ(original, read_all(h));
  11833. }
  11834. }
  11835. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11836. TEST(ParityTest, Gzip) {
  11837. test_compression_parity<detail::gzip_compressor>(
  11838. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  11839. }
  11840. #endif
  11841. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11842. TEST(ParityTest, Brotli) {
  11843. test_compression_parity<detail::brotli_compressor>(
  11844. "Hello, brotli parity test payload", "/parity-br", "br");
  11845. }
  11846. #endif
  11847. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11848. TEST(ParityTest, Zstd) {
  11849. test_compression_parity<detail::zstd_compressor>(
  11850. "Zstandard parity test payload", "/parity-zstd", "zstd");
  11851. }
  11852. #endif
  11853. //==============================================================================
  11854. // New Stream API Tests
  11855. //==============================================================================
  11856. inline std::string read_body(httplib::stream::Result &result) {
  11857. std::string body;
  11858. while (result.next()) {
  11859. body.append(result.data(), result.size());
  11860. }
  11861. return body;
  11862. }
  11863. TEST(ClientConnectionTest, Basic) {
  11864. httplib::ClientConnection conn;
  11865. EXPECT_FALSE(conn.is_open());
  11866. conn.sock = 1;
  11867. EXPECT_TRUE(conn.is_open());
  11868. httplib::ClientConnection conn2(std::move(conn));
  11869. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  11870. conn2.sock = INVALID_SOCKET;
  11871. }
  11872. // Unified test server for all stream::* tests
  11873. class StreamApiTest : public ::testing::Test {
  11874. protected:
  11875. void SetUp() override {
  11876. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11877. res.set_content("Hello World!", "text/plain");
  11878. });
  11879. svr_.Get("/echo-params",
  11880. [](const httplib::Request &req, httplib::Response &res) {
  11881. std::string r;
  11882. for (const auto &p : req.params) {
  11883. if (!r.empty()) r += "&";
  11884. r += p.first + "=" + p.second;
  11885. }
  11886. res.set_content(r, "text/plain");
  11887. });
  11888. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11889. res.set_content(req.body, req.get_header_value("Content-Type"));
  11890. });
  11891. svr_.Post("/echo-headers",
  11892. [](const httplib::Request &req, httplib::Response &res) {
  11893. std::string r;
  11894. for (const auto &h : req.headers)
  11895. r += h.first + ": " + h.second + "\n";
  11896. res.set_content(r, "text/plain");
  11897. });
  11898. svr_.Post("/echo-params",
  11899. [](const httplib::Request &req, httplib::Response &res) {
  11900. std::string r = "params:";
  11901. for (const auto &p : req.params)
  11902. r += p.first + "=" + p.second + ";";
  11903. res.set_content(r + " body:" + req.body, "text/plain");
  11904. });
  11905. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  11906. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  11907. });
  11908. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11909. res.set_content("PUT:" + req.body, "text/plain");
  11910. });
  11911. svr_.Patch("/echo",
  11912. [](const httplib::Request &req, httplib::Response &res) {
  11913. res.set_content("PATCH:" + req.body, "text/plain");
  11914. });
  11915. svr_.Delete(
  11916. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  11917. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  11918. "text/plain");
  11919. });
  11920. svr_.Get("/head-test",
  11921. [](const httplib::Request &, httplib::Response &res) {
  11922. res.set_content("body for HEAD", "text/plain");
  11923. });
  11924. svr_.Options("/options",
  11925. [](const httplib::Request &, httplib::Response &res) {
  11926. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  11927. });
  11928. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  11929. svr_.wait_until_ready();
  11930. }
  11931. void TearDown() override {
  11932. svr_.stop();
  11933. if (thread_.joinable()) thread_.join();
  11934. }
  11935. httplib::Server svr_;
  11936. std::thread thread_;
  11937. };
  11938. // stream::Get tests
  11939. TEST_F(StreamApiTest, GetBasic) {
  11940. httplib::Client cli(HOST, PORT);
  11941. auto result = httplib::stream::Get(cli, "/hello");
  11942. ASSERT_TRUE(result.is_valid());
  11943. EXPECT_EQ(200, result.status());
  11944. EXPECT_EQ("Hello World!", read_body(result));
  11945. }
  11946. TEST_F(StreamApiTest, GetWithParams) {
  11947. httplib::Client cli(HOST, PORT);
  11948. httplib::Params params{{"foo", "bar"}};
  11949. auto result = httplib::stream::Get(cli, "/echo-params", params);
  11950. ASSERT_TRUE(result.is_valid());
  11951. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  11952. }
  11953. TEST_F(StreamApiTest, GetConnectionError) {
  11954. httplib::Client cli(HOST, 9999);
  11955. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  11956. }
  11957. TEST_F(StreamApiTest, Get404) {
  11958. httplib::Client cli(HOST, PORT);
  11959. auto result = httplib::stream::Get(cli, "/nonexistent");
  11960. EXPECT_TRUE(result.is_valid());
  11961. EXPECT_EQ(404, result.status());
  11962. }
  11963. // stream::Post tests
  11964. TEST_F(StreamApiTest, PostBasic) {
  11965. httplib::Client cli(HOST, PORT);
  11966. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  11967. "application/json");
  11968. ASSERT_TRUE(result.is_valid());
  11969. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  11970. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  11971. }
  11972. TEST_F(StreamApiTest, PostWithHeaders) {
  11973. httplib::Client cli(HOST, PORT);
  11974. httplib::Headers headers{{"X-Custom", "value"}};
  11975. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  11976. "text/plain");
  11977. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  11978. }
  11979. TEST_F(StreamApiTest, PostWithParams) {
  11980. httplib::Client cli(HOST, PORT);
  11981. httplib::Params params{{"k", "v"}};
  11982. auto result =
  11983. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  11984. auto body = read_body(result);
  11985. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  11986. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  11987. }
  11988. TEST_F(StreamApiTest, PostLarge) {
  11989. httplib::Client cli(HOST, PORT);
  11990. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  11991. size_t total = 0;
  11992. while (result.next()) {
  11993. total += result.size();
  11994. }
  11995. EXPECT_EQ(100u * 1024u, total);
  11996. }
  11997. // stream::Put/Patch tests
  11998. TEST_F(StreamApiTest, PutAndPatch) {
  11999. httplib::Client cli(HOST, PORT);
  12000. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  12001. EXPECT_EQ("PUT:test", read_body(put));
  12002. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  12003. EXPECT_EQ("PATCH:test", read_body(patch));
  12004. }
  12005. // stream::Delete tests
  12006. TEST_F(StreamApiTest, Delete) {
  12007. httplib::Client cli(HOST, PORT);
  12008. auto del1 = httplib::stream::Delete(cli, "/resource");
  12009. EXPECT_EQ("Deleted", read_body(del1));
  12010. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  12011. EXPECT_EQ("Deleted:data", read_body(del2));
  12012. }
  12013. // stream::Head/Options tests
  12014. TEST_F(StreamApiTest, HeadAndOptions) {
  12015. httplib::Client cli(HOST, PORT);
  12016. auto head = httplib::stream::Head(cli, "/head-test");
  12017. EXPECT_TRUE(head.is_valid());
  12018. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  12019. auto opts = httplib::stream::Options(cli, "/options");
  12020. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  12021. }
  12022. // SSL stream::* tests
  12023. #ifdef CPPHTTPLIB_SSL_ENABLED
  12024. class SSLStreamApiTest : public ::testing::Test {
  12025. protected:
  12026. void SetUp() override {
  12027. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12028. res.set_content("Hello SSL!", "text/plain");
  12029. });
  12030. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12031. res.set_content(req.body, "text/plain");
  12032. });
  12033. port_ = svr_.bind_to_any_port("127.0.0.1");
  12034. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12035. svr_.wait_until_ready();
  12036. }
  12037. void TearDown() override {
  12038. svr_.stop();
  12039. if (thread_.joinable()) thread_.join();
  12040. }
  12041. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  12042. std::thread thread_;
  12043. int port_ = 0;
  12044. };
  12045. TEST_F(SSLStreamApiTest, GetAndPost) {
  12046. httplib::SSLClient cli("127.0.0.1", port_);
  12047. cli.enable_server_certificate_verification(false);
  12048. auto get = httplib::stream::Get(cli, "/hello");
  12049. EXPECT_EQ("Hello SSL!", read_body(get));
  12050. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  12051. EXPECT_EQ("test", read_body(post));
  12052. }
  12053. #endif
  12054. // Tests for Error::Timeout and Error::ConnectionClosed error types
  12055. // These errors are set in SocketStream/SSLSocketStream and propagated through
  12056. // BodyReader
  12057. TEST(ErrorHandlingTest, StreamReadTimeout) {
  12058. // Test that read timeout during streaming is detected
  12059. // Use a large content-length response where server delays mid-stream
  12060. Server svr;
  12061. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12062. // Send a large response with delay in the middle
  12063. res.set_content_provider(
  12064. 1000, // content_length
  12065. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  12066. if (offset < 100) {
  12067. // Send first 100 bytes immediately
  12068. std::string data(100, 'A');
  12069. sink.write(data.c_str(), data.size());
  12070. return true;
  12071. }
  12072. // Then delay longer than client timeout
  12073. std::this_thread::sleep_for(std::chrono::seconds(3));
  12074. std::string data(900, 'B');
  12075. sink.write(data.c_str(), data.size());
  12076. return true;
  12077. });
  12078. });
  12079. auto port = 8091;
  12080. std::thread t([&]() { svr.listen("localhost", port); });
  12081. svr.wait_until_ready();
  12082. Client cli("localhost", port);
  12083. cli.set_read_timeout(1, 0); // 1 second timeout
  12084. auto handle = cli.open_stream("GET", "/slow-stream");
  12085. ASSERT_TRUE(handle.is_valid());
  12086. char buf[256];
  12087. ssize_t total = 0;
  12088. ssize_t n;
  12089. bool got_error = false;
  12090. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12091. total += n;
  12092. }
  12093. if (n < 0) {
  12094. got_error = true;
  12095. // Should be timeout or read error
  12096. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12097. handle.get_read_error() == Error::Read)
  12098. << "Actual error: " << to_string(handle.get_read_error());
  12099. }
  12100. // Either we got an error, or we got less data than expected
  12101. EXPECT_TRUE(got_error || total < 1000)
  12102. << "Expected timeout but got all " << total << " bytes";
  12103. svr.stop();
  12104. t.join();
  12105. }
  12106. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  12107. // Test connection closed detection via BodyReader
  12108. Server svr;
  12109. std::atomic<bool> close_now{false};
  12110. svr.Get("/will-close", [&](const Request &, Response &res) {
  12111. res.set_content_provider(
  12112. 10000, // Large content_length that we won't fully send
  12113. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12114. if (offset < 100) {
  12115. std::string data(100, 'X');
  12116. sink.write(data.c_str(), data.size());
  12117. return true;
  12118. }
  12119. // Wait for signal then abort
  12120. while (!close_now) {
  12121. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12122. }
  12123. return false; // Abort - server will close connection
  12124. });
  12125. });
  12126. auto port = 8092;
  12127. std::thread t([&]() { svr.listen("localhost", port); });
  12128. svr.wait_until_ready();
  12129. Client cli("localhost", port);
  12130. auto handle = cli.open_stream("GET", "/will-close");
  12131. ASSERT_TRUE(handle.is_valid());
  12132. char buf[256];
  12133. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12134. EXPECT_GT(n, 0) << "First read should succeed";
  12135. // Signal server to close
  12136. close_now = true;
  12137. // Keep reading until error or EOF
  12138. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12139. // Keep reading
  12140. }
  12141. // Should get an error since content_length wasn't satisfied
  12142. if (n < 0) {
  12143. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12144. handle.get_read_error() == Error::Read)
  12145. << "Actual error: " << to_string(handle.get_read_error());
  12146. }
  12147. svr.stop();
  12148. t.join();
  12149. }
  12150. #ifdef CPPHTTPLIB_SSL_ENABLED
  12151. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  12152. // Test that read timeout during SSL streaming is detected
  12153. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12154. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12155. res.set_content_provider(
  12156. 1000, "text/plain",
  12157. [](size_t offset, size_t /*length*/, DataSink &sink) {
  12158. if (offset < 100) {
  12159. std::string data(100, 'A');
  12160. sink.write(data.c_str(), data.size());
  12161. return true;
  12162. }
  12163. std::this_thread::sleep_for(std::chrono::seconds(3));
  12164. std::string data(900, 'B');
  12165. sink.write(data.c_str(), data.size());
  12166. return true;
  12167. });
  12168. });
  12169. auto port = 8093;
  12170. std::thread t([&]() { svr.listen("localhost", port); });
  12171. svr.wait_until_ready();
  12172. SSLClient cli("localhost", port);
  12173. cli.enable_server_certificate_verification(false);
  12174. cli.set_read_timeout(1, 0); // 1 second timeout
  12175. auto handle = cli.open_stream("GET", "/slow-stream");
  12176. ASSERT_TRUE(handle.is_valid());
  12177. char buf[256];
  12178. ssize_t total = 0;
  12179. ssize_t n;
  12180. bool got_error = false;
  12181. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12182. total += n;
  12183. }
  12184. if (n < 0) {
  12185. got_error = true;
  12186. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12187. handle.get_read_error() == Error::Read)
  12188. << "Actual error: " << to_string(handle.get_read_error());
  12189. }
  12190. EXPECT_TRUE(got_error || total < 1000)
  12191. << "Expected timeout but got all " << total << " bytes";
  12192. svr.stop();
  12193. t.join();
  12194. }
  12195. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  12196. // Test SSL connection closed detection
  12197. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12198. std::atomic<bool> close_now{false};
  12199. svr.Get("/will-close", [&](const Request &, Response &res) {
  12200. res.set_content_provider(
  12201. 10000, "text/plain",
  12202. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12203. if (offset < 100) {
  12204. std::string data(100, 'X');
  12205. sink.write(data.c_str(), data.size());
  12206. return true;
  12207. }
  12208. while (!close_now) {
  12209. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12210. }
  12211. return false;
  12212. });
  12213. });
  12214. auto port = 8094;
  12215. std::thread t([&]() { svr.listen("localhost", port); });
  12216. svr.wait_until_ready();
  12217. SSLClient cli("localhost", port);
  12218. cli.enable_server_certificate_verification(false);
  12219. auto handle = cli.open_stream("GET", "/will-close");
  12220. ASSERT_TRUE(handle.is_valid());
  12221. char buf[256];
  12222. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12223. EXPECT_GT(n, 0);
  12224. // Signal server to close
  12225. close_now = true;
  12226. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12227. // Keep reading
  12228. }
  12229. if (n < 0) {
  12230. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12231. handle.get_read_error() == Error::Read)
  12232. << "Actual error: " << to_string(handle.get_read_error());
  12233. }
  12234. svr.stop();
  12235. t.join();
  12236. }
  12237. #endif
  12238. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  12239. using namespace httplib;
  12240. // Create a test file
  12241. const char *fname = "etag_testfile.txt";
  12242. const char *content = "etag-content";
  12243. {
  12244. std::ofstream ofs(fname);
  12245. ofs << content;
  12246. ASSERT_TRUE(ofs.good());
  12247. }
  12248. Server svr;
  12249. svr.set_mount_point("/static", ".");
  12250. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12251. svr.wait_until_ready();
  12252. Client cli(HOST, PORT);
  12253. // First request: should get 200 with ETag header
  12254. auto res1 = cli.Get("/static/etag_testfile.txt");
  12255. ASSERT_TRUE(res1);
  12256. ASSERT_EQ(200, res1->status);
  12257. ASSERT_TRUE(res1->has_header("ETag"));
  12258. std::string etag = res1->get_header_value("ETag");
  12259. EXPECT_FALSE(etag.empty());
  12260. // Verify ETag format: W/"hex-hex"
  12261. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  12262. EXPECT_EQ('W', etag[0]);
  12263. EXPECT_EQ('/', etag[1]);
  12264. EXPECT_EQ('"', etag[2]);
  12265. EXPECT_EQ('"', etag.back());
  12266. // Exact match: expect 304 Not Modified
  12267. Headers h2 = {{"If-None-Match", etag}};
  12268. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  12269. ASSERT_TRUE(res2);
  12270. EXPECT_EQ(304, res2->status);
  12271. // Wildcard match: expect 304 Not Modified
  12272. Headers h3 = {{"If-None-Match", "*"}};
  12273. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  12274. ASSERT_TRUE(res3);
  12275. EXPECT_EQ(304, res3->status);
  12276. // Non-matching ETag: expect 200
  12277. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  12278. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  12279. ASSERT_TRUE(res4);
  12280. EXPECT_EQ(200, res4->status);
  12281. // Multiple ETags with one matching: expect 304
  12282. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  12283. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  12284. ASSERT_TRUE(res5);
  12285. EXPECT_EQ(304, res5->status);
  12286. svr.stop();
  12287. t.join();
  12288. std::remove(fname);
  12289. }
  12290. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  12291. using namespace httplib;
  12292. Server svr;
  12293. svr.set_mount_point("/static", ".");
  12294. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12295. svr.wait_until_ready();
  12296. Client cli(HOST, PORT);
  12297. // Send If-None-Match: * to a non-existent file
  12298. Headers h = {{"If-None-Match", "*"}};
  12299. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  12300. ASSERT_TRUE(res);
  12301. EXPECT_EQ(404, res->status);
  12302. svr.stop();
  12303. t.join();
  12304. }
  12305. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  12306. using namespace httplib;
  12307. // Create a test file
  12308. const char *fname = "etag_boundary_testfile.txt";
  12309. const char *content = "boundary-test";
  12310. {
  12311. std::ofstream ofs(fname);
  12312. ofs << content;
  12313. ASSERT_TRUE(ofs.good());
  12314. }
  12315. Server svr;
  12316. svr.set_mount_point("/static", ".");
  12317. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12318. svr.wait_until_ready();
  12319. Client cli(HOST, PORT);
  12320. // Get the actual ETag
  12321. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  12322. ASSERT_TRUE(res1);
  12323. ASSERT_EQ(200, res1->status);
  12324. ASSERT_TRUE(res1->has_header("ETag"));
  12325. std::string etag = res1->get_header_value("ETag");
  12326. // Test 1: Very long ETag value (longer than actual ETag)
  12327. // Should NOT match and return 200 (not trigger out-of-bounds read)
  12328. Headers h1 = {{"If-None-Match", "W/"
  12329. "\"very-long-etag-value-that-is-much-longer-"
  12330. "than-the-actual-etag-value\""}};
  12331. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  12332. ASSERT_TRUE(res2);
  12333. EXPECT_EQ(200, res2->status); // Should not match
  12334. // Test 2: Long string followed by wildcard
  12335. // Should match on "*" and return 304 (without out-of-bounds read on the long
  12336. // string)
  12337. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  12338. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  12339. ASSERT_TRUE(res3);
  12340. EXPECT_EQ(304, res3->status); // Should match on "*"
  12341. // Test 3: Wildcard followed by long string
  12342. // Should match on "*" immediately and return 304
  12343. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  12344. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  12345. ASSERT_TRUE(res4);
  12346. EXPECT_EQ(304, res4->status); // Should match on "*"
  12347. // Test 4: Multiple long non-matching values
  12348. // Should NOT match and return 200 (test that all comparisons are safe)
  12349. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  12350. "W/\"second-long-non-matching-value\", "
  12351. "W/\"third-long-non-matching-value\""}};
  12352. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  12353. ASSERT_TRUE(res5);
  12354. EXPECT_EQ(200, res5->status); // Should not match
  12355. // Test 5: Single character that is not "*" (edge case)
  12356. Headers h5 = {{"If-None-Match", "X"}};
  12357. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  12358. ASSERT_TRUE(res6);
  12359. EXPECT_EQ(200, res6->status); // Should not match
  12360. svr.stop();
  12361. t.join();
  12362. std::remove(fname);
  12363. }
  12364. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  12365. using namespace httplib;
  12366. // Create a test file
  12367. const char *fname = "ims_testfile.txt";
  12368. const char *content = "if-modified-since-test";
  12369. {
  12370. std::ofstream ofs(fname);
  12371. ofs << content;
  12372. ASSERT_TRUE(ofs.good());
  12373. }
  12374. Server svr;
  12375. svr.set_mount_point("/static", ".");
  12376. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12377. svr.wait_until_ready();
  12378. Client cli(HOST, PORT);
  12379. // First request: should get 200 with Last-Modified header
  12380. auto res1 = cli.Get("/static/ims_testfile.txt");
  12381. ASSERT_TRUE(res1);
  12382. ASSERT_EQ(200, res1->status);
  12383. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12384. std::string last_modified = res1->get_header_value("Last-Modified");
  12385. EXPECT_FALSE(last_modified.empty());
  12386. // If-Modified-Since with same time: expect 304
  12387. Headers h2 = {{"If-Modified-Since", last_modified}};
  12388. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  12389. ASSERT_TRUE(res2);
  12390. EXPECT_EQ(304, res2->status);
  12391. // If-Modified-Since with future time: expect 304
  12392. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12393. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  12394. ASSERT_TRUE(res3);
  12395. EXPECT_EQ(304, res3->status);
  12396. // If-Modified-Since with past time: expect 200
  12397. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12398. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  12399. ASSERT_TRUE(res4);
  12400. EXPECT_EQ(200, res4->status);
  12401. // If-None-Match takes precedence over If-Modified-Since
  12402. // (send matching ETag with old If-Modified-Since -> should still be 304)
  12403. ASSERT_TRUE(res1->has_header("ETag"));
  12404. std::string etag = res1->get_header_value("ETag");
  12405. Headers h5 = {{"If-None-Match", etag},
  12406. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12407. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  12408. ASSERT_TRUE(res5);
  12409. EXPECT_EQ(304, res5->status);
  12410. svr.stop();
  12411. t.join();
  12412. std::remove(fname);
  12413. }
  12414. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  12415. using namespace httplib;
  12416. Server svr;
  12417. // Endpoint that returns compressible content
  12418. svr.Get("/compressible", [](const Request &, Response &res) {
  12419. // Return a large enough body to trigger compression
  12420. std::string body(1000, 'a');
  12421. res.set_content(body, "text/plain");
  12422. });
  12423. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12424. svr.wait_until_ready();
  12425. Client cli(HOST, PORT);
  12426. // Request with gzip support: should get Vary header when compressed
  12427. cli.set_compress(true);
  12428. auto res1 = cli.Get("/compressible");
  12429. ASSERT_TRUE(res1);
  12430. EXPECT_EQ(200, res1->status);
  12431. // If Content-Encoding is set, Vary should also be set
  12432. if (res1->has_header("Content-Encoding")) {
  12433. EXPECT_TRUE(res1->has_header("Vary"));
  12434. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  12435. }
  12436. // Request without Accept-Encoding header: should not have compression
  12437. Headers h_no_compress;
  12438. auto res2 = cli.Get("/compressible", h_no_compress);
  12439. ASSERT_TRUE(res2);
  12440. EXPECT_EQ(200, res2->status);
  12441. // Verify Vary header is present when compression is applied
  12442. // (the exact behavior depends on server configuration)
  12443. svr.stop();
  12444. t.join();
  12445. }
  12446. TEST(ETagTest, IfRangeWithETag) {
  12447. using namespace httplib;
  12448. // Create a test file with known content
  12449. const char *fname = "if_range_testfile.txt";
  12450. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  12451. {
  12452. std::ofstream ofs(fname);
  12453. ofs << content;
  12454. ASSERT_TRUE(ofs.good());
  12455. }
  12456. Server svr;
  12457. svr.set_mount_point("/static", ".");
  12458. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12459. svr.wait_until_ready();
  12460. Client cli(HOST, PORT);
  12461. // First request: get ETag
  12462. auto res1 = cli.Get("/static/if_range_testfile.txt");
  12463. ASSERT_TRUE(res1);
  12464. ASSERT_EQ(200, res1->status);
  12465. ASSERT_TRUE(res1->has_header("ETag"));
  12466. std::string etag = res1->get_header_value("ETag");
  12467. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  12468. // Since our server generates weak ETags (W/"..."), If-Range with our
  12469. // ETag should NOT result in partial content - it should return full content.
  12470. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  12471. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  12472. ASSERT_TRUE(res2);
  12473. // Weak ETag in If-Range -> full content (200), not partial (206)
  12474. EXPECT_EQ(200, res2->status);
  12475. EXPECT_EQ(content, res2->body);
  12476. EXPECT_FALSE(res2->has_header("Content-Range"));
  12477. // Range request with non-matching If-Range (ETag): should get 200 (full
  12478. // content)
  12479. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  12480. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  12481. ASSERT_TRUE(res3);
  12482. EXPECT_EQ(200, res3->status);
  12483. EXPECT_EQ(content, res3->body);
  12484. EXPECT_FALSE(res3->has_header("Content-Range"));
  12485. // Range request with strong ETag (hypothetical - our server doesn't generate
  12486. // strong ETags, but if client sends a strong ETag that doesn't match, it
  12487. // should return full content)
  12488. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  12489. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  12490. ASSERT_TRUE(res4);
  12491. EXPECT_EQ(200, res4->status);
  12492. EXPECT_EQ(content, res4->body);
  12493. EXPECT_FALSE(res4->has_header("Content-Range"));
  12494. svr.stop();
  12495. t.join();
  12496. std::remove(fname);
  12497. }
  12498. TEST(ETagTest, IfRangeWithDate) {
  12499. using namespace httplib;
  12500. // Create a test file
  12501. const char *fname = "if_range_date_testfile.txt";
  12502. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  12503. {
  12504. std::ofstream ofs(fname);
  12505. ofs << content;
  12506. ASSERT_TRUE(ofs.good());
  12507. }
  12508. Server svr;
  12509. svr.set_mount_point("/static", ".");
  12510. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12511. svr.wait_until_ready();
  12512. Client cli(HOST, PORT);
  12513. // First request: get Last-Modified
  12514. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  12515. ASSERT_TRUE(res1);
  12516. ASSERT_EQ(200, res1->status);
  12517. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12518. std::string last_modified = res1->get_header_value("Last-Modified");
  12519. // Range request with matching If-Range (date): should get 206
  12520. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  12521. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  12522. ASSERT_TRUE(res2);
  12523. EXPECT_EQ(206, res2->status);
  12524. EXPECT_EQ("FGHIJ", res2->body);
  12525. // Range request with old If-Range date: should get 200 (full content)
  12526. Headers h3 = {{"Range", "bytes=5-9"},
  12527. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12528. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  12529. ASSERT_TRUE(res3);
  12530. EXPECT_EQ(200, res3->status);
  12531. EXPECT_EQ(content, res3->body);
  12532. // Range request with future If-Range date: should get 206
  12533. Headers h4 = {{"Range", "bytes=0-4"},
  12534. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12535. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  12536. ASSERT_TRUE(res4);
  12537. EXPECT_EQ(206, res4->status);
  12538. EXPECT_EQ("ABCDE", res4->body);
  12539. svr.stop();
  12540. t.join();
  12541. std::remove(fname);
  12542. }
  12543. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  12544. using namespace httplib;
  12545. const char *fname = "etag_malformed.txt";
  12546. const char *content = "malformed-etag";
  12547. {
  12548. std::ofstream ofs(fname);
  12549. ofs << content;
  12550. ASSERT_TRUE(ofs.good());
  12551. }
  12552. Server svr;
  12553. svr.set_mount_point("/static", ".");
  12554. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12555. svr.wait_until_ready();
  12556. Client cli(HOST, PORT);
  12557. // baseline: should get 200 and an ETag
  12558. auto res1 = cli.Get("/static/etag_malformed.txt");
  12559. ASSERT_TRUE(res1);
  12560. ASSERT_EQ(200, res1->status);
  12561. ASSERT_TRUE(res1->has_header("ETag"));
  12562. // Malformed ETag value (missing quotes) should be treated as non-matching
  12563. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  12564. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  12565. ASSERT_TRUE(res_bad);
  12566. EXPECT_EQ(200, res_bad->status);
  12567. // Whitespace-only header value should be considered invalid / non-matching
  12568. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  12569. "Host: localhost\r\n"
  12570. "If-None-Match: \r\n"
  12571. "Connection: close\r\n"
  12572. "\r\n";
  12573. std::string out;
  12574. ASSERT_TRUE(send_request(5, raw_req, &out));
  12575. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12576. svr.stop();
  12577. t.join();
  12578. std::remove(fname);
  12579. }
  12580. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  12581. using namespace httplib;
  12582. const char *fname = "ims_invalid_format.txt";
  12583. const char *content = "ims-bad-format";
  12584. {
  12585. std::ofstream ofs(fname);
  12586. ofs << content;
  12587. ASSERT_TRUE(ofs.good());
  12588. }
  12589. Server svr;
  12590. svr.set_mount_point("/static", ".");
  12591. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12592. svr.wait_until_ready();
  12593. Client cli(HOST, PORT);
  12594. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  12595. ASSERT_TRUE(res1);
  12596. ASSERT_EQ(200, res1->status);
  12597. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12598. // If-Modified-Since with invalid format should not result in 304
  12599. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  12600. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  12601. ASSERT_TRUE(res_bad);
  12602. EXPECT_EQ(200, res_bad->status);
  12603. // If-Range with invalid date format should be treated as mismatch -> full
  12604. // content (200)
  12605. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  12606. {"If-Range", "invalid-date"}};
  12607. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  12608. ASSERT_TRUE(res_ifrange);
  12609. EXPECT_EQ(200, res_ifrange->status);
  12610. svr.stop();
  12611. t.join();
  12612. std::remove(fname);
  12613. }
  12614. TEST(ETagTest, IfRangeWithMalformedETag) {
  12615. using namespace httplib;
  12616. const char *fname = "ifrange_malformed.txt";
  12617. const std::string content = "0123456789";
  12618. {
  12619. std::ofstream ofs(fname);
  12620. ofs << content;
  12621. ASSERT_TRUE(ofs.good());
  12622. }
  12623. Server svr;
  12624. svr.set_mount_point("/static", ".");
  12625. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12626. svr.wait_until_ready();
  12627. Client cli(HOST, PORT);
  12628. // First request: get ETag
  12629. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  12630. ASSERT_TRUE(res1);
  12631. ASSERT_EQ(200, res1->status);
  12632. ASSERT_TRUE(res1->has_header("ETag"));
  12633. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  12634. // full content (200)
  12635. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  12636. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  12637. ASSERT_TRUE(res2);
  12638. EXPECT_EQ(200, res2->status);
  12639. EXPECT_EQ(content, res2->body);
  12640. svr.stop();
  12641. t.join();
  12642. std::remove(fname);
  12643. }
  12644. TEST(ETagTest, ExtremeLargeDateValues) {
  12645. using namespace httplib;
  12646. const char *fname = "ims_extreme_date.txt";
  12647. const char *content = "ims-extreme-date";
  12648. {
  12649. std::ofstream ofs(fname);
  12650. ofs << content;
  12651. ASSERT_TRUE(ofs.good());
  12652. }
  12653. Server svr;
  12654. svr.set_mount_point("/static", ".");
  12655. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12656. svr.wait_until_ready();
  12657. Client cli(HOST, PORT);
  12658. auto res1 = cli.Get(std::string("/static/") + fname);
  12659. ASSERT_TRUE(res1);
  12660. ASSERT_EQ(200, res1->status);
  12661. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12662. // Extremely large year that may overflow date parsing routines.
  12663. Headers h_large_date = {
  12664. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12665. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  12666. ASSERT_TRUE(res_bad);
  12667. // Expect server to treat this as invalid/mismatch and return full content
  12668. EXPECT_EQ(200, res_bad->status);
  12669. // If-Range with extremely large date should be treated as mismatch -> full
  12670. // content (200)
  12671. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  12672. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12673. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  12674. ASSERT_TRUE(res_ifrange);
  12675. EXPECT_EQ(200, res_ifrange->status);
  12676. svr.stop();
  12677. t.join();
  12678. std::remove(fname);
  12679. }
  12680. TEST(ETagTest, NegativeFileModificationTime) {
  12681. using namespace httplib;
  12682. const char *fname = "ims_negative_mtime.txt";
  12683. const std::string content = "negative-mtime";
  12684. {
  12685. std::ofstream ofs(fname);
  12686. ofs << content;
  12687. ASSERT_TRUE(ofs.good());
  12688. }
  12689. // Try to set file mtime to a negative value. This may fail on some
  12690. // platforms/filesystems; if it fails, the test will still verify server
  12691. // behaves safely by performing a regular conditional request.
  12692. #if defined(__APPLE__) || defined(__linux__)
  12693. bool set_negative = false;
  12694. do {
  12695. struct timeval times[2];
  12696. // access time: now
  12697. times[0].tv_sec = time(nullptr);
  12698. times[0].tv_usec = 0;
  12699. // modification time: negative (e.g., -1)
  12700. times[1].tv_sec = -1;
  12701. times[1].tv_usec = 0;
  12702. if (utimes(fname, times) == 0) { set_negative = true; }
  12703. } while (0);
  12704. #else
  12705. bool set_negative = false;
  12706. #endif
  12707. Server svr;
  12708. svr.set_mount_point("/static", ".");
  12709. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12710. svr.wait_until_ready();
  12711. Client cli(HOST, PORT);
  12712. auto res1 = cli.Get(std::string("/static/") + fname);
  12713. ASSERT_TRUE(res1);
  12714. ASSERT_EQ(200, res1->status);
  12715. bool has_last_modified = res1->has_header("Last-Modified");
  12716. std::string last_modified;
  12717. if (has_last_modified) {
  12718. last_modified = res1->get_header_value("Last-Modified");
  12719. }
  12720. if (set_negative) {
  12721. // If we successfully set a negative mtime, ensure server returns a
  12722. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  12723. // with an old date and ensure server handles it without crash.
  12724. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  12725. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  12726. ASSERT_TRUE(res2);
  12727. // Behavior may vary; at minimum ensure server responds (200 or 304).
  12728. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  12729. } else {
  12730. // Could not set negative mtime on this platform; fall back to verifying
  12731. // that normal invalid/malformed dates are treated safely (non-304).
  12732. Headers h_bad_date = {
  12733. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12734. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  12735. ASSERT_TRUE(res_bad);
  12736. EXPECT_EQ(200, res_bad->status);
  12737. }
  12738. svr.stop();
  12739. t.join();
  12740. std::remove(fname);
  12741. }
  12742. //==============================================================================
  12743. // SSE Parsing Tests
  12744. //==============================================================================
  12745. class SSEParsingTest : public ::testing::Test {
  12746. protected:
  12747. // Test helper that mimics SSE parsing behavior
  12748. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  12749. int &retry_ms) {
  12750. // Blank line signals end of event
  12751. if (line.empty() || line == "\r") { return true; }
  12752. // Lines starting with ':' are comments (ignored)
  12753. if (!line.empty() && line[0] == ':') { return false; }
  12754. // Find the colon separator
  12755. auto colon_pos = line.find(':');
  12756. if (colon_pos == std::string::npos) {
  12757. // Line with no colon is treated as field name with empty value
  12758. return false;
  12759. }
  12760. std::string field = line.substr(0, colon_pos);
  12761. std::string value;
  12762. // Value starts after colon, skip optional single space
  12763. if (colon_pos + 1 < line.size()) {
  12764. size_t value_start = colon_pos + 1;
  12765. if (line[value_start] == ' ') { value_start++; }
  12766. value = line.substr(value_start);
  12767. // Remove trailing \r if present
  12768. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  12769. }
  12770. // Handle known fields
  12771. if (field == "event") {
  12772. msg.event = value;
  12773. } else if (field == "data") {
  12774. // Multiple data lines are concatenated with newlines
  12775. if (!msg.data.empty()) { msg.data += "\n"; }
  12776. msg.data += value;
  12777. } else if (field == "id") {
  12778. // Empty id is valid (clears the last event ID)
  12779. msg.id = value;
  12780. } else if (field == "retry") {
  12781. // Parse retry interval in milliseconds
  12782. {
  12783. int v = 0;
  12784. auto res =
  12785. detail::from_chars(value.data(), value.data() + value.size(), v);
  12786. if (res.ec == std::errc{}) { retry_ms = v; }
  12787. }
  12788. }
  12789. // Unknown fields are ignored per SSE spec
  12790. return false;
  12791. }
  12792. };
  12793. // Test: Single-line data
  12794. TEST_F(SSEParsingTest, SingleLineData) {
  12795. sse::SSEMessage msg;
  12796. int retry_ms = 3000;
  12797. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  12798. EXPECT_EQ(msg.data, "hello");
  12799. EXPECT_EQ(msg.event, "message");
  12800. // Blank line ends event
  12801. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12802. }
  12803. // Test: Multi-line data
  12804. TEST_F(SSEParsingTest, MultiLineData) {
  12805. sse::SSEMessage msg;
  12806. int retry_ms = 3000;
  12807. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  12808. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  12809. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  12810. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  12811. }
  12812. // Test: Custom event types
  12813. TEST_F(SSEParsingTest, CustomEventType) {
  12814. sse::SSEMessage msg;
  12815. int retry_ms = 3000;
  12816. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  12817. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  12818. EXPECT_EQ(msg.event, "update");
  12819. EXPECT_EQ(msg.data, "payload");
  12820. }
  12821. // Test: Event ID handling
  12822. TEST_F(SSEParsingTest, EventIdHandling) {
  12823. sse::SSEMessage msg;
  12824. int retry_ms = 3000;
  12825. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  12826. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  12827. EXPECT_EQ(msg.id, "12345");
  12828. }
  12829. // Test: Empty event ID (clears last event ID)
  12830. TEST_F(SSEParsingTest, EmptyEventId) {
  12831. sse::SSEMessage msg;
  12832. msg.id = "previous";
  12833. int retry_ms = 3000;
  12834. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  12835. EXPECT_EQ(msg.id, "");
  12836. }
  12837. // Test: Retry field parsing
  12838. TEST_F(SSEParsingTest, RetryFieldParsing) {
  12839. sse::SSEMessage msg;
  12840. int retry_ms = 3000;
  12841. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  12842. EXPECT_EQ(retry_ms, 5000);
  12843. }
  12844. // Test: Invalid retry value
  12845. TEST_F(SSEParsingTest, InvalidRetryValue) {
  12846. sse::SSEMessage msg;
  12847. int retry_ms = 3000;
  12848. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  12849. EXPECT_EQ(retry_ms, 3000); // Unchanged
  12850. }
  12851. // Test: Comments (lines starting with :)
  12852. TEST_F(SSEParsingTest, CommentsIgnored) {
  12853. sse::SSEMessage msg;
  12854. int retry_ms = 3000;
  12855. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  12856. EXPECT_EQ(msg.data, "");
  12857. EXPECT_EQ(msg.event, "message");
  12858. }
  12859. // Test: Colon in value
  12860. TEST_F(SSEParsingTest, ColonInValue) {
  12861. sse::SSEMessage msg;
  12862. int retry_ms = 3000;
  12863. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  12864. EXPECT_EQ(msg.data, "hello:world:test");
  12865. }
  12866. // Test: Line with no colon (field name only)
  12867. TEST_F(SSEParsingTest, FieldNameOnly) {
  12868. sse::SSEMessage msg;
  12869. int retry_ms = 3000;
  12870. // According to SSE spec, this is treated as field name with empty value
  12871. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  12872. // Since we don't recognize "data" without colon, data should be empty
  12873. EXPECT_EQ(msg.data, "");
  12874. }
  12875. // Test: Trailing \r handling
  12876. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  12877. sse::SSEMessage msg;
  12878. int retry_ms = 3000;
  12879. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  12880. EXPECT_EQ(msg.data, "hello");
  12881. }
  12882. // Test: Unknown fields ignored
  12883. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  12884. sse::SSEMessage msg;
  12885. int retry_ms = 3000;
  12886. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  12887. EXPECT_EQ(msg.data, "");
  12888. EXPECT_EQ(msg.event, "message");
  12889. }
  12890. // Test: Space after colon is optional
  12891. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  12892. sse::SSEMessage msg1, msg2;
  12893. int retry_ms = 3000;
  12894. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  12895. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  12896. EXPECT_EQ(msg1.data, "hello");
  12897. EXPECT_EQ(msg2.data, "hello");
  12898. }
  12899. // Test: SSEMessage clear
  12900. TEST_F(SSEParsingTest, MessageClear) {
  12901. sse::SSEMessage msg;
  12902. msg.event = "custom";
  12903. msg.data = "some data";
  12904. msg.id = "123";
  12905. msg.clear();
  12906. EXPECT_EQ(msg.event, "message");
  12907. EXPECT_EQ(msg.data, "");
  12908. EXPECT_EQ(msg.id, "");
  12909. }
  12910. // Test: Complete event parsing
  12911. TEST_F(SSEParsingTest, CompleteEventParsing) {
  12912. sse::SSEMessage msg;
  12913. int retry_ms = 3000;
  12914. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  12915. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  12916. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  12917. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  12918. // Blank line ends event
  12919. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12920. EXPECT_EQ(msg.event, "notification");
  12921. EXPECT_EQ(msg.id, "evt-42");
  12922. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  12923. EXPECT_EQ(retry_ms, 1000);
  12924. }
  12925. //==============================================================================
  12926. // Integration Tests with Server
  12927. //==============================================================================
  12928. class SSEIntegrationTest : public ::testing::Test {
  12929. protected:
  12930. void SetUp() override {
  12931. stop_server_.store(false);
  12932. events_.clear();
  12933. server_ = httplib::detail::make_unique<Server>();
  12934. setup_server();
  12935. start_server();
  12936. }
  12937. void TearDown() override {
  12938. stop_server_.store(true);
  12939. event_cv_.notify_all();
  12940. server_->stop();
  12941. if (server_thread_.joinable()) { server_thread_.join(); }
  12942. }
  12943. void setup_server() {
  12944. // Simple SSE endpoint
  12945. server_->Get("/events", [this](const Request &req, Response &res) {
  12946. auto last_id = req.get_header_value("Last-Event-ID");
  12947. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  12948. res.set_chunked_content_provider(
  12949. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  12950. std::unique_lock<std::mutex> lock(event_mutex_);
  12951. if (event_cv_.wait_for(
  12952. lock, std::chrono::milliseconds(200), [this] {
  12953. return !events_.empty() || stop_server_.load();
  12954. })) {
  12955. if (stop_server_.load()) { return false; }
  12956. if (!events_.empty()) {
  12957. std::string event = events_.front();
  12958. events_.erase(events_.begin());
  12959. sink.write(event.data(), event.size());
  12960. return true;
  12961. }
  12962. }
  12963. return !stop_server_.load();
  12964. });
  12965. });
  12966. // Endpoint that returns error
  12967. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  12968. res.status = 500;
  12969. res.set_content("Internal Server Error", "text/plain");
  12970. });
  12971. // Endpoint for custom event types
  12972. server_->Get("/custom-events", [](const Request &, Response &res) {
  12973. res.set_chunked_content_provider(
  12974. "text/event-stream", [](size_t offset, DataSink &sink) {
  12975. if (offset == 0) {
  12976. std::string event = "event: update\ndata: updated\n\n"
  12977. "event: delete\ndata: deleted\n\n";
  12978. sink.write(event.data(), event.size());
  12979. }
  12980. return false; // End stream after sending
  12981. });
  12982. });
  12983. }
  12984. void start_server() {
  12985. port_ = server_->bind_to_any_port(HOST);
  12986. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  12987. // Wait for server to start
  12988. while (!server_->is_running()) {
  12989. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12990. }
  12991. }
  12992. int get_port() const { return port_; }
  12993. void send_event(const std::string &event) {
  12994. std::lock_guard<std::mutex> lock(event_mutex_);
  12995. events_.push_back(event);
  12996. event_cv_.notify_all();
  12997. }
  12998. std::unique_ptr<Server> server_;
  12999. std::thread server_thread_;
  13000. std::mutex event_mutex_;
  13001. std::condition_variable event_cv_;
  13002. std::vector<std::string> events_;
  13003. std::atomic<bool> stop_server_{false};
  13004. std::string last_received_event_id_;
  13005. int port_ = 0;
  13006. };
  13007. // Test: Successful connection and on_open callback
  13008. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  13009. // Add a simple endpoint that sends one event and closes
  13010. server_->Get("/simple-event", [](const Request &, Response &res) {
  13011. res.set_chunked_content_provider(
  13012. "text/event-stream", [](size_t offset, DataSink &sink) {
  13013. if (offset == 0) {
  13014. std::string event = "data: hello\n\n";
  13015. sink.write(event.data(), event.size());
  13016. }
  13017. return false; // Close stream after sending
  13018. });
  13019. });
  13020. Client client("localhost", get_port());
  13021. sse::SSEClient sse(client, "/simple-event");
  13022. std::atomic<bool> open_called{false};
  13023. std::atomic<bool> message_received{false};
  13024. sse.on_open([&open_called]() { open_called.store(true); });
  13025. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  13026. if (msg.data == "hello") { message_received.store(true); }
  13027. });
  13028. sse.set_reconnect_interval(100);
  13029. sse.set_max_reconnect_attempts(1);
  13030. // Start async
  13031. sse.start_async();
  13032. // Wait for message to be processed
  13033. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13034. sse.stop();
  13035. EXPECT_TRUE(open_called.load());
  13036. EXPECT_TRUE(message_received.load());
  13037. }
  13038. // Test: on_message callback
  13039. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  13040. // Endpoint that sends multiple events then closes
  13041. server_->Get("/multi-event", [](const Request &, Response &res) {
  13042. res.set_chunked_content_provider(
  13043. "text/event-stream", [](size_t offset, DataSink &sink) {
  13044. if (offset == 0) {
  13045. std::string events = "data: message1\n\ndata: message2\n\n";
  13046. sink.write(events.data(), events.size());
  13047. }
  13048. return false;
  13049. });
  13050. });
  13051. Client client("localhost", get_port());
  13052. sse::SSEClient sse(client, "/multi-event");
  13053. std::vector<std::string> received_messages;
  13054. std::mutex messages_mutex;
  13055. sse.on_message([&](const sse::SSEMessage &msg) {
  13056. std::lock_guard<std::mutex> lock(messages_mutex);
  13057. received_messages.push_back(msg.data);
  13058. });
  13059. sse.set_reconnect_interval(100);
  13060. sse.set_max_reconnect_attempts(1);
  13061. sse.start_async();
  13062. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13063. sse.stop();
  13064. std::lock_guard<std::mutex> lock(messages_mutex);
  13065. EXPECT_GE(received_messages.size(), 2u);
  13066. if (received_messages.size() >= 2) {
  13067. EXPECT_EQ(received_messages[0], "message1");
  13068. EXPECT_EQ(received_messages[1], "message2");
  13069. }
  13070. }
  13071. // Test: on_event for specific types
  13072. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  13073. Client client("localhost", get_port());
  13074. sse::SSEClient sse(client, "/custom-events");
  13075. std::atomic<bool> update_received{false};
  13076. std::atomic<bool> delete_received{false};
  13077. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  13078. if (msg.data == "updated") { update_received.store(true); }
  13079. });
  13080. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  13081. if (msg.data == "deleted") { delete_received.store(true); }
  13082. });
  13083. sse.set_max_reconnect_attempts(1);
  13084. sse.start_async();
  13085. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  13086. sse.stop();
  13087. EXPECT_TRUE(update_received.load());
  13088. EXPECT_TRUE(delete_received.load());
  13089. }
  13090. // Test: on_error callback on connection failure
  13091. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  13092. // Connect to a non-existent port
  13093. Client client("localhost", 59999);
  13094. sse::SSEClient sse(client, "/events");
  13095. std::atomic<bool> error_called{false};
  13096. Error received_error = Error::Success;
  13097. sse.on_error([&](Error err) {
  13098. error_called.store(true);
  13099. received_error = err;
  13100. });
  13101. sse.set_reconnect_interval(50);
  13102. sse.set_max_reconnect_attempts(1);
  13103. sse.start_async();
  13104. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13105. sse.stop();
  13106. EXPECT_TRUE(error_called.load());
  13107. EXPECT_NE(received_error, Error::Success);
  13108. }
  13109. // Test: Last-Event-ID header sent on reconnect
  13110. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  13111. // Endpoint that sends event with ID
  13112. server_->Get("/event-with-id", [](const Request &, Response &res) {
  13113. res.set_chunked_content_provider(
  13114. "text/event-stream", [](size_t offset, DataSink &sink) {
  13115. if (offset == 0) {
  13116. std::string event = "id: evt-123\ndata: test\n\n";
  13117. sink.write(event.data(), event.size());
  13118. }
  13119. return false;
  13120. });
  13121. });
  13122. Client client("localhost", get_port());
  13123. sse::SSEClient sse(client, "/event-with-id");
  13124. std::atomic<bool> id_received{false};
  13125. sse.on_message([&](const sse::SSEMessage &msg) {
  13126. if (!msg.id.empty()) { id_received.store(true); }
  13127. });
  13128. sse.set_reconnect_interval(100);
  13129. sse.set_max_reconnect_attempts(1);
  13130. sse.start_async();
  13131. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13132. sse.stop();
  13133. EXPECT_TRUE(id_received.load());
  13134. EXPECT_EQ(sse.last_event_id(), "evt-123");
  13135. }
  13136. // Test: Manual stop
  13137. TEST_F(SSEIntegrationTest, ManualStop) {
  13138. // Endpoint that sends one event and stays open briefly
  13139. std::atomic<bool> handler_running{true};
  13140. server_->Get("/stay-open", [&handler_running](const Request &,
  13141. Response &res) {
  13142. res.set_chunked_content_provider(
  13143. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  13144. if (offset == 0) {
  13145. std::string event = "data: connected\n\n";
  13146. sink.write(event.data(), event.size());
  13147. }
  13148. // Keep connection open while handler_running is true
  13149. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  13150. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13151. }
  13152. return false;
  13153. });
  13154. });
  13155. Client client("localhost", get_port());
  13156. sse::SSEClient sse(client, "/stay-open");
  13157. std::atomic<bool> connected{false};
  13158. sse.on_open([&connected]() { connected.store(true); });
  13159. sse.set_reconnect_interval(100);
  13160. sse.set_max_reconnect_attempts(1);
  13161. sse.start_async();
  13162. // Wait for connection to establish
  13163. for (int i = 0; i < 20 && !connected.load(); ++i) {
  13164. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13165. }
  13166. EXPECT_TRUE(connected.load());
  13167. EXPECT_TRUE(sse.is_connected());
  13168. // Signal handler to stop
  13169. handler_running.store(false);
  13170. // Stop SSE client
  13171. sse.stop();
  13172. EXPECT_FALSE(sse.is_connected());
  13173. }
  13174. // Test: SSEClient with custom headers
  13175. TEST_F(SSEIntegrationTest, CustomHeaders) {
  13176. // Setup a server endpoint that checks for custom header
  13177. std::atomic<bool> header_received{false};
  13178. server_->Get("/header-check", [&](const Request &req, Response &res) {
  13179. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  13180. header_received.store(true);
  13181. }
  13182. res.set_chunked_content_provider("text/event-stream",
  13183. [](size_t, DataSink &) { return false; });
  13184. });
  13185. Client client("localhost", get_port());
  13186. Headers headers = {{"X-Custom-Header", "custom-value"}};
  13187. sse::SSEClient sse(client, "/header-check", headers);
  13188. sse.set_max_reconnect_attempts(1);
  13189. sse.start_async();
  13190. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13191. sse.stop();
  13192. EXPECT_TRUE(header_received.load());
  13193. }
  13194. // Test: Reconnect interval configuration
  13195. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  13196. Client client("localhost", get_port());
  13197. sse::SSEClient sse(client, "/events");
  13198. auto &result = sse.set_reconnect_interval(500);
  13199. // Builder pattern should return reference to self
  13200. EXPECT_EQ(&result, &sse);
  13201. }
  13202. // Test: Max reconnect attempts
  13203. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  13204. // Connect to non-existent port to force reconnects
  13205. Client client("localhost", 59998);
  13206. sse::SSEClient sse(client, "/events");
  13207. std::atomic<int> error_count{0};
  13208. sse.on_error([&](Error) { error_count.fetch_add(1); });
  13209. sse.set_reconnect_interval(50);
  13210. sse.set_max_reconnect_attempts(2);
  13211. auto start = std::chrono::steady_clock::now();
  13212. sse.start(); // Blocking call
  13213. auto end = std::chrono::steady_clock::now();
  13214. // Should have stopped after 2 failed attempts
  13215. EXPECT_GE(error_count.load(), 2);
  13216. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  13217. auto duration =
  13218. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  13219. #ifdef _WIN32
  13220. // Windows is much slower for socket connection failures
  13221. EXPECT_LT(duration.count(), 7000);
  13222. #else
  13223. EXPECT_LT(duration.count(), 1000);
  13224. #endif
  13225. }
  13226. // Test: Multi-line data in integration
  13227. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  13228. // Endpoint with multi-line data
  13229. server_->Get("/multiline-data", [](const Request &, Response &res) {
  13230. res.set_chunked_content_provider(
  13231. "text/event-stream", [](size_t offset, DataSink &sink) {
  13232. if (offset == 0) {
  13233. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  13234. sink.write(event.data(), event.size());
  13235. }
  13236. return false;
  13237. });
  13238. });
  13239. Client client("localhost", get_port());
  13240. sse::SSEClient sse(client, "/multiline-data");
  13241. std::string received_data;
  13242. std::mutex data_mutex;
  13243. sse.on_message([&](const sse::SSEMessage &msg) {
  13244. std::lock_guard<std::mutex> lock(data_mutex);
  13245. received_data = msg.data;
  13246. });
  13247. sse.set_reconnect_interval(100);
  13248. sse.set_max_reconnect_attempts(1);
  13249. sse.start_async();
  13250. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13251. sse.stop();
  13252. std::lock_guard<std::mutex> lock(data_mutex);
  13253. EXPECT_EQ(received_data, "line1\nline2\nline3");
  13254. }
  13255. // Test: Auto-reconnect after server disconnection
  13256. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  13257. std::atomic<int> connection_count{0};
  13258. std::atomic<int> message_count{0};
  13259. // Endpoint that sends one event and closes, forcing reconnect
  13260. server_->Get("/reconnect-test",
  13261. [&connection_count](const Request &, Response &res) {
  13262. connection_count.fetch_add(1);
  13263. res.set_chunked_content_provider(
  13264. "text/event-stream", [](size_t offset, DataSink &sink) {
  13265. if (offset == 0) {
  13266. std::string event = "data: hello\n\n";
  13267. sink.write(event.data(), event.size());
  13268. }
  13269. return false; // Close connection after sending
  13270. });
  13271. });
  13272. Client client("localhost", get_port());
  13273. sse::SSEClient sse(client, "/reconnect-test");
  13274. sse.on_message([&message_count](const sse::SSEMessage &) {
  13275. message_count.fetch_add(1);
  13276. });
  13277. sse.set_reconnect_interval(100);
  13278. sse.set_max_reconnect_attempts(3);
  13279. sse.start_async();
  13280. // Wait long enough for multiple reconnects
  13281. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13282. sse.stop();
  13283. // Should have connected multiple times (initial + reconnects)
  13284. EXPECT_GE(connection_count.load(), 2);
  13285. // Should have received messages from multiple connections
  13286. EXPECT_GE(message_count.load(), 2);
  13287. }
  13288. // Test: Last-Event-ID sent on reconnect
  13289. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  13290. std::atomic<int> connection_count{0};
  13291. std::vector<std::string> received_last_event_ids;
  13292. std::mutex id_mutex;
  13293. // Endpoint that checks Last-Event-ID header and sends event with ID
  13294. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  13295. int conn = connection_count.fetch_add(1);
  13296. // Capture the Last-Event-ID header from each connection
  13297. {
  13298. std::lock_guard<std::mutex> lock(id_mutex);
  13299. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  13300. }
  13301. res.set_chunked_content_provider(
  13302. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  13303. if (offset == 0) {
  13304. std::string event =
  13305. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  13306. sink.write(event.data(), event.size());
  13307. }
  13308. return false;
  13309. });
  13310. });
  13311. Client client("localhost", get_port());
  13312. sse::SSEClient sse(client, "/reconnect-with-id");
  13313. sse.set_reconnect_interval(100);
  13314. sse.set_max_reconnect_attempts(3);
  13315. sse.start_async();
  13316. // Wait for at least 2 connections
  13317. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13318. sse.stop();
  13319. // Verify behavior
  13320. std::lock_guard<std::mutex> lock(id_mutex);
  13321. EXPECT_GE(received_last_event_ids.size(), 2u);
  13322. // First connection should have no Last-Event-ID
  13323. if (!received_last_event_ids.empty()) {
  13324. EXPECT_EQ(received_last_event_ids[0], "");
  13325. }
  13326. // Second connection should have Last-Event-ID from first connection
  13327. if (received_last_event_ids.size() >= 2) {
  13328. EXPECT_EQ(received_last_event_ids[1], "event-0");
  13329. }
  13330. }
  13331. TEST(Issue2318Test, EmptyHostString) {
  13332. {
  13333. httplib::Client cli_empty("", PORT);
  13334. auto res = cli_empty.Get("/");
  13335. ASSERT_FALSE(res);
  13336. EXPECT_EQ(httplib::Error::Connection, res.error());
  13337. }
  13338. {
  13339. httplib::Client cli(" ", PORT);
  13340. auto res = cli.Get("/");
  13341. ASSERT_FALSE(res);
  13342. EXPECT_EQ(httplib::Error::Connection, res.error());
  13343. }
  13344. }
  13345. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13346. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  13347. Server svr;
  13348. // Set a small payload limit (1KB)
  13349. svr.set_payload_max_length(1024);
  13350. svr.Post("/test", [&](const Request &req, Response &res) {
  13351. res.set_content("Body size: " + std::to_string(req.body.size()),
  13352. "text/plain");
  13353. });
  13354. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13355. auto se = detail::scope_exit([&] {
  13356. svr.stop();
  13357. listen_thread.join();
  13358. });
  13359. svr.wait_until_ready();
  13360. // Create data that compresses well but exceeds limit when decompressed
  13361. // 8KB of repeated null bytes compresses to a very small size
  13362. std::string original_data(8 * 1024, '\0');
  13363. // Compress the data using gzip
  13364. std::string compressed_data;
  13365. detail::gzip_compressor compressor;
  13366. compressor.compress(original_data.data(), original_data.size(), true,
  13367. [&](const char *data, size_t size) {
  13368. compressed_data.append(data, size);
  13369. return true;
  13370. });
  13371. // Verify compression worked (compressed should be much smaller)
  13372. ASSERT_LT(compressed_data.size(), original_data.size());
  13373. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  13374. // Send compressed data with Content-Encoding: gzip
  13375. Client cli(HOST, PORT);
  13376. Headers headers = {{"Content-Encoding", "gzip"}};
  13377. auto res =
  13378. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  13379. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  13380. ASSERT_TRUE(res);
  13381. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13382. }
  13383. #endif
  13384. // ============================================================================
  13385. // OpenSSL-Specific Tests
  13386. // ============================================================================
  13387. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13388. X509 *readCertificate(const std::string &strFileName) {
  13389. std::ifstream inStream(strFileName);
  13390. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  13391. std::istreambuf_iterator<char>());
  13392. if (strCertPEM.empty()) return (nullptr);
  13393. BIO *pbCert = BIO_new(BIO_s_mem());
  13394. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  13395. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  13396. BIO_free(pbCert);
  13397. return (pCert);
  13398. }
  13399. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  13400. std::ifstream inStream(strFileName);
  13401. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  13402. std::istreambuf_iterator<char>());
  13403. if (strPrivateKeyPEM.empty()) return (nullptr);
  13404. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  13405. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  13406. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  13407. BIO_free(pbPrivKey);
  13408. return (pPrivateKey);
  13409. }
  13410. TEST(BindServerTest, UpdateCerts) {
  13411. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13412. int port = svr.bind_to_any_port("0.0.0.0");
  13413. ASSERT_TRUE(svr.is_valid());
  13414. ASSERT_TRUE(port > 0);
  13415. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13416. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13417. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13418. ASSERT_TRUE(cert != nullptr);
  13419. ASSERT_TRUE(ca_cert != nullptr);
  13420. ASSERT_TRUE(key != nullptr);
  13421. X509_STORE *cert_store = X509_STORE_new();
  13422. X509_STORE_add_cert(cert_store, ca_cert);
  13423. // svr.update_certs(cert, key, cert_store); // deprecated
  13424. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13425. CLIENT_CA_CERT_FILE);
  13426. ASSERT_TRUE(svr.is_valid());
  13427. svr.stop();
  13428. X509_STORE_free(cert_store);
  13429. X509_free(cert);
  13430. X509_free(ca_cert);
  13431. EVP_PKEY_free(key);
  13432. }
  13433. // Test that SSLServer(X509*, EVP_PKEY*, X509_STORE*) constructor sets
  13434. // client CA list correctly for TLS handshake
  13435. TEST(SSLClientServerTest, X509ConstructorSetsClientCAList) {
  13436. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13437. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13438. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13439. ASSERT_TRUE(cert != nullptr);
  13440. ASSERT_TRUE(ca_cert != nullptr);
  13441. ASSERT_TRUE(key != nullptr);
  13442. X509_STORE *cert_store = X509_STORE_new();
  13443. X509_STORE_add_cert(cert_store, ca_cert);
  13444. // Use X509-based constructor (deprecated but should still work correctly)
  13445. #pragma GCC diagnostic push
  13446. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  13447. SSLServer svr(cert, key, cert_store);
  13448. #pragma GCC diagnostic pop
  13449. ASSERT_TRUE(svr.is_valid());
  13450. // Verify that client CA list is set in SSL_CTX
  13451. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13452. ASSERT_TRUE(ssl_ctx != nullptr);
  13453. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13454. ASSERT_TRUE(ca_list != nullptr);
  13455. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13456. X509_free(cert);
  13457. X509_free(ca_cert);
  13458. EVP_PKEY_free(key);
  13459. }
  13460. // Test that update_certs() updates client CA list correctly
  13461. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  13462. // Start with file-based constructor
  13463. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13464. ASSERT_TRUE(svr.is_valid());
  13465. // Initially no client CA list should be set
  13466. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13467. ASSERT_TRUE(ssl_ctx != nullptr);
  13468. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  13469. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  13470. EXPECT_EQ(0, count_before);
  13471. // Now update with client CA (PEM string)
  13472. std::string cert_pem, key_pem, ca_pem;
  13473. read_file(SERVER_CERT_FILE, cert_pem);
  13474. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13475. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13476. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  13477. ASSERT_TRUE(svr.is_valid());
  13478. // Now client CA list should be set
  13479. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  13480. ASSERT_TRUE(ca_list_after != nullptr);
  13481. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  13482. }
  13483. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  13484. // Test that the file-path SSLServer constructor properly sets the client CA
  13485. // list that is sent to clients during the TLS handshake (CertificateRequest)
  13486. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13487. ASSERT_TRUE(svr.is_valid());
  13488. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13489. ASSERT_TRUE(ssl_ctx != nullptr);
  13490. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13491. ASSERT_TRUE(ca_list != nullptr);
  13492. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13493. }
  13494. #endif
  13495. // ============================================================================
  13496. // MbedTLS-Specific Tests
  13497. // ============================================================================
  13498. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  13499. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  13500. using namespace httplib::tls;
  13501. // Track if callback was invoked
  13502. bool callback_invoked = false;
  13503. // The callback receives void* ctx which is actually MbedTlsContext*
  13504. // We can access the mbedtls_ssl_config via the context
  13505. auto setup_callback = [&callback_invoked](void *ctx) {
  13506. callback_invoked = true;
  13507. // Cast to MbedTlsContext* to access the ssl config
  13508. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  13509. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  13510. // Use static variables to hold certificate data (simplified for test)
  13511. static mbedtls_x509_crt own_cert;
  13512. static mbedtls_pk_context own_key;
  13513. static mbedtls_x509_crt ca_chain;
  13514. static bool initialized = false;
  13515. if (!initialized) {
  13516. mbedtls_x509_crt_init(&own_cert);
  13517. mbedtls_pk_init(&own_key);
  13518. mbedtls_x509_crt_init(&ca_chain);
  13519. // Load server certificate
  13520. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  13521. return false;
  13522. }
  13523. // Load server private key
  13524. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  13525. #if MBEDTLS_VERSION_MAJOR >= 3
  13526. ,
  13527. mbedtls_ctr_drbg_random, nullptr
  13528. #endif
  13529. ) != 0) {
  13530. return false;
  13531. }
  13532. // Load CA chain for client verification
  13533. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  13534. return false;
  13535. }
  13536. initialized = true;
  13537. }
  13538. // Configure the SSL config
  13539. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  13540. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  13541. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  13542. // Set minimum TLS version using mbedTLS native API
  13543. #if MBEDTLS_VERSION_MAJOR >= 3
  13544. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  13545. #else
  13546. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  13547. MBEDTLS_SSL_MINOR_VERSION_3);
  13548. #endif
  13549. return true;
  13550. };
  13551. SSLServer svr(setup_callback);
  13552. ASSERT_TRUE(svr.is_valid());
  13553. ASSERT_TRUE(callback_invoked);
  13554. svr.Get("/test", [&](const Request &req, Response &res) {
  13555. res.set_content("test", "text/plain");
  13556. auto cert = req.peer_cert();
  13557. ASSERT_TRUE(static_cast<bool>(cert));
  13558. auto common_name = cert.subject_cn();
  13559. EXPECT_EQ("Common Name", common_name);
  13560. });
  13561. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13562. auto se = detail::scope_exit([&] {
  13563. svr.stop();
  13564. t.join();
  13565. ASSERT_FALSE(svr.is_running());
  13566. });
  13567. svr.wait_until_ready();
  13568. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13569. cli.enable_server_certificate_verification(false);
  13570. cli.set_connection_timeout(30);
  13571. auto res = cli.Get("/test");
  13572. ASSERT_TRUE(res);
  13573. ASSERT_EQ(StatusCode::OK_200, res->status);
  13574. }
  13575. #endif
  13576. // WebSocket Tests
  13577. TEST(WebSocketTest, RSVBitsMustBeZero) {
  13578. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  13579. // defining the meaning of these bits has been negotiated.
  13580. auto make_frame = [](uint8_t first_byte) {
  13581. std::string frame;
  13582. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  13583. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  13584. frame += "Hello";
  13585. return frame;
  13586. };
  13587. // RSV1 set (0x40)
  13588. {
  13589. detail::BufferStream strm;
  13590. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  13591. ws::Opcode opcode;
  13592. std::string payload;
  13593. bool fin;
  13594. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13595. false, 1024));
  13596. }
  13597. // RSV2 set (0x20)
  13598. {
  13599. detail::BufferStream strm;
  13600. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  13601. ws::Opcode opcode;
  13602. std::string payload;
  13603. bool fin;
  13604. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13605. false, 1024));
  13606. }
  13607. // RSV3 set (0x10)
  13608. {
  13609. detail::BufferStream strm;
  13610. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  13611. ws::Opcode opcode;
  13612. std::string payload;
  13613. bool fin;
  13614. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13615. false, 1024));
  13616. }
  13617. // No RSV bits set - should succeed
  13618. {
  13619. detail::BufferStream strm;
  13620. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  13621. ws::Opcode opcode;
  13622. std::string payload;
  13623. bool fin;
  13624. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13625. false, 1024));
  13626. EXPECT_EQ(ws::Opcode::Text, opcode);
  13627. EXPECT_EQ("Hello", payload);
  13628. EXPECT_TRUE(fin);
  13629. }
  13630. }
  13631. TEST(WebSocketTest, ControlFrameValidation) {
  13632. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  13633. // payload length <= 125.
  13634. // Ping with FIN=0 - must be rejected
  13635. {
  13636. detail::BufferStream strm;
  13637. std::string frame;
  13638. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  13639. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13640. strm.write(frame.data(), frame.size());
  13641. ws::Opcode opcode;
  13642. std::string payload;
  13643. bool fin;
  13644. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13645. false, 1024));
  13646. }
  13647. // Close with FIN=0 - must be rejected
  13648. {
  13649. detail::BufferStream strm;
  13650. std::string frame;
  13651. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  13652. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13653. strm.write(frame.data(), frame.size());
  13654. ws::Opcode opcode;
  13655. std::string payload;
  13656. bool fin;
  13657. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13658. false, 1024));
  13659. }
  13660. // Ping with payload_len=126 (extended length) - must be rejected
  13661. {
  13662. detail::BufferStream strm;
  13663. std::string frame;
  13664. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13665. frame += static_cast<char>(126); // payload_len=126 (>125)
  13666. frame += static_cast<char>(0x00); // extended length high byte
  13667. frame += static_cast<char>(126); // extended length low byte
  13668. frame += std::string(126, 'x');
  13669. strm.write(frame.data(), frame.size());
  13670. ws::Opcode opcode;
  13671. std::string payload;
  13672. bool fin;
  13673. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13674. false, 1024));
  13675. }
  13676. // Ping with FIN=1 and payload_len=125 - should succeed
  13677. {
  13678. detail::BufferStream strm;
  13679. std::string frame;
  13680. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13681. frame += static_cast<char>(125); // payload_len=125
  13682. frame += std::string(125, 'x');
  13683. strm.write(frame.data(), frame.size());
  13684. ws::Opcode opcode;
  13685. std::string payload;
  13686. bool fin;
  13687. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13688. false, 1024));
  13689. EXPECT_EQ(ws::Opcode::Ping, opcode);
  13690. EXPECT_EQ(125u, payload.size());
  13691. EXPECT_TRUE(fin);
  13692. }
  13693. }
  13694. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  13695. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  13696. // length MUST be 0.
  13697. // MSB set - must be rejected
  13698. {
  13699. detail::BufferStream strm;
  13700. std::string frame;
  13701. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13702. frame += static_cast<char>(127); // 64-bit extended length
  13703. frame += static_cast<char>(0x80); // MSB set (invalid)
  13704. frame += std::string(7, '\0'); // remaining 7 bytes of length
  13705. strm.write(frame.data(), frame.size());
  13706. ws::Opcode opcode;
  13707. std::string payload;
  13708. bool fin;
  13709. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13710. false, 1024));
  13711. }
  13712. // MSB clear - should pass length parsing (will be rejected by max_len,
  13713. // but that's a different check; use a small length to verify)
  13714. {
  13715. detail::BufferStream strm;
  13716. std::string frame;
  13717. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13718. frame += static_cast<char>(127); // 64-bit extended length
  13719. frame += std::string(7, '\0'); // high bytes = 0
  13720. frame += static_cast<char>(0x03); // length = 3
  13721. frame += "abc";
  13722. strm.write(frame.data(), frame.size());
  13723. ws::Opcode opcode;
  13724. std::string payload;
  13725. bool fin;
  13726. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13727. false, 1024));
  13728. EXPECT_EQ(ws::Opcode::Text, opcode);
  13729. EXPECT_EQ("abc", payload);
  13730. }
  13731. }
  13732. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  13733. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  13734. // Valid UTF-8
  13735. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  13736. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  13737. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  13738. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  13739. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  13740. // Invalid UTF-8
  13741. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  13742. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  13743. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  13744. EXPECT_FALSE(
  13745. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  13746. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  13747. }
  13748. TEST(WebSocketTest, ConnectAndDisconnect) {
  13749. Server svr;
  13750. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  13751. std::string msg;
  13752. while (ws.read(msg)) {}
  13753. });
  13754. auto port = svr.bind_to_any_port(HOST);
  13755. std::thread t([&]() { svr.listen_after_bind(); });
  13756. svr.wait_until_ready();
  13757. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  13758. ASSERT_TRUE(client.connect());
  13759. EXPECT_TRUE(client.is_open());
  13760. client.close();
  13761. EXPECT_FALSE(client.is_open());
  13762. svr.stop();
  13763. t.join();
  13764. }
  13765. TEST(WebSocketTest, ValidURL) {
  13766. ws::WebSocketClient ws1("ws://localhost:8080/path");
  13767. EXPECT_TRUE(ws1.is_valid());
  13768. ws::WebSocketClient ws2("ws://example.com/path");
  13769. EXPECT_TRUE(ws2.is_valid());
  13770. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  13771. EXPECT_TRUE(ws3.is_valid());
  13772. #ifdef CPPHTTPLIB_SSL_ENABLED
  13773. ws::WebSocketClient wss1("wss://example.com/path");
  13774. EXPECT_TRUE(wss1.is_valid());
  13775. ws::WebSocketClient wss2("wss://example.com:443/path");
  13776. EXPECT_TRUE(wss2.is_valid());
  13777. #endif
  13778. }
  13779. TEST(WebSocketTest, InvalidURL) {
  13780. // No scheme
  13781. ws::WebSocketClient ws1("localhost:8080/path");
  13782. EXPECT_FALSE(ws1.is_valid());
  13783. // No path
  13784. ws::WebSocketClient ws2("ws://localhost:8080");
  13785. EXPECT_FALSE(ws2.is_valid());
  13786. // Empty string
  13787. ws::WebSocketClient ws3("");
  13788. EXPECT_FALSE(ws3.is_valid());
  13789. // Missing host
  13790. ws::WebSocketClient ws4("ws://:8080/path");
  13791. EXPECT_FALSE(ws4.is_valid());
  13792. // Port number overflow — should not crash
  13793. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  13794. EXPECT_FALSE(ws5.is_valid());
  13795. // Port out of range
  13796. ws::WebSocketClient ws6("ws://localhost:99999/path");
  13797. EXPECT_FALSE(ws6.is_valid());
  13798. }
  13799. TEST(WebSocketTest, UnsupportedScheme) {
  13800. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13801. ws::WebSocketClient ws1("http://localhost:8080/path");
  13802. EXPECT_FALSE(ws1.is_valid());
  13803. ws::WebSocketClient ws2("https://localhost:8080/path");
  13804. EXPECT_FALSE(ws2.is_valid());
  13805. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  13806. EXPECT_FALSE(ws3.is_valid());
  13807. #else
  13808. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  13809. std::invalid_argument);
  13810. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  13811. std::invalid_argument);
  13812. #endif
  13813. }
  13814. TEST(WebSocketTest, ConnectWhenInvalid) {
  13815. ws::WebSocketClient ws("not a valid url");
  13816. EXPECT_FALSE(ws.is_valid());
  13817. EXPECT_FALSE(ws.connect());
  13818. }
  13819. TEST(WebSocketTest, DefaultPort) {
  13820. ws::WebSocketClient ws1("ws://example.com/path");
  13821. EXPECT_TRUE(ws1.is_valid());
  13822. // ws:// defaults to port 80 (verified by successful parse)
  13823. #ifdef CPPHTTPLIB_SSL_ENABLED
  13824. ws::WebSocketClient ws2("wss://example.com/path");
  13825. EXPECT_TRUE(ws2.is_valid());
  13826. // wss:// defaults to port 443 (verified by successful parse)
  13827. #endif
  13828. }
  13829. TEST(WebSocketTest, IPv6LiteralAddress) {
  13830. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  13831. EXPECT_TRUE(ws1.is_valid());
  13832. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  13833. EXPECT_TRUE(ws2.is_valid());
  13834. }
  13835. TEST(WebSocketTest, ComplexPath) {
  13836. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  13837. EXPECT_TRUE(ws1.is_valid());
  13838. ws::WebSocketClient ws2("ws://localhost:8080/");
  13839. EXPECT_TRUE(ws2.is_valid());
  13840. }
  13841. class WebSocketIntegrationTest : public ::testing::Test {
  13842. protected:
  13843. void SetUp() override {
  13844. server_ = httplib::detail::make_unique<Server>();
  13845. setup_server();
  13846. start_server();
  13847. }
  13848. void TearDown() override {
  13849. server_->stop();
  13850. if (server_thread_.joinable()) { server_thread_.join(); }
  13851. }
  13852. void setup_server() {
  13853. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  13854. std::string msg;
  13855. ws::ReadResult ret;
  13856. while ((ret = ws.read(msg))) {
  13857. if (ret == ws::Binary) {
  13858. ws.send(msg.data(), msg.size());
  13859. } else {
  13860. ws.send(msg);
  13861. }
  13862. }
  13863. });
  13864. server_->WebSocket("/ws-echo-string",
  13865. [](const Request &, ws::WebSocket &ws) {
  13866. std::string msg;
  13867. while (ws.read(msg)) {
  13868. ws.send("echo: " + msg);
  13869. }
  13870. });
  13871. server_->WebSocket(
  13872. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  13873. // Echo back request metadata
  13874. ws.send("path:" + req.path);
  13875. ws.send("header:" + req.get_header_value("X-Test-Header"));
  13876. std::string msg;
  13877. while (ws.read(msg)) {}
  13878. });
  13879. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  13880. std::string msg;
  13881. ws.read(msg); // wait for a message
  13882. ws.close();
  13883. });
  13884. server_->WebSocket("/ws-close-status",
  13885. [](const Request &, ws::WebSocket &ws) {
  13886. std::string msg;
  13887. ws.read(msg); // wait for a message
  13888. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  13889. });
  13890. server_->WebSocket(
  13891. "/ws-subprotocol",
  13892. [](const Request &, ws::WebSocket &ws) {
  13893. std::string msg;
  13894. while (ws.read(msg)) {
  13895. ws.send(msg);
  13896. }
  13897. },
  13898. [](const std::vector<std::string> &protocols) -> std::string {
  13899. for (const auto &p : protocols) {
  13900. if (p == "graphql-ws") { return p; }
  13901. }
  13902. return "";
  13903. });
  13904. }
  13905. void start_server() {
  13906. port_ = server_->bind_to_any_port(HOST);
  13907. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13908. server_->wait_until_ready();
  13909. }
  13910. std::unique_ptr<Server> server_;
  13911. std::thread server_thread_;
  13912. int port_ = 0;
  13913. };
  13914. TEST_F(WebSocketIntegrationTest, TextEcho) {
  13915. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13916. "/ws-echo");
  13917. ASSERT_TRUE(client.connect());
  13918. ASSERT_TRUE(client.is_open());
  13919. ASSERT_TRUE(client.send("Hello WebSocket"));
  13920. std::string msg;
  13921. EXPECT_EQ(ws::Text, client.read(msg));
  13922. EXPECT_EQ("Hello WebSocket", msg);
  13923. client.close();
  13924. }
  13925. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  13926. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13927. "/ws-echo");
  13928. ASSERT_TRUE(client.connect());
  13929. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  13930. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  13931. std::string msg;
  13932. EXPECT_EQ(ws::Binary, client.read(msg));
  13933. EXPECT_EQ(binary_data, msg);
  13934. client.close();
  13935. }
  13936. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  13937. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13938. "/ws-echo");
  13939. ASSERT_TRUE(client.connect());
  13940. for (int i = 0; i < 10; i++) {
  13941. auto text = "message " + std::to_string(i);
  13942. ASSERT_TRUE(client.send(text));
  13943. std::string msg;
  13944. ASSERT_TRUE(client.read(msg));
  13945. EXPECT_EQ(text, msg);
  13946. }
  13947. client.close();
  13948. }
  13949. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  13950. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13951. "/ws-close");
  13952. ASSERT_TRUE(client.connect());
  13953. // Send a message to trigger the server to close
  13954. ASSERT_TRUE(client.send("trigger close"));
  13955. // The server will close, so read should return false
  13956. std::string msg;
  13957. EXPECT_FALSE(client.read(msg));
  13958. EXPECT_FALSE(client.is_open());
  13959. }
  13960. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  13961. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13962. "/ws-echo");
  13963. ASSERT_TRUE(client.connect());
  13964. // 128KB message
  13965. std::string large_data(128 * 1024, 'X');
  13966. ASSERT_TRUE(client.send(large_data));
  13967. std::string msg;
  13968. ASSERT_TRUE(client.read(msg));
  13969. EXPECT_EQ(large_data, msg);
  13970. client.close();
  13971. }
  13972. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  13973. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13974. "/ws-echo");
  13975. ASSERT_TRUE(client.connect());
  13976. const int num_threads = 4;
  13977. std::vector<std::thread> threads;
  13978. std::atomic<int> send_count{0};
  13979. for (int t = 0; t < num_threads; t++) {
  13980. threads.emplace_back([&client, &send_count, t]() {
  13981. for (int i = 0; i < 5; i++) {
  13982. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  13983. if (client.send(text)) { send_count++; }
  13984. }
  13985. });
  13986. }
  13987. for (auto &th : threads) {
  13988. th.join();
  13989. }
  13990. int received = 0;
  13991. std::string msg;
  13992. while (received < send_count.load()) {
  13993. if (!client.read(msg)) { break; }
  13994. received++;
  13995. }
  13996. EXPECT_EQ(send_count.load(), received);
  13997. client.close();
  13998. }
  13999. TEST_F(WebSocketIntegrationTest, ReadString) {
  14000. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14001. "/ws-echo-string");
  14002. ASSERT_TRUE(client.connect());
  14003. ASSERT_TRUE(client.send("hello"));
  14004. std::string msg;
  14005. ASSERT_TRUE(client.read(msg));
  14006. EXPECT_EQ("echo: hello", msg);
  14007. ASSERT_TRUE(client.send("world"));
  14008. ASSERT_TRUE(client.read(msg));
  14009. EXPECT_EQ("echo: world", msg);
  14010. client.close();
  14011. }
  14012. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  14013. Headers headers = {{"X-Test-Header", "test-value"}};
  14014. ws::WebSocketClient client(
  14015. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  14016. ASSERT_TRUE(client.connect());
  14017. std::string msg;
  14018. ASSERT_TRUE(client.read(msg));
  14019. EXPECT_EQ("path:/ws-request-info", msg);
  14020. ASSERT_TRUE(client.read(msg));
  14021. EXPECT_EQ("header:test-value", msg);
  14022. client.close();
  14023. }
  14024. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  14025. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14026. "/ws-echo");
  14027. client.set_read_timeout(1, 0); // 1 second
  14028. ASSERT_TRUE(client.connect());
  14029. // Don't send anything — server echo handler waits for a message,
  14030. // so read() should time out and return false.
  14031. std::string msg;
  14032. EXPECT_FALSE(client.read(msg));
  14033. }
  14034. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  14035. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14036. "/ws-echo");
  14037. client.set_read_timeout(5, 0);
  14038. ASSERT_TRUE(client.connect());
  14039. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14040. // The server should reject it and close the connection.
  14041. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  14042. client.send(oversized);
  14043. // The server's read() should have failed due to payload limit,
  14044. // so our read() should return false (connection closed).
  14045. std::string msg;
  14046. EXPECT_FALSE(client.read(msg));
  14047. }
  14048. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  14049. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14050. "/ws-echo");
  14051. client.set_read_timeout(10, 0);
  14052. ASSERT_TRUE(client.connect());
  14053. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14054. // This should succeed.
  14055. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  14056. ASSERT_TRUE(client.send(at_limit));
  14057. std::string msg;
  14058. ASSERT_TRUE(client.read(msg));
  14059. EXPECT_EQ(at_limit.size(), msg.size());
  14060. client.close();
  14061. }
  14062. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  14063. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14064. "/nonexistent");
  14065. EXPECT_FALSE(client.connect());
  14066. EXPECT_FALSE(client.is_open());
  14067. }
  14068. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  14069. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14070. "/ws-echo");
  14071. ASSERT_TRUE(client.connect());
  14072. ASSERT_TRUE(client.send(""));
  14073. std::string msg;
  14074. EXPECT_EQ(ws::Text, client.read(msg));
  14075. EXPECT_EQ("", msg);
  14076. client.close();
  14077. }
  14078. TEST_F(WebSocketIntegrationTest, Reconnect) {
  14079. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14080. "/ws-echo");
  14081. // First connection
  14082. ASSERT_TRUE(client.connect());
  14083. ASSERT_TRUE(client.send("first"));
  14084. std::string msg;
  14085. ASSERT_TRUE(client.read(msg));
  14086. EXPECT_EQ("first", msg);
  14087. client.close();
  14088. EXPECT_FALSE(client.is_open());
  14089. // Reconnect using the same client object
  14090. ASSERT_TRUE(client.connect());
  14091. ASSERT_TRUE(client.is_open());
  14092. ASSERT_TRUE(client.send("second"));
  14093. ASSERT_TRUE(client.read(msg));
  14094. EXPECT_EQ("second", msg);
  14095. client.close();
  14096. }
  14097. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  14098. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14099. "/ws-close-status");
  14100. ASSERT_TRUE(client.connect());
  14101. // Trigger the server to close with GoingAway status
  14102. ASSERT_TRUE(client.send("trigger"));
  14103. // read() should return false after receiving the close frame
  14104. std::string msg;
  14105. EXPECT_FALSE(client.read(msg));
  14106. EXPECT_FALSE(client.is_open());
  14107. }
  14108. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  14109. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14110. "/ws-echo");
  14111. ASSERT_TRUE(client.connect());
  14112. client.close(ws::CloseStatus::GoingAway, "client leaving");
  14113. EXPECT_FALSE(client.is_open());
  14114. }
  14115. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  14116. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  14117. ws::WebSocketClient client(
  14118. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14119. ASSERT_TRUE(client.connect());
  14120. // Server should have selected graphql-ws
  14121. EXPECT_EQ("graphql-ws", client.subprotocol());
  14122. client.close();
  14123. }
  14124. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  14125. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  14126. ws::WebSocketClient client(
  14127. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14128. ASSERT_TRUE(client.connect());
  14129. // Server should not have selected any subprotocol
  14130. EXPECT_TRUE(client.subprotocol().empty());
  14131. client.close();
  14132. }
  14133. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  14134. // Connect without requesting any subprotocol
  14135. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14136. "/ws-subprotocol");
  14137. ASSERT_TRUE(client.connect());
  14138. EXPECT_TRUE(client.subprotocol().empty());
  14139. client.close();
  14140. }
  14141. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  14142. Server svr;
  14143. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  14144. if (!req.has_header("Authorization")) {
  14145. res.status = StatusCode::Unauthorized_401;
  14146. res.set_content("Unauthorized", "text/plain");
  14147. return Server::HandlerResponse::Handled;
  14148. }
  14149. return Server::HandlerResponse::Unhandled;
  14150. });
  14151. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14152. std::string msg;
  14153. while (ws.read(msg)) {
  14154. ws.send(msg);
  14155. }
  14156. });
  14157. auto port = svr.bind_to_any_port("localhost");
  14158. std::thread t([&]() { svr.listen_after_bind(); });
  14159. svr.wait_until_ready();
  14160. // Without Authorization header - should be rejected before upgrade
  14161. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  14162. EXPECT_FALSE(client1.connect());
  14163. // With Authorization header - should succeed
  14164. Headers headers = {{"Authorization", "Bearer token123"}};
  14165. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  14166. headers);
  14167. ASSERT_TRUE(client2.connect());
  14168. ASSERT_TRUE(client2.send("hello"));
  14169. std::string msg;
  14170. ASSERT_TRUE(client2.read(msg));
  14171. EXPECT_EQ("hello", msg);
  14172. client2.close();
  14173. svr.stop();
  14174. t.join();
  14175. }
  14176. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14177. class WebSocketSSLIntegrationTest : public ::testing::Test {
  14178. protected:
  14179. void SetUp() override {
  14180. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  14181. SERVER_PRIVATE_KEY_FILE);
  14182. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14183. std::string msg;
  14184. ws::ReadResult ret;
  14185. while ((ret = ws.read(msg))) {
  14186. if (ret == ws::Binary) {
  14187. ws.send(msg.data(), msg.size());
  14188. } else {
  14189. ws.send(msg);
  14190. }
  14191. }
  14192. });
  14193. port_ = server_->bind_to_any_port(HOST);
  14194. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14195. server_->wait_until_ready();
  14196. }
  14197. void TearDown() override {
  14198. server_->stop();
  14199. if (server_thread_.joinable()) { server_thread_.join(); }
  14200. }
  14201. std::unique_ptr<SSLServer> server_;
  14202. std::thread server_thread_;
  14203. int port_ = 0;
  14204. };
  14205. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  14206. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  14207. "/ws-echo");
  14208. client.enable_server_certificate_verification(false);
  14209. ASSERT_TRUE(client.connect());
  14210. ASSERT_TRUE(client.is_open());
  14211. ASSERT_TRUE(client.send("Hello WSS"));
  14212. std::string msg;
  14213. EXPECT_EQ(ws::Text, client.read(msg));
  14214. EXPECT_EQ("Hello WSS", msg);
  14215. client.close();
  14216. }
  14217. #endif
  14218. #if !defined(_WIN32)
  14219. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  14220. auto secret_dir = std::string("./symlink_test_secret");
  14221. auto served_dir = std::string("./symlink_test_served");
  14222. auto secret_file = secret_dir + "/secret.txt";
  14223. auto symlink_path = served_dir + "/escape";
  14224. // Setup: create directories and files
  14225. mkdir(secret_dir.c_str(), 0755);
  14226. mkdir(served_dir.c_str(), 0755);
  14227. {
  14228. std::ofstream ofs(secret_file);
  14229. ofs << "SECRET_DATA";
  14230. }
  14231. // Create symlink using absolute path so it resolves correctly
  14232. char abs_secret[PATH_MAX];
  14233. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  14234. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  14235. auto se = detail::scope_exit([&] {
  14236. unlink(symlink_path.c_str());
  14237. unlink(secret_file.c_str());
  14238. rmdir(served_dir.c_str());
  14239. rmdir(secret_dir.c_str());
  14240. });
  14241. Server svr;
  14242. svr.set_mount_point("/", served_dir);
  14243. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  14244. auto se2 = detail::scope_exit([&] {
  14245. svr.stop();
  14246. listen_thread.join();
  14247. });
  14248. svr.wait_until_ready();
  14249. Client cli("localhost", PORT);
  14250. // Symlink pointing outside base dir should be blocked
  14251. auto res = cli.Get("/escape/secret.txt");
  14252. ASSERT_TRUE(res);
  14253. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  14254. }
  14255. #endif