test.cc 526 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #if __cplusplus >= 202002L
  28. inline std::string u8_to_string(const char8_t *s) {
  29. return std::string(reinterpret_cast<const char *>(s));
  30. }
  31. #define U8(x) u8_to_string(u8##x)
  32. #else
  33. #define U8(x) u8##x
  34. #endif
  35. #define SERVER_CERT_FILE "./cert.pem"
  36. #define SERVER_CERT2_FILE "./cert2.pem"
  37. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  38. #define CA_CERT_FILE "./ca-bundle.crt"
  39. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  40. #define CLIENT_CA_CERT_DIR "."
  41. #define CLIENT_CERT_FILE "./client.cert.pem"
  42. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  43. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  44. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  45. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  46. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  47. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  48. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  49. using namespace std;
  50. using namespace httplib;
  51. const char *HOST = "localhost";
  52. static int get_base_port() {
  53. const char *shard = getenv("GTEST_SHARD_INDEX");
  54. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  55. }
  56. const int PORT = get_base_port();
  57. const string LONG_QUERY_VALUE = string(25000, '@');
  58. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  59. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  60. const string TOO_LONG_QUERY_URL =
  61. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  62. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  63. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  64. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  65. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  66. return file.name == key;
  67. });
  68. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  69. return *it;
  70. #else
  71. if (it != items.end()) { return *it; }
  72. throw std::runtime_error("invalid multipart form data name error");
  73. #endif
  74. }
  75. static void read_file(const std::string &path, std::string &out) {
  76. std::ifstream fs(path, std::ios_base::binary);
  77. if (!fs) {
  78. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  79. return;
  80. #else
  81. throw std::runtime_error("File not found: " + path);
  82. #endif
  83. }
  84. fs.seekg(0, std::ios_base::end);
  85. auto size = fs.tellg();
  86. fs.seekg(0);
  87. out.resize(static_cast<size_t>(size));
  88. fs.read(&out[0], static_cast<std::streamsize>(size));
  89. }
  90. void performance_test(const char *host) {
  91. Server svr;
  92. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  93. res.set_content("Benchmark Response", "text/plain");
  94. });
  95. auto listen_thread = std::thread([&]() { svr.listen(host, PORT); });
  96. auto se = detail::scope_exit([&] {
  97. svr.stop();
  98. listen_thread.join();
  99. ASSERT_FALSE(svr.is_running());
  100. });
  101. svr.wait_until_ready();
  102. Client cli(host, PORT);
  103. // Warm-up request to establish connection and resolve DNS
  104. auto warmup_res = cli.Get("/benchmark");
  105. ASSERT_TRUE(warmup_res); // Ensure server is responding correctly
  106. // Run multiple trials and collect timings
  107. const int num_trials = 20;
  108. std::vector<int64_t> timings;
  109. timings.reserve(num_trials);
  110. for (int i = 0; i < num_trials; i++) {
  111. auto start = std::chrono::high_resolution_clock::now();
  112. auto res = cli.Get("/benchmark");
  113. auto end = std::chrono::high_resolution_clock::now();
  114. auto elapsed =
  115. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  116. .count();
  117. // Assertions after timing measurement to avoid overhead
  118. ASSERT_TRUE(res);
  119. EXPECT_EQ(StatusCode::OK_200, res->status);
  120. timings.push_back(elapsed);
  121. }
  122. // Calculate 25th percentile (lower quartile)
  123. std::sort(timings.begin(), timings.end());
  124. auto p25 = timings[num_trials / 4];
  125. // Format timings for output
  126. std::ostringstream timings_str;
  127. timings_str << "[";
  128. for (size_t i = 0; i < timings.size(); i++) {
  129. if (i > 0) timings_str << ", ";
  130. timings_str << timings[i];
  131. }
  132. timings_str << "]";
  133. // Localhost HTTP GET should be fast even in CI environments
  134. EXPECT_LE(p25, 5) << "25th percentile performance is too slow: " << p25
  135. << "ms (Issue #1777). Timings: " << timings_str.str();
  136. }
  137. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  138. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  139. class UnixSocketTest : public ::testing::Test {
  140. protected:
  141. void TearDown() override { std::remove(pathname_.c_str()); }
  142. void client_GET(const std::string &addr) {
  143. httplib::Client cli{addr};
  144. cli.set_address_family(AF_UNIX);
  145. ASSERT_TRUE(cli.is_valid());
  146. const auto &result = cli.Get(pattern_);
  147. ASSERT_TRUE(result) << "error: " << result.error();
  148. const auto &resp = result.value();
  149. EXPECT_EQ(resp.status, StatusCode::OK_200);
  150. EXPECT_EQ(resp.body, content_);
  151. }
  152. static std::string make_sock_path() {
  153. const char *shard = getenv("GTEST_SHARD_INDEX");
  154. return shard ? std::string("./httplib-server-") + shard + ".sock"
  155. : "./httplib-server.sock";
  156. }
  157. const std::string pathname_{make_sock_path()};
  158. const std::string pattern_{"/hi"};
  159. const std::string content_{"Hello World!"};
  160. };
  161. TEST_F(UnixSocketTest, pathname) {
  162. httplib::Server svr;
  163. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  164. res.set_content(content_, "text/plain");
  165. });
  166. std::thread t{[&] {
  167. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  168. }};
  169. auto se = detail::scope_exit([&] {
  170. svr.stop();
  171. t.join();
  172. ASSERT_FALSE(svr.is_running());
  173. });
  174. svr.wait_until_ready();
  175. ASSERT_TRUE(svr.is_running());
  176. client_GET(pathname_);
  177. }
  178. #if defined(__linux__) || \
  179. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  180. TEST_F(UnixSocketTest, PeerPid) {
  181. httplib::Server svr;
  182. std::string remote_port_val;
  183. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  184. res.set_content(content_, "text/plain");
  185. remote_port_val = std::to_string(req.remote_port);
  186. });
  187. std::thread t{[&] {
  188. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  189. }};
  190. auto se = detail::scope_exit([&] {
  191. svr.stop();
  192. t.join();
  193. ASSERT_FALSE(svr.is_running());
  194. });
  195. svr.wait_until_ready();
  196. ASSERT_TRUE(svr.is_running());
  197. client_GET(pathname_);
  198. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  199. }
  200. #endif
  201. #ifdef __linux__
  202. TEST_F(UnixSocketTest, abstract) {
  203. constexpr char svr_path[]{"\x00httplib-server.sock"};
  204. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  205. httplib::Server svr;
  206. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  207. res.set_content(content_, "text/plain");
  208. });
  209. std::thread t{[&] {
  210. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  211. }};
  212. auto se = detail::scope_exit([&] {
  213. svr.stop();
  214. t.join();
  215. ASSERT_FALSE(svr.is_running());
  216. });
  217. svr.wait_until_ready();
  218. ASSERT_TRUE(svr.is_running());
  219. client_GET(abstract_addr);
  220. }
  221. #endif
  222. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  223. httplib::Server svr;
  224. std::string received_host_header;
  225. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  226. // Capture the Host header sent by the client
  227. auto host_iter = req.headers.find("Host");
  228. if (host_iter != req.headers.end()) {
  229. received_host_header = host_iter->second;
  230. }
  231. res.set_content(content_, "text/plain");
  232. });
  233. std::thread t{[&] {
  234. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  235. }};
  236. auto se = detail::scope_exit([&] {
  237. svr.stop();
  238. t.join();
  239. ASSERT_FALSE(svr.is_running());
  240. });
  241. svr.wait_until_ready();
  242. ASSERT_TRUE(svr.is_running());
  243. // Test that Host header is automatically set to "localhost" for Unix socket
  244. // connections
  245. httplib::Client cli{pathname_};
  246. cli.set_address_family(AF_UNIX);
  247. ASSERT_TRUE(cli.is_valid());
  248. const auto &result = cli.Get(pattern_);
  249. ASSERT_TRUE(result) << "error: " << result.error();
  250. const auto &resp = result.value();
  251. EXPECT_EQ(resp.status, StatusCode::OK_200);
  252. EXPECT_EQ(resp.body, content_);
  253. // Verify that Host header was automatically set to "localhost"
  254. EXPECT_EQ(received_host_header, "localhost");
  255. }
  256. #ifndef _WIN32
  257. TEST(SocketStream, wait_writable_UNIX) {
  258. int fds[2];
  259. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  260. const auto asSocketStream = [&](socket_t fd,
  261. std::function<bool(Stream &)> func) {
  262. return detail::process_client_socket(
  263. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  264. };
  265. asSocketStream(fds[0], [&](Stream &s0) {
  266. EXPECT_EQ(s0.socket(), fds[0]);
  267. EXPECT_TRUE(s0.wait_writable());
  268. EXPECT_TRUE(s0.is_peer_alive());
  269. EXPECT_EQ(0, close(fds[1]));
  270. EXPECT_FALSE(s0.is_peer_alive());
  271. return true;
  272. });
  273. EXPECT_EQ(0, close(fds[0]));
  274. }
  275. TEST(SocketStream, wait_writable_INET) {
  276. sockaddr_in addr;
  277. memset(&addr, 0, sizeof(addr));
  278. addr.sin_family = AF_INET;
  279. addr.sin_port = htons(PORT + 1);
  280. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  281. int disconnected_svr_sock = -1;
  282. std::thread svr{[&] {
  283. const int s = socket(AF_INET, SOCK_STREAM, 0);
  284. ASSERT_LE(0, s);
  285. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  286. ASSERT_EQ(0, listen(s, 1));
  287. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  288. ASSERT_EQ(0, close(s));
  289. }};
  290. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  291. std::thread cli{[&] {
  292. const int s = socket(AF_INET, SOCK_STREAM, 0);
  293. ASSERT_LE(0, s);
  294. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  295. ASSERT_EQ(0, close(s));
  296. }};
  297. cli.join();
  298. svr.join();
  299. ASSERT_NE(disconnected_svr_sock, -1);
  300. const auto asSocketStream = [&](socket_t fd,
  301. std::function<bool(Stream &)> func) {
  302. return detail::process_client_socket(
  303. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  304. };
  305. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  306. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  307. // wait_writable() returns true because select_write() only checks if the
  308. // send buffer has space. Peer disconnection is detected later by send().
  309. EXPECT_TRUE(ss.wait_writable());
  310. return true;
  311. });
  312. ASSERT_EQ(0, close(disconnected_svr_sock));
  313. }
  314. #endif // #ifndef _WIN32
  315. TEST(ClientTest, MoveConstructible) {
  316. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  317. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  318. }
  319. TEST(ClientTest, MoveAssignable) {
  320. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  321. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  322. }
  323. #ifdef _WIN32
  324. TEST(StartupTest, WSAStartup) {
  325. WSADATA wsaData;
  326. int ret = WSAStartup(0x0002, &wsaData);
  327. ASSERT_EQ(0, ret);
  328. }
  329. #endif
  330. TEST(DecodePathTest, PercentCharacter) {
  331. EXPECT_EQ(
  332. decode_path_component(
  333. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  334. U8("descrip=Gastos áéíóúñÑ 6"));
  335. }
  336. TEST(DecodePathTest, PercentCharacterNUL) {
  337. string expected;
  338. expected.push_back('x');
  339. expected.push_back('\0');
  340. expected.push_back('x');
  341. EXPECT_EQ(decode_path_component("x%00x"), expected);
  342. }
  343. TEST(DecodePathTest, UnicodeEncoding) {
  344. // %u0041 = 'A' (1-byte UTF-8)
  345. EXPECT_EQ("A", decode_path_component("%u0041"));
  346. // %u00E9 = 'é' (2-byte UTF-8)
  347. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  348. // %u3042 = 'あ' (3-byte UTF-8)
  349. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  350. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  351. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  352. // %uD800 = surrogate (invalid, silently dropped)
  353. EXPECT_EQ("", decode_path_component("%uD800"));
  354. }
  355. TEST(SanitizeFilenameTest, VariousPatterns) {
  356. // Path traversal
  357. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  358. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  359. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  360. // Normal and edge cases
  361. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  362. EXPECT_EQ("filename.txt",
  363. httplib::sanitize_filename("/path/to/filename.txt"));
  364. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  365. EXPECT_EQ("", httplib::sanitize_filename(".."));
  366. EXPECT_EQ("", httplib::sanitize_filename(""));
  367. // Null bytes stripped
  368. EXPECT_EQ("safe.txt",
  369. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  370. // Whitespace-only rejected
  371. EXPECT_EQ("", httplib::sanitize_filename(" "));
  372. }
  373. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  374. string unescapedCharacters = "-_.!~*'()";
  375. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  376. }
  377. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  378. string reservedCharacters = ";,/?:@&=+$";
  379. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  380. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  381. }
  382. TEST(ClientQueryOrder, PreserveOrder) {
  383. // This test reproduces Issue #2259: client may reorder query parameters
  384. // when sending a GET request. The expected behavior is that the client
  385. // preserves the original query string order when the caller supplied it
  386. // as part of the path.
  387. Server svr;
  388. svr.Get("/", [&](const Request &req, Response &res) {
  389. // Echo back the raw target so the test can assert ordering
  390. res.set_content(req.target, "text/plain");
  391. });
  392. std::thread t{[&] { svr.listen(HOST, PORT); }};
  393. auto se = detail::scope_exit([&] {
  394. svr.stop();
  395. t.join();
  396. ASSERT_FALSE(svr.is_running());
  397. });
  398. svr.wait_until_ready();
  399. Client cli(HOST, PORT);
  400. ASSERT_TRUE(cli.is_valid());
  401. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  402. auto res = cli.Get(original);
  403. ASSERT_TRUE(res);
  404. // Expect the echoed target to exactly match the original path (order
  405. // preserved)
  406. EXPECT_EQ(res->body, original);
  407. }
  408. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  409. string chineseCharacters = U8("中国語");
  410. string russianCharacters = U8("дом");
  411. string brazilianCharacters = U8("óculos");
  412. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  413. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  414. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  415. "%D0%B4%D0%BE%D0%BC");
  416. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  417. }
  418. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  419. string unescapedCharacters = "-_.!~*'()";
  420. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  421. }
  422. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  423. string reservedCharacters = ";,/?:@&=+$";
  424. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  425. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  426. }
  427. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  428. string chineseCharacters = U8("中国語");
  429. string russianCharacters = U8("дом");
  430. string brazilianCharacters = U8("óculos");
  431. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  432. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  433. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  434. "%D0%B4%D0%BE%D0%BC");
  435. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  436. }
  437. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  438. // Issue #2082 use case: encoding path component with ampersand
  439. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  440. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  441. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  442. }
  443. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  444. string unescapedCharacters = "-_.!~*'()";
  445. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  446. }
  447. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  448. string reservedCharacters = ";,/?:@&=+$#";
  449. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  450. }
  451. TEST(EncodeUriTest, TestUTF8Characters) {
  452. string chineseCharacters = U8("中国語");
  453. string russianCharacters = U8("дом");
  454. string brazilianCharacters = U8("óculos");
  455. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  456. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  457. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  458. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  459. }
  460. TEST(EncodeUriTest, TestCompleteUri) {
  461. string uri =
  462. "https://example.com/path/to/resource?query=value&param=test#fragment";
  463. EXPECT_EQ(
  464. httplib::encode_uri(uri),
  465. "https://example.com/path/to/resource?query=value&param=test#fragment");
  466. }
  467. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  468. string uri =
  469. "https://example.com/path with spaces/file name.html?q=hello world";
  470. EXPECT_EQ(httplib::encode_uri(uri),
  471. "https://example.com/path%20with%20spaces/"
  472. "file%20name.html?q=hello%20world");
  473. }
  474. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  475. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  476. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  477. }
  478. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  479. string unescapedCharacters = "-_.!~*'()";
  480. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  481. }
  482. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  483. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  484. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  485. string encodedBrazilian = "%C3%B3culos";
  486. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  487. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  488. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  489. }
  490. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  491. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  492. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  493. "Piri Tommy Villiers - on & on");
  494. }
  495. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  496. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  497. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  498. }
  499. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  500. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  501. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  502. }
  503. TEST(DecodeUriTest, TestUTF8Characters) {
  504. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  505. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  506. string encodedBrazilian = "%C3%B3culos";
  507. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  508. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  509. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  510. }
  511. TEST(DecodeUriTest, TestCompleteUri) {
  512. string encodedUri = "https://example.com/path%20with%20spaces/"
  513. "file%20name.html?q=hello%20world";
  514. EXPECT_EQ(
  515. httplib::decode_uri(encodedUri),
  516. "https://example.com/path with spaces/file name.html?q=hello world");
  517. }
  518. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  519. string original =
  520. "https://example.com/path with spaces/file name.html?q=hello world";
  521. string encoded = httplib::encode_uri(original);
  522. string decoded = httplib::decode_uri(encoded);
  523. EXPECT_EQ(decoded, original);
  524. }
  525. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  526. string original = "Piri Tommy Villiers - on & on";
  527. string encoded = httplib::encode_uri_component(original);
  528. string decoded = httplib::decode_uri_component(encoded);
  529. EXPECT_EQ(decoded, original);
  530. }
  531. TEST(TrimTests, TrimStringTests) {
  532. EXPECT_EQ("abc", detail::trim_copy("abc"));
  533. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  534. EXPECT_TRUE(detail::trim_copy("").empty());
  535. }
  536. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  537. // Simple case without quality values
  538. std::vector<std::string> result1;
  539. EXPECT_TRUE(detail::parse_accept_header(
  540. "text/html,application/json,text/plain", result1));
  541. EXPECT_EQ(result1.size(), 3U);
  542. EXPECT_EQ(result1[0], "text/html");
  543. EXPECT_EQ(result1[1], "application/json");
  544. EXPECT_EQ(result1[2], "text/plain");
  545. // With quality values
  546. std::vector<std::string> result2;
  547. EXPECT_TRUE(detail::parse_accept_header(
  548. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  549. EXPECT_EQ(result2.size(), 3U);
  550. EXPECT_EQ(result2[0], "application/json"); // highest q value
  551. EXPECT_EQ(result2[1], "text/html");
  552. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  553. }
  554. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  555. // Mixed with and without quality values
  556. std::vector<std::string> result;
  557. EXPECT_TRUE(detail::parse_accept_header(
  558. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  559. EXPECT_EQ(result.size(), 3U);
  560. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  561. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  562. EXPECT_EQ(result[2], "application/json"); // q=0.5
  563. }
  564. TEST(ParseAcceptHeaderTest, EdgeCases) {
  565. // Empty header
  566. std::vector<std::string> empty_result;
  567. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  568. EXPECT_TRUE(empty_result.empty());
  569. // Single type
  570. std::vector<std::string> single_result;
  571. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  572. EXPECT_EQ(single_result.size(), 1U);
  573. EXPECT_EQ(single_result[0], "application/json");
  574. // Wildcard types
  575. std::vector<std::string> wildcard_result;
  576. EXPECT_TRUE(detail::parse_accept_header(
  577. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  578. EXPECT_EQ(wildcard_result.size(), 3U);
  579. EXPECT_EQ(wildcard_result[0], "application/json");
  580. EXPECT_EQ(wildcard_result[1], "text/*");
  581. EXPECT_EQ(wildcard_result[2], "*/*");
  582. }
  583. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  584. // Common browser Accept header
  585. std::vector<std::string> browser_result;
  586. EXPECT_TRUE(
  587. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  588. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  589. browser_result));
  590. EXPECT_EQ(browser_result.size(), 6U);
  591. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  592. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  593. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  594. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  595. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  596. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  597. // API client header
  598. std::vector<std::string> api_result;
  599. EXPECT_TRUE(detail::parse_accept_header(
  600. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  601. api_result));
  602. EXPECT_EQ(api_result.size(), 3U);
  603. EXPECT_EQ(api_result[0], "application/json");
  604. EXPECT_EQ(api_result[1], "application/xml");
  605. EXPECT_EQ(api_result[2], "text/plain");
  606. }
  607. TEST(ParseAcceptHeaderTest, SpecialCases) {
  608. // Quality value with 3 decimal places
  609. std::vector<std::string> decimal_result;
  610. EXPECT_TRUE(detail::parse_accept_header(
  611. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  612. EXPECT_EQ(decimal_result.size(), 2U);
  613. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  614. EXPECT_EQ(decimal_result[1], "text/html");
  615. // Zero quality (should still be included but with lowest priority)
  616. std::vector<std::string> zero_q_result;
  617. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  618. zero_q_result));
  619. EXPECT_EQ(zero_q_result.size(), 2U);
  620. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  621. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  622. // No spaces around commas
  623. std::vector<std::string> no_space_result;
  624. EXPECT_TRUE(detail::parse_accept_header(
  625. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  626. no_space_result));
  627. EXPECT_EQ(no_space_result.size(), 3U);
  628. EXPECT_EQ(no_space_result[0], "text/html");
  629. EXPECT_EQ(no_space_result[1], "application/json");
  630. EXPECT_EQ(no_space_result[2], "text/plain");
  631. }
  632. TEST(ParseAcceptHeaderTest, InvalidCases) {
  633. std::vector<std::string> result;
  634. // Invalid quality value (> 1.0)
  635. EXPECT_FALSE(
  636. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  637. // Invalid quality value (< 0.0)
  638. EXPECT_FALSE(
  639. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  640. // Invalid quality value (not a number)
  641. EXPECT_FALSE(detail::parse_accept_header(
  642. "text/html;q=invalid,application/json", result));
  643. // Empty quality value
  644. EXPECT_FALSE(
  645. detail::parse_accept_header("text/html;q=,application/json", result));
  646. // Invalid media type format (no slash and not wildcard)
  647. EXPECT_FALSE(
  648. detail::parse_accept_header("invalidtype,application/json", result));
  649. // Empty media type
  650. result.clear();
  651. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  652. // Only commas
  653. result.clear();
  654. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  655. // Valid cases should still work
  656. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  657. EXPECT_EQ(result.size(), 1U);
  658. EXPECT_EQ(result[0], "*/*");
  659. EXPECT_TRUE(detail::parse_accept_header("*", result));
  660. EXPECT_EQ(result.size(), 1U);
  661. EXPECT_EQ(result[0], "*");
  662. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  663. EXPECT_EQ(result.size(), 1U);
  664. EXPECT_EQ(result[0], "text/*");
  665. }
  666. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  667. Server svr;
  668. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  669. EXPECT_EQ(req.accept_content_types.size(), 3U);
  670. EXPECT_EQ(req.accept_content_types[0], "application/json");
  671. EXPECT_EQ(req.accept_content_types[1], "text/html");
  672. EXPECT_EQ(req.accept_content_types[2], "*/*");
  673. res.set_content("ok", "text/plain");
  674. });
  675. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  676. EXPECT_TRUE(false);
  677. res.set_content("bad request", "text/plain");
  678. });
  679. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  680. auto se = detail::scope_exit([&] {
  681. svr.stop();
  682. listen_thread.join();
  683. ASSERT_FALSE(svr.is_running());
  684. });
  685. svr.wait_until_ready();
  686. Client cli("localhost", PORT);
  687. {
  688. auto res =
  689. cli.Get("/accept_ok",
  690. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  691. ASSERT_TRUE(res);
  692. EXPECT_EQ(StatusCode::OK_200, res->status);
  693. }
  694. {
  695. auto res = cli.Get("/accept_bad_request",
  696. {{"Accept", "text/html;q=abc,application/json"}});
  697. ASSERT_TRUE(res);
  698. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  699. }
  700. }
  701. TEST(DivideTest, DivideStringTests) {
  702. auto divide = [](const std::string &str, char d) {
  703. std::string lhs;
  704. std::string rhs;
  705. detail::divide(str, d,
  706. [&](const char *lhs_data, std::size_t lhs_size,
  707. const char *rhs_data, std::size_t rhs_size) {
  708. lhs.assign(lhs_data, lhs_size);
  709. rhs.assign(rhs_data, rhs_size);
  710. });
  711. return std::make_pair(std::move(lhs), std::move(rhs));
  712. };
  713. {
  714. const auto res = divide("", '=');
  715. EXPECT_EQ(res.first, "");
  716. EXPECT_EQ(res.second, "");
  717. }
  718. {
  719. const auto res = divide("=", '=');
  720. EXPECT_EQ(res.first, "");
  721. EXPECT_EQ(res.second, "");
  722. }
  723. {
  724. const auto res = divide(" ", '=');
  725. EXPECT_EQ(res.first, " ");
  726. EXPECT_EQ(res.second, "");
  727. }
  728. {
  729. const auto res = divide("a", '=');
  730. EXPECT_EQ(res.first, "a");
  731. EXPECT_EQ(res.second, "");
  732. }
  733. {
  734. const auto res = divide("a=", '=');
  735. EXPECT_EQ(res.first, "a");
  736. EXPECT_EQ(res.second, "");
  737. }
  738. {
  739. const auto res = divide("=b", '=');
  740. EXPECT_EQ(res.first, "");
  741. EXPECT_EQ(res.second, "b");
  742. }
  743. {
  744. const auto res = divide("a=b", '=');
  745. EXPECT_EQ(res.first, "a");
  746. EXPECT_EQ(res.second, "b");
  747. }
  748. {
  749. const auto res = divide("a=b=", '=');
  750. EXPECT_EQ(res.first, "a");
  751. EXPECT_EQ(res.second, "b=");
  752. }
  753. {
  754. const auto res = divide("a=b=c", '=');
  755. EXPECT_EQ(res.first, "a");
  756. EXPECT_EQ(res.second, "b=c");
  757. }
  758. }
  759. TEST(SplitTest, ParseQueryString) {
  760. string s = "key1=val1&key2=val2&key3=val3";
  761. Params dic;
  762. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  763. [&](const char *b, const char *e) {
  764. string key, val;
  765. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  766. if (key.empty()) {
  767. key.assign(b2, e2);
  768. } else {
  769. val.assign(b2, e2);
  770. }
  771. });
  772. dic.emplace(key, val);
  773. });
  774. EXPECT_EQ("val1", dic.find("key1")->second);
  775. EXPECT_EQ("val2", dic.find("key2")->second);
  776. EXPECT_EQ("val3", dic.find("key3")->second);
  777. }
  778. TEST(SplitTest, ParseInvalidQueryTests) {
  779. {
  780. string s = " ";
  781. Params dict;
  782. detail::parse_query_text(s, dict);
  783. EXPECT_TRUE(dict.empty());
  784. }
  785. {
  786. string s = " = =";
  787. Params dict;
  788. detail::parse_query_text(s, dict);
  789. EXPECT_TRUE(dict.empty());
  790. }
  791. }
  792. TEST(ParseQueryTest, ParseQueryString) {
  793. {
  794. std::string s = "key1=val1&key2=val2&key3=val3";
  795. Params dic;
  796. detail::parse_query_text(s, dic);
  797. EXPECT_EQ("val1", dic.find("key1")->second);
  798. EXPECT_EQ("val2", dic.find("key2")->second);
  799. EXPECT_EQ("val3", dic.find("key3")->second);
  800. }
  801. {
  802. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  803. Params dic;
  804. detail::parse_query_text(s, dic);
  805. EXPECT_EQ("", dic.find("key1")->second);
  806. EXPECT_EQ("val1", dic.find("key2")->second);
  807. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  808. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  809. }
  810. }
  811. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  812. Params dic;
  813. EXPECT_EQ(detail::params_to_query_str(dic), "");
  814. dic.emplace("key1", "val1");
  815. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  816. dic.emplace("key2", "val2");
  817. dic.emplace("key3", "val3");
  818. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  819. }
  820. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  821. string content_type = "multipart/form-data; boundary=something";
  822. string boundary;
  823. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  824. EXPECT_TRUE(ret);
  825. EXPECT_EQ(boundary, "something");
  826. }
  827. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  828. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  829. string boundary;
  830. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  831. EXPECT_TRUE(ret);
  832. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  833. }
  834. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  835. string content_type =
  836. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  837. string boundary;
  838. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  839. EXPECT_TRUE(ret);
  840. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  841. }
  842. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  843. string content_type =
  844. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  845. string boundary;
  846. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  847. EXPECT_TRUE(ret);
  848. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  849. }
  850. TEST(GetHeaderValueTest, DefaultValue) {
  851. Headers headers = {{"Dummy", "Dummy"}};
  852. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  853. EXPECT_STREQ("text/plain", val);
  854. }
  855. TEST(GetHeaderValueTest, DefaultValueInt) {
  856. Headers headers = {{"Dummy", "Dummy"}};
  857. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  858. EXPECT_EQ(100ull, val);
  859. }
  860. TEST(GetHeaderValueTest, RegularValue) {
  861. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  862. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  863. EXPECT_STREQ("text/html", val);
  864. }
  865. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  866. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  867. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  868. EXPECT_STREQ("text/html", val);
  869. }
  870. TEST(GetHeaderValueTest, SetContent) {
  871. Response res;
  872. res.set_content("html", "text/html");
  873. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  874. res.set_content("text", "text/plain");
  875. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  876. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  877. }
  878. TEST(GetHeaderValueTest, RegularValueInt) {
  879. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  880. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  881. EXPECT_EQ(100ull, val);
  882. }
  883. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  884. Headers headers = {{"Content-Length", "x"}};
  885. auto is_invalid_value = false;
  886. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  887. is_invalid_value);
  888. EXPECT_EQ(0ull, val);
  889. EXPECT_TRUE(is_invalid_value);
  890. }
  891. TEST(GetHeaderValueTest, Range) {
  892. {
  893. Headers headers = {make_range_header({{1, -1}})};
  894. auto val = detail::get_header_value(headers, "Range", 0, 0);
  895. EXPECT_STREQ("bytes=1-", val);
  896. }
  897. {
  898. Headers headers = {make_range_header({{-1, 1}})};
  899. auto val = detail::get_header_value(headers, "Range", 0, 0);
  900. EXPECT_STREQ("bytes=-1", val);
  901. }
  902. {
  903. Headers headers = {make_range_header({{1, 10}})};
  904. auto val = detail::get_header_value(headers, "Range", 0, 0);
  905. EXPECT_STREQ("bytes=1-10", val);
  906. }
  907. {
  908. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  909. auto val = detail::get_header_value(headers, "Range", 0, 0);
  910. EXPECT_STREQ("bytes=1-10, 100-", val);
  911. }
  912. {
  913. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  914. auto val = detail::get_header_value(headers, "Range", 0, 0);
  915. EXPECT_STREQ("bytes=1-10, 100-200", val);
  916. }
  917. {
  918. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  919. auto val = detail::get_header_value(headers, "Range", 0, 0);
  920. EXPECT_STREQ("bytes=0-0, -1", val);
  921. }
  922. }
  923. TEST(ParseHeaderValueTest, Range) {
  924. {
  925. Ranges ranges;
  926. auto ret = detail::parse_range_header("bytes=1-", ranges);
  927. EXPECT_TRUE(ret);
  928. EXPECT_EQ(1u, ranges.size());
  929. EXPECT_EQ(1u, ranges[0].first);
  930. EXPECT_EQ(-1, ranges[0].second);
  931. }
  932. {
  933. Ranges ranges;
  934. auto ret = detail::parse_range_header("bytes=-1", ranges);
  935. EXPECT_TRUE(ret);
  936. EXPECT_EQ(1u, ranges.size());
  937. EXPECT_EQ(-1, ranges[0].first);
  938. EXPECT_EQ(1u, ranges[0].second);
  939. }
  940. {
  941. Ranges ranges;
  942. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  943. EXPECT_TRUE(ret);
  944. EXPECT_EQ(1u, ranges.size());
  945. EXPECT_EQ(1u, ranges[0].first);
  946. EXPECT_EQ(10u, ranges[0].second);
  947. }
  948. {
  949. Ranges ranges;
  950. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  951. EXPECT_FALSE(ret);
  952. }
  953. {
  954. Ranges ranges;
  955. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  956. EXPECT_TRUE(ret);
  957. EXPECT_EQ(2u, ranges.size());
  958. EXPECT_EQ(1u, ranges[0].first);
  959. EXPECT_EQ(10u, ranges[0].second);
  960. EXPECT_EQ(100u, ranges[1].first);
  961. EXPECT_EQ(-1, ranges[1].second);
  962. }
  963. {
  964. Ranges ranges;
  965. auto ret =
  966. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  967. EXPECT_TRUE(ret);
  968. EXPECT_EQ(3u, ranges.size());
  969. EXPECT_EQ(1u, ranges[0].first);
  970. EXPECT_EQ(10u, ranges[0].second);
  971. EXPECT_EQ(100u, ranges[1].first);
  972. EXPECT_EQ(200u, ranges[1].second);
  973. EXPECT_EQ(300u, ranges[2].first);
  974. EXPECT_EQ(400u, ranges[2].second);
  975. }
  976. {
  977. Ranges ranges;
  978. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  979. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  980. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  981. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  982. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  983. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  984. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  985. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  986. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  987. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  988. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  989. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  990. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  991. EXPECT_TRUE(ranges.empty());
  992. }
  993. }
  994. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  995. Request req;
  996. req.set_header("Accept-Encoding", "gzip");
  997. Response res;
  998. res.set_header("Content-Type", "text/plain");
  999. auto ret = detail::encoding_type(req, res);
  1000. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1001. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1002. #else
  1003. EXPECT_TRUE(ret == detail::EncodingType::None);
  1004. #endif
  1005. }
  1006. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1007. Request req;
  1008. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1009. Response res;
  1010. res.set_header("Content-Type", "text/plain");
  1011. auto ret = detail::encoding_type(req, res);
  1012. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1013. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1014. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1015. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1016. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1017. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1018. #else
  1019. EXPECT_TRUE(ret == detail::EncodingType::None);
  1020. #endif
  1021. }
  1022. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1023. Request req;
  1024. req.set_header("Accept-Encoding",
  1025. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1026. Response res;
  1027. res.set_header("Content-Type", "text/plain");
  1028. auto ret = detail::encoding_type(req, res);
  1029. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1030. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1031. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1032. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1033. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1034. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1035. #else
  1036. EXPECT_TRUE(ret == detail::EncodingType::None);
  1037. #endif
  1038. }
  1039. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1040. // All supported encodings rejected with q=0 should return None
  1041. Request req;
  1042. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1043. Response res;
  1044. res.set_header("Content-Type", "text/plain");
  1045. auto ret = detail::encoding_type(req, res);
  1046. EXPECT_TRUE(ret == detail::EncodingType::None);
  1047. }
  1048. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1049. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1050. Request req;
  1051. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1052. Response res;
  1053. res.set_header("Content-Type", "text/plain");
  1054. auto ret = detail::encoding_type(req, res);
  1055. EXPECT_TRUE(ret == detail::EncodingType::None);
  1056. }
  1057. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1058. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1059. Request req;
  1060. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1061. Response res;
  1062. res.set_header("Content-Type", "text/plain");
  1063. auto ret = detail::encoding_type(req, res);
  1064. EXPECT_TRUE(ret == detail::EncodingType::None);
  1065. }
  1066. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1067. // RFC 7231: Accept-Encoding values are case-insensitive
  1068. Request req;
  1069. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1070. Response res;
  1071. res.set_header("Content-Type", "text/plain");
  1072. auto ret = detail::encoding_type(req, res);
  1073. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1074. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1075. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1076. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1077. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1078. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1079. #else
  1080. EXPECT_TRUE(ret == detail::EncodingType::None);
  1081. #endif
  1082. }
  1083. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1084. // q value should determine priority, not hardcoded order
  1085. Request req;
  1086. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1087. Response res;
  1088. res.set_header("Content-Type", "text/plain");
  1089. auto ret = detail::encoding_type(req, res);
  1090. // gzip has highest q=1.0, so it should be selected even though
  1091. // br and zstd are also supported
  1092. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1093. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1094. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1095. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1096. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1097. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1098. #else
  1099. EXPECT_TRUE(ret == detail::EncodingType::None);
  1100. #endif
  1101. }
  1102. TEST(BufferStreamTest, read) {
  1103. detail::BufferStream strm1;
  1104. Stream &strm = strm1;
  1105. EXPECT_EQ(5, strm.write("hello"));
  1106. char buf[512];
  1107. EXPECT_EQ(2, strm.read(buf, 2));
  1108. EXPECT_EQ('h', buf[0]);
  1109. EXPECT_EQ('e', buf[1]);
  1110. EXPECT_EQ(2, strm.read(buf, 2));
  1111. EXPECT_EQ('l', buf[0]);
  1112. EXPECT_EQ('l', buf[1]);
  1113. EXPECT_EQ(1, strm.read(buf, 1));
  1114. EXPECT_EQ('o', buf[0]);
  1115. EXPECT_EQ(0, strm.read(buf, 1));
  1116. }
  1117. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1118. auto host = "www.httpwatch.com";
  1119. auto ip = hosted_at(host);
  1120. EXPECT_EQ("23.96.13.243", ip);
  1121. std::vector<std::string> addrs;
  1122. hosted_at(host, addrs);
  1123. EXPECT_EQ(1u, addrs.size());
  1124. }
  1125. #if 0 // It depends on each test environment...
  1126. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1127. auto host = "www.youtube.com";
  1128. std::vector<std::string> addrs;
  1129. hosted_at(host, addrs);
  1130. EXPECT_EQ(20u, addrs.size());
  1131. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1132. EXPECT_TRUE(it != addrs.end());
  1133. }
  1134. #endif
  1135. class ChunkedEncodingTest : public ::testing::Test {
  1136. protected:
  1137. ChunkedEncodingTest()
  1138. : cli_(HOST, PORT)
  1139. #ifdef CPPHTTPLIB_SSL_ENABLED
  1140. ,
  1141. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1142. #endif
  1143. {
  1144. cli_.set_connection_timeout(2);
  1145. #ifdef CPPHTTPLIB_SSL_ENABLED
  1146. cli_.enable_server_certificate_verification(false);
  1147. #endif
  1148. }
  1149. virtual void SetUp() {
  1150. read_file("./image.jpg", image_data_);
  1151. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1152. res.set_content("Hello World!", "text/plain");
  1153. });
  1154. svr_.Get(
  1155. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1156. res.set_chunked_content_provider(
  1157. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1158. size_t remaining = image_data_.size() - offset;
  1159. if (remaining == 0) {
  1160. sink.done();
  1161. } else {
  1162. constexpr size_t CHUNK_SIZE = 1024;
  1163. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1164. sink.write(&image_data_[offset], send_size);
  1165. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1166. }
  1167. return true;
  1168. });
  1169. });
  1170. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1171. svr_.wait_until_ready();
  1172. }
  1173. virtual void TearDown() {
  1174. svr_.stop();
  1175. if (!request_threads_.empty()) {
  1176. std::this_thread::sleep_for(std::chrono::seconds(1));
  1177. for (auto &t : request_threads_) {
  1178. t.join();
  1179. }
  1180. }
  1181. t_.join();
  1182. }
  1183. #ifdef CPPHTTPLIB_SSL_ENABLED
  1184. SSLClient cli_;
  1185. SSLServer svr_;
  1186. #else
  1187. Client cli_;
  1188. Server svr_;
  1189. #endif
  1190. thread t_;
  1191. std::vector<thread> request_threads_;
  1192. std::string image_data_;
  1193. };
  1194. TEST_F(ChunkedEncodingTest, NormalGet) {
  1195. auto res = cli_.Get("/chunked");
  1196. ASSERT_TRUE(res);
  1197. std::string out;
  1198. read_file("./image.jpg", out);
  1199. EXPECT_EQ(StatusCode::OK_200, res->status);
  1200. EXPECT_EQ(out, res->body);
  1201. }
  1202. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1203. std::string body;
  1204. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1205. body.append(data, data_length);
  1206. return true;
  1207. });
  1208. ASSERT_TRUE(res);
  1209. std::string out;
  1210. read_file("./image.jpg", out);
  1211. EXPECT_EQ(StatusCode::OK_200, res->status);
  1212. EXPECT_EQ(out, body);
  1213. }
  1214. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1215. std::string body;
  1216. auto res = cli_.Get(
  1217. "/chunked",
  1218. [&](const Response &response) {
  1219. EXPECT_EQ(StatusCode::OK_200, response.status);
  1220. return true;
  1221. },
  1222. [&](const char *data, size_t data_length) {
  1223. body.append(data, data_length);
  1224. return true;
  1225. });
  1226. ASSERT_TRUE(res);
  1227. std::string out;
  1228. read_file("./image.jpg", out);
  1229. EXPECT_EQ(StatusCode::OK_200, res->status);
  1230. EXPECT_EQ(out, body);
  1231. }
  1232. TEST(RangeTest, FromHTTPBin_Online) {
  1233. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1234. auto host = "httpcan.org";
  1235. auto path = std::string{"/range/32"};
  1236. #else
  1237. auto host = "nghttp2.org";
  1238. auto path = std::string{"/httpbin/range/32"};
  1239. #endif
  1240. #ifdef CPPHTTPLIB_SSL_ENABLED
  1241. auto port = 443;
  1242. SSLClient cli(host, port);
  1243. #else
  1244. auto port = 80;
  1245. Client cli(host, port);
  1246. #endif
  1247. cli.set_connection_timeout(5);
  1248. {
  1249. auto res = cli.Get(path);
  1250. ASSERT_TRUE(res);
  1251. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1252. EXPECT_EQ(StatusCode::OK_200, res->status);
  1253. }
  1254. {
  1255. Headers headers = {make_range_header({{1, -1}})};
  1256. auto res = cli.Get(path, headers);
  1257. ASSERT_TRUE(res);
  1258. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1259. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1260. }
  1261. {
  1262. Headers headers = {make_range_header({{1, 10}})};
  1263. auto res = cli.Get(path, headers);
  1264. ASSERT_TRUE(res);
  1265. EXPECT_EQ("bcdefghijk", res->body);
  1266. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1267. }
  1268. {
  1269. Headers headers = {make_range_header({{0, 31}})};
  1270. auto res = cli.Get(path, headers);
  1271. ASSERT_TRUE(res);
  1272. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1273. EXPECT_EQ(StatusCode::OK_200, res->status);
  1274. }
  1275. {
  1276. Headers headers = {make_range_header({{0, -1}})};
  1277. auto res = cli.Get(path, headers);
  1278. ASSERT_TRUE(res);
  1279. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1280. EXPECT_EQ(StatusCode::OK_200, res->status);
  1281. }
  1282. {
  1283. Headers headers = {make_range_header({{0, 32}})};
  1284. auto res = cli.Get(path, headers);
  1285. ASSERT_TRUE(res);
  1286. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1287. }
  1288. }
  1289. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1290. auto host = "unresolvableaddress.local";
  1291. auto path = std::string{"/"};
  1292. #ifdef CPPHTTPLIB_SSL_ENABLED
  1293. auto port = 443;
  1294. SSLClient cli(host, port);
  1295. #else
  1296. auto port = 80;
  1297. Client cli(host, port);
  1298. #endif
  1299. cli.set_connection_timeout(1);
  1300. {
  1301. auto res = cli.Get(path);
  1302. ASSERT_FALSE(res);
  1303. }
  1304. std::this_thread::sleep_for(std::chrono::seconds(8));
  1305. }
  1306. TEST(ConnectionErrorTest, InvalidHost) {
  1307. auto host = "-abcde.com";
  1308. #ifdef CPPHTTPLIB_SSL_ENABLED
  1309. auto port = 443;
  1310. SSLClient cli(host, port);
  1311. #else
  1312. auto port = 80;
  1313. Client cli(host, port);
  1314. #endif
  1315. cli.set_connection_timeout(std::chrono::seconds(2));
  1316. auto res = cli.Get("/");
  1317. ASSERT_TRUE(!res);
  1318. EXPECT_EQ(Error::Connection, res.error());
  1319. }
  1320. TEST(ConnectionErrorTest, InvalidHost2) {
  1321. auto host = "httpcan.org/";
  1322. #ifdef CPPHTTPLIB_SSL_ENABLED
  1323. SSLClient cli(host);
  1324. #else
  1325. Client cli(host);
  1326. #endif
  1327. cli.set_connection_timeout(std::chrono::seconds(2));
  1328. auto res = cli.Get("/");
  1329. ASSERT_TRUE(!res);
  1330. EXPECT_EQ(Error::Connection, res.error());
  1331. }
  1332. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1333. auto host = "httpcan.org/";
  1334. #ifdef CPPHTTPLIB_SSL_ENABLED
  1335. SSLClient cli(host);
  1336. #else
  1337. Client cli(host);
  1338. #endif
  1339. cli.set_connection_timeout(std::chrono::seconds(2));
  1340. auto res = cli.Get("/");
  1341. ASSERT_TRUE(!res);
  1342. stringstream s;
  1343. s << "error code: " << res.error();
  1344. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1345. }
  1346. TEST(ConnectionErrorTest, InvalidPort) {
  1347. auto host = "localhost";
  1348. auto port = 44380;
  1349. #ifdef CPPHTTPLIB_SSL_ENABLED
  1350. SSLClient cli(host, port);
  1351. #else
  1352. Client cli(host, port);
  1353. #endif
  1354. cli.set_connection_timeout(std::chrono::seconds(2));
  1355. auto res = cli.Get("/");
  1356. ASSERT_TRUE(!res);
  1357. EXPECT_TRUE(Error::Connection == res.error() ||
  1358. Error::ConnectionTimeout == res.error());
  1359. }
  1360. TEST(ConnectionErrorTest, Timeout_Online) {
  1361. auto host = "google.com";
  1362. #ifdef CPPHTTPLIB_SSL_ENABLED
  1363. auto port = 44380;
  1364. SSLClient cli(host, port);
  1365. #else
  1366. auto port = 8080;
  1367. Client cli(host, port);
  1368. #endif
  1369. cli.set_connection_timeout(std::chrono::seconds(2));
  1370. // only probe one address type so that the error reason
  1371. // correlates to the timed-out IPv4, not the unsupported
  1372. // IPv6 connection attempt
  1373. cli.set_address_family(AF_INET);
  1374. auto res = cli.Get("/");
  1375. ASSERT_TRUE(!res);
  1376. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1377. }
  1378. TEST(CancelTest, NoCancel_Online) {
  1379. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1380. auto host = "httpcan.org";
  1381. auto path = std::string{"/range/32"};
  1382. #else
  1383. auto host = "nghttp2.org";
  1384. auto path = std::string{"/httpbin/range/32"};
  1385. #endif
  1386. #ifdef CPPHTTPLIB_SSL_ENABLED
  1387. auto port = 443;
  1388. SSLClient cli(host, port);
  1389. #else
  1390. auto port = 80;
  1391. Client cli(host, port);
  1392. #endif
  1393. cli.set_connection_timeout(std::chrono::seconds(5));
  1394. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1395. ASSERT_TRUE(res);
  1396. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1397. EXPECT_EQ(StatusCode::OK_200, res->status);
  1398. }
  1399. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1400. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1401. auto host = "httpcan.org";
  1402. auto path = std::string{"/range/32"};
  1403. #else
  1404. auto host = "nghttp2.org";
  1405. auto path = std::string{"/httpbin/range/32"};
  1406. #endif
  1407. #ifdef CPPHTTPLIB_SSL_ENABLED
  1408. auto port = 443;
  1409. SSLClient cli(host, port);
  1410. #else
  1411. auto port = 80;
  1412. Client cli(host, port);
  1413. #endif
  1414. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1415. cli.set_connection_timeout(std::chrono::seconds(5));
  1416. ASSERT_TRUE(!res);
  1417. EXPECT_EQ(Error::Canceled, res.error());
  1418. }
  1419. TEST(CancelTest, WithCancelLargePayload_Online) {
  1420. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1421. auto host = "httpcan.org";
  1422. auto path = std::string{"/range/65536"};
  1423. #else
  1424. auto host = "nghttp2.org";
  1425. auto path = std::string{"/httpbin/range/65536"};
  1426. #endif
  1427. #ifdef CPPHTTPLIB_SSL_ENABLED
  1428. auto port = 443;
  1429. SSLClient cli(host, port);
  1430. #else
  1431. auto port = 80;
  1432. Client cli(host, port);
  1433. #endif
  1434. cli.set_connection_timeout(std::chrono::seconds(5));
  1435. uint32_t count = 0;
  1436. auto res =
  1437. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1438. ASSERT_TRUE(!res);
  1439. EXPECT_EQ(Error::Canceled, res.error());
  1440. }
  1441. TEST(CancelTest, NoCancelPost) {
  1442. Server svr;
  1443. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1444. res.set_content("Hello World!", "text/plain");
  1445. });
  1446. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1447. auto se = detail::scope_exit([&] {
  1448. svr.stop();
  1449. thread.join();
  1450. ASSERT_FALSE(svr.is_running());
  1451. });
  1452. svr.wait_until_ready();
  1453. Client cli(HOST, PORT);
  1454. cli.set_connection_timeout(std::chrono::seconds(5));
  1455. auto res =
  1456. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1457. "application/json", [](uint64_t, uint64_t) { return true; });
  1458. ASSERT_TRUE(res);
  1459. EXPECT_EQ("Hello World!", res->body);
  1460. EXPECT_EQ(StatusCode::OK_200, res->status);
  1461. }
  1462. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1463. Server svr;
  1464. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1465. res.set_content("Hello World!", "text/plain");
  1466. });
  1467. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1468. auto se = detail::scope_exit([&] {
  1469. svr.stop();
  1470. thread.join();
  1471. ASSERT_FALSE(svr.is_running());
  1472. });
  1473. svr.wait_until_ready();
  1474. Client cli(HOST, PORT);
  1475. cli.set_connection_timeout(std::chrono::seconds(5));
  1476. auto res =
  1477. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1478. "application/json", [](uint64_t, uint64_t) { return false; });
  1479. ASSERT_TRUE(!res);
  1480. EXPECT_EQ(Error::Canceled, res.error());
  1481. }
  1482. TEST(CancelTest, WithCancelLargePayloadPost) {
  1483. Server svr;
  1484. svr.set_payload_max_length(200 * 1024 * 1024);
  1485. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1486. res.set_content(LARGE_DATA, "text/plain");
  1487. });
  1488. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1489. auto se = detail::scope_exit([&] {
  1490. svr.stop();
  1491. thread.join();
  1492. ASSERT_FALSE(svr.is_running());
  1493. });
  1494. svr.wait_until_ready();
  1495. Client cli(HOST, PORT);
  1496. cli.set_payload_max_length(200 * 1024 * 1024);
  1497. cli.set_connection_timeout(std::chrono::seconds(5));
  1498. auto res =
  1499. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1500. "application/json", [](uint64_t, uint64_t) { return false; });
  1501. ASSERT_TRUE(!res);
  1502. EXPECT_EQ(Error::Canceled, res.error());
  1503. }
  1504. TEST(CancelTest, NoCancelPut) {
  1505. Server svr;
  1506. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1507. res.set_content("Hello World!", "text/plain");
  1508. });
  1509. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1510. auto se = detail::scope_exit([&] {
  1511. svr.stop();
  1512. thread.join();
  1513. ASSERT_FALSE(svr.is_running());
  1514. });
  1515. svr.wait_until_ready();
  1516. Client cli(HOST, PORT);
  1517. cli.set_connection_timeout(std::chrono::seconds(5));
  1518. auto res =
  1519. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1520. "application/json", [](uint64_t, uint64_t) { return true; });
  1521. ASSERT_TRUE(res);
  1522. EXPECT_EQ("Hello World!", res->body);
  1523. EXPECT_EQ(StatusCode::OK_200, res->status);
  1524. }
  1525. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1526. Server svr;
  1527. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1528. res.set_content("Hello World!", "text/plain");
  1529. });
  1530. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1531. auto se = detail::scope_exit([&] {
  1532. svr.stop();
  1533. thread.join();
  1534. ASSERT_FALSE(svr.is_running());
  1535. });
  1536. svr.wait_until_ready();
  1537. Client cli(HOST, PORT);
  1538. cli.set_connection_timeout(std::chrono::seconds(5));
  1539. auto res =
  1540. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1541. "application/json", [](uint64_t, uint64_t) { return false; });
  1542. ASSERT_TRUE(!res);
  1543. EXPECT_EQ(Error::Canceled, res.error());
  1544. }
  1545. TEST(CancelTest, WithCancelLargePayloadPut) {
  1546. Server svr;
  1547. svr.set_payload_max_length(200 * 1024 * 1024);
  1548. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1549. res.set_content(LARGE_DATA, "text/plain");
  1550. });
  1551. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1552. auto se = detail::scope_exit([&] {
  1553. svr.stop();
  1554. thread.join();
  1555. ASSERT_FALSE(svr.is_running());
  1556. });
  1557. svr.wait_until_ready();
  1558. Client cli(HOST, PORT);
  1559. cli.set_payload_max_length(200 * 1024 * 1024);
  1560. cli.set_connection_timeout(std::chrono::seconds(5));
  1561. auto res =
  1562. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1563. "application/json", [](uint64_t, uint64_t) { return false; });
  1564. ASSERT_TRUE(!res);
  1565. EXPECT_EQ(Error::Canceled, res.error());
  1566. }
  1567. TEST(CancelTest, NoCancelPatch) {
  1568. Server svr;
  1569. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1570. res.set_content("Hello World!", "text/plain");
  1571. });
  1572. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1573. auto se = detail::scope_exit([&] {
  1574. svr.stop();
  1575. thread.join();
  1576. ASSERT_FALSE(svr.is_running());
  1577. });
  1578. svr.wait_until_ready();
  1579. Client cli(HOST, PORT);
  1580. cli.set_connection_timeout(std::chrono::seconds(5));
  1581. auto res =
  1582. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1583. "application/json", [](uint64_t, uint64_t) { return true; });
  1584. ASSERT_TRUE(res);
  1585. EXPECT_EQ("Hello World!", res->body);
  1586. EXPECT_EQ(StatusCode::OK_200, res->status);
  1587. }
  1588. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1589. Server svr;
  1590. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1591. res.set_content("Hello World!", "text/plain");
  1592. });
  1593. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1594. auto se = detail::scope_exit([&] {
  1595. svr.stop();
  1596. thread.join();
  1597. ASSERT_FALSE(svr.is_running());
  1598. });
  1599. svr.wait_until_ready();
  1600. Client cli(HOST, PORT);
  1601. cli.set_connection_timeout(std::chrono::seconds(5));
  1602. auto res =
  1603. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1604. "application/json", [](uint64_t, uint64_t) { return false; });
  1605. ASSERT_TRUE(!res);
  1606. EXPECT_EQ(Error::Canceled, res.error());
  1607. }
  1608. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1609. Server svr;
  1610. svr.set_payload_max_length(200 * 1024 * 1024);
  1611. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1612. res.set_content(LARGE_DATA, "text/plain");
  1613. });
  1614. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1615. auto se = detail::scope_exit([&] {
  1616. svr.stop();
  1617. thread.join();
  1618. ASSERT_FALSE(svr.is_running());
  1619. });
  1620. svr.wait_until_ready();
  1621. Client cli(HOST, PORT);
  1622. cli.set_payload_max_length(200 * 1024 * 1024);
  1623. cli.set_connection_timeout(std::chrono::seconds(5));
  1624. auto res =
  1625. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1626. "application/json", [](uint64_t, uint64_t) { return false; });
  1627. ASSERT_TRUE(!res);
  1628. EXPECT_EQ(Error::Canceled, res.error());
  1629. }
  1630. TEST(CancelTest, NoCancelDelete) {
  1631. Server svr;
  1632. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1633. res.set_content("Hello World!", "text/plain");
  1634. });
  1635. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1636. auto se = detail::scope_exit([&] {
  1637. svr.stop();
  1638. thread.join();
  1639. ASSERT_FALSE(svr.is_running());
  1640. });
  1641. svr.wait_until_ready();
  1642. Client cli(HOST, PORT);
  1643. cli.set_connection_timeout(std::chrono::seconds(5));
  1644. auto res =
  1645. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1646. "application/json", [](uint64_t, uint64_t) { return true; });
  1647. ASSERT_TRUE(res);
  1648. EXPECT_EQ("Hello World!", res->body);
  1649. EXPECT_EQ(StatusCode::OK_200, res->status);
  1650. }
  1651. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1652. Server svr;
  1653. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1654. res.set_content("Hello World!", "text/plain");
  1655. });
  1656. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1657. auto se = detail::scope_exit([&] {
  1658. svr.stop();
  1659. thread.join();
  1660. ASSERT_FALSE(svr.is_running());
  1661. });
  1662. svr.wait_until_ready();
  1663. Client cli(HOST, PORT);
  1664. cli.set_connection_timeout(std::chrono::seconds(5));
  1665. auto res =
  1666. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1667. "application/json", [](uint64_t, uint64_t) { return false; });
  1668. ASSERT_TRUE(!res);
  1669. EXPECT_EQ(Error::Canceled, res.error());
  1670. }
  1671. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1672. Server svr;
  1673. svr.set_payload_max_length(200 * 1024 * 1024);
  1674. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1675. res.set_content(LARGE_DATA, "text/plain");
  1676. });
  1677. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1678. auto se = detail::scope_exit([&] {
  1679. svr.stop();
  1680. thread.join();
  1681. ASSERT_FALSE(svr.is_running());
  1682. });
  1683. svr.wait_until_ready();
  1684. Client cli(HOST, PORT);
  1685. cli.set_payload_max_length(200 * 1024 * 1024);
  1686. cli.set_connection_timeout(std::chrono::seconds(5));
  1687. auto res =
  1688. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1689. "application/json", [](uint64_t, uint64_t) { return false; });
  1690. ASSERT_TRUE(!res);
  1691. EXPECT_EQ(Error::Canceled, res.error());
  1692. }
  1693. static std::string remove_whitespace(const std::string &input) {
  1694. std::string output;
  1695. output.reserve(input.size());
  1696. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1697. [](unsigned char c) { return !std::isspace(c); });
  1698. return output;
  1699. }
  1700. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1701. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1702. auto host = "httpcan.org";
  1703. auto path = std::string{"/basic-auth/hello/world"};
  1704. #else
  1705. auto host = "nghttp2.org";
  1706. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1707. #endif
  1708. #ifdef CPPHTTPLIB_SSL_ENABLED
  1709. auto port = 443;
  1710. SSLClient cli(host, port);
  1711. #else
  1712. auto port = 80;
  1713. Client cli(host, port);
  1714. #endif
  1715. {
  1716. auto res = cli.Get(path);
  1717. ASSERT_TRUE(res);
  1718. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1719. }
  1720. {
  1721. auto res =
  1722. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1723. ASSERT_TRUE(res);
  1724. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1725. remove_whitespace(res->body));
  1726. EXPECT_EQ(StatusCode::OK_200, res->status);
  1727. }
  1728. {
  1729. cli.set_basic_auth("hello", "world");
  1730. auto res = cli.Get(path);
  1731. ASSERT_TRUE(res);
  1732. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1733. remove_whitespace(res->body));
  1734. EXPECT_EQ(StatusCode::OK_200, res->status);
  1735. }
  1736. {
  1737. cli.set_basic_auth("hello", "bad");
  1738. auto res = cli.Get(path);
  1739. ASSERT_TRUE(res);
  1740. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1741. }
  1742. {
  1743. cli.set_basic_auth("bad", "world");
  1744. auto res = cli.Get(path);
  1745. ASSERT_TRUE(res);
  1746. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1747. }
  1748. }
  1749. #ifdef CPPHTTPLIB_SSL_ENABLED
  1750. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1751. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1752. auto host = "httpcan.org";
  1753. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1754. auto paths = std::vector<std::string>{
  1755. "/digest-auth/auth/hello/world/MD5",
  1756. "/digest-auth/auth/hello/world/SHA-256",
  1757. "/digest-auth/auth/hello/world/SHA-512",
  1758. };
  1759. #else
  1760. auto host = "nghttp2.org";
  1761. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1762. auto paths = std::vector<std::string>{
  1763. "/httpbin/digest-auth/auth/hello/world/MD5",
  1764. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1765. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1766. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1767. };
  1768. #endif
  1769. auto port = 443;
  1770. SSLClient cli(host, port);
  1771. {
  1772. auto res = cli.Get(unauth_path);
  1773. ASSERT_TRUE(res);
  1774. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1775. }
  1776. {
  1777. cli.set_digest_auth("hello", "world");
  1778. for (const auto &path : paths) {
  1779. auto res = cli.Get(path.c_str());
  1780. ASSERT_TRUE(res);
  1781. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1782. std::string algo(path.substr(path.rfind('/') + 1));
  1783. EXPECT_EQ(
  1784. remove_whitespace("{\"algorithm\":\"" + algo +
  1785. "\",\"authenticated\":true,\"user\":\"hello\"}\n"),
  1786. remove_whitespace(res->body));
  1787. #else
  1788. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1789. remove_whitespace(res->body));
  1790. #endif
  1791. EXPECT_EQ(StatusCode::OK_200, res->status);
  1792. }
  1793. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1794. cli.set_digest_auth("hello", "bad");
  1795. for (const auto &path : paths) {
  1796. auto res = cli.Get(path.c_str());
  1797. ASSERT_TRUE(res);
  1798. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1799. }
  1800. #endif
  1801. }
  1802. }
  1803. #endif
  1804. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1805. auto host = "google.com";
  1806. auto another_host = "example.com";
  1807. auto wrong_ip = "0.0.0.0";
  1808. #ifdef CPPHTTPLIB_SSL_ENABLED
  1809. SSLClient cli(host);
  1810. #else
  1811. Client cli(host);
  1812. #endif
  1813. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1814. auto res = cli.Get("/");
  1815. ASSERT_TRUE(res);
  1816. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1817. }
  1818. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1819. auto host = "google.com";
  1820. auto wrong_ip = "0.0.0.0";
  1821. #ifdef CPPHTTPLIB_SSL_ENABLED
  1822. SSLClient cli(host);
  1823. #else
  1824. Client cli(host);
  1825. #endif
  1826. cli.set_hostname_addr_map({{host, wrong_ip}});
  1827. auto res = cli.Get("/");
  1828. ASSERT_TRUE(!res);
  1829. EXPECT_EQ(Error::Connection, res.error());
  1830. }
  1831. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1832. auto host = "nghttp2.org";
  1833. #ifdef CPPHTTPLIB_SSL_ENABLED
  1834. SSLClient cli(host);
  1835. #else
  1836. Client cli(host);
  1837. #endif
  1838. cli.set_follow_location(true);
  1839. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1840. ASSERT_TRUE(res);
  1841. EXPECT_EQ(StatusCode::OK_200, res->status);
  1842. }
  1843. TEST(RedirectTest, Redirect_Online) {
  1844. auto host = "nghttp2.org";
  1845. #ifdef CPPHTTPLIB_SSL_ENABLED
  1846. SSLClient cli(host);
  1847. #else
  1848. Client cli(host);
  1849. #endif
  1850. cli.set_follow_location(true);
  1851. auto res = cli.Get("/httpbin/redirect/3");
  1852. ASSERT_TRUE(res);
  1853. EXPECT_EQ(StatusCode::OK_200, res->status);
  1854. }
  1855. TEST(RelativeRedirectTest, Redirect_Online) {
  1856. auto host = "nghttp2.org";
  1857. #ifdef CPPHTTPLIB_SSL_ENABLED
  1858. SSLClient cli(host);
  1859. #else
  1860. Client cli(host);
  1861. #endif
  1862. cli.set_follow_location(true);
  1863. auto res = cli.Get("/httpbin/relative-redirect/3");
  1864. ASSERT_TRUE(res);
  1865. EXPECT_EQ(StatusCode::OK_200, res->status);
  1866. }
  1867. TEST(TooManyRedirectTest, Redirect_Online) {
  1868. auto host = "nghttp2.org";
  1869. #ifdef CPPHTTPLIB_SSL_ENABLED
  1870. SSLClient cli(host);
  1871. #else
  1872. Client cli(host);
  1873. #endif
  1874. cli.set_follow_location(true);
  1875. auto res = cli.Get("/httpbin/redirect/21");
  1876. ASSERT_TRUE(!res);
  1877. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1878. }
  1879. #ifdef CPPHTTPLIB_SSL_ENABLED
  1880. TEST(YahooRedirectTest, Redirect_Online) {
  1881. Client cli("yahoo.com");
  1882. auto res = cli.Get("/");
  1883. ASSERT_TRUE(res);
  1884. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1885. cli.set_follow_location(true);
  1886. res = cli.Get("/");
  1887. ASSERT_TRUE(res);
  1888. EXPECT_EQ(StatusCode::OK_200, res->status);
  1889. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1890. }
  1891. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1892. #define REDIR_HOST "httpbingo.org"
  1893. #define REDIR_PATH "/redirect-to"
  1894. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1895. SSLClient cli(REDIR_HOST);
  1896. cli.set_follow_location(true);
  1897. auto res =
  1898. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1899. ASSERT_TRUE(res);
  1900. EXPECT_EQ(StatusCode::OK_200, res->status);
  1901. }
  1902. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1903. SSLClient cli(REDIR_HOST);
  1904. cli.set_follow_location(true);
  1905. Params params;
  1906. params.emplace("url", "http://example.com");
  1907. params.emplace("status_code", "302");
  1908. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1909. ASSERT_TRUE(res);
  1910. EXPECT_EQ(StatusCode::OK_200, res->status);
  1911. }
  1912. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1913. SSLClient cli(REDIR_HOST);
  1914. cli.set_follow_location(true);
  1915. Params params;
  1916. params.emplace("url", "http://example.com");
  1917. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1918. ASSERT_TRUE(res);
  1919. EXPECT_EQ(StatusCode::OK_200, res->status);
  1920. }
  1921. TEST(UrlWithSpace, Redirect_Online) {
  1922. SSLClient cli("edge.forgecdn.net");
  1923. cli.set_follow_location(true);
  1924. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1925. ASSERT_TRUE(res);
  1926. EXPECT_EQ(StatusCode::OK_200, res->status);
  1927. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1928. }
  1929. #endif
  1930. #if !defined(_WIN32) && !defined(_WIN64)
  1931. TEST(ReceiveSignals, Signal) {
  1932. auto setupSignalHandlers = []() {
  1933. struct sigaction act;
  1934. sigemptyset(&act.sa_mask);
  1935. act.sa_flags = SA_SIGINFO;
  1936. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1937. switch (sig) {
  1938. case SIGINT:
  1939. default: break;
  1940. }
  1941. };
  1942. ::sigaction(SIGINT, &act, nullptr);
  1943. };
  1944. Server svr;
  1945. int port = 0;
  1946. auto thread = std::thread([&]() {
  1947. setupSignalHandlers();
  1948. port = svr.bind_to_any_port(HOST);
  1949. svr.listen_after_bind();
  1950. });
  1951. auto se = detail::scope_exit([&] {
  1952. svr.stop();
  1953. thread.join();
  1954. ASSERT_FALSE(svr.is_running());
  1955. });
  1956. svr.wait_until_ready();
  1957. ASSERT_TRUE(svr.is_running());
  1958. pthread_kill(thread.native_handle(), SIGINT);
  1959. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1960. ASSERT_TRUE(svr.is_running());
  1961. }
  1962. #endif
  1963. TEST(RedirectToDifferentPort, Redirect) {
  1964. Server svr1;
  1965. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1966. res.set_content("Hello World!", "text/plain");
  1967. });
  1968. int svr1_port = 0;
  1969. auto thread1 = std::thread([&]() {
  1970. svr1_port = svr1.bind_to_any_port(HOST);
  1971. svr1.listen_after_bind();
  1972. });
  1973. Server svr2;
  1974. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1975. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1976. });
  1977. int svr2_port = 0;
  1978. auto thread2 = std::thread([&]() {
  1979. svr2_port = svr2.bind_to_any_port(HOST);
  1980. svr2.listen_after_bind();
  1981. });
  1982. auto se = detail::scope_exit([&] {
  1983. svr2.stop();
  1984. thread2.join();
  1985. svr1.stop();
  1986. thread1.join();
  1987. ASSERT_FALSE(svr2.is_running());
  1988. ASSERT_FALSE(svr1.is_running());
  1989. });
  1990. svr1.wait_until_ready();
  1991. svr2.wait_until_ready();
  1992. Client cli("localhost", svr2_port);
  1993. cli.set_follow_location(true);
  1994. auto res = cli.Get("/2");
  1995. ASSERT_TRUE(res);
  1996. EXPECT_EQ(StatusCode::OK_200, res->status);
  1997. EXPECT_EQ("Hello World!", res->body);
  1998. }
  1999. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2000. Server svr;
  2001. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2002. // Port number that overflows int — should not crash
  2003. res.set_redirect("http://localhost:99999999999999999999/target");
  2004. });
  2005. auto port = svr.bind_to_any_port(HOST);
  2006. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2007. auto se = detail::scope_exit([&] {
  2008. svr.stop();
  2009. thread.join();
  2010. ASSERT_FALSE(svr.is_running());
  2011. });
  2012. svr.wait_until_ready();
  2013. Client cli(HOST, port);
  2014. cli.set_follow_location(true);
  2015. auto res = cli.Get("/redir");
  2016. // Should fail gracefully, not crash (no valid response due to bad port)
  2017. EXPECT_FALSE(res);
  2018. }
  2019. TEST(RedirectFromPageWithContent, Redirect) {
  2020. Server svr;
  2021. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2022. res.set_content("___", "text/plain");
  2023. res.set_redirect("/2");
  2024. });
  2025. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2026. res.set_content("Hello World!", "text/plain");
  2027. });
  2028. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2029. auto se = detail::scope_exit([&] {
  2030. svr.stop();
  2031. th.join();
  2032. ASSERT_FALSE(svr.is_running());
  2033. });
  2034. svr.wait_until_ready();
  2035. {
  2036. Client cli("localhost", PORT);
  2037. cli.set_follow_location(true);
  2038. std::string body;
  2039. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2040. body.append(data, data_length);
  2041. return true;
  2042. });
  2043. ASSERT_TRUE(res);
  2044. EXPECT_EQ(StatusCode::OK_200, res->status);
  2045. EXPECT_EQ("Hello World!", body);
  2046. }
  2047. {
  2048. Client cli("localhost", PORT);
  2049. std::string body;
  2050. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2051. body.append(data, data_length);
  2052. return true;
  2053. });
  2054. ASSERT_TRUE(res);
  2055. EXPECT_EQ(StatusCode::Found_302, res->status);
  2056. EXPECT_EQ("___", body);
  2057. }
  2058. }
  2059. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2060. Server svr;
  2061. auto port_str = std::to_string(PORT);
  2062. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2063. auto expected_host = "[::1]:" + port_str;
  2064. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2065. res.set_content("___", "text/plain");
  2066. // res.set_redirect("/2");
  2067. res.set_redirect(redirect_url);
  2068. });
  2069. svr.Get("/2", [&](const Request &req, Response &res) {
  2070. auto host_header = req.headers.find("Host");
  2071. ASSERT_TRUE(host_header != req.headers.end());
  2072. EXPECT_EQ(expected_host, host_header->second);
  2073. res.set_content("Hello World!", "text/plain");
  2074. });
  2075. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2076. auto se = detail::scope_exit([&] {
  2077. svr.stop();
  2078. th.join();
  2079. ASSERT_FALSE(svr.is_running());
  2080. });
  2081. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2082. // actually starts anything, so the condition !svr.is_running() will
  2083. // always remain true, and the loop never stops.
  2084. // This basically counts how many milliseconds have passed since the
  2085. // call to svr.listen(), and if after 5 seconds nothing started yet
  2086. // aborts the test.
  2087. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2088. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2089. ASSERT_LT(milliseconds, 5000U);
  2090. }
  2091. {
  2092. Client cli("::1", PORT);
  2093. cli.set_follow_location(true);
  2094. std::string body;
  2095. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2096. body.append(data, data_length);
  2097. return true;
  2098. });
  2099. ASSERT_TRUE(res);
  2100. EXPECT_EQ(StatusCode::OK_200, res->status);
  2101. EXPECT_EQ("Hello World!", body);
  2102. }
  2103. {
  2104. Client cli("::1", PORT);
  2105. std::string body;
  2106. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2107. body.append(data, data_length);
  2108. return true;
  2109. });
  2110. ASSERT_TRUE(res);
  2111. EXPECT_EQ(StatusCode::Found_302, res->status);
  2112. EXPECT_EQ("___", body);
  2113. }
  2114. }
  2115. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2116. Server svr;
  2117. svr.Get("/foo", [](const Request &req, Response &res) {
  2118. auto a = req.params.find("a");
  2119. if (a != req.params.end()) {
  2120. res.set_content((*a).second, "text/plain");
  2121. res.status = StatusCode::OK_200;
  2122. } else {
  2123. res.status = StatusCode::BadRequest_400;
  2124. }
  2125. });
  2126. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2127. auto se = detail::scope_exit([&] {
  2128. svr.stop();
  2129. thread.join();
  2130. ASSERT_FALSE(svr.is_running());
  2131. });
  2132. svr.wait_until_ready();
  2133. {
  2134. Client cli(HOST, PORT);
  2135. cli.set_path_encode(false);
  2136. auto res = cli.Get("/foo?a=explicitly+encoded");
  2137. ASSERT_TRUE(res);
  2138. EXPECT_EQ(StatusCode::OK_200, res->status);
  2139. // This expects it back with a space, as the `+` won't have been
  2140. // url-encoded, and server-side the params get decoded turning `+`
  2141. // into spaces.
  2142. EXPECT_EQ("explicitly encoded", res->body);
  2143. }
  2144. }
  2145. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2146. Server svr;
  2147. svr.Get("/", [](const Request &req, Response &) {
  2148. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2149. });
  2150. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2151. auto se = detail::scope_exit([&] {
  2152. svr.stop();
  2153. thread.join();
  2154. ASSERT_FALSE(svr.is_running());
  2155. });
  2156. svr.wait_until_ready();
  2157. {
  2158. Client cli(HOST, PORT);
  2159. cli.set_path_encode(false);
  2160. auto res = cli.Get("/?something=%0A");
  2161. ASSERT_TRUE(res);
  2162. EXPECT_EQ(StatusCode::OK_200, res->status);
  2163. }
  2164. }
  2165. TEST(BindServerTest, BindDualStack) {
  2166. Server svr;
  2167. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2168. res.set_content("Hello World!", "text/plain");
  2169. });
  2170. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2171. auto se = detail::scope_exit([&] {
  2172. svr.stop();
  2173. thread.join();
  2174. ASSERT_FALSE(svr.is_running());
  2175. });
  2176. svr.wait_until_ready();
  2177. {
  2178. Client cli("127.0.0.1", PORT);
  2179. auto res = cli.Get("/1");
  2180. ASSERT_TRUE(res);
  2181. EXPECT_EQ(StatusCode::OK_200, res->status);
  2182. EXPECT_EQ("Hello World!", res->body);
  2183. }
  2184. {
  2185. Client cli("::1", PORT);
  2186. auto res = cli.Get("/1");
  2187. ASSERT_TRUE(res);
  2188. EXPECT_EQ(StatusCode::OK_200, res->status);
  2189. EXPECT_EQ("Hello World!", res->body);
  2190. }
  2191. }
  2192. TEST(BindServerTest, BindAndListenSeparately) {
  2193. Server svr;
  2194. int port = svr.bind_to_any_port("0.0.0.0");
  2195. ASSERT_TRUE(svr.is_valid());
  2196. ASSERT_TRUE(port > 0);
  2197. svr.stop();
  2198. }
  2199. #ifdef CPPHTTPLIB_SSL_ENABLED
  2200. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2201. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2202. CLIENT_CA_CERT_DIR);
  2203. int port = svr.bind_to_any_port("0.0.0.0");
  2204. ASSERT_TRUE(svr.is_valid());
  2205. ASSERT_TRUE(port > 0);
  2206. svr.stop();
  2207. }
  2208. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2209. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2210. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2211. int port = svr.bind_to_any_port("0.0.0.0");
  2212. ASSERT_TRUE(svr.is_valid());
  2213. ASSERT_TRUE(port > 0);
  2214. svr.stop();
  2215. }
  2216. TEST(BindServerTest, UpdateCertsPem) {
  2217. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2218. int port = svr.bind_to_any_port("0.0.0.0");
  2219. ASSERT_TRUE(svr.is_valid());
  2220. ASSERT_TRUE(port > 0);
  2221. // Read PEM files
  2222. std::string cert_pem, key_pem, ca_pem;
  2223. read_file(SERVER_CERT_FILE, cert_pem);
  2224. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2225. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2226. // Update server certificates using PEM API
  2227. ASSERT_TRUE(
  2228. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2229. ASSERT_TRUE(svr.is_valid());
  2230. svr.stop();
  2231. }
  2232. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2233. // Start server with client CA (enables client auth)
  2234. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2235. ASSERT_TRUE(svr.is_valid());
  2236. bool handler_called = false;
  2237. svr.Get("/test", [&](const Request &req, Response &res) {
  2238. handler_called = true;
  2239. // Verify client certificate is present
  2240. auto cert = req.peer_cert();
  2241. EXPECT_TRUE(static_cast<bool>(cert));
  2242. res.set_content("ok", "text/plain");
  2243. });
  2244. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2245. auto se = detail::scope_exit([&] {
  2246. svr.stop();
  2247. t.join();
  2248. ASSERT_FALSE(svr.is_running());
  2249. });
  2250. svr.wait_until_ready();
  2251. // Read PEM files
  2252. std::string cert_pem, key_pem, ca_pem;
  2253. read_file(SERVER_CERT_FILE, cert_pem);
  2254. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2255. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2256. // Update server certificates and client CA using PEM API while server running
  2257. ASSERT_TRUE(
  2258. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2259. // Connect with client certificate
  2260. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2261. cli.enable_server_certificate_verification(false);
  2262. cli.set_connection_timeout(30);
  2263. auto res = cli.Get("/test");
  2264. ASSERT_TRUE(res);
  2265. ASSERT_EQ(StatusCode::OK_200, res->status);
  2266. ASSERT_TRUE(handler_called);
  2267. EXPECT_EQ("ok", res->body);
  2268. }
  2269. #endif
  2270. TEST(ErrorHandlerTest, ContentLength) {
  2271. Server svr;
  2272. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2273. res.status = StatusCode::OK_200;
  2274. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2275. "text/html"); // <= Content-Length still 13
  2276. });
  2277. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2278. res.set_content("Hello World!\n", "text/plain");
  2279. res.status = 524;
  2280. });
  2281. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2282. auto se = detail::scope_exit([&] {
  2283. svr.stop();
  2284. thread.join();
  2285. ASSERT_FALSE(svr.is_running());
  2286. });
  2287. svr.wait_until_ready();
  2288. {
  2289. Client cli(HOST, PORT);
  2290. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2291. ASSERT_TRUE(res);
  2292. EXPECT_EQ(StatusCode::OK_200, res->status);
  2293. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2294. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2295. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2296. }
  2297. }
  2298. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2299. TEST(ExceptionTest, WithoutExceptionHandler) {
  2300. Server svr;
  2301. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2302. throw std::runtime_error("exception...");
  2303. });
  2304. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2305. throw std::runtime_error("exception\r\n...");
  2306. });
  2307. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2308. auto se = detail::scope_exit([&] {
  2309. svr.stop();
  2310. listen_thread.join();
  2311. ASSERT_FALSE(svr.is_running());
  2312. });
  2313. svr.wait_until_ready();
  2314. Client cli("localhost", PORT);
  2315. {
  2316. auto res = cli.Get("/exception");
  2317. ASSERT_TRUE(res);
  2318. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2319. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2320. }
  2321. {
  2322. auto res = cli.Get("/unknown");
  2323. ASSERT_TRUE(res);
  2324. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2325. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2326. }
  2327. }
  2328. TEST(ExceptionTest, WithExceptionHandler) {
  2329. Server svr;
  2330. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2331. std::exception_ptr ep) {
  2332. EXPECT_FALSE(ep == nullptr);
  2333. try {
  2334. std::rethrow_exception(ep);
  2335. } catch (std::exception &e) {
  2336. EXPECT_EQ("abc", std::string(e.what()));
  2337. } catch (...) {}
  2338. res.status = StatusCode::InternalServerError_500;
  2339. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2340. "text/html"); // <= Content-Length still 13 at this point
  2341. });
  2342. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2343. res.set_content("Hello World!\n", "text/plain");
  2344. throw std::runtime_error("abc");
  2345. });
  2346. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2347. auto se = detail::scope_exit([&] {
  2348. svr.stop();
  2349. thread.join();
  2350. ASSERT_FALSE(svr.is_running());
  2351. });
  2352. svr.wait_until_ready();
  2353. for (size_t i = 0; i < 10; i++) {
  2354. Client cli(HOST, PORT);
  2355. for (size_t j = 0; j < 100; j++) {
  2356. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2357. ASSERT_TRUE(res);
  2358. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2359. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2360. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2361. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2362. }
  2363. cli.set_keep_alive(true);
  2364. for (size_t j = 0; j < 100; j++) {
  2365. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2366. ASSERT_TRUE(res);
  2367. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2368. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2369. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2370. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2371. }
  2372. }
  2373. }
  2374. TEST(ExceptionTest, AndErrorHandler) {
  2375. Server svr;
  2376. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2377. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2378. });
  2379. svr.set_exception_handler(
  2380. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2381. EXPECT_FALSE(ep == nullptr);
  2382. try {
  2383. std::rethrow_exception(ep);
  2384. } catch (std::exception &e) {
  2385. res.set_content(e.what(), "text/html");
  2386. } catch (...) {}
  2387. res.status = StatusCode::InternalServerError_500;
  2388. });
  2389. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2390. throw std::runtime_error("EXCEPTION");
  2391. });
  2392. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2393. res.set_content("ERROR", "text/html");
  2394. res.status = StatusCode::InternalServerError_500;
  2395. });
  2396. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2397. auto se = detail::scope_exit([&] {
  2398. svr.stop();
  2399. thread.join();
  2400. ASSERT_FALSE(svr.is_running());
  2401. });
  2402. svr.wait_until_ready();
  2403. Client cli(HOST, PORT);
  2404. {
  2405. auto res = cli.Get("/exception");
  2406. ASSERT_TRUE(res);
  2407. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2408. EXPECT_EQ("EXCEPTION", res->body);
  2409. }
  2410. {
  2411. auto res = cli.Get("/error");
  2412. ASSERT_TRUE(res);
  2413. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2414. EXPECT_EQ("ERROR", res->body);
  2415. }
  2416. {
  2417. auto res = cli.Get("/invalid");
  2418. ASSERT_TRUE(res);
  2419. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2420. EXPECT_EQ("NOT_FOUND", res->body);
  2421. }
  2422. }
  2423. #endif
  2424. TEST(NoContentTest, ContentLength) {
  2425. Server svr;
  2426. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2427. res.status = StatusCode::NoContent_204;
  2428. });
  2429. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2430. auto se = detail::scope_exit([&] {
  2431. svr.stop();
  2432. thread.join();
  2433. ASSERT_FALSE(svr.is_running());
  2434. });
  2435. svr.wait_until_ready();
  2436. {
  2437. Client cli(HOST, PORT);
  2438. auto res = cli.Get("/hi");
  2439. ASSERT_TRUE(res);
  2440. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2441. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2442. }
  2443. }
  2444. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2445. #ifdef CPPHTTPLIB_SSL_ENABLED
  2446. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2447. ASSERT_TRUE(svr.is_valid());
  2448. #else
  2449. Server svr;
  2450. #endif
  2451. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2452. if (req.path == "/routing_handler") {
  2453. res.set_header("PRE_ROUTING", "on");
  2454. res.set_content("Routing Handler", "text/plain");
  2455. return httplib::Server::HandlerResponse::Handled;
  2456. }
  2457. return httplib::Server::HandlerResponse::Unhandled;
  2458. });
  2459. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2460. res.set_content("Error", "text/html");
  2461. });
  2462. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2463. if (req.path == "/routing_handler") {
  2464. res.set_header("POST_ROUTING", "on");
  2465. }
  2466. });
  2467. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2468. res.set_content("Hello World!\n", "text/plain");
  2469. });
  2470. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2471. auto se = detail::scope_exit([&] {
  2472. svr.stop();
  2473. thread.join();
  2474. ASSERT_FALSE(svr.is_running());
  2475. });
  2476. svr.wait_until_ready();
  2477. {
  2478. #ifdef CPPHTTPLIB_SSL_ENABLED
  2479. SSLClient cli(HOST, PORT);
  2480. cli.enable_server_certificate_verification(false);
  2481. #else
  2482. Client cli(HOST, PORT);
  2483. #endif
  2484. auto res = cli.Get("/routing_handler");
  2485. ASSERT_TRUE(res);
  2486. EXPECT_EQ(StatusCode::OK_200, res->status);
  2487. EXPECT_EQ("Routing Handler", res->body);
  2488. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2489. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2490. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2491. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2492. }
  2493. {
  2494. #ifdef CPPHTTPLIB_SSL_ENABLED
  2495. SSLClient cli(HOST, PORT);
  2496. cli.enable_server_certificate_verification(false);
  2497. #else
  2498. Client cli(HOST, PORT);
  2499. #endif
  2500. auto res = cli.Get("/hi");
  2501. ASSERT_TRUE(res);
  2502. EXPECT_EQ(StatusCode::OK_200, res->status);
  2503. EXPECT_EQ("Hello World!\n", res->body);
  2504. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2505. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2506. }
  2507. {
  2508. #ifdef CPPHTTPLIB_SSL_ENABLED
  2509. SSLClient cli(HOST, PORT);
  2510. cli.enable_server_certificate_verification(false);
  2511. #else
  2512. Client cli(HOST, PORT);
  2513. #endif
  2514. auto res = cli.Get("/aaa");
  2515. ASSERT_TRUE(res);
  2516. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2517. EXPECT_EQ("Error", res->body);
  2518. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2519. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2520. }
  2521. }
  2522. TEST(RequestHandlerTest, PreRequestHandler) {
  2523. auto route_path = "/user/:user";
  2524. Server svr;
  2525. svr.Get("/hi", [](const Request &, Response &res) {
  2526. res.set_content("hi", "text/plain");
  2527. });
  2528. svr.Get(route_path, [](const Request &req, Response &res) {
  2529. res.set_content(req.path_params.at("user"), "text/plain");
  2530. });
  2531. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2532. if (req.matched_route == route_path) {
  2533. auto user = req.path_params.at("user");
  2534. if (user != "john") {
  2535. res.status = StatusCode::Forbidden_403;
  2536. res.set_content("error", "text/html");
  2537. return Server::HandlerResponse::Handled;
  2538. }
  2539. }
  2540. return Server::HandlerResponse::Unhandled;
  2541. });
  2542. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2543. auto se = detail::scope_exit([&] {
  2544. svr.stop();
  2545. thread.join();
  2546. ASSERT_FALSE(svr.is_running());
  2547. });
  2548. svr.wait_until_ready();
  2549. Client cli(HOST, PORT);
  2550. {
  2551. auto res = cli.Get("/hi");
  2552. ASSERT_TRUE(res);
  2553. EXPECT_EQ(StatusCode::OK_200, res->status);
  2554. EXPECT_EQ("hi", res->body);
  2555. }
  2556. {
  2557. auto res = cli.Get("/user/john");
  2558. ASSERT_TRUE(res);
  2559. EXPECT_EQ(StatusCode::OK_200, res->status);
  2560. EXPECT_EQ("john", res->body);
  2561. }
  2562. {
  2563. auto res = cli.Get("/user/invalid-user");
  2564. ASSERT_TRUE(res);
  2565. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2566. EXPECT_EQ("error", res->body);
  2567. }
  2568. }
  2569. TEST(AnyTest, BasicOperations) {
  2570. // Default construction
  2571. httplib::any a;
  2572. EXPECT_FALSE(a.has_value());
  2573. // Value construction and any_cast (pointer form, noexcept)
  2574. httplib::any b(42);
  2575. EXPECT_TRUE(b.has_value());
  2576. auto *p = httplib::any_cast<int>(&b);
  2577. ASSERT_NE(nullptr, p);
  2578. EXPECT_EQ(42, *p);
  2579. // Type mismatch → nullptr
  2580. auto *q = httplib::any_cast<std::string>(&b);
  2581. EXPECT_EQ(nullptr, q);
  2582. // any_cast (value form) succeeds
  2583. EXPECT_EQ(42, httplib::any_cast<int>(b));
  2584. // any_cast (value form) throws on type mismatch
  2585. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2586. EXPECT_THROW(httplib::any_cast<std::string>(b), httplib::bad_any_cast);
  2587. #endif
  2588. // Copy
  2589. httplib::any c = b;
  2590. EXPECT_EQ(42, httplib::any_cast<int>(c));
  2591. // Move
  2592. httplib::any d = std::move(c);
  2593. EXPECT_EQ(42, httplib::any_cast<int>(d));
  2594. // Assignment with different type
  2595. b = std::string("hello");
  2596. EXPECT_EQ("hello", httplib::any_cast<std::string>(b));
  2597. // Reset
  2598. b.reset();
  2599. EXPECT_FALSE(b.has_value());
  2600. }
  2601. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2602. struct AuthCtx {
  2603. std::string user_id;
  2604. };
  2605. Server svr;
  2606. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2607. res.user_data["auth"] = AuthCtx{"alice"};
  2608. return Server::HandlerResponse::Unhandled;
  2609. });
  2610. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2611. auto *ctx = httplib::any_cast<AuthCtx>(&res.user_data["auth"]);
  2612. ASSERT_NE(nullptr, ctx);
  2613. res.set_content("Hello " + ctx->user_id, "text/plain");
  2614. });
  2615. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2616. auto se = detail::scope_exit([&] {
  2617. svr.stop();
  2618. thread.join();
  2619. ASSERT_FALSE(svr.is_running());
  2620. });
  2621. svr.wait_until_ready();
  2622. Client cli(HOST, PORT);
  2623. auto res = cli.Get("/me");
  2624. ASSERT_TRUE(res);
  2625. EXPECT_EQ(StatusCode::OK_200, res->status);
  2626. EXPECT_EQ("Hello alice", res->body);
  2627. }
  2628. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2629. struct RoleCtx {
  2630. std::string role;
  2631. };
  2632. Server svr;
  2633. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2634. res.user_data["role"] = RoleCtx{"admin"};
  2635. return Server::HandlerResponse::Unhandled;
  2636. });
  2637. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2638. auto *ctx = httplib::any_cast<RoleCtx>(&res.user_data["role"]);
  2639. ASSERT_NE(nullptr, ctx);
  2640. res.set_content(ctx->role, "text/plain");
  2641. });
  2642. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2643. auto se = detail::scope_exit([&] {
  2644. svr.stop();
  2645. thread.join();
  2646. ASSERT_FALSE(svr.is_running());
  2647. });
  2648. svr.wait_until_ready();
  2649. Client cli(HOST, PORT);
  2650. auto res = cli.Get("/role");
  2651. ASSERT_TRUE(res);
  2652. EXPECT_EQ(StatusCode::OK_200, res->status);
  2653. EXPECT_EQ("admin", res->body);
  2654. }
  2655. TEST(InvalidFormatTest, StatusCode) {
  2656. Server svr;
  2657. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2658. res.set_content("Hello World!\n", "text/plain");
  2659. res.status = 9999; // Status should be a three-digit code...
  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. auto res = cli.Get("/hi");
  2671. ASSERT_FALSE(res);
  2672. }
  2673. }
  2674. TEST(URLFragmentTest, WithFragment) {
  2675. Server svr;
  2676. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2677. EXPECT_TRUE(req.target == "/hi");
  2678. });
  2679. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2680. auto se = detail::scope_exit([&] {
  2681. svr.stop();
  2682. thread.join();
  2683. ASSERT_FALSE(svr.is_running());
  2684. });
  2685. svr.wait_until_ready();
  2686. {
  2687. Client cli(HOST, PORT);
  2688. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2689. EXPECT_TRUE(res);
  2690. EXPECT_EQ(StatusCode::OK_200, res->status);
  2691. res = cli.Get("/hi%23key1=val1=key2=val2");
  2692. EXPECT_TRUE(res);
  2693. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2694. }
  2695. }
  2696. TEST(HeaderWriter, SetHeaderWriter) {
  2697. Server svr;
  2698. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2699. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2700. return detail::write_headers(strm, hdrs);
  2701. });
  2702. svr.Get("/hi", [](const Request &req, Response &res) {
  2703. auto it = req.headers.find("CustomClientHeader");
  2704. EXPECT_TRUE(it != req.headers.end());
  2705. EXPECT_EQ(it->second, "CustomClientValue");
  2706. res.set_content("Hello World!\n", "text/plain");
  2707. });
  2708. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2709. auto se = detail::scope_exit([&] {
  2710. svr.stop();
  2711. thread.join();
  2712. ASSERT_FALSE(svr.is_running());
  2713. });
  2714. svr.wait_until_ready();
  2715. {
  2716. Client cli(HOST, PORT);
  2717. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2718. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2719. return detail::write_headers(strm, hdrs);
  2720. });
  2721. auto res = cli.Get("/hi");
  2722. EXPECT_TRUE(res);
  2723. EXPECT_EQ(StatusCode::OK_200, res->status);
  2724. auto it = res->headers.find("CustomServerHeader");
  2725. EXPECT_TRUE(it != res->headers.end());
  2726. EXPECT_EQ(it->second, "CustomServerValue");
  2727. }
  2728. }
  2729. class ServerTest : public ::testing::Test {
  2730. protected:
  2731. ServerTest()
  2732. : cli_(HOST, PORT)
  2733. #ifdef CPPHTTPLIB_SSL_ENABLED
  2734. ,
  2735. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2736. #endif
  2737. {
  2738. #ifdef CPPHTTPLIB_SSL_ENABLED
  2739. cli_.enable_server_certificate_verification(false);
  2740. #endif
  2741. // Allow LARGE_DATA (100MB) responses
  2742. cli_.set_payload_max_length(200 * 1024 * 1024);
  2743. }
  2744. virtual void SetUp() {
  2745. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2746. svr_.set_payload_max_length(200 * 1024 * 1024);
  2747. svr_.set_mount_point("/", "./www");
  2748. svr_.set_mount_point("/mount", "./www2");
  2749. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2750. svr_.Get("/hi",
  2751. [&](const Request & /*req*/, Response &res) {
  2752. res.set_content("Hello World!", "text/plain");
  2753. })
  2754. .Get("/file_content",
  2755. [&](const Request & /*req*/, Response &res) {
  2756. res.set_file_content("./www/dir/test.html");
  2757. })
  2758. .Get("/file_content_with_content_type",
  2759. [&](const Request & /*req*/, Response &res) {
  2760. res.set_file_content("./www/file", "text/plain");
  2761. })
  2762. .Get("/invalid_file_content",
  2763. [&](const Request & /*req*/, Response &res) {
  2764. res.set_file_content("./www/dir/invalid_file_path");
  2765. })
  2766. .Get("/http_response_splitting",
  2767. [&](const Request & /*req*/, Response &res) {
  2768. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2769. EXPECT_EQ(0U, res.headers.size());
  2770. EXPECT_FALSE(res.has_header("a"));
  2771. res.set_header("a", "1\nSet-Cookie: a=1");
  2772. EXPECT_EQ(0U, res.headers.size());
  2773. EXPECT_FALSE(res.has_header("a"));
  2774. res.set_header("a", "1\rSet-Cookie: a=1");
  2775. EXPECT_EQ(0U, res.headers.size());
  2776. EXPECT_FALSE(res.has_header("a"));
  2777. res.set_header("a\r\nb", "0");
  2778. EXPECT_EQ(0U, res.headers.size());
  2779. EXPECT_FALSE(res.has_header("a"));
  2780. res.set_header("a\rb", "0");
  2781. EXPECT_EQ(0U, res.headers.size());
  2782. EXPECT_FALSE(res.has_header("a"));
  2783. res.set_header("a\nb", "0");
  2784. EXPECT_EQ(0U, res.headers.size());
  2785. EXPECT_FALSE(res.has_header("a"));
  2786. res.set_redirect("1\r\nSet-Cookie: a=1");
  2787. EXPECT_EQ(0U, res.headers.size());
  2788. EXPECT_FALSE(res.has_header("Location"));
  2789. })
  2790. .Get("/slow",
  2791. [&](const Request & /*req*/, Response &res) {
  2792. std::this_thread::sleep_for(std::chrono::seconds(2));
  2793. res.set_content("slow", "text/plain");
  2794. })
  2795. #if 0
  2796. .Post("/slowpost",
  2797. [&](const Request & /*req*/, Response &res) {
  2798. std::this_thread::sleep_for(std::chrono::seconds(2));
  2799. res.set_content("slow", "text/plain");
  2800. })
  2801. #endif
  2802. .Get("/remote_addr",
  2803. [&](const Request &req, Response &res) {
  2804. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2805. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2806. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2807. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2808. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2809. #endif
  2810. res.set_content(req.remote_addr, "text/plain");
  2811. })
  2812. .Get("/local_addr",
  2813. [&](const Request &req, Response &res) {
  2814. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2815. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2816. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2817. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2818. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2819. #endif
  2820. auto local_addr = req.local_addr;
  2821. auto local_port = std::to_string(req.local_port);
  2822. res.set_content(local_addr.append(":").append(local_port),
  2823. "text/plain");
  2824. })
  2825. .Get("/endwith%",
  2826. [&](const Request & /*req*/, Response &res) {
  2827. res.set_content("Hello World!", "text/plain");
  2828. })
  2829. .Get("/a\\+\\+b",
  2830. [&](const Request &req, Response &res) {
  2831. ASSERT_TRUE(req.has_param("a +b"));
  2832. auto val = req.get_param_value("a +b");
  2833. res.set_content(val, "text/plain");
  2834. })
  2835. .Get("/", [&](const Request & /*req*/,
  2836. Response &res) { res.set_redirect("/hi"); })
  2837. .Post("/1",
  2838. [](const Request & /*req*/, Response &res) {
  2839. res.set_redirect("/2", StatusCode::SeeOther_303);
  2840. })
  2841. .Get("/2",
  2842. [](const Request & /*req*/, Response &res) {
  2843. res.set_content("redirected.", "text/plain");
  2844. res.status = StatusCode::OK_200;
  2845. })
  2846. .Post("/person",
  2847. [&](const Request &req, Response &res) {
  2848. if (req.has_param("name") && req.has_param("note")) {
  2849. persons_[req.get_param_value("name")] =
  2850. req.get_param_value("note");
  2851. } else {
  2852. res.status = StatusCode::BadRequest_400;
  2853. }
  2854. })
  2855. .Put("/person",
  2856. [&](const Request &req, Response &res) {
  2857. if (req.has_param("name") && req.has_param("note")) {
  2858. persons_[req.get_param_value("name")] =
  2859. req.get_param_value("note");
  2860. } else {
  2861. res.status = StatusCode::BadRequest_400;
  2862. }
  2863. })
  2864. .Get("/person/(.*)",
  2865. [&](const Request &req, Response &res) {
  2866. string name = req.matches[1];
  2867. if (persons_.find(name) != persons_.end()) {
  2868. auto note = persons_[name];
  2869. res.set_content(note, "text/plain");
  2870. } else {
  2871. res.status = StatusCode::NotFound_404;
  2872. }
  2873. })
  2874. .Delete("/person",
  2875. [&](const Request &req, Response &res) {
  2876. if (req.has_param("name")) {
  2877. string name = req.get_param_value("name");
  2878. if (persons_.find(name) != persons_.end()) {
  2879. persons_.erase(name);
  2880. res.set_content("DELETED", "text/plain");
  2881. } else {
  2882. res.status = StatusCode::NotFound_404;
  2883. }
  2884. } else {
  2885. res.status = StatusCode::BadRequest_400;
  2886. }
  2887. })
  2888. .Post("/x-www-form-urlencoded-json",
  2889. [&](const Request &req, Response &res) {
  2890. auto json = req.get_param_value("json");
  2891. ASSERT_EQ(JSON_DATA, json);
  2892. res.set_content(json, "appliation/json");
  2893. res.status = StatusCode::OK_200;
  2894. })
  2895. .Get("/streamed-chunked",
  2896. [&](const Request & /*req*/, Response &res) {
  2897. res.set_chunked_content_provider(
  2898. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2899. sink.os << "123";
  2900. sink.os << "456";
  2901. sink.os << "789";
  2902. sink.done();
  2903. return true;
  2904. });
  2905. })
  2906. .Get("/streamed-chunked-with-prohibited-trailer",
  2907. [&](const Request & /*req*/, Response &res) {
  2908. auto i = new int(0);
  2909. // Declare both a prohibited trailer (Content-Length) and an
  2910. // allowed one
  2911. res.set_header("Trailer", "Content-Length, X-Allowed");
  2912. res.set_chunked_content_provider(
  2913. "text/plain",
  2914. [i](size_t /*offset*/, DataSink &sink) {
  2915. switch (*i) {
  2916. case 0: sink.os << "123"; break;
  2917. case 1: sink.os << "456"; break;
  2918. case 2: sink.os << "789"; break;
  2919. case 3: {
  2920. sink.done_with_trailer(
  2921. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2922. } break;
  2923. }
  2924. (*i)++;
  2925. return true;
  2926. },
  2927. [i](bool success) {
  2928. EXPECT_TRUE(success);
  2929. delete i;
  2930. });
  2931. })
  2932. .Get("/streamed-chunked2",
  2933. [&](const Request & /*req*/, Response &res) {
  2934. auto i = new int(0);
  2935. res.set_chunked_content_provider(
  2936. "text/plain",
  2937. [i](size_t /*offset*/, DataSink &sink) {
  2938. switch (*i) {
  2939. case 0: sink.os << "123"; break;
  2940. case 1: sink.os << "456"; break;
  2941. case 2: sink.os << "789"; break;
  2942. case 3: sink.done(); break;
  2943. }
  2944. (*i)++;
  2945. return true;
  2946. },
  2947. [i](bool success) {
  2948. EXPECT_TRUE(success);
  2949. delete i;
  2950. });
  2951. })
  2952. .Get("/streamed-chunked-with-trailer",
  2953. [&](const Request & /*req*/, Response &res) {
  2954. auto i = new int(0);
  2955. res.set_header("Trailer", "Dummy1, Dummy2");
  2956. res.set_chunked_content_provider(
  2957. "text/plain",
  2958. [i](size_t /*offset*/, DataSink &sink) {
  2959. switch (*i) {
  2960. case 0: sink.os << "123"; break;
  2961. case 1: sink.os << "456"; break;
  2962. case 2: sink.os << "789"; break;
  2963. case 3: {
  2964. sink.done_with_trailer(
  2965. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2966. } break;
  2967. }
  2968. (*i)++;
  2969. return true;
  2970. },
  2971. [i](bool success) {
  2972. EXPECT_TRUE(success);
  2973. delete i;
  2974. });
  2975. })
  2976. .Get("/streamed",
  2977. [&](const Request & /*req*/, Response &res) {
  2978. res.set_content_provider(
  2979. 6, "text/plain",
  2980. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2981. sink.os << (offset < 3 ? "a" : "b");
  2982. return true;
  2983. });
  2984. })
  2985. .Get("/streamed-with-range",
  2986. [&](const Request &req, Response &res) {
  2987. auto data = new std::string("abcdefg");
  2988. res.set_content_provider(
  2989. data->size(), "text/plain",
  2990. [data](size_t offset, size_t length, DataSink &sink) {
  2991. size_t DATA_CHUNK_SIZE = 4;
  2992. const auto &d = *data;
  2993. auto out_len =
  2994. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2995. auto ret =
  2996. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2997. EXPECT_TRUE(ret);
  2998. return true;
  2999. },
  3000. [data, &req](bool success) {
  3001. EXPECT_EQ(success, !req.has_param("error"));
  3002. delete data;
  3003. });
  3004. })
  3005. .Get("/streamed-cancel",
  3006. [&](const Request & /*req*/, Response &res) {
  3007. res.set_content_provider(
  3008. size_t(-1), "text/plain",
  3009. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3010. sink.os << "data_chunk";
  3011. return true;
  3012. });
  3013. })
  3014. .Get("/regex-with-delimiter",
  3015. [&](const Request &req, Response & /*res*/) {
  3016. ASSERT_TRUE(req.has_param("key"));
  3017. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3018. })
  3019. .Get("/with-range",
  3020. [&](const Request & /*req*/, Response &res) {
  3021. res.set_content("abcdefg", "text/plain");
  3022. })
  3023. .Get("/test-start-time",
  3024. [&](const Request &req, Response & /*res*/) {
  3025. EXPECT_NE(req.start_time_,
  3026. std::chrono::steady_clock::time_point::min());
  3027. })
  3028. .Get("/with-range-customized-response",
  3029. [&](const Request & /*req*/, Response &res) {
  3030. res.status = StatusCode::BadRequest_400;
  3031. res.set_content(JSON_DATA, "application/json");
  3032. })
  3033. .Post("/chunked",
  3034. [&](const Request &req, Response & /*res*/) {
  3035. EXPECT_EQ(req.body, "dechunked post body");
  3036. })
  3037. .Post("/large-chunked",
  3038. [&](const Request &req, Response & /*res*/) {
  3039. std::string expected(6 * 30 * 1024u, 'a');
  3040. EXPECT_EQ(req.body, expected);
  3041. })
  3042. .Post("/multipart",
  3043. [&](const Request &req, Response & /*res*/) {
  3044. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3045. req.form.get_field_count("text2") +
  3046. req.form.get_field_count("file3") +
  3047. req.form.get_field_count("file4"));
  3048. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3049. req.form.get_file_count("file2"));
  3050. ASSERT_TRUE(!req.form.has_file("???"));
  3051. ASSERT_TRUE(!req.form.has_field("???"));
  3052. ASSERT_TRUE(req.body.empty());
  3053. {
  3054. const auto &text = req.form.get_field("text1");
  3055. EXPECT_EQ("text default", text);
  3056. }
  3057. {
  3058. const auto &text = req.form.get_field("text2");
  3059. EXPECT_EQ("aωb", text);
  3060. }
  3061. {
  3062. const auto &file = req.form.get_file("file1");
  3063. EXPECT_EQ("hello.txt", file.filename);
  3064. EXPECT_EQ("text/plain", file.content_type);
  3065. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3066. }
  3067. {
  3068. const auto &file = req.form.get_file("file2");
  3069. EXPECT_EQ("world.json", file.filename);
  3070. EXPECT_EQ("application/json", file.content_type);
  3071. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3072. }
  3073. {
  3074. const auto &text = req.form.get_field("file3");
  3075. EXPECT_EQ(0u, text.size());
  3076. }
  3077. {
  3078. const auto &text = req.form.get_field("file4");
  3079. EXPECT_EQ(0u, text.size());
  3080. }
  3081. })
  3082. .Post("/multipart/multi_file_values",
  3083. [&](const Request &req, Response & /*res*/) {
  3084. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3085. req.form.get_field_count("multi_text1"));
  3086. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3087. ASSERT_TRUE(!req.form.has_file("???"));
  3088. ASSERT_TRUE(!req.form.has_field("???"));
  3089. ASSERT_TRUE(req.body.empty());
  3090. {
  3091. const auto &text = req.form.get_field("text");
  3092. EXPECT_EQ("default text", text);
  3093. }
  3094. {
  3095. const auto &text1_values = req.form.get_fields("multi_text1");
  3096. EXPECT_EQ(2u, text1_values.size());
  3097. EXPECT_EQ("aaaaa", text1_values[0]);
  3098. EXPECT_EQ("bbbbb", text1_values[1]);
  3099. }
  3100. {
  3101. const auto &file1_values = req.form.get_files("multi_file1");
  3102. EXPECT_EQ(2u, file1_values.size());
  3103. auto file1 = file1_values[0];
  3104. EXPECT_EQ(file1.filename, "hello.txt");
  3105. EXPECT_EQ(file1.content_type, "text/plain");
  3106. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3107. auto file2 = file1_values[1];
  3108. EXPECT_EQ(file2.filename, "world.json");
  3109. EXPECT_EQ(file2.content_type, "application/json");
  3110. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3111. }
  3112. })
  3113. .Post("/empty",
  3114. [&](const Request &req, Response &res) {
  3115. EXPECT_EQ(req.body, "");
  3116. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3117. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3118. res.set_content("empty", "text/plain");
  3119. })
  3120. .Post("/empty-no-content-type",
  3121. [&](const Request &req, Response &res) {
  3122. EXPECT_EQ(req.body, "");
  3123. EXPECT_FALSE(req.has_header("Content-Type"));
  3124. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3125. res.set_content("empty-no-content-type", "text/plain");
  3126. })
  3127. .Post("/path-only",
  3128. [&](const Request &req, Response &res) {
  3129. EXPECT_EQ(req.body, "");
  3130. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3131. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3132. res.set_content("path-only", "text/plain");
  3133. })
  3134. .Post("/path-headers-only",
  3135. [&](const Request &req, Response &res) {
  3136. EXPECT_EQ(req.body, "");
  3137. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3138. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3139. EXPECT_EQ("world", req.get_header_value("hello"));
  3140. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3141. res.set_content("path-headers-only", "text/plain");
  3142. })
  3143. .Post("/post-large",
  3144. [&](const Request &req, Response &res) {
  3145. EXPECT_EQ(req.body, LARGE_DATA);
  3146. res.set_content(req.body, "text/plain");
  3147. })
  3148. .Post("/post-loopback",
  3149. [&](const Request &, Response &res,
  3150. ContentReader const &content_reader) {
  3151. std::string body;
  3152. content_reader([&](const char *data, size_t data_length) {
  3153. body.append(data, data_length);
  3154. return true;
  3155. });
  3156. res.set_content(body, "text/plain");
  3157. })
  3158. .Put("/put-loopback",
  3159. [&](const Request &, Response &res,
  3160. ContentReader const &content_reader) {
  3161. std::string body;
  3162. content_reader([&](const char *data, size_t data_length) {
  3163. body.append(data, data_length);
  3164. return true;
  3165. });
  3166. res.set_content(body, "text/plain");
  3167. })
  3168. .Patch("/patch-loopback",
  3169. [&](const Request &, Response &res,
  3170. ContentReader const &content_reader) {
  3171. std::string body;
  3172. content_reader([&](const char *data, size_t data_length) {
  3173. body.append(data, data_length);
  3174. return true;
  3175. });
  3176. res.set_content(body, "text/plain");
  3177. })
  3178. .Put("/empty-no-content-type",
  3179. [&](const Request &req, Response &res) {
  3180. EXPECT_EQ(req.body, "");
  3181. EXPECT_FALSE(req.has_header("Content-Type"));
  3182. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3183. res.set_content("empty-no-content-type", "text/plain");
  3184. })
  3185. .Put("/put",
  3186. [&](const Request &req, Response &res) {
  3187. EXPECT_EQ(req.body, "PUT");
  3188. res.set_content(req.body, "text/plain");
  3189. })
  3190. .Put("/put-large",
  3191. [&](const Request &req, Response &res) {
  3192. EXPECT_EQ(req.body, LARGE_DATA);
  3193. res.set_content(req.body, "text/plain");
  3194. })
  3195. .Patch("/patch",
  3196. [&](const Request &req, Response &res) {
  3197. EXPECT_EQ(req.body, "PATCH");
  3198. res.set_content(req.body, "text/plain");
  3199. })
  3200. .Delete("/delete",
  3201. [&](const Request & /*req*/, Response &res) {
  3202. res.set_content("DELETE", "text/plain");
  3203. })
  3204. .Delete("/delete-body",
  3205. [&](const Request &req, Response &res) {
  3206. EXPECT_EQ(req.body, "content");
  3207. res.set_content(req.body, "text/plain");
  3208. })
  3209. .Options(R"(\*)",
  3210. [&](const Request & /*req*/, Response &res) {
  3211. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3212. })
  3213. .Get("/request-target",
  3214. [&](const Request &req, Response & /*res*/) {
  3215. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3216. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3217. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3218. })
  3219. .Get("/long-query-value",
  3220. [&](const Request &req, Response & /*res*/) {
  3221. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3222. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3223. })
  3224. .Get("/too-long-query-value",
  3225. [&](const Request &req, Response & /*res*/) {
  3226. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3227. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3228. })
  3229. .Get("/array-param",
  3230. [&](const Request &req, Response & /*res*/) {
  3231. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3232. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3233. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3234. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3235. })
  3236. .Post("/validate-no-multiple-headers",
  3237. [&](const Request &req, Response & /*res*/) {
  3238. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3239. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3240. })
  3241. .Post("/content_receiver",
  3242. [&](const Request &req, Response &res,
  3243. const ContentReader &content_reader) {
  3244. if (req.is_multipart_form_data()) {
  3245. std::vector<FormData> items;
  3246. content_reader(
  3247. [&](const FormData &file) {
  3248. items.push_back(file);
  3249. return true;
  3250. },
  3251. [&](const char *data, size_t data_length) {
  3252. items.back().content.append(data, data_length);
  3253. return true;
  3254. });
  3255. EXPECT_EQ(5u, items.size());
  3256. {
  3257. const auto &file = get_file_value(items, "text1");
  3258. EXPECT_TRUE(file.filename.empty());
  3259. EXPECT_EQ("text default", file.content);
  3260. }
  3261. {
  3262. const auto &file = get_file_value(items, "text2");
  3263. EXPECT_TRUE(file.filename.empty());
  3264. EXPECT_EQ("aωb", file.content);
  3265. }
  3266. {
  3267. const auto &file = get_file_value(items, "file1");
  3268. EXPECT_EQ("hello.txt", file.filename);
  3269. EXPECT_EQ("text/plain", file.content_type);
  3270. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3271. }
  3272. {
  3273. const auto &file = get_file_value(items, "file2");
  3274. EXPECT_EQ("world.json", file.filename);
  3275. EXPECT_EQ("application/json", file.content_type);
  3276. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3277. }
  3278. {
  3279. const auto &file = get_file_value(items, "file3");
  3280. EXPECT_TRUE(file.filename.empty());
  3281. EXPECT_EQ("application/octet-stream", file.content_type);
  3282. EXPECT_EQ(0u, file.content.size());
  3283. }
  3284. } else {
  3285. std::string body;
  3286. content_reader([&](const char *data, size_t data_length) {
  3287. EXPECT_EQ(7U, data_length);
  3288. body.append(data, data_length);
  3289. return true;
  3290. });
  3291. EXPECT_EQ(body, "content");
  3292. res.set_content(body, "text/plain");
  3293. }
  3294. })
  3295. .Put("/content_receiver",
  3296. [&](const Request & /*req*/, Response &res,
  3297. const ContentReader &content_reader) {
  3298. std::string body;
  3299. content_reader([&](const char *data, size_t data_length) {
  3300. body.append(data, data_length);
  3301. return true;
  3302. });
  3303. EXPECT_EQ(body, "content");
  3304. res.set_content(body, "text/plain");
  3305. })
  3306. .Patch("/content_receiver",
  3307. [&](const Request & /*req*/, Response &res,
  3308. const ContentReader &content_reader) {
  3309. std::string body;
  3310. content_reader([&](const char *data, size_t data_length) {
  3311. body.append(data, data_length);
  3312. return true;
  3313. });
  3314. EXPECT_EQ(body, "content");
  3315. res.set_content(body, "text/plain");
  3316. })
  3317. .Post("/query-string-and-body",
  3318. [&](const Request &req, Response & /*res*/) {
  3319. ASSERT_TRUE(req.has_param("key"));
  3320. EXPECT_EQ(req.get_param_value("key"), "value");
  3321. EXPECT_EQ(req.body, "content");
  3322. })
  3323. .Get("/last-request",
  3324. [&](const Request &req, Response & /*res*/) {
  3325. EXPECT_EQ("close", req.get_header_value("Connection"));
  3326. })
  3327. .Get(R"(/redirect/(\d+))",
  3328. [&](const Request &req, Response &res) {
  3329. auto num = std::stoi(req.matches[1]) + 1;
  3330. std::string url = "/redirect/" + std::to_string(num);
  3331. res.set_redirect(url);
  3332. })
  3333. .Post("/binary",
  3334. [&](const Request &req, Response &res) {
  3335. EXPECT_EQ(4U, req.body.size());
  3336. EXPECT_EQ("application/octet-stream",
  3337. req.get_header_value("Content-Type"));
  3338. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3339. res.set_content(req.body, "application/octet-stream");
  3340. })
  3341. .Put("/binary",
  3342. [&](const Request &req, Response &res) {
  3343. EXPECT_EQ(4U, req.body.size());
  3344. EXPECT_EQ("application/octet-stream",
  3345. req.get_header_value("Content-Type"));
  3346. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3347. res.set_content(req.body, "application/octet-stream");
  3348. })
  3349. .Patch("/binary",
  3350. [&](const Request &req, Response &res) {
  3351. EXPECT_EQ(4U, req.body.size());
  3352. EXPECT_EQ("application/octet-stream",
  3353. req.get_header_value("Content-Type"));
  3354. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3355. res.set_content(req.body, "application/octet-stream");
  3356. })
  3357. .Delete("/binary",
  3358. [&](const Request &req, Response &res) {
  3359. EXPECT_EQ(4U, req.body.size());
  3360. EXPECT_EQ("application/octet-stream",
  3361. req.get_header_value("Content-Type"));
  3362. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3363. res.set_content(req.body, "application/octet-stream");
  3364. })
  3365. .Get("/issue1772",
  3366. [&](const Request & /*req*/, Response &res) {
  3367. res.status = 401;
  3368. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3369. })
  3370. .Delete("/issue609",
  3371. [](const httplib::Request &, httplib::Response &res,
  3372. const httplib::ContentReader &) {
  3373. res.set_content("ok", "text/plain");
  3374. })
  3375. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3376. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3377. .Get("/compress",
  3378. [&](const Request & /*req*/, Response &res) {
  3379. res.set_content(
  3380. "12345678901234567890123456789012345678901234567890123456789"
  3381. "01234567890123456789012345678901234567890",
  3382. "text/plain");
  3383. })
  3384. .Get("/compress-with-charset",
  3385. [&](const Request & /*req*/, Response &res) {
  3386. res.set_content(
  3387. "12345678901234567890123456789012345678901234567890123456789"
  3388. "01234567890123456789012345678901234567890",
  3389. "application/json; charset=utf-8");
  3390. })
  3391. .Get("/nocompress",
  3392. [&](const Request & /*req*/, Response &res) {
  3393. res.set_content(
  3394. "12345678901234567890123456789012345678901234567890123456789"
  3395. "01234567890123456789012345678901234567890",
  3396. "application/octet-stream");
  3397. })
  3398. .Post("/compress-multipart",
  3399. [&](const Request &req, Response & /*res*/) {
  3400. EXPECT_EQ(2u, req.form.fields.size());
  3401. ASSERT_TRUE(!req.form.has_field("???"));
  3402. {
  3403. const auto &text = req.form.get_field("key1");
  3404. EXPECT_EQ("test", text);
  3405. }
  3406. {
  3407. const auto &text = req.form.get_field("key2");
  3408. EXPECT_EQ("--abcdefg123", text);
  3409. }
  3410. })
  3411. #endif
  3412. ;
  3413. persons_["john"] = "programmer";
  3414. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3415. svr_.wait_until_ready();
  3416. }
  3417. virtual void TearDown() {
  3418. svr_.stop();
  3419. if (!request_threads_.empty()) {
  3420. std::this_thread::sleep_for(std::chrono::seconds(1));
  3421. for (auto &t : request_threads_) {
  3422. t.join();
  3423. }
  3424. }
  3425. t_.join();
  3426. }
  3427. map<string, string> persons_;
  3428. #ifdef CPPHTTPLIB_SSL_ENABLED
  3429. SSLClient cli_;
  3430. SSLServer svr_;
  3431. #else
  3432. Client cli_;
  3433. Server svr_;
  3434. #endif
  3435. thread t_;
  3436. std::vector<thread> request_threads_;
  3437. };
  3438. TEST_F(ServerTest, GetMethod200) {
  3439. auto res = cli_.Get("/hi");
  3440. ASSERT_TRUE(res);
  3441. EXPECT_EQ("HTTP/1.1", res->version);
  3442. EXPECT_EQ(StatusCode::OK_200, res->status);
  3443. EXPECT_EQ("OK", res->reason);
  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, GetEmptyFile) {
  3449. auto res = cli_.Get("/empty_file");
  3450. ASSERT_TRUE(res);
  3451. EXPECT_EQ(StatusCode::OK_200, res->status);
  3452. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3453. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3454. EXPECT_EQ("", res->body);
  3455. }
  3456. TEST_F(ServerTest, GetFileContent) {
  3457. auto res = cli_.Get("/file_content");
  3458. ASSERT_TRUE(res);
  3459. EXPECT_EQ(StatusCode::OK_200, res->status);
  3460. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3461. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3462. EXPECT_EQ("test.html", res->body);
  3463. }
  3464. TEST_F(ServerTest, GetFileContentWithRange) {
  3465. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3466. ASSERT_TRUE(res);
  3467. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3468. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3469. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3470. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3471. EXPECT_EQ("est", res->body);
  3472. }
  3473. TEST_F(ServerTest, GetFileContentWithContentType) {
  3474. auto res = cli_.Get("/file_content_with_content_type");
  3475. ASSERT_TRUE(res);
  3476. EXPECT_EQ(StatusCode::OK_200, res->status);
  3477. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3478. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3479. EXPECT_EQ("file\n", res->body);
  3480. }
  3481. TEST_F(ServerTest, GetInvalidFileContent) {
  3482. auto res = cli_.Get("/invalid_file_content");
  3483. ASSERT_TRUE(res);
  3484. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3485. }
  3486. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3487. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3488. ASSERT_TRUE(res);
  3489. EXPECT_EQ("HTTP/1.1", res->version);
  3490. EXPECT_EQ(StatusCode::OK_200, res->status);
  3491. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3492. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3493. EXPECT_EQ("Hello World!", res->body);
  3494. }
  3495. TEST_F(ServerTest, GetMethod302) {
  3496. auto res = cli_.Get("/");
  3497. ASSERT_TRUE(res);
  3498. EXPECT_EQ(StatusCode::Found_302, res->status);
  3499. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3500. }
  3501. TEST_F(ServerTest, GetMethod302Redirect) {
  3502. cli_.set_follow_location(true);
  3503. auto res = cli_.Get("/");
  3504. ASSERT_TRUE(res);
  3505. EXPECT_EQ(StatusCode::OK_200, res->status);
  3506. EXPECT_EQ("Hello World!", res->body);
  3507. EXPECT_EQ("/hi", res->location);
  3508. }
  3509. TEST_F(ServerTest, GetMethod404) {
  3510. auto res = cli_.Get("/invalid");
  3511. ASSERT_TRUE(res);
  3512. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3513. }
  3514. TEST_F(ServerTest, HeadMethod200) {
  3515. auto res = cli_.Head("/hi");
  3516. ASSERT_TRUE(res);
  3517. EXPECT_EQ(StatusCode::OK_200, res->status);
  3518. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3519. EXPECT_TRUE(res->body.empty());
  3520. }
  3521. TEST_F(ServerTest, HeadMethod200Static) {
  3522. auto res = cli_.Head("/mount/dir/index.html");
  3523. ASSERT_TRUE(res);
  3524. EXPECT_EQ(StatusCode::OK_200, res->status);
  3525. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3526. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3527. EXPECT_TRUE(res->body.empty());
  3528. }
  3529. TEST_F(ServerTest, HeadMethod404) {
  3530. auto res = cli_.Head("/invalid");
  3531. ASSERT_TRUE(res);
  3532. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3533. EXPECT_TRUE(res->body.empty());
  3534. }
  3535. TEST_F(ServerTest, GetMethodPersonJohn) {
  3536. auto res = cli_.Get("/person/john");
  3537. ASSERT_TRUE(res);
  3538. EXPECT_EQ(StatusCode::OK_200, res->status);
  3539. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3540. EXPECT_EQ("programmer", res->body);
  3541. }
  3542. TEST_F(ServerTest, PostMethod1) {
  3543. auto res = cli_.Get("/person/john1");
  3544. ASSERT_TRUE(res);
  3545. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3546. res = cli_.Post("/person", "name=john1&note=coder",
  3547. "application/x-www-form-urlencoded");
  3548. ASSERT_TRUE(res);
  3549. ASSERT_EQ(StatusCode::OK_200, res->status);
  3550. res = cli_.Get("/person/john1");
  3551. ASSERT_TRUE(res);
  3552. ASSERT_EQ(StatusCode::OK_200, res->status);
  3553. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3554. ASSERT_EQ("coder", res->body);
  3555. }
  3556. TEST_F(ServerTest, PostMethod2) {
  3557. auto res = cli_.Get("/person/john2");
  3558. ASSERT_TRUE(res);
  3559. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3560. Params params;
  3561. params.emplace("name", "john2");
  3562. params.emplace("note", "coder");
  3563. res = cli_.Post("/person", params);
  3564. ASSERT_TRUE(res);
  3565. ASSERT_EQ(StatusCode::OK_200, res->status);
  3566. res = cli_.Get("/person/john2");
  3567. ASSERT_TRUE(res);
  3568. ASSERT_EQ(StatusCode::OK_200, res->status);
  3569. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3570. ASSERT_EQ("coder", res->body);
  3571. }
  3572. TEST_F(ServerTest, PutMethod3) {
  3573. auto res = cli_.Get("/person/john3");
  3574. ASSERT_TRUE(res);
  3575. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3576. Params params;
  3577. params.emplace("name", "john3");
  3578. params.emplace("note", "coder");
  3579. res = cli_.Put("/person", params);
  3580. ASSERT_TRUE(res);
  3581. ASSERT_EQ(StatusCode::OK_200, res->status);
  3582. res = cli_.Get("/person/john3");
  3583. ASSERT_TRUE(res);
  3584. ASSERT_EQ(StatusCode::OK_200, res->status);
  3585. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3586. ASSERT_EQ("coder", res->body);
  3587. }
  3588. TEST_F(ServerTest, DeleteMethod1) {
  3589. auto res = cli_.Get("/person/john4");
  3590. ASSERT_TRUE(res);
  3591. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3592. Params params;
  3593. params.emplace("name", "john4");
  3594. params.emplace("note", "coder");
  3595. res = cli_.Post("/person", params);
  3596. ASSERT_TRUE(res);
  3597. ASSERT_EQ(StatusCode::OK_200, res->status);
  3598. res = cli_.Get("/person/john4");
  3599. ASSERT_TRUE(res);
  3600. ASSERT_EQ(StatusCode::OK_200, res->status);
  3601. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3602. ASSERT_EQ("coder", res->body);
  3603. Params delete_params;
  3604. delete_params.emplace("name", "john4");
  3605. res = cli_.Delete("/person", delete_params);
  3606. ASSERT_TRUE(res);
  3607. ASSERT_EQ(StatusCode::OK_200, res->status);
  3608. ASSERT_EQ("DELETED", res->body);
  3609. res = cli_.Get("/person/john4");
  3610. ASSERT_TRUE(res);
  3611. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3612. }
  3613. TEST_F(ServerTest, DeleteMethod2) {
  3614. auto res = cli_.Get("/person/john5");
  3615. ASSERT_TRUE(res);
  3616. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3617. Params params;
  3618. params.emplace("name", "john5");
  3619. params.emplace("note", "developer");
  3620. res = cli_.Post("/person", params);
  3621. ASSERT_TRUE(res);
  3622. ASSERT_EQ(StatusCode::OK_200, res->status);
  3623. res = cli_.Get("/person/john5");
  3624. ASSERT_TRUE(res);
  3625. ASSERT_EQ(StatusCode::OK_200, res->status);
  3626. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3627. ASSERT_EQ("developer", res->body);
  3628. Params delete_params;
  3629. delete_params.emplace("name", "john5");
  3630. Headers headers;
  3631. headers.emplace("Custom-Header", "test-value");
  3632. res = cli_.Delete("/person", headers, delete_params);
  3633. ASSERT_TRUE(res);
  3634. ASSERT_EQ(StatusCode::OK_200, res->status);
  3635. ASSERT_EQ("DELETED", res->body);
  3636. res = cli_.Get("/person/john5");
  3637. ASSERT_TRUE(res);
  3638. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3639. }
  3640. TEST_F(ServerTest, DeleteMethod3) {
  3641. auto res = cli_.Get("/person/john6");
  3642. ASSERT_TRUE(res);
  3643. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3644. Params params;
  3645. params.emplace("name", "john6");
  3646. params.emplace("note", "tester");
  3647. res = cli_.Post("/person", params);
  3648. ASSERT_TRUE(res);
  3649. ASSERT_EQ(StatusCode::OK_200, res->status);
  3650. res = cli_.Get("/person/john6");
  3651. ASSERT_TRUE(res);
  3652. ASSERT_EQ(StatusCode::OK_200, res->status);
  3653. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3654. ASSERT_EQ("tester", res->body);
  3655. Params delete_params;
  3656. delete_params.emplace("name", "john6");
  3657. Headers headers;
  3658. headers.emplace("Custom-Header", "test-value");
  3659. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3660. ASSERT_TRUE(res);
  3661. ASSERT_EQ(StatusCode::OK_200, res->status);
  3662. ASSERT_EQ("DELETED", res->body);
  3663. res = cli_.Get("/person/john6");
  3664. ASSERT_TRUE(res);
  3665. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3666. }
  3667. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3668. Params params;
  3669. params.emplace("json", JSON_DATA);
  3670. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3671. ASSERT_TRUE(res);
  3672. ASSERT_EQ(StatusCode::OK_200, res->status);
  3673. ASSERT_EQ(JSON_DATA, res->body);
  3674. }
  3675. TEST_F(ServerTest, PostEmptyContent) {
  3676. auto res = cli_.Post("/empty", "", "text/plain");
  3677. ASSERT_TRUE(res);
  3678. ASSERT_EQ(StatusCode::OK_200, res->status);
  3679. ASSERT_EQ("empty", res->body);
  3680. }
  3681. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3682. auto res = cli_.Post("/empty-no-content-type");
  3683. ASSERT_TRUE(res);
  3684. ASSERT_EQ(StatusCode::OK_200, res->status);
  3685. ASSERT_EQ("empty-no-content-type", res->body);
  3686. }
  3687. TEST_F(ServerTest, PostPathOnly) {
  3688. auto res = cli_.Post("/path-only");
  3689. ASSERT_TRUE(res);
  3690. ASSERT_EQ(StatusCode::OK_200, res->status);
  3691. ASSERT_EQ("path-only", res->body);
  3692. }
  3693. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3694. auto res = cli_.Post("/path-headers-only",
  3695. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3696. ASSERT_TRUE(res);
  3697. ASSERT_EQ(StatusCode::OK_200, res->status);
  3698. ASSERT_EQ("path-headers-only", res->body);
  3699. }
  3700. TEST_F(ServerTest, PostLarge) {
  3701. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3702. ASSERT_TRUE(res);
  3703. ASSERT_EQ(StatusCode::OK_200, res->status);
  3704. EXPECT_EQ(LARGE_DATA, res->body);
  3705. }
  3706. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3707. auto res = cli_.Put("/empty-no-content-type");
  3708. ASSERT_TRUE(res);
  3709. ASSERT_EQ(StatusCode::OK_200, res->status);
  3710. ASSERT_EQ("empty-no-content-type", res->body);
  3711. }
  3712. TEST_F(ServerTest, GetMethodDir) {
  3713. auto res = cli_.Get("/dir/");
  3714. ASSERT_TRUE(res);
  3715. EXPECT_EQ(StatusCode::OK_200, res->status);
  3716. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3717. auto body = R"(<html>
  3718. <head>
  3719. </head>
  3720. <body>
  3721. <a href="/dir/test.html">Test</a>
  3722. <a href="/hi">hi</a>
  3723. </body>
  3724. </html>
  3725. )";
  3726. EXPECT_EQ(body, res->body);
  3727. }
  3728. TEST_F(ServerTest, GetMethodDirTest) {
  3729. auto res = cli_.Get("/dir/test.html");
  3730. ASSERT_TRUE(res);
  3731. EXPECT_EQ(StatusCode::OK_200, res->status);
  3732. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3733. EXPECT_EQ("test.html", res->body);
  3734. }
  3735. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3736. auto res = cli_.Get("/dir/../dir/test.html");
  3737. ASSERT_TRUE(res);
  3738. EXPECT_EQ(StatusCode::OK_200, res->status);
  3739. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3740. EXPECT_EQ("test.html", res->body);
  3741. }
  3742. TEST_F(ServerTest, GetMethodInvalidPath) {
  3743. auto res = cli_.Get("/dir/../test.html");
  3744. ASSERT_TRUE(res);
  3745. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3746. }
  3747. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3748. auto res = cli_.Get("/../www/dir/test.html");
  3749. ASSERT_TRUE(res);
  3750. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3751. }
  3752. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3753. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3754. ASSERT_TRUE(res);
  3755. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3756. }
  3757. TEST_F(ServerTest, GetMethodDirMountTest) {
  3758. auto res = cli_.Get("/mount/dir/test.html");
  3759. ASSERT_TRUE(res);
  3760. EXPECT_EQ(StatusCode::OK_200, res->status);
  3761. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3762. EXPECT_EQ("test.html", res->body);
  3763. }
  3764. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3765. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3766. ASSERT_TRUE(res);
  3767. EXPECT_EQ(StatusCode::OK_200, res->status);
  3768. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3769. EXPECT_EQ("test.html", res->body);
  3770. }
  3771. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3772. auto res = cli_.Get("/mount/dir/../test.html");
  3773. ASSERT_TRUE(res);
  3774. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3775. }
  3776. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3777. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3778. ASSERT_TRUE(res);
  3779. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3780. }
  3781. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3782. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3783. ASSERT_TRUE(res);
  3784. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3785. }
  3786. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3787. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3788. ASSERT_TRUE(res);
  3789. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3790. }
  3791. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3792. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3793. ASSERT_TRUE(res);
  3794. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3795. }
  3796. TEST_F(ServerTest, PostMethod303) {
  3797. auto res = cli_.Post("/1", "body", "text/plain");
  3798. ASSERT_TRUE(res);
  3799. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3800. EXPECT_EQ("/2", res->get_header_value("Location"));
  3801. }
  3802. TEST_F(ServerTest, PostMethod303Redirect) {
  3803. cli_.set_follow_location(true);
  3804. auto res = cli_.Post("/1", "body", "text/plain");
  3805. ASSERT_TRUE(res);
  3806. EXPECT_EQ(StatusCode::OK_200, res->status);
  3807. EXPECT_EQ("redirected.", res->body);
  3808. EXPECT_EQ("/2", res->location);
  3809. }
  3810. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3811. auto res = cli_.Get("/dir/test.abcde");
  3812. ASSERT_TRUE(res);
  3813. EXPECT_EQ(StatusCode::OK_200, res->status);
  3814. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3815. EXPECT_EQ("abcde", res->body);
  3816. }
  3817. TEST_F(ServerTest, StaticFileRange) {
  3818. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3819. ASSERT_TRUE(res);
  3820. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3821. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3822. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3823. EXPECT_EQ(true, res->has_header("Content-Range"));
  3824. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3825. EXPECT_EQ(std::string("cd"), res->body);
  3826. }
  3827. TEST_F(ServerTest, StaticFileRanges) {
  3828. auto res =
  3829. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3830. ASSERT_TRUE(res);
  3831. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3832. EXPECT_TRUE(
  3833. res->get_header_value("Content-Type")
  3834. .find(
  3835. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3836. 0);
  3837. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3838. }
  3839. TEST_F(ServerTest, StaticFileRangeHead) {
  3840. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3841. ASSERT_TRUE(res);
  3842. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3843. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3844. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3845. EXPECT_EQ(true, res->has_header("Content-Range"));
  3846. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3847. }
  3848. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3849. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3850. ASSERT_TRUE(res);
  3851. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3852. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3853. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3854. EXPECT_EQ(true, res->has_header("Content-Range"));
  3855. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3856. res->get_header_value("Content-Range"));
  3857. EXPECT_EQ("LAST\n", res->body);
  3858. }
  3859. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3860. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3861. ASSERT_TRUE(res);
  3862. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3863. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3864. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3865. EXPECT_EQ(true, res->has_header("Content-Range"));
  3866. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3867. }
  3868. TEST_F(ServerTest, StaticFileBigFile) {
  3869. auto res = cli_.Get("/dir/1MB.txt");
  3870. ASSERT_TRUE(res);
  3871. EXPECT_EQ(StatusCode::OK_200, res->status);
  3872. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3873. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3874. }
  3875. TEST_F(ServerTest, InvalidBaseDirMount) {
  3876. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3877. }
  3878. TEST_F(ServerTest, Binary) {
  3879. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3880. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3881. "application/octet-stream");
  3882. ASSERT_TRUE(res);
  3883. ASSERT_EQ(StatusCode::OK_200, res->status);
  3884. ASSERT_EQ(4U, res->body.size());
  3885. res = cli_.Put("/binary", binary.data(), binary.size(),
  3886. "application/octet-stream");
  3887. ASSERT_TRUE(res);
  3888. ASSERT_EQ(StatusCode::OK_200, res->status);
  3889. ASSERT_EQ(4U, res->body.size());
  3890. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3891. "application/octet-stream");
  3892. ASSERT_TRUE(res);
  3893. ASSERT_EQ(StatusCode::OK_200, res->status);
  3894. ASSERT_EQ(4U, res->body.size());
  3895. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3896. "application/octet-stream");
  3897. ASSERT_TRUE(res);
  3898. ASSERT_EQ(StatusCode::OK_200, res->status);
  3899. ASSERT_EQ(4U, res->body.size());
  3900. }
  3901. TEST_F(ServerTest, BinaryString) {
  3902. auto binary = std::string("\x00\x01\x02\x03", 4);
  3903. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3904. ASSERT_TRUE(res);
  3905. ASSERT_EQ(StatusCode::OK_200, res->status);
  3906. ASSERT_EQ(4U, res->body.size());
  3907. res = cli_.Put("/binary", binary, "application/octet-stream");
  3908. ASSERT_TRUE(res);
  3909. ASSERT_EQ(StatusCode::OK_200, res->status);
  3910. ASSERT_EQ(4U, res->body.size());
  3911. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3912. ASSERT_TRUE(res);
  3913. ASSERT_EQ(StatusCode::OK_200, res->status);
  3914. ASSERT_EQ(4U, res->body.size());
  3915. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3916. ASSERT_TRUE(res);
  3917. ASSERT_EQ(StatusCode::OK_200, res->status);
  3918. ASSERT_EQ(4U, res->body.size());
  3919. }
  3920. TEST_F(ServerTest, EmptyRequest) {
  3921. auto res = cli_.Get("");
  3922. ASSERT_TRUE(!res);
  3923. EXPECT_EQ(Error::Connection, res.error());
  3924. }
  3925. TEST_F(ServerTest, LongRequest) {
  3926. std::string request;
  3927. for (size_t i = 0; i < 545; i++) {
  3928. request += "/TooLongRequest";
  3929. }
  3930. request += "OK";
  3931. auto res = cli_.Get(request.c_str());
  3932. ASSERT_TRUE(res);
  3933. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3934. }
  3935. TEST_F(ServerTest, TooLongRequest) {
  3936. std::string request;
  3937. for (size_t i = 0; i < 546; i++) {
  3938. request += "/TooLongRequest";
  3939. }
  3940. request += "_NG";
  3941. auto start = std::chrono::high_resolution_clock::now();
  3942. cli_.set_keep_alive(true);
  3943. auto res = cli_.Get(request.c_str());
  3944. auto end = std::chrono::high_resolution_clock::now();
  3945. auto elapsed =
  3946. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3947. .count();
  3948. ASSERT_TRUE(res);
  3949. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3950. EXPECT_LE(elapsed, 1000);
  3951. EXPECT_EQ("close", res->get_header_value("Connection"));
  3952. EXPECT_FALSE(cli_.is_socket_open());
  3953. }
  3954. TEST_F(ServerTest, AlmostTooLongRequest) {
  3955. // test for #2046 - URI length check shouldn't include other content on req
  3956. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3957. // leading /, space, HTTP/1.1)
  3958. std::string request =
  3959. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3960. auto res = cli_.Get(request.c_str());
  3961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3962. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3963. }
  3964. TEST_F(ServerTest, LongHeader) {
  3965. Request req;
  3966. req.method = "GET";
  3967. req.path = "/hi";
  3968. std::string host_and_port;
  3969. host_and_port += HOST;
  3970. host_and_port += ":";
  3971. host_and_port += std::to_string(PORT);
  3972. req.headers.emplace("Host", host_and_port.c_str());
  3973. req.headers.emplace("Accept", "*/*");
  3974. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3975. req.headers.emplace(
  3976. "Header-Name",
  3977. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3978. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3979. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3980. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3981. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3982. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3983. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3984. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3985. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3986. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3987. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3988. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3989. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3990. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3991. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3992. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3993. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3994. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3995. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3996. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3997. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3998. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3999. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4000. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4001. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4002. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4003. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4004. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4005. "@@@@@@@@@@@@@@@@");
  4006. auto res = std::make_shared<Response>();
  4007. auto error = Error::Success;
  4008. auto ret = cli_.send(req, *res, error);
  4009. ASSERT_TRUE(ret);
  4010. EXPECT_EQ(StatusCode::OK_200, res->status);
  4011. }
  4012. TEST_F(ServerTest, LongQueryValue) {
  4013. auto start = std::chrono::high_resolution_clock::now();
  4014. cli_.set_keep_alive(true);
  4015. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4016. auto end = std::chrono::high_resolution_clock::now();
  4017. auto elapsed =
  4018. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4019. .count();
  4020. ASSERT_TRUE(res);
  4021. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4022. EXPECT_LE(elapsed, 1000);
  4023. EXPECT_EQ("close", res->get_header_value("Connection"));
  4024. EXPECT_FALSE(cli_.is_socket_open());
  4025. }
  4026. TEST_F(ServerTest, TooLongQueryValue) {
  4027. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4028. ASSERT_FALSE(res);
  4029. EXPECT_EQ(Error::Read, res.error());
  4030. }
  4031. TEST_F(ServerTest, TooLongHeader) {
  4032. Request req;
  4033. req.method = "GET";
  4034. req.path = "/hi";
  4035. std::string host_and_port;
  4036. host_and_port += HOST;
  4037. host_and_port += ":";
  4038. host_and_port += std::to_string(PORT);
  4039. req.headers.emplace("Host", host_and_port.c_str());
  4040. req.headers.emplace("Accept", "*/*");
  4041. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4042. req.headers.emplace(
  4043. "Header-Name",
  4044. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4045. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4046. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4047. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4048. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4049. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4050. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4051. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4052. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4053. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4054. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4055. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4056. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4057. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4058. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4059. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4060. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4061. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4062. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4063. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4064. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4065. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4066. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4067. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4068. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4069. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4070. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4071. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4072. "@@@@@@@@@@@@@@@@@");
  4073. auto res = std::make_shared<Response>();
  4074. auto error = Error::Success;
  4075. auto ret = cli_.send(req, *res, error);
  4076. ASSERT_TRUE(ret);
  4077. EXPECT_EQ(StatusCode::OK_200, res->status);
  4078. }
  4079. TEST_F(ServerTest, HeaderCountAtLimit) {
  4080. // Test with headers just under the 100 limit
  4081. httplib::Headers headers;
  4082. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4083. // This should keep us just under the 100 header limit
  4084. for (int i = 0; i < 95; i++) {
  4085. std::string name = "X-Test-Header-" + std::to_string(i);
  4086. std::string value = "value" + std::to_string(i);
  4087. headers.emplace(name, value);
  4088. }
  4089. // This should work fine as we're under the limit
  4090. auto res = cli_.Get("/hi", headers);
  4091. EXPECT_TRUE(res);
  4092. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4093. }
  4094. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4095. // Test with many headers to exceed the 100 limit
  4096. httplib::Headers headers;
  4097. // Add 150 headers to definitely exceed the 100 limit
  4098. for (int i = 0; i < 150; i++) {
  4099. std::string name = "X-Test-Header-" + std::to_string(i);
  4100. std::string value = "value" + std::to_string(i);
  4101. headers.emplace(name, value);
  4102. }
  4103. // This should fail due to exceeding header count limit
  4104. cli_.set_keep_alive(true);
  4105. auto res = cli_.Get("/hi", headers);
  4106. // The server should respond with 400 Bad Request
  4107. ASSERT_TRUE(res);
  4108. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4109. EXPECT_EQ("close", res->get_header_value("Connection"));
  4110. EXPECT_FALSE(cli_.is_socket_open());
  4111. }
  4112. TEST_F(ServerTest, PercentEncoding) {
  4113. auto res = cli_.Get("/e%6edwith%");
  4114. ASSERT_TRUE(res);
  4115. EXPECT_EQ(StatusCode::OK_200, res->status);
  4116. }
  4117. TEST_F(ServerTest, PercentEncodingUnicode) {
  4118. auto res = cli_.Get("/e%u006edwith%");
  4119. ASSERT_TRUE(res);
  4120. EXPECT_EQ(StatusCode::OK_200, res->status);
  4121. }
  4122. TEST_F(ServerTest, InvalidPercentEncoding) {
  4123. auto res = cli_.Get("/%endwith%");
  4124. ASSERT_TRUE(res);
  4125. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4126. }
  4127. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4128. auto res = cli_.Get("/%uendwith%");
  4129. ASSERT_TRUE(res);
  4130. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4131. }
  4132. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4133. auto res = cli_.Get("/hello?aaa=bbb%");
  4134. ASSERT_TRUE(res);
  4135. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4136. }
  4137. TEST_F(ServerTest, PlusSignEncoding) {
  4138. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4139. ASSERT_TRUE(res);
  4140. EXPECT_EQ(StatusCode::OK_200, res->status);
  4141. EXPECT_EQ("a +b", res->body);
  4142. }
  4143. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4144. // This test simulates a potential DoS attack using many headers
  4145. // to verify our security fix prevents memory exhaustion
  4146. httplib::Headers attack_headers;
  4147. // Attempt to add many headers like an attacker would (200 headers to far
  4148. // exceed limit)
  4149. for (int i = 0; i < 200; i++) {
  4150. std::string name = "X-Attack-Header-" + std::to_string(i);
  4151. std::string value = "attack_payload_" + std::to_string(i);
  4152. attack_headers.emplace(name, value);
  4153. }
  4154. // Try to POST with excessive headers
  4155. cli_.set_keep_alive(true);
  4156. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4157. // Should either fail or return 400 Bad Request due to security limit
  4158. if (res) {
  4159. // If we get a response, it should be 400 Bad Request
  4160. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4161. EXPECT_EQ("close", res->get_header_value("Connection"));
  4162. }
  4163. EXPECT_FALSE(cli_.is_socket_open());
  4164. }
  4165. TEST_F(ServerTest, MultipartFormData) {
  4166. UploadFormDataItems items = {
  4167. {"text1", "text default", "", ""},
  4168. {"text2", "aωb", "", ""},
  4169. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4170. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4171. {"file3", "", "", "application/octet-stream"},
  4172. {"file4", "", "", " application/json tmp-string "}};
  4173. auto res = cli_.Post("/multipart", items);
  4174. ASSERT_TRUE(res);
  4175. EXPECT_EQ(StatusCode::OK_200, res->status);
  4176. }
  4177. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4178. UploadFormDataItems items = {
  4179. {"text", "default text", "", ""},
  4180. {"multi_text1", "aaaaa", "", ""},
  4181. {"multi_text1", "bbbbb", "", ""},
  4182. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4183. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4184. "application/json"},
  4185. };
  4186. auto res = cli_.Post("/multipart/multi_file_values", items);
  4187. ASSERT_TRUE(res);
  4188. EXPECT_EQ(StatusCode::OK_200, res->status);
  4189. }
  4190. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4191. auto res = cli_.Get("/hi");
  4192. ASSERT_TRUE(res);
  4193. EXPECT_EQ(StatusCode::OK_200, res->status);
  4194. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4195. EXPECT_EQ("Hello World!", res->body);
  4196. }
  4197. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4198. Request req;
  4199. req.method = "POST";
  4200. req.path = "/chunked";
  4201. std::string host_and_port;
  4202. host_and_port += HOST;
  4203. host_and_port += ":";
  4204. host_and_port += std::to_string(PORT);
  4205. req.headers.emplace("Host", host_and_port.c_str());
  4206. req.headers.emplace("Accept", "*/*");
  4207. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4208. req.headers.emplace("Content-Type", "text/plain");
  4209. req.headers.emplace("Content-Length", "0");
  4210. req.headers.emplace(
  4211. "Transfer-Encoding",
  4212. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4213. // Client does not chunk, so make a chunked body manually.
  4214. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4215. auto res = std::make_shared<Response>();
  4216. auto error = Error::Success;
  4217. auto ret = cli_.send(req, *res, error);
  4218. ASSERT_TRUE(ret);
  4219. EXPECT_EQ(StatusCode::OK_200, res->status);
  4220. }
  4221. TEST_F(ServerTest, GetStreamed2) {
  4222. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4223. ASSERT_TRUE(res);
  4224. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4225. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4226. EXPECT_EQ(true, res->has_header("Content-Range"));
  4227. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4228. EXPECT_EQ(std::string("ab"), res->body);
  4229. }
  4230. TEST_F(ServerTest, GetStreamed) {
  4231. auto res = cli_.Get("/streamed");
  4232. ASSERT_TRUE(res);
  4233. EXPECT_EQ(StatusCode::OK_200, res->status);
  4234. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4235. EXPECT_EQ(std::string("aaabbb"), res->body);
  4236. }
  4237. TEST_F(ServerTest, GetStreamedWithRange1) {
  4238. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4239. ASSERT_TRUE(res);
  4240. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4241. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4242. EXPECT_EQ(true, res->has_header("Content-Range"));
  4243. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4244. EXPECT_EQ(std::string("def"), res->body);
  4245. }
  4246. TEST_F(ServerTest, GetStreamedWithRange2) {
  4247. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4248. ASSERT_TRUE(res);
  4249. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4250. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4251. EXPECT_EQ(true, res->has_header("Content-Range"));
  4252. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4253. EXPECT_EQ(std::string("bcdefg"), res->body);
  4254. }
  4255. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4256. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4257. ASSERT_TRUE(res);
  4258. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4259. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4260. EXPECT_EQ(true, res->has_header("Content-Range"));
  4261. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4262. EXPECT_EQ(std::string("efg"), res->body);
  4263. }
  4264. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4265. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4266. ASSERT_TRUE(res);
  4267. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4268. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4269. EXPECT_EQ(false, res->has_header("Content-Range"));
  4270. EXPECT_EQ(0U, res->body.size());
  4271. }
  4272. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4273. auto res = cli_.Get("/streamed-with-range",
  4274. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4275. "92233720368547758079223372036854775807"}});
  4276. ASSERT_TRUE(res);
  4277. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4278. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4279. EXPECT_EQ(false, res->has_header("Content-Range"));
  4280. EXPECT_EQ(0U, res->body.size());
  4281. }
  4282. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4283. auto res = cli_.Get(
  4284. "/with-range",
  4285. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4286. {"Accept-Encoding", ""}});
  4287. ASSERT_TRUE(res);
  4288. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4289. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4290. EXPECT_EQ(true, res->has_header("Content-Range"));
  4291. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4292. EXPECT_EQ(std::string("abcdefg"), res->body);
  4293. }
  4294. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4295. auto res = cli_.Get("/with-range", {
  4296. {"Range", "bytes=0-"},
  4297. {"Accept-Encoding", ""},
  4298. });
  4299. ASSERT_TRUE(res);
  4300. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4301. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4302. EXPECT_EQ(true, res->has_header("Content-Range"));
  4303. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4304. EXPECT_EQ(std::string("abcdefg"), res->body);
  4305. }
  4306. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4307. auto res =
  4308. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4309. ASSERT_TRUE(res);
  4310. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4311. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4312. EXPECT_EQ(false, res->has_header("Content-Range"));
  4313. EXPECT_EQ(267U, res->body.size());
  4314. // Check that both range contents are present
  4315. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4316. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4317. // Check that Content-Range headers are present for both ranges
  4318. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4319. std::string::npos);
  4320. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4321. std::string::npos);
  4322. }
  4323. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4324. Ranges ranges;
  4325. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4326. ranges.emplace_back(0, -1);
  4327. }
  4328. auto res =
  4329. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4330. ASSERT_TRUE(res);
  4331. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4332. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4333. EXPECT_EQ(false, res->has_header("Content-Range"));
  4334. EXPECT_EQ(0U, res->body.size());
  4335. }
  4336. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4337. auto res =
  4338. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4339. ASSERT_TRUE(res);
  4340. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4341. EXPECT_EQ(5U, res->body.size());
  4342. // Check that overlapping ranges are coalesced into a single range
  4343. EXPECT_EQ("bcdef", res->body);
  4344. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4345. // Should be single range, not multipart
  4346. EXPECT_TRUE(res->has_header("Content-Range"));
  4347. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4348. }
  4349. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4350. auto res =
  4351. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4352. ASSERT_TRUE(res);
  4353. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4354. EXPECT_EQ(268U, res->body.size());
  4355. // Check that both range contents are present
  4356. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4357. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4358. // Check that Content-Range headers are present for both ranges
  4359. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4360. std::string::npos);
  4361. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4362. std::string::npos);
  4363. }
  4364. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4365. auto res =
  4366. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4367. ASSERT_TRUE(res);
  4368. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4369. EXPECT_EQ(269U, res->body.size());
  4370. // Check that both duplicate range contents are present
  4371. size_t first_abc = res->body.find("abc\r\n");
  4372. EXPECT_TRUE(first_abc != std::string::npos);
  4373. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4374. EXPECT_TRUE(second_abc != std::string::npos);
  4375. // Check that Content-Range headers are present for both ranges
  4376. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4377. EXPECT_TRUE(first_range != std::string::npos);
  4378. size_t second_range =
  4379. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4380. EXPECT_TRUE(second_range != std::string::npos);
  4381. }
  4382. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4383. auto res = cli_.Get("/streamed-with-range?error",
  4384. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4385. ASSERT_TRUE(res);
  4386. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4387. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4388. EXPECT_EQ(false, res->has_header("Content-Range"));
  4389. EXPECT_EQ(0U, res->body.size());
  4390. }
  4391. TEST_F(ServerTest, GetStreamedEndless) {
  4392. uint64_t offset = 0;
  4393. auto res = cli_.Get("/streamed-cancel",
  4394. [&](const char * /*data*/, uint64_t data_length) {
  4395. if (offset < 100) {
  4396. offset += data_length;
  4397. return true;
  4398. }
  4399. return false;
  4400. });
  4401. ASSERT_TRUE(!res);
  4402. EXPECT_EQ(Error::Canceled, res.error());
  4403. }
  4404. TEST_F(ServerTest, ClientStop) {
  4405. std::atomic_size_t count{4};
  4406. std::vector<std::thread> threads;
  4407. for (auto i = count.load(); i != 0; --i) {
  4408. threads.emplace_back([&]() {
  4409. auto res = cli_.Get("/streamed-cancel",
  4410. [&](const char *, uint64_t) { return true; });
  4411. --count;
  4412. ASSERT_TRUE(!res);
  4413. EXPECT_TRUE(res.error() == Error::Canceled ||
  4414. res.error() == Error::Read || res.error() == Error::Write);
  4415. });
  4416. }
  4417. std::this_thread::sleep_for(std::chrono::seconds(2));
  4418. while (count != 0) {
  4419. cli_.stop();
  4420. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4421. }
  4422. for (auto &t : threads) {
  4423. t.join();
  4424. }
  4425. }
  4426. TEST_F(ServerTest, GetWithRange1) {
  4427. auto res = cli_.Get("/with-range", {
  4428. make_range_header({{3, 5}}),
  4429. {"Accept-Encoding", ""},
  4430. });
  4431. ASSERT_TRUE(res);
  4432. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4433. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4434. EXPECT_EQ(true, res->has_header("Content-Range"));
  4435. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4436. EXPECT_EQ(std::string("def"), res->body);
  4437. }
  4438. TEST_F(ServerTest, GetWithRange2) {
  4439. auto res = cli_.Get("/with-range", {
  4440. make_range_header({{1, -1}}),
  4441. {"Accept-Encoding", ""},
  4442. });
  4443. ASSERT_TRUE(res);
  4444. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4445. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4446. EXPECT_EQ(true, res->has_header("Content-Range"));
  4447. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4448. EXPECT_EQ(std::string("bcdefg"), res->body);
  4449. }
  4450. TEST_F(ServerTest, GetWithRange3) {
  4451. auto res = cli_.Get("/with-range", {
  4452. make_range_header({{0, 0}}),
  4453. {"Accept-Encoding", ""},
  4454. });
  4455. ASSERT_TRUE(res);
  4456. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4457. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4458. EXPECT_EQ(true, res->has_header("Content-Range"));
  4459. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4460. EXPECT_EQ(std::string("a"), res->body);
  4461. }
  4462. TEST_F(ServerTest, GetWithRange4) {
  4463. auto res = cli_.Get("/with-range", {
  4464. make_range_header({{-1, 2}}),
  4465. {"Accept-Encoding", ""},
  4466. });
  4467. ASSERT_TRUE(res);
  4468. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4469. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4470. EXPECT_EQ(true, res->has_header("Content-Range"));
  4471. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4472. EXPECT_EQ(std::string("fg"), res->body);
  4473. }
  4474. TEST_F(ServerTest, GetWithRange5) {
  4475. auto res = cli_.Get("/with-range", {
  4476. make_range_header({{0, 5}}),
  4477. {"Accept-Encoding", ""},
  4478. });
  4479. ASSERT_TRUE(res);
  4480. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4481. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4482. EXPECT_EQ(true, res->has_header("Content-Range"));
  4483. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4484. EXPECT_EQ(std::string("abcdef"), res->body);
  4485. }
  4486. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4487. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4488. ASSERT_TRUE(res);
  4489. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4490. }
  4491. TEST_F(ServerTest, GetWithRangeMultipart) {
  4492. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4493. ASSERT_TRUE(res);
  4494. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4495. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4496. EXPECT_EQ(false, res->has_header("Content-Range"));
  4497. EXPECT_EQ(267U, res->body.size());
  4498. }
  4499. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4500. auto res =
  4501. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4502. ASSERT_TRUE(res);
  4503. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4504. }
  4505. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4506. auto res = cli_.Get("/with-range-customized-response",
  4507. {{make_range_header({{1, 2}})}});
  4508. ASSERT_TRUE(res);
  4509. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4510. EXPECT_EQ(true, res->has_header("Content-Length"));
  4511. EXPECT_EQ(false, res->has_header("Content-Range"));
  4512. EXPECT_EQ(JSON_DATA, res->body);
  4513. }
  4514. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4515. auto res = cli_.Get("/with-range-customized-response",
  4516. {{make_range_header({{1, 2}, {4, 5}})}});
  4517. ASSERT_TRUE(res);
  4518. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4519. EXPECT_EQ(true, res->has_header("Content-Length"));
  4520. EXPECT_EQ(false, res->has_header("Content-Range"));
  4521. EXPECT_EQ(JSON_DATA, res->body);
  4522. }
  4523. TEST_F(ServerTest, Issue1772) {
  4524. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4525. ASSERT_TRUE(res);
  4526. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4527. }
  4528. TEST_F(ServerTest, Issue609) {
  4529. auto res = cli_.Delete("/issue609");
  4530. ASSERT_TRUE(res);
  4531. EXPECT_EQ(StatusCode::OK_200, res->status);
  4532. EXPECT_EQ(std::string("ok"), res->body);
  4533. }
  4534. TEST_F(ServerTest, GetStreamedChunked) {
  4535. auto res = cli_.Get("/streamed-chunked");
  4536. ASSERT_TRUE(res);
  4537. EXPECT_EQ(StatusCode::OK_200, res->status);
  4538. EXPECT_EQ(std::string("123456789"), res->body);
  4539. }
  4540. TEST_F(ServerTest, GetStreamedChunked2) {
  4541. auto res = cli_.Get("/streamed-chunked2");
  4542. ASSERT_TRUE(res);
  4543. EXPECT_EQ(StatusCode::OK_200, res->status);
  4544. EXPECT_EQ(std::string("123456789"), res->body);
  4545. }
  4546. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4547. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4548. ASSERT_TRUE(res);
  4549. EXPECT_EQ(StatusCode::OK_200, res->status);
  4550. EXPECT_EQ(std::string("123456789"), res->body);
  4551. EXPECT_TRUE(res->has_header("Trailer"));
  4552. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4553. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4554. // Trailers are now stored separately from headers (security fix)
  4555. EXPECT_EQ(2U, res->trailers.size());
  4556. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4557. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4558. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4559. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4560. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4561. // Verify trailers are NOT in headers (security verification)
  4562. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4563. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4564. }
  4565. TEST_F(ServerTest, LargeChunkedPost) {
  4566. Request req;
  4567. req.method = "POST";
  4568. req.path = "/large-chunked";
  4569. std::string host_and_port;
  4570. host_and_port += HOST;
  4571. host_and_port += ":";
  4572. host_and_port += std::to_string(PORT);
  4573. req.headers.emplace("Host", host_and_port.c_str());
  4574. req.headers.emplace("Accept", "*/*");
  4575. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4576. req.headers.emplace("Content-Type", "text/plain");
  4577. req.headers.emplace("Content-Length", "0");
  4578. req.headers.emplace("Transfer-Encoding", "chunked");
  4579. std::string long_string(30 * 1024u, 'a');
  4580. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4581. // Attempt to make a large enough post to exceed OS buffers, to test that
  4582. // the server handles short reads if the full chunk data isn't available.
  4583. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4584. auto res = std::make_shared<Response>();
  4585. auto error = Error::Success;
  4586. auto ret = cli_.send(req, *res, error);
  4587. ASSERT_TRUE(ret);
  4588. EXPECT_EQ(StatusCode::OK_200, res->status);
  4589. }
  4590. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4591. auto res = cli_.Get("/remote_addr");
  4592. ASSERT_TRUE(res);
  4593. EXPECT_EQ(StatusCode::OK_200, res->status);
  4594. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4595. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4596. }
  4597. TEST_F(ServerTest, GetMethodLocalAddr) {
  4598. auto res = cli_.Get("/local_addr");
  4599. ASSERT_TRUE(res);
  4600. EXPECT_EQ(StatusCode::OK_200, res->status);
  4601. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4602. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4603. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4604. }
  4605. TEST_F(ServerTest, HTTPResponseSplitting) {
  4606. auto res = cli_.Get("/http_response_splitting");
  4607. ASSERT_TRUE(res);
  4608. EXPECT_EQ(StatusCode::OK_200, res->status);
  4609. }
  4610. TEST_F(ServerTest, SlowRequest) {
  4611. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4612. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4613. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4614. }
  4615. #if 0
  4616. TEST_F(ServerTest, SlowPost) {
  4617. char buffer[64 * 1024];
  4618. memset(buffer, 0x42, sizeof(buffer));
  4619. auto res = cli_.Post(
  4620. "/slowpost", 64 * 1024 * 1024,
  4621. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4622. auto ret = sink.write(buffer, sizeof(buffer));
  4623. EXPECT_TRUE(ret);
  4624. return true;
  4625. },
  4626. "text/plain");
  4627. ASSERT_TRUE(res);
  4628. EXPECT_EQ(StatusCode::OK_200, res->status);
  4629. }
  4630. TEST_F(ServerTest, SlowPostFail) {
  4631. char buffer[64 * 1024];
  4632. memset(buffer, 0x42, sizeof(buffer));
  4633. cli_.set_write_timeout(std::chrono::seconds(0));
  4634. auto res = cli_.Post(
  4635. "/slowpost", 64 * 1024 * 1024,
  4636. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4637. sink.write(buffer, sizeof(buffer));
  4638. return true;
  4639. },
  4640. "text/plain");
  4641. ASSERT_TRUE(!res);
  4642. EXPECT_EQ(Error::Write, res.error());
  4643. }
  4644. #endif
  4645. TEST_F(ServerTest, Put) {
  4646. auto res = cli_.Put("/put", "PUT", "text/plain");
  4647. ASSERT_TRUE(res);
  4648. EXPECT_EQ(StatusCode::OK_200, res->status);
  4649. EXPECT_EQ("PUT", res->body);
  4650. }
  4651. TEST_F(ServerTest, PutWithContentProvider) {
  4652. auto res = cli_.Put(
  4653. "/put", 3,
  4654. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4655. sink.os << "PUT";
  4656. return true;
  4657. },
  4658. "text/plain");
  4659. ASSERT_TRUE(res);
  4660. EXPECT_EQ(StatusCode::OK_200, res->status);
  4661. EXPECT_EQ("PUT", res->body);
  4662. }
  4663. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4664. auto res = cli_.Post(
  4665. "/post", 42,
  4666. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4667. return false;
  4668. },
  4669. "text/plain");
  4670. ASSERT_TRUE(!res);
  4671. EXPECT_EQ(Error::Canceled, res.error());
  4672. }
  4673. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4674. auto res = cli_.Put(
  4675. "/put",
  4676. [](size_t /*offset*/, DataSink &sink) {
  4677. sink.os << "PUT";
  4678. sink.done();
  4679. return true;
  4680. },
  4681. "text/plain");
  4682. ASSERT_TRUE(res);
  4683. EXPECT_EQ(StatusCode::OK_200, res->status);
  4684. EXPECT_EQ("PUT", res->body);
  4685. }
  4686. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4687. auto res = cli_.Post(
  4688. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4689. "text/plain");
  4690. ASSERT_TRUE(!res);
  4691. EXPECT_EQ(Error::Canceled, res.error());
  4692. }
  4693. TEST_F(ServerTest, PostLoopBack) {
  4694. std::string body;
  4695. auto res = cli_.Post(
  4696. "/post-loopback", 9,
  4697. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4698. EXPECT_EQ(9u, length);
  4699. sink.write("123", 3);
  4700. sink.write("456", 3);
  4701. sink.write("789", 3);
  4702. return true;
  4703. },
  4704. "text/plain",
  4705. [&body](const char *data, size_t data_length) {
  4706. body.append(data, data_length);
  4707. return true;
  4708. });
  4709. ASSERT_TRUE(res);
  4710. EXPECT_EQ(StatusCode::OK_200, res->status);
  4711. EXPECT_EQ("123456789", body);
  4712. }
  4713. TEST_F(ServerTest, PutLoopBack) {
  4714. std::string body;
  4715. auto res = cli_.Put(
  4716. "/put-loopback", 9,
  4717. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4718. EXPECT_EQ(9u, length);
  4719. sink.write("123", 3);
  4720. sink.write("456", 3);
  4721. sink.write("789", 3);
  4722. return true;
  4723. },
  4724. "text/plain",
  4725. [&body](const char *data, size_t data_length) {
  4726. body.append(data, data_length);
  4727. return true;
  4728. });
  4729. ASSERT_TRUE(res);
  4730. EXPECT_EQ(StatusCode::OK_200, res->status);
  4731. EXPECT_EQ("123456789", body);
  4732. }
  4733. TEST_F(ServerTest, PatchLoopBack) {
  4734. std::string body;
  4735. auto res = cli_.Patch(
  4736. "/patch-loopback", 9,
  4737. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4738. EXPECT_EQ(9u, length);
  4739. sink.write("123", 3);
  4740. sink.write("456", 3);
  4741. sink.write("789", 3);
  4742. return true;
  4743. },
  4744. "text/plain",
  4745. [&body](const char *data, size_t data_length) {
  4746. body.append(data, data_length);
  4747. return true;
  4748. });
  4749. ASSERT_TRUE(res);
  4750. EXPECT_EQ(StatusCode::OK_200, res->status);
  4751. EXPECT_EQ("123456789", body);
  4752. }
  4753. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4754. std::string body;
  4755. auto res = cli_.Post(
  4756. "/post-loopback",
  4757. [](size_t /*offset*/, DataSink &sink) {
  4758. sink.write("123", 3);
  4759. sink.write("456", 3);
  4760. sink.write("789", 3);
  4761. sink.done();
  4762. return true;
  4763. },
  4764. "text/plain",
  4765. [&body](const char *data, size_t data_length) {
  4766. body.append(data, data_length);
  4767. return true;
  4768. });
  4769. ASSERT_TRUE(res);
  4770. EXPECT_EQ(StatusCode::OK_200, res->status);
  4771. EXPECT_EQ("123456789", body);
  4772. }
  4773. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4774. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4775. cli_.set_compress(true);
  4776. auto res = cli_.Put(
  4777. "/put", 3,
  4778. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4779. sink.os << "PUT";
  4780. return true;
  4781. },
  4782. "text/plain");
  4783. ASSERT_TRUE(res);
  4784. EXPECT_EQ(StatusCode::OK_200, res->status);
  4785. EXPECT_EQ("PUT", res->body);
  4786. }
  4787. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4788. cli_.set_compress(true);
  4789. auto res = cli_.Post(
  4790. "/post", 42,
  4791. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4792. return false;
  4793. },
  4794. "text/plain");
  4795. ASSERT_TRUE(!res);
  4796. EXPECT_EQ(Error::Canceled, res.error());
  4797. }
  4798. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4799. cli_.set_compress(true);
  4800. auto res = cli_.Put(
  4801. "/put",
  4802. [](size_t /*offset*/, DataSink &sink) {
  4803. sink.os << "PUT";
  4804. sink.done();
  4805. return true;
  4806. },
  4807. "text/plain");
  4808. ASSERT_TRUE(res);
  4809. EXPECT_EQ(StatusCode::OK_200, res->status);
  4810. EXPECT_EQ("PUT", res->body);
  4811. }
  4812. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4813. cli_.set_compress(true);
  4814. auto res = cli_.Post(
  4815. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4816. "text/plain");
  4817. ASSERT_TRUE(!res);
  4818. EXPECT_EQ(Error::Canceled, res.error());
  4819. }
  4820. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4821. cli_.set_compress(true);
  4822. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4823. ASSERT_TRUE(res);
  4824. EXPECT_EQ(StatusCode::OK_200, res->status);
  4825. EXPECT_EQ(LARGE_DATA, res->body);
  4826. }
  4827. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4828. #ifdef CPPHTTPLIB_SSL_ENABLED
  4829. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4830. Client cli(s.c_str());
  4831. cli.enable_server_certificate_verification(false);
  4832. #else
  4833. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4834. Client cli(s.c_str());
  4835. #endif
  4836. cli.set_compress(true);
  4837. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4838. ASSERT_TRUE(res);
  4839. EXPECT_EQ(StatusCode::OK_200, res->status);
  4840. EXPECT_EQ(LARGE_DATA, res->body);
  4841. // The compressed size should be less than a 10th of the original. May vary
  4842. // depending on the zlib library.
  4843. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4844. static_cast<uint64_t>(10 * 1024 * 1024));
  4845. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4846. }
  4847. TEST_F(ServerTest, PutContentWithDeflate) {
  4848. cli_.set_compress(false);
  4849. Headers headers;
  4850. headers.emplace("Content-Encoding", "deflate");
  4851. // PUT in deflate format:
  4852. auto res = cli_.Put("/put", headers,
  4853. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4854. ASSERT_TRUE(res);
  4855. EXPECT_EQ(StatusCode::OK_200, res->status);
  4856. EXPECT_EQ("PUT", res->body);
  4857. }
  4858. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4859. Headers headers;
  4860. headers.emplace("Accept-Encoding", "gzip, deflate");
  4861. auto res = cli_.Get("/streamed-chunked", headers);
  4862. ASSERT_TRUE(res);
  4863. EXPECT_EQ(StatusCode::OK_200, res->status);
  4864. EXPECT_EQ(std::string("123456789"), res->body);
  4865. }
  4866. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4867. Headers headers;
  4868. headers.emplace("Accept-Encoding", "gzip, deflate");
  4869. auto res = cli_.Get("/streamed-chunked2", headers);
  4870. ASSERT_TRUE(res);
  4871. EXPECT_EQ(StatusCode::OK_200, res->status);
  4872. EXPECT_EQ(std::string("123456789"), res->body);
  4873. }
  4874. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4875. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4876. ASSERT_TRUE(res);
  4877. EXPECT_EQ(StatusCode::OK_200, res->status);
  4878. }
  4879. TEST(GzipDecompressor, ChunkedDecompression) {
  4880. std::string data;
  4881. for (size_t i = 0; i < 32 * 1024; ++i) {
  4882. data.push_back(static_cast<char>('a' + i % 26));
  4883. }
  4884. std::string compressed_data;
  4885. {
  4886. httplib::detail::gzip_compressor compressor;
  4887. bool result = compressor.compress(
  4888. data.data(), data.size(),
  4889. /*last=*/true,
  4890. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4891. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4892. compressed_data_size);
  4893. return true;
  4894. });
  4895. ASSERT_TRUE(result);
  4896. }
  4897. std::string decompressed_data;
  4898. {
  4899. httplib::detail::gzip_decompressor decompressor;
  4900. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4901. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4902. size_t chunk_size = 130;
  4903. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4904. chunk_begin += chunk_size) {
  4905. size_t current_chunk_size =
  4906. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4907. bool result = decompressor.decompress(
  4908. compressed_data.data() + chunk_begin, current_chunk_size,
  4909. [&](const char *decompressed_data_chunk,
  4910. size_t decompressed_data_chunk_size) {
  4911. decompressed_data.insert(decompressed_data.size(),
  4912. decompressed_data_chunk,
  4913. decompressed_data_chunk_size);
  4914. return true;
  4915. });
  4916. ASSERT_TRUE(result);
  4917. }
  4918. }
  4919. ASSERT_EQ(data, decompressed_data);
  4920. }
  4921. TEST(GzipDecompressor, DeflateDecompression) {
  4922. std::string original_text = "Raw deflate without gzip";
  4923. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4924. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4925. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4926. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4927. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4928. std::string decompressed_data;
  4929. {
  4930. httplib::detail::gzip_decompressor decompressor;
  4931. bool result = decompressor.decompress(
  4932. compressed_data.data(), compressed_data.size(),
  4933. [&](const char *decompressed_data_chunk,
  4934. size_t decompressed_data_chunk_size) {
  4935. decompressed_data.insert(decompressed_data.size(),
  4936. decompressed_data_chunk,
  4937. decompressed_data_chunk_size);
  4938. return true;
  4939. });
  4940. ASSERT_TRUE(result);
  4941. }
  4942. ASSERT_EQ(original_text, decompressed_data);
  4943. }
  4944. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4945. std::string original_text = "Raw deflate without gzip";
  4946. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4947. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4948. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4949. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4950. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4951. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4952. std::string decompressed_data;
  4953. {
  4954. httplib::detail::gzip_decompressor decompressor;
  4955. bool result = decompressor.decompress(
  4956. compressed_data.data(), compressed_data.size(),
  4957. [&](const char *decompressed_data_chunk,
  4958. size_t decompressed_data_chunk_size) {
  4959. decompressed_data.insert(decompressed_data.size(),
  4960. decompressed_data_chunk,
  4961. decompressed_data_chunk_size);
  4962. return true;
  4963. });
  4964. ASSERT_TRUE(result);
  4965. }
  4966. ASSERT_EQ(original_text, decompressed_data);
  4967. }
  4968. #ifdef _WIN32
  4969. TEST(GzipDecompressor, LargeRandomData) {
  4970. // prepare large random data that is difficult to be compressed and is
  4971. // expected to have large size even when compressed
  4972. std::random_device seed_gen;
  4973. std::mt19937 random(seed_gen());
  4974. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4975. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4976. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4977. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4978. // compress data over 4GiB
  4979. std::string compressed_data;
  4980. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4981. httplib::detail::gzip_compressor compressor;
  4982. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4983. data.size() * sizeof(std::uint32_t), true,
  4984. [&](const char *data, size_t size) {
  4985. compressed_data.insert(
  4986. compressed_data.size(), data, size);
  4987. return true;
  4988. });
  4989. ASSERT_TRUE(result);
  4990. // FIXME: compressed data size is expected to be greater than 4GiB,
  4991. // but there is no guarantee
  4992. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4993. // decompress data over 4GiB
  4994. std::string decompressed_data;
  4995. decompressed_data.reserve(data_size);
  4996. httplib::detail::gzip_decompressor decompressor;
  4997. result = decompressor.decompress(
  4998. compressed_data.data(), compressed_data.size(),
  4999. [&](const char *data, size_t size) {
  5000. decompressed_data.insert(decompressed_data.size(), data, size);
  5001. return true;
  5002. });
  5003. ASSERT_TRUE(result);
  5004. // compare
  5005. ASSERT_EQ(data_size, decompressed_data.size());
  5006. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  5007. 0);
  5008. }
  5009. #endif
  5010. #endif
  5011. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5012. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5013. Headers headers;
  5014. headers.emplace("Accept-Encoding", "br");
  5015. auto res = cli_.Get("/streamed-chunked", headers);
  5016. ASSERT_TRUE(res);
  5017. EXPECT_EQ(StatusCode::OK_200, res->status);
  5018. EXPECT_EQ(std::string("123456789"), res->body);
  5019. }
  5020. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5021. Headers headers;
  5022. headers.emplace("Accept-Encoding", "br");
  5023. auto res = cli_.Get("/streamed-chunked2", headers);
  5024. ASSERT_TRUE(res);
  5025. EXPECT_EQ(StatusCode::OK_200, res->status);
  5026. EXPECT_EQ(std::string("123456789"), res->body);
  5027. }
  5028. #endif
  5029. TEST_F(ServerTest, Patch) {
  5030. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5031. ASSERT_TRUE(res);
  5032. EXPECT_EQ(StatusCode::OK_200, res->status);
  5033. EXPECT_EQ("PATCH", res->body);
  5034. }
  5035. TEST_F(ServerTest, Delete) {
  5036. auto res = cli_.Delete("/delete");
  5037. ASSERT_TRUE(res);
  5038. EXPECT_EQ(StatusCode::OK_200, res->status);
  5039. EXPECT_EQ("DELETE", res->body);
  5040. }
  5041. TEST_F(ServerTest, DeleteContentReceiver) {
  5042. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5043. ASSERT_TRUE(res);
  5044. EXPECT_EQ(StatusCode::OK_200, res->status);
  5045. EXPECT_EQ("content", res->body);
  5046. }
  5047. TEST_F(ServerTest, Options) {
  5048. auto res = cli_.Options("*");
  5049. ASSERT_TRUE(res);
  5050. EXPECT_EQ(StatusCode::OK_200, res->status);
  5051. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5052. EXPECT_TRUE(res->body.empty());
  5053. }
  5054. TEST_F(ServerTest, URL) {
  5055. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5056. ASSERT_TRUE(res);
  5057. EXPECT_EQ(StatusCode::OK_200, res->status);
  5058. }
  5059. TEST_F(ServerTest, ArrayParam) {
  5060. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5061. ASSERT_TRUE(res);
  5062. EXPECT_EQ(StatusCode::OK_200, res->status);
  5063. }
  5064. TEST_F(ServerTest, NoMultipleHeaders) {
  5065. Headers headers = {{"Content-Length", "5"}};
  5066. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5067. "text/plain");
  5068. ASSERT_TRUE(res);
  5069. EXPECT_EQ(StatusCode::OK_200, res->status);
  5070. }
  5071. TEST_F(ServerTest, PostContentReceiver) {
  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, PostMultipartFileContentReceiver) {
  5078. UploadFormDataItems items = {
  5079. {"text1", "text default", "", ""},
  5080. {"text2", "aωb", "", ""},
  5081. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5082. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5083. {"file3", "", "", "application/octet-stream"},
  5084. };
  5085. auto res = cli_.Post("/content_receiver", items);
  5086. ASSERT_TRUE(res);
  5087. EXPECT_EQ(StatusCode::OK_200, res->status);
  5088. }
  5089. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5090. UploadFormDataItems items = {
  5091. {"text1", "text default", "", ""},
  5092. {"text2", "aωb", "", ""},
  5093. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5094. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5095. {"file3", "", "", "application/octet-stream"},
  5096. };
  5097. auto boundary = std::string("+++++");
  5098. std::string body;
  5099. for (const auto &item : items) {
  5100. body += "--" + boundary + "\r\n";
  5101. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5102. if (!item.filename.empty()) {
  5103. body += "; filename=\"" + item.filename + "\"";
  5104. }
  5105. body += "\r\n";
  5106. if (!item.content_type.empty()) {
  5107. body += "Content-Type: " + item.content_type + "\r\n";
  5108. }
  5109. body += "\r\n";
  5110. body += item.content + "\r\n";
  5111. }
  5112. body += "--" + boundary + "--\r\n";
  5113. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5114. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5115. ASSERT_TRUE(res);
  5116. EXPECT_EQ(StatusCode::OK_200, res->status);
  5117. }
  5118. TEST_F(ServerTest, PostContentReceiverGzip) {
  5119. cli_.set_compress(true);
  5120. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5121. ASSERT_TRUE(res);
  5122. ASSERT_EQ(StatusCode::OK_200, res->status);
  5123. ASSERT_EQ("content", res->body);
  5124. }
  5125. TEST_F(ServerTest, PutContentReceiver) {
  5126. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5127. ASSERT_TRUE(res);
  5128. ASSERT_EQ(StatusCode::OK_200, res->status);
  5129. ASSERT_EQ("content", res->body);
  5130. }
  5131. TEST_F(ServerTest, PatchContentReceiver) {
  5132. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5133. ASSERT_TRUE(res);
  5134. ASSERT_EQ(StatusCode::OK_200, res->status);
  5135. ASSERT_EQ("content", res->body);
  5136. }
  5137. template <typename ClientType>
  5138. void TestWithHeadersAndContentReceiver(
  5139. ClientType &cli,
  5140. std::function<Result(ClientType &, const std::string &, const Headers &,
  5141. const std::string &, const std::string &,
  5142. ContentReceiver, DownloadProgress)>
  5143. request_func) {
  5144. Headers headers;
  5145. headers.emplace("X-Custom-Header", "test-value");
  5146. std::string received_body;
  5147. auto res = request_func(
  5148. cli, "/content_receiver", headers, "content", "application/json",
  5149. [&](const char *data, size_t data_length) {
  5150. received_body.append(data, data_length);
  5151. return true;
  5152. },
  5153. nullptr);
  5154. ASSERT_TRUE(res);
  5155. EXPECT_EQ(StatusCode::OK_200, res->status);
  5156. EXPECT_EQ("content", received_body);
  5157. }
  5158. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5159. #ifdef CPPHTTPLIB_SSL_ENABLED
  5160. using ClientT = SSLClient;
  5161. #else
  5162. using ClientT = Client;
  5163. #endif
  5164. TestWithHeadersAndContentReceiver<ClientT>(
  5165. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5166. const std::string &body, const std::string &content_type,
  5167. ContentReceiver receiver, DownloadProgress progress) {
  5168. return cli.Post(path, headers, body, content_type, receiver, progress);
  5169. });
  5170. }
  5171. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5172. #ifdef CPPHTTPLIB_SSL_ENABLED
  5173. using ClientT = SSLClient;
  5174. #else
  5175. using ClientT = Client;
  5176. #endif
  5177. TestWithHeadersAndContentReceiver<ClientT>(
  5178. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5179. const std::string &body, const std::string &content_type,
  5180. ContentReceiver receiver, DownloadProgress progress) {
  5181. return cli.Put(path, headers, body, content_type, receiver, progress);
  5182. });
  5183. }
  5184. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5185. #ifdef CPPHTTPLIB_SSL_ENABLED
  5186. using ClientT = SSLClient;
  5187. #else
  5188. using ClientT = Client;
  5189. #endif
  5190. TestWithHeadersAndContentReceiver<ClientT>(
  5191. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5192. const std::string &body, const std::string &content_type,
  5193. ContentReceiver receiver, DownloadProgress progress) {
  5194. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5195. });
  5196. }
  5197. template <typename ClientType>
  5198. void TestWithHeadersAndContentReceiverWithProgress(
  5199. ClientType &cli,
  5200. std::function<Result(ClientType &, const std::string &, const Headers &,
  5201. const std::string &, const std::string &,
  5202. ContentReceiver, DownloadProgress)>
  5203. request_func) {
  5204. Headers headers;
  5205. headers.emplace("X-Test-Header", "progress-test");
  5206. std::string received_body;
  5207. auto progress_called = false;
  5208. auto res = request_func(
  5209. cli, "/content_receiver", headers, "content", "text/plain",
  5210. [&](const char *data, size_t data_length) {
  5211. received_body.append(data, data_length);
  5212. return true;
  5213. },
  5214. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5215. progress_called = true;
  5216. return true;
  5217. });
  5218. ASSERT_TRUE(res);
  5219. EXPECT_EQ(StatusCode::OK_200, res->status);
  5220. EXPECT_EQ("content", received_body);
  5221. EXPECT_TRUE(progress_called);
  5222. }
  5223. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5224. #ifdef CPPHTTPLIB_SSL_ENABLED
  5225. using ClientT = SSLClient;
  5226. #else
  5227. using ClientT = Client;
  5228. #endif
  5229. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5230. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5231. const std::string &body, const std::string &content_type,
  5232. ContentReceiver receiver, DownloadProgress progress) {
  5233. return cli.Post(path, headers, body, content_type, receiver, progress);
  5234. });
  5235. }
  5236. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5237. #ifdef CPPHTTPLIB_SSL_ENABLED
  5238. using ClientT = SSLClient;
  5239. #else
  5240. using ClientT = Client;
  5241. #endif
  5242. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5243. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5244. const std::string &body, const std::string &content_type,
  5245. ContentReceiver receiver, DownloadProgress progress) {
  5246. return cli.Put(path, headers, body, content_type, receiver, progress);
  5247. });
  5248. }
  5249. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5250. #ifdef CPPHTTPLIB_SSL_ENABLED
  5251. using ClientT = SSLClient;
  5252. #else
  5253. using ClientT = Client;
  5254. #endif
  5255. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5256. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5257. const std::string &body, const std::string &content_type,
  5258. ContentReceiver receiver, DownloadProgress progress) {
  5259. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5260. });
  5261. }
  5262. template <typename ClientType>
  5263. void TestWithHeadersAndContentReceiverError(
  5264. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5265. const Headers &, const std::string &,
  5266. const std::string &, ContentReceiver)>
  5267. request_func) {
  5268. Headers headers;
  5269. headers.emplace("X-Error-Test", "true");
  5270. std::string received_body;
  5271. auto receiver_failed = false;
  5272. auto res =
  5273. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5274. [&](const char *data, size_t data_length) {
  5275. received_body.append(data, data_length);
  5276. receiver_failed = true;
  5277. return false;
  5278. });
  5279. ASSERT_FALSE(res);
  5280. EXPECT_TRUE(receiver_failed);
  5281. }
  5282. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5283. #ifdef CPPHTTPLIB_SSL_ENABLED
  5284. using ClientT = SSLClient;
  5285. #else
  5286. using ClientT = Client;
  5287. #endif
  5288. TestWithHeadersAndContentReceiverError<ClientT>(
  5289. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5290. const std::string &body, const std::string &content_type,
  5291. ContentReceiver receiver) {
  5292. return cli.Post(path, headers, body, content_type, receiver);
  5293. });
  5294. }
  5295. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5296. #ifdef CPPHTTPLIB_SSL_ENABLED
  5297. using ClientT = SSLClient;
  5298. #else
  5299. using ClientT = Client;
  5300. #endif
  5301. TestWithHeadersAndContentReceiverError<ClientT>(
  5302. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5303. const std::string &body, const std::string &content_type,
  5304. ContentReceiver receiver) {
  5305. return cli.Put(path, headers, body, content_type, receiver);
  5306. });
  5307. }
  5308. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5309. #ifdef CPPHTTPLIB_SSL_ENABLED
  5310. using ClientT = SSLClient;
  5311. #else
  5312. using ClientT = Client;
  5313. #endif
  5314. TestWithHeadersAndContentReceiverError<ClientT>(
  5315. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5316. const std::string &body, const std::string &content_type,
  5317. ContentReceiver receiver) {
  5318. return cli.Patch(path, headers, body, content_type, receiver);
  5319. });
  5320. }
  5321. TEST_F(ServerTest, PostQueryStringAndBody) {
  5322. auto res =
  5323. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5324. ASSERT_TRUE(res);
  5325. ASSERT_EQ(StatusCode::OK_200, res->status);
  5326. }
  5327. TEST_F(ServerTest, HTTP2Magic) {
  5328. Request req;
  5329. req.method = "PRI";
  5330. req.path = "*";
  5331. req.body = "SM";
  5332. auto res = std::make_shared<Response>();
  5333. auto error = Error::Success;
  5334. auto ret = cli_.send(req, *res, error);
  5335. ASSERT_TRUE(ret);
  5336. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5337. }
  5338. TEST_F(ServerTest, KeepAlive) {
  5339. auto res = cli_.Get("/hi");
  5340. ASSERT_TRUE(res);
  5341. EXPECT_EQ(StatusCode::OK_200, res->status);
  5342. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5343. EXPECT_EQ("Hello World!", res->body);
  5344. res = cli_.Get("/hi");
  5345. ASSERT_TRUE(res);
  5346. EXPECT_EQ(StatusCode::OK_200, res->status);
  5347. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5348. EXPECT_EQ("Hello World!", res->body);
  5349. res = cli_.Get("/hi");
  5350. ASSERT_TRUE(res);
  5351. EXPECT_EQ(StatusCode::OK_200, res->status);
  5352. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5353. EXPECT_EQ("Hello World!", res->body);
  5354. res = cli_.Get("/not-exist");
  5355. ASSERT_TRUE(res);
  5356. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5357. res = cli_.Post("/empty", "", "text/plain");
  5358. ASSERT_TRUE(res);
  5359. EXPECT_EQ(StatusCode::OK_200, res->status);
  5360. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5361. EXPECT_EQ("empty", res->body);
  5362. EXPECT_EQ("close", res->get_header_value("Connection"));
  5363. res = cli_.Post(
  5364. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5365. "text/plain");
  5366. ASSERT_TRUE(res);
  5367. EXPECT_EQ(StatusCode::OK_200, res->status);
  5368. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5369. EXPECT_EQ("empty", res->body);
  5370. cli_.set_keep_alive(false);
  5371. res = cli_.Get("/last-request");
  5372. ASSERT_TRUE(res);
  5373. EXPECT_EQ(StatusCode::OK_200, res->status);
  5374. EXPECT_EQ("close", res->get_header_value("Connection"));
  5375. }
  5376. TEST_F(ServerTest, TooManyRedirect) {
  5377. cli_.set_follow_location(true);
  5378. auto res = cli_.Get("/redirect/0");
  5379. ASSERT_TRUE(!res);
  5380. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5381. }
  5382. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5383. Request req;
  5384. req.method = "FOOBAR";
  5385. req.path = "/hi";
  5386. cli_.set_keep_alive(true);
  5387. auto res = cli_.send(req);
  5388. ASSERT_TRUE(res);
  5389. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5390. EXPECT_EQ("close", res->get_header_value("Connection"));
  5391. EXPECT_FALSE(cli_.is_socket_open());
  5392. }
  5393. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5394. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5395. TEST_F(ServerTest, Gzip) {
  5396. Headers headers;
  5397. headers.emplace("Accept-Encoding", "gzip, deflate");
  5398. auto res = cli_.Get("/compress", headers);
  5399. ASSERT_TRUE(res);
  5400. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5401. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5402. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5403. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5404. "7890123456789012345678901234567890",
  5405. res->body);
  5406. EXPECT_EQ(StatusCode::OK_200, res->status);
  5407. }
  5408. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5409. Headers headers;
  5410. headers.emplace("Accept-Encoding", "gzip, deflate");
  5411. auto res = cli_.Get("/compress-with-charset", headers);
  5412. ASSERT_TRUE(res);
  5413. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5414. EXPECT_EQ("application/json; charset=utf-8",
  5415. res->get_header_value("Content-Type"));
  5416. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5417. "7890123456789012345678901234567890",
  5418. res->body);
  5419. EXPECT_EQ(StatusCode::OK_200, res->status);
  5420. }
  5421. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5422. Headers headers;
  5423. headers.emplace("Accept-Encoding", "");
  5424. auto res = cli_.Get("/compress", headers);
  5425. ASSERT_TRUE(res);
  5426. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5427. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5428. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5429. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5430. "7890123456789012345678901234567890",
  5431. res->body);
  5432. EXPECT_EQ(StatusCode::OK_200, res->status);
  5433. }
  5434. TEST_F(ServerTest, GzipWithContentReceiver) {
  5435. Headers headers;
  5436. headers.emplace("Accept-Encoding", "gzip, deflate");
  5437. std::string body;
  5438. auto res = cli_.Get("/compress", headers,
  5439. [&](const char *data, uint64_t data_length) {
  5440. EXPECT_EQ(100U, data_length);
  5441. body.append(data, data_length);
  5442. return true;
  5443. });
  5444. ASSERT_TRUE(res);
  5445. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5446. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5447. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5448. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5449. "7890123456789012345678901234567890",
  5450. body);
  5451. EXPECT_EQ(StatusCode::OK_200, res->status);
  5452. }
  5453. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5454. Headers headers;
  5455. headers.emplace("Accept-Encoding", "gzip, deflate");
  5456. cli_.set_decompress(false);
  5457. auto res = cli_.Get("/compress", headers);
  5458. ASSERT_TRUE(res);
  5459. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5460. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5461. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5462. EXPECT_EQ(33U, res->body.size());
  5463. EXPECT_EQ(StatusCode::OK_200, res->status);
  5464. }
  5465. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5466. Headers headers;
  5467. headers.emplace("Accept-Encoding", "");
  5468. std::string body;
  5469. auto res = cli_.Get("/compress", headers,
  5470. [&](const char *data, uint64_t data_length) {
  5471. EXPECT_EQ(100U, data_length);
  5472. body.append(data, data_length);
  5473. return true;
  5474. });
  5475. ASSERT_TRUE(res);
  5476. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5477. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5478. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5479. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5480. "7890123456789012345678901234567890",
  5481. body);
  5482. EXPECT_EQ(StatusCode::OK_200, res->status);
  5483. }
  5484. TEST_F(ServerTest, NoGzip) {
  5485. Headers headers;
  5486. headers.emplace("Accept-Encoding", "gzip, deflate");
  5487. auto res = cli_.Get("/nocompress", headers);
  5488. ASSERT_TRUE(res);
  5489. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5490. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5491. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5492. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5493. "7890123456789012345678901234567890",
  5494. res->body);
  5495. EXPECT_EQ(StatusCode::OK_200, res->status);
  5496. }
  5497. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5498. Headers headers;
  5499. headers.emplace("Accept-Encoding", "gzip, deflate");
  5500. std::string body;
  5501. auto res = cli_.Get("/nocompress", headers,
  5502. [&](const char *data, uint64_t data_length) {
  5503. EXPECT_EQ(100U, data_length);
  5504. body.append(data, data_length);
  5505. return true;
  5506. });
  5507. ASSERT_TRUE(res);
  5508. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5509. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5510. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5511. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5512. "7890123456789012345678901234567890",
  5513. body);
  5514. EXPECT_EQ(StatusCode::OK_200, res->status);
  5515. }
  5516. TEST_F(ServerTest, MultipartFormDataGzip) {
  5517. UploadFormDataItems items = {
  5518. {"key1", "test", "", ""},
  5519. {"key2", "--abcdefg123", "", ""},
  5520. };
  5521. cli_.set_compress(true);
  5522. auto res = cli_.Post("/compress-multipart", items);
  5523. ASSERT_TRUE(res);
  5524. EXPECT_EQ(StatusCode::OK_200, res->status);
  5525. }
  5526. #endif
  5527. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5528. TEST_F(ServerTest, Brotli) {
  5529. Headers headers;
  5530. headers.emplace("Accept-Encoding", "br");
  5531. auto res = cli_.Get("/compress", headers);
  5532. ASSERT_TRUE(res);
  5533. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5534. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5535. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5536. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5537. "7890123456789012345678901234567890",
  5538. res->body);
  5539. EXPECT_EQ(StatusCode::OK_200, res->status);
  5540. }
  5541. #endif
  5542. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5543. TEST_F(ServerTest, Zstd) {
  5544. Headers headers;
  5545. headers.emplace("Accept-Encoding", "zstd");
  5546. auto res = cli_.Get("/compress", headers);
  5547. ASSERT_TRUE(res);
  5548. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5549. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5550. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5551. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5552. "7890123456789012345678901234567890",
  5553. res->body);
  5554. EXPECT_EQ(StatusCode::OK_200, res->status);
  5555. }
  5556. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5557. Headers headers;
  5558. headers.emplace("Accept-Encoding", "");
  5559. auto res = cli_.Get("/compress", headers);
  5560. ASSERT_TRUE(res);
  5561. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5562. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5563. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5564. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5565. "7890123456789012345678901234567890",
  5566. res->body);
  5567. EXPECT_EQ(StatusCode::OK_200, res->status);
  5568. }
  5569. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5570. Headers headers;
  5571. headers.emplace("Accept-Encoding", "zstd");
  5572. std::string body;
  5573. auto res = cli_.Get("/compress", headers,
  5574. [&](const char *data, uint64_t data_length) {
  5575. EXPECT_EQ(100U, data_length);
  5576. body.append(data, data_length);
  5577. return true;
  5578. });
  5579. ASSERT_TRUE(res);
  5580. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5581. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5582. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5583. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5584. "7890123456789012345678901234567890",
  5585. body);
  5586. EXPECT_EQ(StatusCode::OK_200, res->status);
  5587. }
  5588. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5589. Headers headers;
  5590. headers.emplace("Accept-Encoding", "zstd");
  5591. cli_.set_decompress(false);
  5592. auto res = cli_.Get("/compress", headers);
  5593. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5594. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5595. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5596. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5597. ASSERT_TRUE(res);
  5598. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5599. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5600. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5601. EXPECT_EQ(StatusCode::OK_200, res->status);
  5602. ASSERT_EQ(26U, res->body.size());
  5603. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5604. 0);
  5605. }
  5606. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5607. Headers headers;
  5608. headers.emplace("Accept-Encoding", "");
  5609. std::string body;
  5610. auto res = cli_.Get("/compress", headers,
  5611. [&](const char *data, uint64_t data_length) {
  5612. EXPECT_EQ(100U, data_length);
  5613. body.append(data, data_length);
  5614. return true;
  5615. });
  5616. ASSERT_TRUE(res);
  5617. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5618. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5619. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5620. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5621. "7890123456789012345678901234567890",
  5622. body);
  5623. EXPECT_EQ(StatusCode::OK_200, res->status);
  5624. }
  5625. TEST_F(ServerTest, NoZstd) {
  5626. Headers headers;
  5627. headers.emplace("Accept-Encoding", "zstd");
  5628. auto res = cli_.Get("/nocompress", headers);
  5629. ASSERT_TRUE(res);
  5630. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5631. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5632. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5633. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5634. "7890123456789012345678901234567890",
  5635. res->body);
  5636. EXPECT_EQ(StatusCode::OK_200, res->status);
  5637. }
  5638. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5639. Headers headers;
  5640. headers.emplace("Accept-Encoding", "zstd");
  5641. std::string body;
  5642. auto res = cli_.Get("/nocompress", headers,
  5643. [&](const char *data, uint64_t data_length) {
  5644. EXPECT_EQ(100U, data_length);
  5645. body.append(data, data_length);
  5646. return true;
  5647. });
  5648. ASSERT_TRUE(res);
  5649. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5650. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5651. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5652. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5653. "7890123456789012345678901234567890",
  5654. body);
  5655. EXPECT_EQ(StatusCode::OK_200, res->status);
  5656. }
  5657. // TODO: How to enable zstd ??
  5658. TEST_F(ServerTest, MultipartFormDataZstd) {
  5659. UploadFormDataItems items = {
  5660. {"key1", "test", "", ""},
  5661. {"key2", "--abcdefg123", "", ""},
  5662. };
  5663. Headers headers;
  5664. headers.emplace("Accept-Encoding", "zstd");
  5665. cli_.set_compress(true);
  5666. auto res = cli_.Post("/compress-multipart", headers, items);
  5667. ASSERT_TRUE(res);
  5668. EXPECT_EQ(StatusCode::OK_200, res->status);
  5669. }
  5670. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5671. Headers headers;
  5672. headers.emplace("Accept-Encoding", "zstd");
  5673. cli_.set_compress(true);
  5674. auto res = cli_.Put(
  5675. "/put", headers, 3,
  5676. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5677. sink.os << "PUT";
  5678. return true;
  5679. },
  5680. "text/plain");
  5681. ASSERT_TRUE(res);
  5682. EXPECT_EQ(StatusCode::OK_200, res->status);
  5683. EXPECT_EQ("PUT", res->body);
  5684. }
  5685. // Pre-compression logging tests
  5686. TEST_F(ServerTest, PreCompressionLogging) {
  5687. // Test data for compression (matches the actual /compress endpoint content)
  5688. const std::string test_content =
  5689. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5690. "3456789012345678901234567890";
  5691. // Variables to capture logging data
  5692. std::string pre_compression_body;
  5693. std::string pre_compression_content_type;
  5694. std::string pre_compression_content_encoding;
  5695. std::string post_compression_body;
  5696. std::string post_compression_content_type;
  5697. std::string post_compression_content_encoding;
  5698. // Set up pre-compression logger
  5699. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5700. const Response &res) {
  5701. pre_compression_body = res.body;
  5702. pre_compression_content_type = res.get_header_value("Content-Type");
  5703. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5704. });
  5705. // Set up post-compression logger
  5706. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5707. post_compression_body = res.body;
  5708. post_compression_content_type = res.get_header_value("Content-Type");
  5709. post_compression_content_encoding =
  5710. res.get_header_value("Content-Encoding");
  5711. });
  5712. // Test with gzip compression
  5713. Headers headers;
  5714. headers.emplace("Accept-Encoding", "gzip");
  5715. auto res = cli_.Get("/compress", headers);
  5716. // Verify response was compressed
  5717. ASSERT_TRUE(res);
  5718. EXPECT_EQ(StatusCode::OK_200, res->status);
  5719. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5720. // Verify pre-compression logger captured uncompressed content
  5721. EXPECT_EQ(test_content, pre_compression_body);
  5722. EXPECT_EQ("text/plain", pre_compression_content_type);
  5723. EXPECT_TRUE(pre_compression_content_encoding
  5724. .empty()); // No encoding header before compression
  5725. // Verify post-compression logger captured compressed content
  5726. EXPECT_NE(test_content,
  5727. post_compression_body); // Should be different after compression
  5728. EXPECT_EQ("text/plain", post_compression_content_type);
  5729. EXPECT_EQ("gzip", post_compression_content_encoding);
  5730. // Verify compressed content is smaller
  5731. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5732. }
  5733. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5734. const std::string test_content =
  5735. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5736. "3456789012345678901234567890";
  5737. std::string pre_compression_body;
  5738. std::string post_compression_body;
  5739. svr_.set_pre_compression_logger(
  5740. [&](const Request & /*req*/, const Response &res) {
  5741. pre_compression_body = res.body;
  5742. });
  5743. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5744. post_compression_body = res.body;
  5745. });
  5746. Headers headers;
  5747. headers.emplace("Accept-Encoding", "br");
  5748. auto res = cli_.Get("/compress", headers);
  5749. ASSERT_TRUE(res);
  5750. EXPECT_EQ(StatusCode::OK_200, res->status);
  5751. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5752. // Verify pre-compression content is uncompressed
  5753. EXPECT_EQ(test_content, pre_compression_body);
  5754. // Verify post-compression content is compressed
  5755. EXPECT_NE(test_content, post_compression_body);
  5756. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5757. }
  5758. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5759. const std::string test_content =
  5760. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5761. "3456789012345678901234567890";
  5762. std::string pre_compression_body;
  5763. std::string post_compression_body;
  5764. svr_.set_pre_compression_logger(
  5765. [&](const Request & /*req*/, const Response &res) {
  5766. pre_compression_body = res.body;
  5767. });
  5768. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5769. post_compression_body = res.body;
  5770. });
  5771. // Request without compression (use /nocompress endpoint)
  5772. Headers headers;
  5773. auto res = cli_.Get("/nocompress", headers);
  5774. ASSERT_TRUE(res);
  5775. EXPECT_EQ(StatusCode::OK_200, res->status);
  5776. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5777. // Pre-compression logger should not be called when no compression is applied
  5778. EXPECT_TRUE(
  5779. pre_compression_body.empty()); // Pre-compression logger not called
  5780. EXPECT_EQ(
  5781. test_content,
  5782. post_compression_body); // Post-compression logger captures final content
  5783. }
  5784. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5785. const std::string test_content =
  5786. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5787. "3456789012345678901234567890";
  5788. std::string pre_compression_body;
  5789. bool pre_logger_called = false;
  5790. // Set only pre-compression logger
  5791. svr_.set_pre_compression_logger(
  5792. [&](const Request & /*req*/, const Response &res) {
  5793. pre_compression_body = res.body;
  5794. pre_logger_called = true;
  5795. });
  5796. Headers headers;
  5797. headers.emplace("Accept-Encoding", "gzip");
  5798. auto res = cli_.Get("/compress", headers);
  5799. ASSERT_TRUE(res);
  5800. EXPECT_EQ(StatusCode::OK_200, res->status);
  5801. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5802. // Verify pre-compression logger was called
  5803. EXPECT_TRUE(pre_logger_called);
  5804. EXPECT_EQ(test_content, pre_compression_body);
  5805. }
  5806. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5807. {
  5808. // Test with Expect: 100-continue header - success case
  5809. // Server returns 100 Continue, client sends body, server returns 200 OK
  5810. Request req;
  5811. req.method = "POST";
  5812. req.path = "/post-large";
  5813. req.set_header("Expect", "100-continue");
  5814. req.body = LARGE_DATA;
  5815. Response res;
  5816. auto error = Error::Success;
  5817. cli_.set_keep_alive(true);
  5818. auto ret = cli_.send(req, res, error);
  5819. EXPECT_TRUE(ret);
  5820. EXPECT_EQ(StatusCode::OK_200, res.status);
  5821. EXPECT_EQ(LARGE_DATA, res.body);
  5822. }
  5823. {
  5824. // Test with Expect: 100-continue header - error case
  5825. // Client should not send the body when server returns an error
  5826. Request req;
  5827. req.method = "POST";
  5828. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5829. req.set_header("Expect", "100-continue");
  5830. req.body = LARGE_DATA;
  5831. Response res;
  5832. auto error = Error::Success;
  5833. auto start = std::chrono::high_resolution_clock::now();
  5834. cli_.set_keep_alive(true);
  5835. auto ret = cli_.send(req, res, error);
  5836. auto end = std::chrono::high_resolution_clock::now();
  5837. auto elapsed =
  5838. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5839. .count();
  5840. // With Expect: 100-continue, request completes successfully but with error
  5841. EXPECT_TRUE(ret);
  5842. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5843. EXPECT_EQ("close", res.get_header_value("Connection"));
  5844. EXPECT_FALSE(cli_.is_socket_open());
  5845. EXPECT_LE(elapsed, 200);
  5846. }
  5847. {
  5848. // Send an extra GET request to ensure error recovery without hanging
  5849. Request req;
  5850. req.method = "GET";
  5851. req.path = "/hi";
  5852. auto start = std::chrono::high_resolution_clock::now();
  5853. auto res = cli_.send(req);
  5854. auto end = std::chrono::high_resolution_clock::now();
  5855. auto elapsed =
  5856. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5857. .count();
  5858. ASSERT_TRUE(res);
  5859. EXPECT_EQ(StatusCode::OK_200, res->status);
  5860. EXPECT_EQ("Hello World!", res->body);
  5861. EXPECT_LE(elapsed, 500);
  5862. }
  5863. }
  5864. TEST(ZstdDecompressor, ChunkedDecompression) {
  5865. std::string data;
  5866. for (size_t i = 0; i < 32 * 1024; ++i) {
  5867. data.push_back(static_cast<char>('a' + i % 26));
  5868. }
  5869. std::string compressed_data;
  5870. {
  5871. httplib::detail::zstd_compressor compressor;
  5872. bool result = compressor.compress(
  5873. data.data(), data.size(),
  5874. /*last=*/true,
  5875. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5876. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5877. compressed_data_size);
  5878. return true;
  5879. });
  5880. ASSERT_TRUE(result);
  5881. }
  5882. std::string decompressed_data;
  5883. {
  5884. httplib::detail::zstd_decompressor decompressor;
  5885. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5886. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5887. size_t chunk_size = 130;
  5888. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5889. chunk_begin += chunk_size) {
  5890. size_t current_chunk_size =
  5891. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5892. bool result = decompressor.decompress(
  5893. compressed_data.data() + chunk_begin, current_chunk_size,
  5894. [&](const char *decompressed_data_chunk,
  5895. size_t decompressed_data_chunk_size) {
  5896. decompressed_data.insert(decompressed_data.size(),
  5897. decompressed_data_chunk,
  5898. decompressed_data_chunk_size);
  5899. return true;
  5900. });
  5901. ASSERT_TRUE(result);
  5902. }
  5903. }
  5904. ASSERT_EQ(data, decompressed_data);
  5905. }
  5906. TEST(ZstdDecompressor, Decompress) {
  5907. std::string original_text = "Compressed with ZSTD";
  5908. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5909. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5910. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5911. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5912. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5913. std::string decompressed_data;
  5914. {
  5915. httplib::detail::zstd_decompressor decompressor;
  5916. bool result = decompressor.decompress(
  5917. compressed_data.data(), compressed_data.size(),
  5918. [&](const char *decompressed_data_chunk,
  5919. size_t decompressed_data_chunk_size) {
  5920. decompressed_data.insert(decompressed_data.size(),
  5921. decompressed_data_chunk,
  5922. decompressed_data_chunk_size);
  5923. return true;
  5924. });
  5925. ASSERT_TRUE(result);
  5926. }
  5927. ASSERT_EQ(original_text, decompressed_data);
  5928. }
  5929. #endif
  5930. // Sends a raw request to a server listening at HOST:PORT.
  5931. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5932. std::string *resp = nullptr) {
  5933. auto error = Error::Success;
  5934. auto client_sock = detail::create_client_socket(
  5935. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5936. /*connection_timeout_sec=*/5, 0,
  5937. /*read_timeout_sec=*/5, 0,
  5938. /*write_timeout_sec=*/5, 0, std::string(), error);
  5939. if (client_sock == INVALID_SOCKET) { return false; }
  5940. auto ret = detail::process_client_socket(
  5941. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5942. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5943. if (req.size() !=
  5944. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5945. return false;
  5946. }
  5947. char buf[512];
  5948. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5949. while (line_reader.getline()) {
  5950. if (resp) { *resp += line_reader.ptr(); }
  5951. }
  5952. return true;
  5953. });
  5954. detail::close_socket(client_sock);
  5955. return ret;
  5956. }
  5957. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5958. Server svr;
  5959. std::string header_value;
  5960. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5961. header_value = req.get_header_value("foo");
  5962. res.set_content("ok", "text/plain");
  5963. });
  5964. thread t = thread([&] { svr.listen(HOST, PORT); });
  5965. auto se = detail::scope_exit([&] {
  5966. svr.stop();
  5967. t.join();
  5968. ASSERT_FALSE(svr.is_running());
  5969. });
  5970. svr.wait_until_ready();
  5971. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5972. // like characters are not treated the same - use vertical tab and escape.
  5973. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5974. "foo: \t \v bar \x1B\t \r\n"
  5975. "Connection: close\r\n"
  5976. "\r\n";
  5977. std::string res;
  5978. ASSERT_TRUE(send_request(5, req, &res));
  5979. EXPECT_EQ(header_value, "");
  5980. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5981. }
  5982. // Sends a raw request and verifies that there isn't a crash or exception.
  5983. static void test_raw_request(const std::string &req,
  5984. std::string *out = nullptr) {
  5985. Server svr;
  5986. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5987. res.set_content("ok", "text/plain");
  5988. });
  5989. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5990. res.set_content("ok", "text/plain");
  5991. });
  5992. svr.Get("/header_field_value_check",
  5993. [&](const Request & /*req*/, Response &res) {
  5994. res.set_content("ok", "text/plain");
  5995. });
  5996. // Server read timeout must be longer than the client read timeout for the
  5997. // bug to reproduce, probably to force the server to process a request
  5998. // without a trailing blank line.
  5999. const time_t client_read_timeout_sec = 1;
  6000. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  6001. bool listen_thread_ok = false;
  6002. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  6003. auto se = detail::scope_exit([&] {
  6004. svr.stop();
  6005. t.join();
  6006. ASSERT_FALSE(svr.is_running());
  6007. EXPECT_TRUE(listen_thread_ok);
  6008. });
  6009. svr.wait_until_ready();
  6010. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  6011. }
  6012. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  6013. // A certain header line causes an exception if the header property is parsed
  6014. // naively with a single regex. This occurs with libc++ but not libstdc++.
  6015. test_raw_request(
  6016. "GET /hi HTTP/1.1\r\n"
  6017. " : "
  6018. " "
  6019. " ");
  6020. }
  6021. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6022. // A certain header line causes an exception if the header property *name* is
  6023. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6024. // greedy matcher and requires backtracking when there are a lot of ":"
  6025. // characters.
  6026. // This occurs with libc++ but not libstdc++.
  6027. test_raw_request(
  6028. "GET /hi HTTP/1.1\r\n"
  6029. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6030. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6031. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6032. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6033. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6034. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6035. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6036. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6037. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6038. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6039. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6040. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6041. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6042. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6043. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6044. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6045. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6046. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6047. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6048. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6049. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6050. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6051. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6052. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6053. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6054. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6055. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6056. "&&&%%%");
  6057. }
  6058. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6059. // Make sure this doesn't crash the server.
  6060. // In a previous version of the header line regex, the "\r" rendered the line
  6061. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6062. // a new position where the leading white space ended and the field value
  6063. // began.
  6064. // The crash occurs with libc++ but not libstdc++.
  6065. test_raw_request("GET /hi HTTP/1.1\r\n"
  6066. "a:" +
  6067. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6068. "\r\n"
  6069. "\r\n");
  6070. }
  6071. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6072. std::string out;
  6073. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6074. "Content-Type: text/plain\r\n"
  6075. "Transfer-Encoding: chunked\r\n"
  6076. "\r\n"
  6077. "nothex\r\n",
  6078. &out);
  6079. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6080. }
  6081. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6082. std::string out;
  6083. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6084. "Content-Type: text/plain\r\n"
  6085. "Transfer-Encoding: chunked\r\n"
  6086. "\r\n"
  6087. "3\r\n"
  6088. "xyz\r\n"
  6089. "NaN\r\n",
  6090. &out);
  6091. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6092. }
  6093. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6094. std::string out;
  6095. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6096. "Content-Type: text/plain\r\n"
  6097. "Transfer-Encoding: chunked\r\n"
  6098. "\r\n"
  6099. // Length is too large for 64 bits.
  6100. "1ffffffffffffffff\r\n"
  6101. "xyz\r\n",
  6102. &out);
  6103. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6104. }
  6105. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6106. test_raw_request("GET /hi HTTP/1.1\r\n"
  6107. "Content-Type: text/plain\r\n\r");
  6108. }
  6109. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6110. std::string out;
  6111. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6112. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6113. }
  6114. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6115. Server svr;
  6116. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6117. EXPECT_TRUE(!req.remote_addr.empty());
  6118. });
  6119. thread t = thread([&] { svr.listen(HOST, PORT); });
  6120. auto se = detail::scope_exit([&] {
  6121. svr.stop();
  6122. t.join();
  6123. ASSERT_FALSE(svr.is_running());
  6124. });
  6125. svr.wait_until_ready();
  6126. // Send an invalid request line to trigger Bad Request
  6127. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6128. std::string out;
  6129. ASSERT_TRUE(send_request(5, bad_req, &out));
  6130. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6131. }
  6132. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6133. std::string out;
  6134. std::string request(
  6135. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6136. test_raw_request(request, &out);
  6137. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6138. }
  6139. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6140. std::string out;
  6141. std::string request(
  6142. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6143. test_raw_request(request, &out);
  6144. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6145. }
  6146. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6147. std::string out;
  6148. std::string request(
  6149. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6150. test_raw_request(request, &out);
  6151. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6152. }
  6153. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6154. std::string out;
  6155. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6156. "Test: \r\n\r\n",
  6157. &out);
  6158. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6159. }
  6160. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6161. Server svr;
  6162. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6163. res.set_header("Cache-Control", "no-cache");
  6164. res.set_chunked_content_provider(
  6165. "text/event-stream", [](size_t offset, DataSink &sink) {
  6166. std::string s = "data:";
  6167. s += std::to_string(offset);
  6168. s += "\n\n";
  6169. auto ret = sink.write(s.data(), s.size());
  6170. EXPECT_TRUE(ret);
  6171. std::this_thread::sleep_for(std::chrono::seconds(1));
  6172. return true;
  6173. });
  6174. });
  6175. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6176. svr.wait_until_ready();
  6177. Client client(HOST, PORT);
  6178. const Headers headers = {{"Accept", "text/event-stream"}};
  6179. auto get_thread = std::thread([&client, &headers]() {
  6180. auto res = client.Get(
  6181. "/events", headers,
  6182. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6183. });
  6184. auto se = detail::scope_exit([&] {
  6185. svr.stop();
  6186. get_thread.join();
  6187. listen_thread.join();
  6188. ASSERT_FALSE(svr.is_running());
  6189. });
  6190. // Give GET time to get a few messages.
  6191. std::this_thread::sleep_for(std::chrono::seconds(2));
  6192. }
  6193. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6194. httplib::Server svr;
  6195. svr.Post("/hi",
  6196. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6197. res.status = StatusCode::OK_200;
  6198. });
  6199. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6200. svr.wait_until_ready();
  6201. Client cli(HOST, PORT);
  6202. auto res = cli.Post("/hi", "data", "text/plain");
  6203. ASSERT_TRUE(res);
  6204. EXPECT_EQ(StatusCode::OK_200, res->status);
  6205. svr.stop();
  6206. thread.join();
  6207. ASSERT_FALSE(svr.is_running());
  6208. res = cli.Post("/hi", "data", "text/plain");
  6209. ASSERT_FALSE(res);
  6210. }
  6211. TEST(ServerStopTest, ListenFailure) {
  6212. Server svr;
  6213. auto t = thread([&]() {
  6214. auto ret = svr.listen("????", PORT);
  6215. EXPECT_FALSE(ret);
  6216. });
  6217. svr.wait_until_ready();
  6218. svr.stop();
  6219. t.join();
  6220. }
  6221. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6222. TEST(ServerStopTest, Decommision) {
  6223. Server svr;
  6224. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6225. for (int i = 0; i < 4; i++) {
  6226. auto is_even = !(i % 2);
  6227. std::thread t{[&] {
  6228. try {
  6229. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6230. if (is_even) {
  6231. throw std::runtime_error("Some thing that happens to go wrong.");
  6232. }
  6233. svr.listen(HOST, PORT);
  6234. } catch (...) { svr.decommission(); }
  6235. }};
  6236. svr.wait_until_ready();
  6237. // Server is up
  6238. {
  6239. Client cli(HOST, PORT);
  6240. auto res = cli.Get("/hi");
  6241. if (is_even) {
  6242. EXPECT_FALSE(res);
  6243. } else {
  6244. EXPECT_TRUE(res);
  6245. EXPECT_EQ("hi...", res->body);
  6246. }
  6247. }
  6248. svr.stop();
  6249. t.join();
  6250. // Server is down...
  6251. {
  6252. Client cli(HOST, PORT);
  6253. auto res = cli.Get("/hi");
  6254. EXPECT_FALSE(res);
  6255. }
  6256. }
  6257. }
  6258. #endif
  6259. // Helper function for string body upload progress tests
  6260. template <typename SetupHandler, typename ClientCall>
  6261. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6262. ClientCall &&client_call,
  6263. const string &body) {
  6264. Server svr;
  6265. setup_handler(svr);
  6266. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6267. auto se = detail::scope_exit([&] {
  6268. svr.stop();
  6269. t.join();
  6270. });
  6271. svr.wait_until_ready();
  6272. Client cli(HOST, PORT);
  6273. vector<uint64_t> progress_values;
  6274. bool progress_called = false;
  6275. auto res =
  6276. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6277. progress_values.push_back(current);
  6278. progress_called = true;
  6279. return true;
  6280. });
  6281. ASSERT_TRUE(res);
  6282. EXPECT_EQ(200, res->status);
  6283. EXPECT_TRUE(progress_called);
  6284. }
  6285. TEST(UploadProgressTest, PostStringBodyBasic) {
  6286. TestStringBodyUploadProgress(
  6287. [](Server &svr) {
  6288. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6289. res.set_content("received", "text/plain");
  6290. });
  6291. },
  6292. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6293. return cli.Post("/test", body, "text/plain", progress_callback);
  6294. },
  6295. "test data for upload progress");
  6296. }
  6297. TEST(UploadProgressTest, PutStringBodyBasic) {
  6298. TestStringBodyUploadProgress(
  6299. [](Server &svr) {
  6300. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6301. res.set_content("put received", "text/plain");
  6302. });
  6303. },
  6304. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6305. return cli.Put("/test", body, "text/plain", progress_callback);
  6306. },
  6307. "put test data for upload progress");
  6308. }
  6309. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6310. TestStringBodyUploadProgress(
  6311. [](Server &svr) {
  6312. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6313. res.set_content("patch received", "text/plain");
  6314. });
  6315. },
  6316. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6317. return cli.Patch("/test", body, "text/plain", progress_callback);
  6318. },
  6319. "patch test data for upload progress");
  6320. }
  6321. // Helper function for content provider upload progress tests
  6322. template <typename SetupHandler, typename ClientCall>
  6323. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6324. ClientCall &&client_call) {
  6325. Server svr;
  6326. setup_handler(svr);
  6327. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6328. auto se = detail::scope_exit([&] {
  6329. svr.stop();
  6330. t.join();
  6331. });
  6332. svr.wait_until_ready();
  6333. Client cli(HOST, PORT);
  6334. vector<uint64_t> progress_values;
  6335. auto res =
  6336. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6337. progress_values.push_back(current);
  6338. return true;
  6339. });
  6340. ASSERT_TRUE(res);
  6341. EXPECT_EQ(200, res->status);
  6342. EXPECT_FALSE(progress_values.empty());
  6343. }
  6344. TEST(UploadProgressTest, PostContentProviderProgress) {
  6345. TestContentProviderUploadProgress(
  6346. [](Server &svr) {
  6347. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6348. res.set_content("provider received", "text/plain");
  6349. });
  6350. },
  6351. [](Client &cli, UploadProgress progress_callback) {
  6352. return cli.Post(
  6353. "/test", 10,
  6354. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6355. sink.os << "test data";
  6356. return true;
  6357. },
  6358. "text/plain", progress_callback);
  6359. });
  6360. }
  6361. // Helper function for multipart upload progress tests
  6362. template <typename SetupHandler, typename ClientCall>
  6363. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6364. ClientCall &&client_call,
  6365. const string &endpoint) {
  6366. Server svr;
  6367. setup_handler(svr);
  6368. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6369. auto se = detail::scope_exit([&] {
  6370. svr.stop();
  6371. t.join();
  6372. });
  6373. svr.wait_until_ready();
  6374. Client cli(HOST, PORT);
  6375. vector<uint64_t> progress_values;
  6376. UploadFormDataItems items = {
  6377. {"field1", "value1", "", ""},
  6378. {"field2", "longer value for progress tracking test", "", ""},
  6379. {"file1", "file content data for upload progress", "test.txt",
  6380. "text/plain"}};
  6381. auto res = client_call(cli, endpoint, items,
  6382. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6383. progress_values.push_back(current);
  6384. return true;
  6385. });
  6386. ASSERT_TRUE(res);
  6387. EXPECT_EQ(200, res->status);
  6388. EXPECT_FALSE(progress_values.empty());
  6389. }
  6390. TEST(UploadProgressTest, PostMultipartProgress) {
  6391. TestMultipartUploadProgress(
  6392. [](Server &svr) {
  6393. svr.Post("/multipart", [](const Request &req, Response &res) {
  6394. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6395. res.set_content("multipart received", "text/plain");
  6396. });
  6397. },
  6398. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6399. UploadProgress progress_callback) {
  6400. return cli.Post(endpoint, items, progress_callback);
  6401. },
  6402. "/multipart");
  6403. }
  6404. // Helper function for basic download progress tests
  6405. template <typename SetupHandler, typename ClientCall>
  6406. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6407. ClientCall &&client_call, const string &endpoint,
  6408. size_t expected_content_size) {
  6409. Server svr;
  6410. setup_handler(svr);
  6411. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6412. auto se = detail::scope_exit([&] {
  6413. svr.stop();
  6414. t.join();
  6415. });
  6416. svr.wait_until_ready();
  6417. Client cli(HOST, PORT);
  6418. vector<uint64_t> progress_values;
  6419. auto res = client_call(cli, endpoint,
  6420. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6421. progress_values.push_back(current);
  6422. return true;
  6423. });
  6424. ASSERT_TRUE(res);
  6425. EXPECT_EQ(200, res->status);
  6426. EXPECT_FALSE(progress_values.empty());
  6427. EXPECT_EQ(expected_content_size, res->body.size());
  6428. }
  6429. TEST(DownloadProgressTest, GetBasic) {
  6430. TestBasicDownloadProgress(
  6431. [](Server &svr) {
  6432. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6433. string content(1000, 'D');
  6434. res.set_content(content, "text/plain");
  6435. });
  6436. },
  6437. [](Client &cli, const string &endpoint,
  6438. DownloadProgress progress_callback) {
  6439. return cli.Get(endpoint, progress_callback);
  6440. },
  6441. "/download", 1000u);
  6442. }
  6443. // Helper function for content receiver download progress tests
  6444. template <typename SetupHandler, typename ClientCall>
  6445. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6446. ClientCall &&client_call,
  6447. const string &endpoint,
  6448. size_t expected_content_size) {
  6449. Server svr;
  6450. setup_handler(svr);
  6451. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6452. auto se = detail::scope_exit([&] {
  6453. svr.stop();
  6454. t.join();
  6455. });
  6456. svr.wait_until_ready();
  6457. Client cli(HOST, PORT);
  6458. vector<uint64_t> progress_values;
  6459. string received_body;
  6460. auto res = client_call(
  6461. cli, endpoint,
  6462. [&](const char *data, size_t data_length) -> bool {
  6463. received_body.append(data, data_length);
  6464. return true;
  6465. },
  6466. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6467. progress_values.push_back(current);
  6468. return true;
  6469. });
  6470. ASSERT_TRUE(res);
  6471. EXPECT_EQ(200, res->status);
  6472. EXPECT_FALSE(progress_values.empty());
  6473. EXPECT_EQ(expected_content_size, received_body.size());
  6474. EXPECT_TRUE(res->body.empty());
  6475. }
  6476. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6477. TestContentReceiverDownloadProgress(
  6478. [](Server &svr) {
  6479. svr.Get("/download-receiver",
  6480. [](const Request & /*req*/, Response &res) {
  6481. string content(2000, 'R');
  6482. res.set_content(content, "text/plain");
  6483. });
  6484. },
  6485. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6486. DownloadProgress progress_callback) {
  6487. return cli.Get(endpoint, content_receiver, progress_callback);
  6488. },
  6489. "/download-receiver", 2000u);
  6490. }
  6491. TEST(StreamingTest, NoContentLengthStreaming) {
  6492. Server svr;
  6493. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6494. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6495. if (offset < 6) {
  6496. sink.os << (offset < 3 ? "a" : "b");
  6497. } else {
  6498. sink.done();
  6499. }
  6500. return true;
  6501. });
  6502. });
  6503. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6504. auto listen_se = detail::scope_exit([&] {
  6505. svr.stop();
  6506. listen_thread.join();
  6507. ASSERT_FALSE(svr.is_running());
  6508. });
  6509. svr.wait_until_ready();
  6510. Client client(HOST, PORT);
  6511. auto get_thread = std::thread([&client]() {
  6512. std::string s;
  6513. auto res =
  6514. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6515. s += std::string(data, len);
  6516. return true;
  6517. });
  6518. ASSERT_TRUE(res);
  6519. EXPECT_EQ(StatusCode::OK_200, res->status);
  6520. EXPECT_EQ("aaabbb", s);
  6521. });
  6522. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6523. // Give GET time to get a few messages.
  6524. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6525. }
  6526. TEST(MountTest, Unmount) {
  6527. Server svr;
  6528. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6529. auto se = detail::scope_exit([&] {
  6530. svr.stop();
  6531. listen_thread.join();
  6532. ASSERT_FALSE(svr.is_running());
  6533. });
  6534. svr.wait_until_ready();
  6535. Client cli("localhost", PORT);
  6536. svr.set_mount_point("/mount2", "./www2");
  6537. auto res = cli.Get("/");
  6538. ASSERT_TRUE(res);
  6539. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6540. res = cli.Get("/mount2/dir/test.html");
  6541. ASSERT_TRUE(res);
  6542. EXPECT_EQ(StatusCode::OK_200, res->status);
  6543. svr.set_mount_point("/", "./www");
  6544. res = cli.Get("/dir/");
  6545. ASSERT_TRUE(res);
  6546. EXPECT_EQ(StatusCode::OK_200, res->status);
  6547. svr.remove_mount_point("/");
  6548. res = cli.Get("/dir/");
  6549. ASSERT_TRUE(res);
  6550. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6551. svr.remove_mount_point("/mount2");
  6552. res = cli.Get("/mount2/dir/test.html");
  6553. ASSERT_TRUE(res);
  6554. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6555. }
  6556. TEST(MountTest, Redicect) {
  6557. Server svr;
  6558. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6559. auto se = detail::scope_exit([&] {
  6560. svr.stop();
  6561. listen_thread.join();
  6562. ASSERT_FALSE(svr.is_running());
  6563. });
  6564. svr.set_mount_point("/", "./www");
  6565. svr.wait_until_ready();
  6566. Client cli("localhost", PORT);
  6567. auto res = cli.Get("/dir/");
  6568. ASSERT_TRUE(res);
  6569. EXPECT_EQ(StatusCode::OK_200, res->status);
  6570. res = cli.Get("/dir");
  6571. ASSERT_TRUE(res);
  6572. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6573. res = cli.Get("/file");
  6574. ASSERT_TRUE(res);
  6575. EXPECT_EQ(StatusCode::OK_200, res->status);
  6576. res = cli.Get("/file/");
  6577. ASSERT_TRUE(res);
  6578. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6579. cli.set_follow_location(true);
  6580. res = cli.Get("/dir");
  6581. ASSERT_TRUE(res);
  6582. EXPECT_EQ(StatusCode::OK_200, res->status);
  6583. }
  6584. TEST(MountTest, MultibytesPathName) {
  6585. Server svr;
  6586. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6587. auto se = detail::scope_exit([&] {
  6588. svr.stop();
  6589. listen_thread.join();
  6590. ASSERT_FALSE(svr.is_running());
  6591. });
  6592. svr.set_mount_point("/", "./www");
  6593. svr.wait_until_ready();
  6594. Client cli("localhost", PORT);
  6595. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6596. ASSERT_TRUE(res);
  6597. EXPECT_EQ(StatusCode::OK_200, res->status);
  6598. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6599. }
  6600. TEST(KeepAliveTest, ReadTimeout) {
  6601. Server svr;
  6602. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6603. std::this_thread::sleep_for(std::chrono::seconds(2));
  6604. res.set_content("a", "text/plain");
  6605. });
  6606. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6607. res.set_content("b", "text/plain");
  6608. });
  6609. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6610. auto se = detail::scope_exit([&] {
  6611. svr.stop();
  6612. listen_thread.join();
  6613. ASSERT_FALSE(svr.is_running());
  6614. });
  6615. svr.wait_until_ready();
  6616. Client cli("localhost", PORT);
  6617. cli.set_keep_alive(true);
  6618. cli.set_read_timeout(std::chrono::seconds(1));
  6619. auto resa = cli.Get("/a");
  6620. ASSERT_FALSE(resa);
  6621. EXPECT_EQ(Error::Read, resa.error());
  6622. auto resb = cli.Get("/b");
  6623. ASSERT_TRUE(resb);
  6624. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6625. EXPECT_EQ("b", resb->body);
  6626. }
  6627. TEST(KeepAliveTest, MaxCount) {
  6628. size_t keep_alive_max_count = 3;
  6629. Server svr;
  6630. svr.set_keep_alive_max_count(keep_alive_max_count);
  6631. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6632. res.set_content("Hello World!", "text/plain");
  6633. });
  6634. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6635. auto se = detail::scope_exit([&] {
  6636. svr.stop();
  6637. listen_thread.join();
  6638. ASSERT_FALSE(svr.is_running());
  6639. });
  6640. svr.wait_until_ready();
  6641. Client cli(HOST, PORT);
  6642. cli.set_keep_alive(true);
  6643. for (size_t i = 0; i < 5; i++) {
  6644. auto result = cli.Get("/hi");
  6645. ASSERT_TRUE(result);
  6646. EXPECT_EQ(StatusCode::OK_200, result->status);
  6647. if (i == keep_alive_max_count - 1) {
  6648. EXPECT_EQ("close", result->get_header_value("Connection"));
  6649. } else {
  6650. EXPECT_FALSE(result->has_header("Connection"));
  6651. }
  6652. }
  6653. }
  6654. TEST(KeepAliveTest, Issue1041) {
  6655. Server svr;
  6656. svr.set_keep_alive_timeout(3);
  6657. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6658. res.set_content("Hello World!", "text/plain");
  6659. });
  6660. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6661. auto se = detail::scope_exit([&] {
  6662. svr.stop();
  6663. listen_thread.join();
  6664. ASSERT_FALSE(svr.is_running());
  6665. });
  6666. svr.wait_until_ready();
  6667. Client cli(HOST, PORT);
  6668. cli.set_keep_alive(true);
  6669. auto result = cli.Get("/hi");
  6670. ASSERT_TRUE(result);
  6671. EXPECT_EQ(StatusCode::OK_200, result->status);
  6672. std::this_thread::sleep_for(std::chrono::seconds(5));
  6673. result = cli.Get("/hi");
  6674. ASSERT_TRUE(result);
  6675. EXPECT_EQ(StatusCode::OK_200, result->status);
  6676. }
  6677. TEST(KeepAliveTest, Issue1959) {
  6678. Server svr;
  6679. svr.set_keep_alive_timeout(5);
  6680. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6681. res.set_content("a", "text/plain");
  6682. });
  6683. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6684. auto se = detail::scope_exit([&] {
  6685. if (!svr.is_running()) return;
  6686. svr.stop();
  6687. listen_thread.join();
  6688. ASSERT_FALSE(svr.is_running());
  6689. });
  6690. svr.wait_until_ready();
  6691. Client cli("localhost", PORT);
  6692. cli.set_keep_alive(true);
  6693. using namespace std::chrono;
  6694. auto start = steady_clock::now();
  6695. cli.Get("/a");
  6696. svr.stop();
  6697. listen_thread.join();
  6698. auto end = steady_clock::now();
  6699. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6700. EXPECT_LT(elapsed, 5000);
  6701. }
  6702. #ifdef CPPHTTPLIB_SSL_ENABLED
  6703. TEST(KeepAliveTest, SSLClientReconnection) {
  6704. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6705. ASSERT_TRUE(svr.is_valid());
  6706. svr.set_keep_alive_timeout(1);
  6707. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6708. res.set_content("Hello World!", "text/plain");
  6709. });
  6710. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6711. auto se = detail::scope_exit([&] {
  6712. svr.stop();
  6713. listen_thread.join();
  6714. ASSERT_FALSE(svr.is_running());
  6715. });
  6716. svr.wait_until_ready();
  6717. SSLClient cli(HOST, PORT);
  6718. cli.enable_server_certificate_verification(false);
  6719. cli.set_keep_alive(true);
  6720. auto result = cli.Get("/hi");
  6721. ASSERT_TRUE(result);
  6722. EXPECT_EQ(StatusCode::OK_200, result->status);
  6723. result = cli.Get("/hi");
  6724. ASSERT_TRUE(result);
  6725. EXPECT_EQ(StatusCode::OK_200, result->status);
  6726. std::this_thread::sleep_for(std::chrono::seconds(2));
  6727. // Recoonect
  6728. result = cli.Get("/hi");
  6729. ASSERT_TRUE(result);
  6730. EXPECT_EQ(StatusCode::OK_200, result->status);
  6731. result = cli.Get("/hi");
  6732. ASSERT_TRUE(result);
  6733. EXPECT_EQ(StatusCode::OK_200, result->status);
  6734. }
  6735. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6736. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6737. ASSERT_TRUE(svr.is_valid());
  6738. svr.set_keep_alive_timeout(1);
  6739. std::string content = "reconnect";
  6740. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6741. res.set_content("Hello World!", "text/plain");
  6742. });
  6743. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6744. auto se = detail::scope_exit([&] {
  6745. svr.stop();
  6746. listen_thread.join();
  6747. ASSERT_FALSE(svr.is_running());
  6748. });
  6749. svr.wait_until_ready();
  6750. SSLClient cli(HOST, PORT);
  6751. cli.enable_server_certificate_verification(false);
  6752. cli.set_keep_alive(true);
  6753. auto result = cli.Post(
  6754. "/hi", content.size(),
  6755. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6756. sink.write(content.c_str(), content.size());
  6757. return true;
  6758. },
  6759. "text/plain");
  6760. ASSERT_TRUE(result);
  6761. EXPECT_EQ(200, result->status);
  6762. std::this_thread::sleep_for(std::chrono::seconds(2));
  6763. // Recoonect
  6764. result = cli.Post(
  6765. "/hi", content.size(),
  6766. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6767. sink.write(content.c_str(), content.size());
  6768. return true;
  6769. },
  6770. "text/plain");
  6771. ASSERT_TRUE(result);
  6772. EXPECT_EQ(200, result->status);
  6773. result = cli.Post(
  6774. "/hi", content.size(),
  6775. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6776. sink.write(content.c_str(), content.size());
  6777. return true;
  6778. },
  6779. "text/plain");
  6780. ASSERT_TRUE(result);
  6781. EXPECT_EQ(200, result->status);
  6782. }
  6783. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6784. using namespace httplib::tls;
  6785. {
  6786. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6787. ASSERT_TRUE(svr.is_valid());
  6788. svr.Get("/sni", [&](const Request &req, Response &res) {
  6789. std::string expected = req.sni();
  6790. EXPECT_EQ(expected, req.get_param_value("expected"));
  6791. res.set_content("ok", "text/plain");
  6792. });
  6793. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6794. auto se = detail::scope_exit([&] {
  6795. svr.stop();
  6796. listen_thread.join();
  6797. ASSERT_FALSE(svr.is_running());
  6798. });
  6799. svr.wait_until_ready();
  6800. {
  6801. SSLClient cli("localhost", PORT);
  6802. cli.enable_server_certificate_verification(false);
  6803. auto res = cli.Get("/sni?expected=localhost");
  6804. ASSERT_TRUE(res);
  6805. }
  6806. {
  6807. SSLClient cli("::1", PORT);
  6808. cli.enable_server_certificate_verification(false);
  6809. auto res = cli.Get("/sni?expected=");
  6810. // NOTE: This may fail if the server is listening on IPv4 only
  6811. // (e.g., when localhost resolves to 127.0.0.1 only)
  6812. if (res) {
  6813. EXPECT_EQ(StatusCode::OK_200, res->status);
  6814. } else {
  6815. EXPECT_EQ(Error::Connection, res.error());
  6816. }
  6817. }
  6818. }
  6819. }
  6820. #endif
  6821. TEST(ClientProblemDetectionTest, ContentProvider) {
  6822. Server svr;
  6823. size_t content_length = 1024 * 1024;
  6824. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6825. res.set_content_provider(
  6826. content_length, "text/plain",
  6827. [&](size_t offset, size_t length, DataSink &sink) {
  6828. auto out_len = std::min(length, static_cast<size_t>(1024));
  6829. std::string out(out_len, '@');
  6830. sink.write(out.data(), out_len);
  6831. return offset < 4096;
  6832. },
  6833. [](bool success) { ASSERT_FALSE(success); });
  6834. });
  6835. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6836. res.set_content_provider(
  6837. 0, "text/plain",
  6838. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6839. EXPECT_TRUE(false);
  6840. return true;
  6841. },
  6842. [](bool success) { ASSERT_FALSE(success); });
  6843. });
  6844. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6845. auto se = detail::scope_exit([&] {
  6846. svr.stop();
  6847. listen_thread.join();
  6848. ASSERT_FALSE(svr.is_running());
  6849. });
  6850. svr.wait_until_ready();
  6851. Client cli("localhost", PORT);
  6852. {
  6853. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6854. size_t /*data_length*/) { return false; });
  6855. ASSERT_FALSE(res);
  6856. }
  6857. {
  6858. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6859. size_t /*data_length*/) { return false; });
  6860. ASSERT_TRUE(res);
  6861. }
  6862. }
  6863. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6864. Server svr;
  6865. svr.set_error_handler([](Request const &, Response &res) -> void {
  6866. res.set_chunked_content_provider(
  6867. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6868. sink.os << "hello";
  6869. sink.os << "world";
  6870. sink.done();
  6871. return true;
  6872. });
  6873. });
  6874. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6875. auto se = detail::scope_exit([&] {
  6876. svr.stop();
  6877. listen_thread.join();
  6878. ASSERT_FALSE(svr.is_running());
  6879. });
  6880. svr.wait_until_ready();
  6881. Client cli("localhost", PORT);
  6882. auto res = cli.Get("/");
  6883. ASSERT_TRUE(res);
  6884. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6885. EXPECT_EQ("helloworld", res->body);
  6886. }
  6887. TEST(LongPollingTest, ClientCloseDetection) {
  6888. Server svr;
  6889. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6890. res.set_chunked_content_provider(
  6891. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6892. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6893. sink.os << "hello";
  6894. auto count = 10;
  6895. while (count > 0 && sink.is_writable()) {
  6896. this_thread::sleep_for(chrono::milliseconds(10));
  6897. count--;
  6898. }
  6899. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6900. return true;
  6901. });
  6902. });
  6903. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6904. auto se = detail::scope_exit([&] {
  6905. svr.stop();
  6906. listen_thread.join();
  6907. ASSERT_FALSE(svr.is_running());
  6908. });
  6909. svr.wait_until_ready();
  6910. Client cli("localhost", PORT);
  6911. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6912. EXPECT_EQ("hello", string(data, data_length));
  6913. return false; // close the socket immediately.
  6914. });
  6915. ASSERT_FALSE(res);
  6916. }
  6917. TEST(GetWithParametersTest, GetWithParameters) {
  6918. Server svr;
  6919. svr.Get("/", [&](const Request &req, Response &) {
  6920. EXPECT_EQ("world", req.get_param_value("hello"));
  6921. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6922. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6923. });
  6924. svr.Get("/params", [&](const Request &req, Response &) {
  6925. EXPECT_EQ("world", req.get_param_value("hello"));
  6926. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6927. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6928. });
  6929. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6930. EXPECT_EQ("resource-id", req.matches[1]);
  6931. EXPECT_EQ("foo", req.get_param_value("param1"));
  6932. EXPECT_EQ("bar", req.get_param_value("param2"));
  6933. });
  6934. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6935. EXPECT_EQ("user-id", req.path_params.at("id"));
  6936. EXPECT_EQ("foo", req.get_param_value("param1"));
  6937. EXPECT_EQ("bar", req.get_param_value("param2"));
  6938. });
  6939. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6940. auto se = detail::scope_exit([&] {
  6941. svr.stop();
  6942. listen_thread.join();
  6943. ASSERT_FALSE(svr.is_running());
  6944. });
  6945. svr.wait_until_ready();
  6946. {
  6947. Client cli(HOST, PORT);
  6948. Params params;
  6949. params.emplace("hello", "world");
  6950. params.emplace("hello2", "world2");
  6951. params.emplace("hello3", "world3");
  6952. auto res = cli.Get("/", params, Headers{});
  6953. ASSERT_TRUE(res);
  6954. EXPECT_EQ(StatusCode::OK_200, res->status);
  6955. }
  6956. {
  6957. Client cli(HOST, PORT);
  6958. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6959. ASSERT_TRUE(res);
  6960. EXPECT_EQ(StatusCode::OK_200, res->status);
  6961. }
  6962. {
  6963. Client cli(HOST, PORT);
  6964. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6965. ASSERT_TRUE(res);
  6966. EXPECT_EQ(StatusCode::OK_200, res->status);
  6967. }
  6968. {
  6969. Client cli(HOST, PORT);
  6970. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6971. ASSERT_TRUE(res);
  6972. EXPECT_EQ(StatusCode::OK_200, res->status);
  6973. }
  6974. }
  6975. TEST(GetWithParametersTest, GetWithParameters2) {
  6976. Server svr;
  6977. svr.Get("/", [&](const Request &req, Response &res) {
  6978. auto text = req.get_param_value("hello");
  6979. res.set_content(text, "text/plain");
  6980. });
  6981. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6982. auto se = detail::scope_exit([&] {
  6983. svr.stop();
  6984. listen_thread.join();
  6985. ASSERT_FALSE(svr.is_running());
  6986. });
  6987. svr.wait_until_ready();
  6988. Client cli("localhost", PORT);
  6989. Params params;
  6990. params.emplace("hello", "world");
  6991. std::string body;
  6992. auto res = cli.Get("/", params, Headers{},
  6993. [&](const char *data, size_t data_length) {
  6994. body.append(data, data_length);
  6995. return true;
  6996. });
  6997. ASSERT_TRUE(res);
  6998. EXPECT_EQ(StatusCode::OK_200, res->status);
  6999. EXPECT_EQ("world", body);
  7000. }
  7001. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  7002. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7003. auto host = "httpcan.org";
  7004. auto path = std::string{"/range/32"};
  7005. #else
  7006. auto host = "nghttp2.org";
  7007. auto path = std::string{"/httpbin/range/32"};
  7008. #endif
  7009. #ifdef CPPHTTPLIB_SSL_ENABLED
  7010. SSLClient cli(host);
  7011. #else
  7012. Client cli(host);
  7013. #endif
  7014. cli.set_default_headers({make_range_header({{1, 10}})});
  7015. cli.set_connection_timeout(5);
  7016. {
  7017. auto res = cli.Get(path);
  7018. ASSERT_TRUE(res);
  7019. EXPECT_EQ("bcdefghijk", res->body);
  7020. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7021. }
  7022. {
  7023. auto res = cli.Get(path);
  7024. ASSERT_TRUE(res);
  7025. EXPECT_EQ("bcdefghijk", res->body);
  7026. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7027. }
  7028. }
  7029. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7030. Server svr;
  7031. svr.set_default_headers({{"Hello", "World"}});
  7032. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7033. res.set_content("ok", "text/plain");
  7034. });
  7035. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7036. auto se = detail::scope_exit([&] {
  7037. svr.stop();
  7038. listen_thread.join();
  7039. ASSERT_FALSE(svr.is_running());
  7040. });
  7041. svr.wait_until_ready();
  7042. Client cli("localhost", PORT);
  7043. auto res = cli.Get("/");
  7044. ASSERT_TRUE(res);
  7045. EXPECT_EQ(StatusCode::OK_200, res->status);
  7046. EXPECT_EQ("ok", res->body);
  7047. EXPECT_EQ("World", res->get_header_value("Hello"));
  7048. }
  7049. #ifdef CPPHTTPLIB_SSL_ENABLED
  7050. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7051. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7052. ASSERT_TRUE(svr.is_valid());
  7053. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7054. std::this_thread::sleep_for(std::chrono::seconds(2));
  7055. res.set_content("a", "text/plain");
  7056. });
  7057. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7058. res.set_content("b", "text/plain");
  7059. });
  7060. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7061. auto se = detail::scope_exit([&] {
  7062. svr.stop();
  7063. listen_thread.join();
  7064. ASSERT_FALSE(svr.is_running());
  7065. });
  7066. svr.wait_until_ready();
  7067. SSLClient cli("localhost", PORT);
  7068. cli.enable_server_certificate_verification(false);
  7069. cli.set_keep_alive(true);
  7070. cli.set_read_timeout(std::chrono::seconds(1));
  7071. auto resa = cli.Get("/a");
  7072. ASSERT_TRUE(!resa);
  7073. EXPECT_EQ(Error::Read, resa.error());
  7074. auto resb = cli.Get("/b");
  7075. ASSERT_TRUE(resb);
  7076. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7077. EXPECT_EQ("b", resb->body);
  7078. }
  7079. #endif
  7080. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7081. protected:
  7082. ServerTestWithAI_PASSIVE()
  7083. : cli_(HOST, PORT)
  7084. #ifdef CPPHTTPLIB_SSL_ENABLED
  7085. ,
  7086. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7087. #endif
  7088. {
  7089. #ifdef CPPHTTPLIB_SSL_ENABLED
  7090. cli_.enable_server_certificate_verification(false);
  7091. #endif
  7092. }
  7093. virtual void SetUp() {
  7094. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7095. res.set_content("Hello World!", "text/plain");
  7096. });
  7097. t_ = thread(
  7098. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7099. svr_.wait_until_ready();
  7100. }
  7101. virtual void TearDown() {
  7102. svr_.stop();
  7103. t_.join();
  7104. }
  7105. #ifdef CPPHTTPLIB_SSL_ENABLED
  7106. SSLClient cli_;
  7107. SSLServer svr_;
  7108. #else
  7109. Client cli_;
  7110. Server svr_;
  7111. #endif
  7112. thread t_;
  7113. };
  7114. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7115. auto res = cli_.Get("/hi");
  7116. ASSERT_TRUE(res);
  7117. EXPECT_EQ(StatusCode::OK_200, res->status);
  7118. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7119. EXPECT_EQ("Hello World!", res->body);
  7120. }
  7121. class ServerUpDownTest : public ::testing::Test {
  7122. protected:
  7123. ServerUpDownTest() : cli_(HOST, PORT) {}
  7124. virtual void SetUp() {
  7125. t_ = thread([&]() {
  7126. svr_.bind_to_any_port(HOST);
  7127. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7128. ASSERT_TRUE(svr_.listen_after_bind());
  7129. });
  7130. svr_.wait_until_ready();
  7131. }
  7132. virtual void TearDown() {
  7133. svr_.stop();
  7134. t_.join();
  7135. }
  7136. Client cli_;
  7137. Server svr_;
  7138. thread t_;
  7139. };
  7140. TEST_F(ServerUpDownTest, QuickStartStop) {
  7141. // Should not crash, especially when run with
  7142. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7143. }
  7144. class PayloadMaxLengthTest : public ::testing::Test {
  7145. protected:
  7146. PayloadMaxLengthTest()
  7147. : cli_(HOST, PORT)
  7148. #ifdef CPPHTTPLIB_SSL_ENABLED
  7149. ,
  7150. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7151. #endif
  7152. {
  7153. #ifdef CPPHTTPLIB_SSL_ENABLED
  7154. cli_.enable_server_certificate_verification(false);
  7155. #endif
  7156. }
  7157. virtual void SetUp() {
  7158. svr_.set_payload_max_length(8);
  7159. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7160. res.set_content("test", "text/plain");
  7161. });
  7162. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7163. svr_.wait_until_ready();
  7164. }
  7165. virtual void TearDown() {
  7166. svr_.stop();
  7167. t_.join();
  7168. }
  7169. #ifdef CPPHTTPLIB_SSL_ENABLED
  7170. SSLClient cli_;
  7171. SSLServer svr_;
  7172. #else
  7173. Client cli_;
  7174. Server svr_;
  7175. #endif
  7176. thread t_;
  7177. };
  7178. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7179. auto res = cli_.Post("/test", "123456789", "text/plain");
  7180. ASSERT_TRUE(res);
  7181. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7182. res = cli_.Post("/test", "12345678", "text/plain");
  7183. ASSERT_TRUE(res);
  7184. EXPECT_EQ(StatusCode::OK_200, res->status);
  7185. }
  7186. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7187. // Test chunked encoding with payload exceeding the 8-byte limit
  7188. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7189. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7190. ASSERT_TRUE(res);
  7191. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7192. }
  7193. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7194. // Test chunked encoding with payload within the 8-byte limit
  7195. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7196. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7197. ASSERT_TRUE(res);
  7198. EXPECT_EQ(StatusCode::OK_200, res->status);
  7199. }
  7200. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7201. // Test using send_request to send chunked data exceeding payload limit
  7202. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7203. "Host: " +
  7204. std::string(HOST) + ":" + std::to_string(PORT) +
  7205. "\r\n"
  7206. "Transfer-Encoding: chunked\r\n"
  7207. "Connection: close\r\n"
  7208. "\r\n"
  7209. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7210. "0123456789\r\n"
  7211. "0\r\n" // End chunk
  7212. "\r\n";
  7213. std::string response;
  7214. bool result = send_request(1, chunked_request, &response);
  7215. if (!result) {
  7216. // If send_request fails, it might be because the server closed the
  7217. // connection due to payload limit enforcement, which is acceptable
  7218. SUCCEED()
  7219. << "Server rejected oversized chunked request (connection closed)";
  7220. } else {
  7221. // If we got a response, check if it's an error response or connection was
  7222. // closed early Short response length indicates connection was closed due to
  7223. // payload limit
  7224. if (response.length() <= 10) {
  7225. SUCCEED() << "Server closed connection for oversized chunked request";
  7226. } else {
  7227. // Check for error status codes
  7228. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7229. response.find("Payload Too Large") != std::string::npos ||
  7230. response.find("400") != std::string::npos);
  7231. }
  7232. }
  7233. }
  7234. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7235. // Test request without Content-Length header exceeding payload limit
  7236. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7237. "Host: " +
  7238. std::string(HOST) + ":" +
  7239. std::to_string(PORT) +
  7240. "\r\n"
  7241. "Connection: close\r\n"
  7242. "\r\n";
  7243. // Add payload exceeding the 8-byte limit
  7244. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7245. request_without_content_length += large_payload;
  7246. std::string response;
  7247. bool result = send_request(1, request_without_content_length, &response);
  7248. if (!result) {
  7249. // If send_request fails, server likely closed connection due to payload
  7250. // limit
  7251. SUCCEED() << "Server rejected oversized request without Content-Length "
  7252. "(connection closed)";
  7253. } else {
  7254. // Check if server responded with error or closed connection early
  7255. if (response.length() <= 10) {
  7256. SUCCEED() << "Server closed connection for oversized request without "
  7257. "Content-Length";
  7258. } else {
  7259. // Check for error status codes
  7260. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7261. response.find("Payload Too Large") != std::string::npos ||
  7262. response.find("400") != std::string::npos);
  7263. }
  7264. }
  7265. }
  7266. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7267. // Test request without Content-Length header within payload limit
  7268. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7269. "Host: " +
  7270. std::string(HOST) + ":" +
  7271. std::to_string(PORT) +
  7272. "\r\n"
  7273. "Connection: close\r\n"
  7274. "\r\n";
  7275. // Add payload within the 8-byte limit
  7276. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7277. request_without_content_length += small_payload;
  7278. std::string response;
  7279. bool result = send_request(1, request_without_content_length, &response);
  7280. // For requests without Content-Length, the server may have different behavior
  7281. // The key is that it should not reject due to payload limit for small
  7282. // payloads
  7283. if (result) {
  7284. // Check for any HTTP response (success or error, but not connection closed)
  7285. if (response.length() > 10) {
  7286. SUCCEED()
  7287. << "Server processed request without Content-Length within limit";
  7288. } else {
  7289. // Short response might indicate connection closed, which is acceptable
  7290. SUCCEED() << "Server closed connection for request without "
  7291. "Content-Length (acceptable behavior)";
  7292. }
  7293. } else {
  7294. // Connection failure might be due to protocol requirements
  7295. SUCCEED() << "Connection issue with request without Content-Length "
  7296. "(environment-specific)";
  7297. }
  7298. }
  7299. class LargePayloadMaxLengthTest : public ::testing::Test {
  7300. protected:
  7301. LargePayloadMaxLengthTest()
  7302. : cli_(HOST, PORT)
  7303. #ifdef CPPHTTPLIB_SSL_ENABLED
  7304. ,
  7305. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7306. #endif
  7307. {
  7308. #ifdef CPPHTTPLIB_SSL_ENABLED
  7309. cli_.enable_server_certificate_verification(false);
  7310. #endif
  7311. }
  7312. virtual void SetUp() {
  7313. // Set 10MB payload limit
  7314. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7315. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7316. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7317. res.set_content("Large payload test", "text/plain");
  7318. });
  7319. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7320. svr_.wait_until_ready();
  7321. }
  7322. virtual void TearDown() {
  7323. svr_.stop();
  7324. t_.join();
  7325. }
  7326. #ifdef CPPHTTPLIB_SSL_ENABLED
  7327. SSLClient cli_;
  7328. SSLServer svr_;
  7329. #else
  7330. Client cli_;
  7331. Server svr_;
  7332. #endif
  7333. thread t_;
  7334. };
  7335. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7336. // Test chunked encoding with payload within 10MB limit
  7337. std::string medium_payload(5 * 1024 * 1024,
  7338. 'A'); // 5MB payload, within 10MB limit
  7339. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7340. ASSERT_TRUE(res);
  7341. EXPECT_EQ(StatusCode::OK_200, res->status);
  7342. }
  7343. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7344. // Test chunked encoding with payload exceeding 10MB limit
  7345. std::string large_payload(12 * 1024 * 1024,
  7346. 'B'); // 12MB payload, exceeds 10MB limit
  7347. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7348. // Server may either return 413 or close the connection
  7349. if (res) {
  7350. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7351. } else {
  7352. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7353. }
  7354. }
  7355. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7356. // Test request without Content-Length header within 10MB limit
  7357. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7358. "Host: " +
  7359. std::string(HOST) + ":" +
  7360. std::to_string(PORT) +
  7361. "\r\n"
  7362. "Connection: close\r\n"
  7363. "\r\n";
  7364. // Add 1MB payload (within 10MB limit)
  7365. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7366. request_without_content_length += medium_payload;
  7367. std::string response;
  7368. bool result = send_request(5, request_without_content_length, &response);
  7369. if (result) {
  7370. // Should get a proper HTTP response for payloads within limit
  7371. if (response.length() > 10) {
  7372. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7373. "10MB limit";
  7374. } else {
  7375. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7376. "Content-Length)";
  7377. }
  7378. } else {
  7379. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7380. }
  7381. }
  7382. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7383. // Test request without Content-Length header exceeding 10MB limit
  7384. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7385. "Host: " +
  7386. std::string(HOST) + ":" +
  7387. std::to_string(PORT) +
  7388. "\r\n"
  7389. "Connection: close\r\n"
  7390. "\r\n";
  7391. // Add 12MB payload (exceeds 10MB limit)
  7392. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7393. request_without_content_length += large_payload;
  7394. std::string response;
  7395. bool result = send_request(10, request_without_content_length, &response);
  7396. if (!result) {
  7397. // Server should close connection due to payload limit
  7398. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7399. "(connection closed)";
  7400. } else {
  7401. // Check for error response
  7402. if (response.length() <= 10) {
  7403. SUCCEED()
  7404. << "Server closed connection for 12MB request exceeding 10MB limit";
  7405. } else {
  7406. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7407. response.find("Payload Too Large") != std::string::npos ||
  7408. response.find("400") != std::string::npos);
  7409. }
  7410. }
  7411. }
  7412. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7413. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7414. // path.
  7415. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7416. Server svr;
  7417. const size_t LIMIT = 64 * 1024; // 64KB
  7418. svr.set_payload_max_length(LIMIT);
  7419. size_t total = 0;
  7420. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7421. const ContentReader &content_reader) {
  7422. content_reader([&](const char * /*data*/, size_t len) {
  7423. total += len;
  7424. return true;
  7425. });
  7426. res.status = 200;
  7427. res.set_content("stream_ok", "text/plain");
  7428. });
  7429. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7430. auto se = detail::scope_exit([&] {
  7431. svr.stop();
  7432. thread.join();
  7433. ASSERT_FALSE(svr.is_running());
  7434. });
  7435. svr.wait_until_ready();
  7436. // Prepare 256KB raw data and gzip-compress it
  7437. std::string raw(256 * 1024, 'A');
  7438. std::string gz;
  7439. {
  7440. z_stream zs{};
  7441. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7442. Z_DEFAULT_STRATEGY);
  7443. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7444. zs.avail_in = static_cast<uInt>(raw.size());
  7445. char outbuf[4096];
  7446. int ret;
  7447. do {
  7448. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7449. zs.avail_out = sizeof(outbuf);
  7450. ret = deflate(&zs, Z_FINISH);
  7451. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7452. } while (ret != Z_STREAM_END);
  7453. deflateEnd(&zs);
  7454. }
  7455. Client cli(HOST, PORT);
  7456. cli.set_connection_timeout(std::chrono::seconds(5));
  7457. Headers headers = {{"Content-Encoding", "gzip"}};
  7458. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7459. "application/octet-stream");
  7460. ASSERT_TRUE(res);
  7461. // Server must reject oversized decompressed payloads with 413.
  7462. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7463. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7464. EXPECT_LE(total, LIMIT);
  7465. }
  7466. #endif
  7467. // Regression test for DoS vulnerability: a malicious server sending a response
  7468. // without Content-Length header must not cause unbounded memory consumption on
  7469. // the client side. The client should stop reading after a reasonable limit,
  7470. // similar to the server-side set_payload_max_length protection.
  7471. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7472. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7473. #ifndef _WIN32
  7474. signal(SIGPIPE, SIG_IGN);
  7475. #endif
  7476. auto server_thread = std::thread([] {
  7477. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7478. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7479. default_socket_options(srv);
  7480. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7481. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7482. sockaddr_in addr{};
  7483. addr.sin_family = AF_INET;
  7484. addr.sin_port = htons(PORT + 2);
  7485. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7486. int opt = 1;
  7487. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7488. #ifdef _WIN32
  7489. reinterpret_cast<const char *>(&opt),
  7490. #else
  7491. &opt,
  7492. #endif
  7493. sizeof(opt));
  7494. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7495. ::listen(srv, 1);
  7496. sockaddr_in cli_addr{};
  7497. socklen_t cli_len = sizeof(cli_addr);
  7498. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7499. if (cli != INVALID_SOCKET) {
  7500. char buf[4096];
  7501. ::recv(cli, buf, sizeof(buf), 0);
  7502. // Malicious response: no Content-Length, no chunked encoding
  7503. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7504. "Connection: close\r\n"
  7505. "\r\n";
  7506. ::send(cli,
  7507. #ifdef _WIN32
  7508. static_cast<const char *>(response_header.c_str()),
  7509. static_cast<int>(response_header.size()),
  7510. #else
  7511. response_header.c_str(), response_header.size(),
  7512. #endif
  7513. 0);
  7514. // Send 10MB of data
  7515. std::string chunk(64 * 1024, 'A');
  7516. size_t total_sent = 0;
  7517. while (total_sent < MALICIOUS_DATA_SIZE) {
  7518. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7519. auto sent = ::send(cli,
  7520. #ifdef _WIN32
  7521. static_cast<const char *>(chunk.c_str()),
  7522. static_cast<int>(to_send),
  7523. #else
  7524. chunk.c_str(), to_send,
  7525. #endif
  7526. 0);
  7527. if (sent <= 0) break;
  7528. total_sent += static_cast<size_t>(sent);
  7529. }
  7530. detail::close_socket(cli);
  7531. }
  7532. detail::close_socket(srv);
  7533. });
  7534. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7535. size_t total_read = 0;
  7536. {
  7537. Client cli("127.0.0.1", PORT + 2);
  7538. cli.set_read_timeout(5, 0);
  7539. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7540. auto stream = cli.open_stream("GET", "/malicious");
  7541. ASSERT_TRUE(stream.is_valid());
  7542. char buffer[64 * 1024];
  7543. ssize_t n;
  7544. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7545. total_read += static_cast<size_t>(n);
  7546. }
  7547. } // StreamHandle and Client destroyed here, closing the socket
  7548. server_thread.join();
  7549. // With set_payload_max_length, the client must stop reading before consuming
  7550. // all 10MB. The read loop should be cut off at or near the configured limit.
  7551. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7552. << "Client read " << total_read << " bytes, exceeding the configured "
  7553. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7554. }
  7555. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7556. // the entire response body without truncation.
  7557. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7558. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7559. #ifndef _WIN32
  7560. signal(SIGPIPE, SIG_IGN);
  7561. #endif
  7562. auto server_thread = std::thread([] {
  7563. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7564. default_socket_options(srv);
  7565. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7566. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7567. sockaddr_in addr{};
  7568. addr.sin_family = AF_INET;
  7569. addr.sin_port = htons(PORT + 2);
  7570. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7571. int opt = 1;
  7572. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7573. #ifdef _WIN32
  7574. reinterpret_cast<const char *>(&opt),
  7575. #else
  7576. &opt,
  7577. #endif
  7578. sizeof(opt));
  7579. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7580. ::listen(srv, 1);
  7581. sockaddr_in cli_addr{};
  7582. socklen_t cli_len = sizeof(cli_addr);
  7583. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7584. if (cli != INVALID_SOCKET) {
  7585. char buf[4096];
  7586. ::recv(cli, buf, sizeof(buf), 0);
  7587. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7588. "Connection: close\r\n"
  7589. "\r\n";
  7590. ::send(cli,
  7591. #ifdef _WIN32
  7592. static_cast<const char *>(response_header.c_str()),
  7593. static_cast<int>(response_header.size()),
  7594. #else
  7595. response_header.c_str(), response_header.size(),
  7596. #endif
  7597. 0);
  7598. std::string chunk(64 * 1024, 'A');
  7599. size_t total_sent = 0;
  7600. while (total_sent < DATA_SIZE) {
  7601. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7602. auto sent = ::send(cli,
  7603. #ifdef _WIN32
  7604. static_cast<const char *>(chunk.c_str()),
  7605. static_cast<int>(to_send),
  7606. #else
  7607. chunk.c_str(), to_send,
  7608. #endif
  7609. 0);
  7610. if (sent <= 0) break;
  7611. total_sent += static_cast<size_t>(sent);
  7612. }
  7613. #ifdef _WIN32
  7614. ::shutdown(cli, SD_SEND);
  7615. #else
  7616. ::shutdown(cli, SHUT_WR);
  7617. #endif
  7618. // Drain until the client closes its end, ensuring all data is delivered
  7619. char drain[1024];
  7620. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7621. detail::close_socket(cli);
  7622. }
  7623. detail::close_socket(srv);
  7624. });
  7625. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7626. size_t total_read = 0;
  7627. {
  7628. Client cli("127.0.0.1", PORT + 2);
  7629. cli.set_read_timeout(5, 0);
  7630. cli.set_payload_max_length(0); // 0 means no limit
  7631. auto stream = cli.open_stream("GET", "/data");
  7632. ASSERT_TRUE(stream.is_valid());
  7633. char buffer[64 * 1024];
  7634. ssize_t n;
  7635. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7636. total_read += static_cast<size_t>(n);
  7637. }
  7638. }
  7639. server_thread.join();
  7640. EXPECT_EQ(total_read, DATA_SIZE)
  7641. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7642. << " bytes without truncation, but only read " << total_read << " bytes.";
  7643. }
  7644. // Verify that content_receiver bypasses the default payload_max_length,
  7645. // allowing streaming downloads larger than 100MB without requiring an explicit
  7646. // set_payload_max_length call.
  7647. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  7648. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7649. #ifndef _WIN32
  7650. signal(SIGPIPE, SIG_IGN);
  7651. #endif
  7652. auto server_thread = std::thread([] {
  7653. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7654. default_socket_options(srv);
  7655. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7656. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7657. sockaddr_in addr{};
  7658. addr.sin_family = AF_INET;
  7659. addr.sin_port = htons(PORT + 2);
  7660. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7661. int opt = 1;
  7662. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7663. #ifdef _WIN32
  7664. reinterpret_cast<const char *>(&opt),
  7665. #else
  7666. &opt,
  7667. #endif
  7668. sizeof(opt));
  7669. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7670. ::listen(srv, 1);
  7671. sockaddr_in cli_addr{};
  7672. socklen_t cli_len = sizeof(cli_addr);
  7673. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7674. if (cli != INVALID_SOCKET) {
  7675. char buf[4096];
  7676. ::recv(cli, buf, sizeof(buf), 0);
  7677. // Response with Content-Length larger than default 100MB limit
  7678. auto content_length = std::to_string(DATA_SIZE);
  7679. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7680. "Content-Length: " +
  7681. content_length +
  7682. "\r\n"
  7683. "Connection: close\r\n"
  7684. "\r\n";
  7685. ::send(cli,
  7686. #ifdef _WIN32
  7687. static_cast<const char *>(response_header.c_str()),
  7688. static_cast<int>(response_header.size()),
  7689. #else
  7690. response_header.c_str(), response_header.size(),
  7691. #endif
  7692. 0);
  7693. std::string chunk(64 * 1024, 'A');
  7694. size_t total_sent = 0;
  7695. while (total_sent < DATA_SIZE) {
  7696. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7697. auto sent = ::send(cli,
  7698. #ifdef _WIN32
  7699. static_cast<const char *>(chunk.c_str()),
  7700. static_cast<int>(to_send),
  7701. #else
  7702. chunk.c_str(), to_send,
  7703. #endif
  7704. 0);
  7705. if (sent <= 0) break;
  7706. total_sent += static_cast<size_t>(sent);
  7707. }
  7708. detail::close_socket(cli);
  7709. }
  7710. detail::close_socket(srv);
  7711. });
  7712. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7713. size_t total_received = 0;
  7714. {
  7715. Client cli("127.0.0.1", PORT + 2);
  7716. cli.set_read_timeout(10, 0);
  7717. // Do NOT call set_payload_max_length — use the default 100MB limit
  7718. auto res =
  7719. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7720. total_received += data_length;
  7721. return true;
  7722. });
  7723. ASSERT_TRUE(res);
  7724. EXPECT_EQ(StatusCode::OK_200, res->status);
  7725. }
  7726. server_thread.join();
  7727. EXPECT_EQ(total_received, DATA_SIZE)
  7728. << "With content_receiver, the client should read all " << DATA_SIZE
  7729. << " bytes despite the default 100MB payload_max_length, but only read "
  7730. << total_received << " bytes.";
  7731. }
  7732. // Verify that an explicit set_payload_max_length smaller than the response is
  7733. // enforced even when a content_receiver is used.
  7734. TEST(ClientVulnerabilityTest,
  7735. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  7736. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7737. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  7738. #ifndef _WIN32
  7739. signal(SIGPIPE, SIG_IGN);
  7740. #endif
  7741. auto server_thread = std::thread([] {
  7742. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7743. default_socket_options(srv);
  7744. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7745. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7746. sockaddr_in addr{};
  7747. addr.sin_family = AF_INET;
  7748. addr.sin_port = htons(PORT + 2);
  7749. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7750. int opt = 1;
  7751. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7752. #ifdef _WIN32
  7753. reinterpret_cast<const char *>(&opt),
  7754. #else
  7755. &opt,
  7756. #endif
  7757. sizeof(opt));
  7758. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7759. ::listen(srv, 1);
  7760. sockaddr_in cli_addr{};
  7761. socklen_t cli_len = sizeof(cli_addr);
  7762. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7763. if (cli != INVALID_SOCKET) {
  7764. char buf[4096];
  7765. ::recv(cli, buf, sizeof(buf), 0);
  7766. auto content_length = std::to_string(DATA_SIZE);
  7767. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7768. "Content-Length: " +
  7769. content_length +
  7770. "\r\n"
  7771. "Connection: close\r\n"
  7772. "\r\n";
  7773. ::send(cli,
  7774. #ifdef _WIN32
  7775. static_cast<const char *>(response_header.c_str()),
  7776. static_cast<int>(response_header.size()),
  7777. #else
  7778. response_header.c_str(), response_header.size(),
  7779. #endif
  7780. 0);
  7781. std::string chunk(64 * 1024, 'A');
  7782. size_t total_sent = 0;
  7783. while (total_sent < DATA_SIZE) {
  7784. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7785. auto sent = ::send(cli,
  7786. #ifdef _WIN32
  7787. static_cast<const char *>(chunk.c_str()),
  7788. static_cast<int>(to_send),
  7789. #else
  7790. chunk.c_str(), to_send,
  7791. #endif
  7792. 0);
  7793. if (sent <= 0) break;
  7794. total_sent += static_cast<size_t>(sent);
  7795. }
  7796. detail::close_socket(cli);
  7797. }
  7798. detail::close_socket(srv);
  7799. });
  7800. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7801. size_t total_received = 0;
  7802. {
  7803. Client cli("127.0.0.1", PORT + 2);
  7804. cli.set_read_timeout(10, 0);
  7805. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  7806. auto res =
  7807. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7808. total_received += data_length;
  7809. return true;
  7810. });
  7811. // Should fail because 200MB exceeds the explicit 150MB limit
  7812. EXPECT_FALSE(res);
  7813. }
  7814. server_thread.join();
  7815. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  7816. << "Client with content_receiver should respect the explicit "
  7817. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  7818. << total_received << " bytes.";
  7819. }
  7820. // Verify that an explicit set_payload_max_length larger than the response
  7821. // allows the content_receiver to read all data successfully.
  7822. TEST(ClientVulnerabilityTest,
  7823. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  7824. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7825. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  7826. #ifndef _WIN32
  7827. signal(SIGPIPE, SIG_IGN);
  7828. #endif
  7829. auto server_thread = std::thread([] {
  7830. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7831. default_socket_options(srv);
  7832. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7833. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7834. sockaddr_in addr{};
  7835. addr.sin_family = AF_INET;
  7836. addr.sin_port = htons(PORT + 2);
  7837. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7838. int opt = 1;
  7839. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7840. #ifdef _WIN32
  7841. reinterpret_cast<const char *>(&opt),
  7842. #else
  7843. &opt,
  7844. #endif
  7845. sizeof(opt));
  7846. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7847. ::listen(srv, 1);
  7848. sockaddr_in cli_addr{};
  7849. socklen_t cli_len = sizeof(cli_addr);
  7850. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7851. if (cli != INVALID_SOCKET) {
  7852. char buf[4096];
  7853. ::recv(cli, buf, sizeof(buf), 0);
  7854. auto content_length = std::to_string(DATA_SIZE);
  7855. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7856. "Content-Length: " +
  7857. content_length +
  7858. "\r\n"
  7859. "Connection: close\r\n"
  7860. "\r\n";
  7861. ::send(cli,
  7862. #ifdef _WIN32
  7863. static_cast<const char *>(response_header.c_str()),
  7864. static_cast<int>(response_header.size()),
  7865. #else
  7866. response_header.c_str(), response_header.size(),
  7867. #endif
  7868. 0);
  7869. std::string chunk(64 * 1024, 'A');
  7870. size_t total_sent = 0;
  7871. while (total_sent < DATA_SIZE) {
  7872. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7873. auto sent = ::send(cli,
  7874. #ifdef _WIN32
  7875. static_cast<const char *>(chunk.c_str()),
  7876. static_cast<int>(to_send),
  7877. #else
  7878. chunk.c_str(), to_send,
  7879. #endif
  7880. 0);
  7881. if (sent <= 0) break;
  7882. total_sent += static_cast<size_t>(sent);
  7883. }
  7884. #ifdef _WIN32
  7885. ::shutdown(cli, SD_SEND);
  7886. #else
  7887. ::shutdown(cli, SHUT_WR);
  7888. #endif
  7889. char drain[1024];
  7890. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7891. detail::close_socket(cli);
  7892. }
  7893. detail::close_socket(srv);
  7894. });
  7895. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7896. size_t total_received = 0;
  7897. {
  7898. Client cli("127.0.0.1", PORT + 2);
  7899. cli.set_read_timeout(10, 0);
  7900. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  7901. auto res =
  7902. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7903. total_received += data_length;
  7904. return true;
  7905. });
  7906. ASSERT_TRUE(res);
  7907. EXPECT_EQ(StatusCode::OK_200, res->status);
  7908. }
  7909. server_thread.join();
  7910. EXPECT_EQ(total_received, DATA_SIZE)
  7911. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  7912. << " bytes (larger than " << DATA_SIZE
  7913. << " bytes response), content_receiver should read all data, but only "
  7914. "read "
  7915. << total_received << " bytes.";
  7916. }
  7917. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  7918. // Regression test for "zip bomb" attack on the client side: a malicious server
  7919. // sends a small gzip-compressed response that decompresses to a huge payload.
  7920. // The client must enforce payload_max_length on the decompressed size.
  7921. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  7922. constexpr size_t DECOMPRESSED_SIZE =
  7923. 10 * 1024 * 1024; // 10MB after decompression
  7924. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7925. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  7926. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  7927. std::string compressed;
  7928. {
  7929. httplib::detail::gzip_compressor compressor;
  7930. bool ok =
  7931. compressor.compress(uncompressed.data(), uncompressed.size(),
  7932. /*last=*/true, [&](const char *buf, size_t len) {
  7933. compressed.append(buf, len);
  7934. return true;
  7935. });
  7936. ASSERT_TRUE(ok);
  7937. }
  7938. // Sanity: compressed data should be much smaller than the decompressed size
  7939. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  7940. #ifndef _WIN32
  7941. signal(SIGPIPE, SIG_IGN);
  7942. #endif
  7943. // Set up the listening socket in the main thread so the server is guaranteed
  7944. // to be ready before the client connects (eliminates race condition).
  7945. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7946. default_socket_options(srv);
  7947. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7948. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7949. sockaddr_in addr{};
  7950. addr.sin_family = AF_INET;
  7951. addr.sin_port = htons(PORT + 3);
  7952. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7953. int opt = 1;
  7954. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7955. #ifdef _WIN32
  7956. reinterpret_cast<const char *>(&opt),
  7957. #else
  7958. &opt,
  7959. #endif
  7960. sizeof(opt));
  7961. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  7962. ASSERT_EQ(0, ::listen(srv, 1));
  7963. auto server_thread = std::thread([&compressed, srv] {
  7964. sockaddr_in cli_addr{};
  7965. socklen_t cli_len = sizeof(cli_addr);
  7966. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7967. if (cli != INVALID_SOCKET) {
  7968. // Read the full HTTP request (until \r\n\r\n)
  7969. char buf[4096];
  7970. size_t total = 0;
  7971. while (total < sizeof(buf)) {
  7972. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  7973. if (n <= 0) break;
  7974. total += static_cast<size_t>(n);
  7975. // Check for end of headers
  7976. if (total >= 4) {
  7977. std::string req(buf, total);
  7978. if (req.find("\r\n\r\n") != std::string::npos) break;
  7979. }
  7980. }
  7981. // Malicious response: gzip-compressed body, no Content-Length
  7982. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7983. "Content-Encoding: gzip\r\n"
  7984. "Connection: close\r\n"
  7985. "\r\n";
  7986. ::send(cli,
  7987. #ifdef _WIN32
  7988. static_cast<const char *>(response_header.c_str()),
  7989. static_cast<int>(response_header.size()),
  7990. #else
  7991. response_header.c_str(), response_header.size(),
  7992. #endif
  7993. 0);
  7994. // Send the compressed payload (small on the wire, huge when decompressed)
  7995. size_t total_sent = 0;
  7996. while (total_sent < compressed.size()) {
  7997. auto to_send = std::min(compressed.size() - total_sent,
  7998. static_cast<size_t>(64 * 1024));
  7999. auto sent =
  8000. ::send(cli,
  8001. #ifdef _WIN32
  8002. static_cast<const char *>(compressed.c_str() + total_sent),
  8003. static_cast<int>(to_send),
  8004. #else
  8005. compressed.c_str() + total_sent, to_send,
  8006. #endif
  8007. 0);
  8008. if (sent <= 0) break;
  8009. total_sent += static_cast<size_t>(sent);
  8010. }
  8011. detail::close_socket(cli);
  8012. }
  8013. });
  8014. auto se = detail::scope_exit([&] {
  8015. detail::close_socket(srv);
  8016. server_thread.join();
  8017. });
  8018. size_t total_decompressed = 0;
  8019. {
  8020. Client cli("127.0.0.1", PORT + 3);
  8021. cli.set_read_timeout(5, 0);
  8022. cli.set_decompress(true);
  8023. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8024. auto stream = cli.open_stream("GET", "/zipbomb");
  8025. ASSERT_TRUE(stream.is_valid());
  8026. char buffer[64 * 1024];
  8027. ssize_t n;
  8028. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8029. total_decompressed += static_cast<size_t>(n);
  8030. }
  8031. }
  8032. // The decompressed size must be capped by payload_max_length. Without
  8033. // protection, the client would decompress the full 10MB from a tiny
  8034. // compressed payload, enabling a zip bomb DoS attack.
  8035. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8036. << "Client decompressed " << total_decompressed
  8037. << " bytes from a gzip response. The decompressed size should be "
  8038. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8039. }
  8040. #endif
  8041. TEST(HostAndPortPropertiesTest, NoSSL) {
  8042. httplib::Client cli("www.google.com", 1234);
  8043. ASSERT_EQ("www.google.com", cli.host());
  8044. ASSERT_EQ(1234, cli.port());
  8045. }
  8046. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8047. httplib::Client cli("www.google.com:1234");
  8048. ASSERT_EQ("www.google.com", cli.host());
  8049. ASSERT_EQ(1234, cli.port());
  8050. }
  8051. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8052. // Port number that overflows int — should not crash, client becomes invalid
  8053. httplib::Client cli("http://www.google.com:99999999999999999999");
  8054. ASSERT_FALSE(cli.is_valid());
  8055. }
  8056. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8057. // Port 99999 exceeds valid range (1-65535) — should not crash
  8058. httplib::Client cli("http://www.google.com:99999");
  8059. ASSERT_FALSE(cli.is_valid());
  8060. }
  8061. #ifdef CPPHTTPLIB_SSL_ENABLED
  8062. TEST(HostAndPortPropertiesTest, SSL) {
  8063. httplib::SSLClient cli("www.google.com");
  8064. ASSERT_EQ("www.google.com", cli.host());
  8065. ASSERT_EQ(443, cli.port());
  8066. }
  8067. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8068. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8069. std::string cert;
  8070. read_file(CA_CERT_FILE, cert);
  8071. httplib::SSLClient httplib_client("www.google.com");
  8072. // Load CA store first time
  8073. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8074. // Load CA store second time (update)
  8075. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8076. // Verify client is still valid and can make connections
  8077. httplib_client.enable_server_certificate_verification(true);
  8078. auto res = httplib_client.Get("/");
  8079. ASSERT_TRUE(res);
  8080. // Google may return 200 or 301 depending on various factors
  8081. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8082. res->status == StatusCode::MovedPermanently_301);
  8083. }
  8084. TEST(SSLClientTest, ServerNameIndication_Online) {
  8085. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  8086. auto host = "httpcan.org";
  8087. auto path = std::string{"/get"};
  8088. #else
  8089. auto host = "nghttp2.org";
  8090. auto path = std::string{"/httpbin/get"};
  8091. #endif
  8092. SSLClient cli(host, 443);
  8093. auto res = cli.Get(path);
  8094. ASSERT_TRUE(res);
  8095. ASSERT_EQ(StatusCode::OK_200, res->status);
  8096. }
  8097. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8098. // Use a site that will cause SSL verification failure due to self-signed cert
  8099. SSLClient cli("self-signed.badssl.com", 443);
  8100. cli.enable_server_certificate_verification(true);
  8101. auto res = cli.Get("/");
  8102. ASSERT_TRUE(!res);
  8103. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8104. // Verify backend error is captured for SSLServerVerification
  8105. // This occurs when certificate verification fails
  8106. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8107. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8108. EXPECT_NE(0UL, res.ssl_backend_error());
  8109. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8110. // For OpenSSL, ssl_error is 0 for verification errors
  8111. EXPECT_EQ(0, res.ssl_error());
  8112. #if !defined(_WIN32) || \
  8113. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8114. // On non-Windows or when Windows Schannel is disabled, the error comes
  8115. // from OpenSSL's verification
  8116. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8117. res.ssl_backend_error());
  8118. #endif
  8119. #endif
  8120. }
  8121. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8122. // Use a site where hostname doesn't match the certificate
  8123. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8124. SSLClient cli("wrong.host.badssl.com", 443);
  8125. cli.enable_server_certificate_verification(true);
  8126. cli.enable_server_hostname_verification(true);
  8127. auto res = cli.Get("/");
  8128. ASSERT_TRUE(!res);
  8129. // The error type depends on when hostname verification occurs:
  8130. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8131. // - Mbed TLS: SSLServerVerification (during handshake)
  8132. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8133. res.error() == Error::SSLServerVerification);
  8134. // Verify backend error is captured for hostname verification failure
  8135. EXPECT_NE(0UL, res.ssl_backend_error());
  8136. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8137. // For OpenSSL, ssl_error is 0 for verification errors
  8138. EXPECT_EQ(0, res.ssl_error());
  8139. #if !defined(_WIN32) || \
  8140. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8141. // On non-Windows or when Windows Schannel is disabled, the error comes
  8142. // from OpenSSL's hostname verification
  8143. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8144. res.ssl_backend_error());
  8145. #endif
  8146. #endif
  8147. }
  8148. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8149. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8150. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8151. SSLClient cli("www.google.com", 443);
  8152. cli.enable_server_certificate_verification(true);
  8153. auto res = cli.Get("/");
  8154. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8155. }
  8156. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8157. SSLClient cli("www.google.com", 443);
  8158. cli.enable_server_certificate_verification(true);
  8159. cli.enable_windows_certificate_verification(false);
  8160. auto res = cli.Get("/");
  8161. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8162. }
  8163. #endif
  8164. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8165. Client cli("https://google.com");
  8166. auto res = cli.Get("/");
  8167. ASSERT_TRUE(res);
  8168. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8169. }
  8170. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8171. SSLClient cli("google.com");
  8172. cli.set_ca_cert_path(CA_CERT_FILE);
  8173. auto res = cli.Get("/");
  8174. ASSERT_TRUE(res);
  8175. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8176. }
  8177. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8178. SSLClient cli("google.com");
  8179. cli.enable_server_certificate_verification(true);
  8180. cli.set_ca_cert_path("hello");
  8181. auto res = cli.Get("/");
  8182. ASSERT_TRUE(!res);
  8183. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8184. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8185. // should be set
  8186. EXPECT_EQ(0, res.ssl_error());
  8187. // Verify backend error is captured for SSLLoadingCerts
  8188. // This error occurs when loading CA certificates fails
  8189. EXPECT_NE(0UL, res.ssl_backend_error());
  8190. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8191. // OpenSSL specific error codes:
  8192. // > openssl errstr 0x80000002
  8193. // error:80000002:system library::No such file or directory
  8194. // > openssl errstr 0xA000126
  8195. // error:0A000126:SSL routines::unexpected eof while reading
  8196. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8197. res.ssl_backend_error() == 0xA000126);
  8198. #endif
  8199. }
  8200. TEST(SSLClientTest, ServerCertificateVerification4) {
  8201. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8202. ASSERT_TRUE(svr.is_valid());
  8203. svr.Get("/test", [&](const Request &, Response &res) {
  8204. res.set_content("test", "text/plain");
  8205. svr.stop();
  8206. ASSERT_TRUE(true);
  8207. });
  8208. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8209. auto se = detail::scope_exit([&] {
  8210. t.join();
  8211. ASSERT_FALSE(svr.is_running());
  8212. });
  8213. svr.wait_until_ready();
  8214. SSLClient cli("127.0.0.1", PORT);
  8215. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8216. cli.enable_server_certificate_verification(true);
  8217. cli.set_connection_timeout(30);
  8218. auto res = cli.Get("/test");
  8219. ASSERT_TRUE(res);
  8220. ASSERT_EQ(StatusCode::OK_200, res->status);
  8221. }
  8222. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8223. std::string cert;
  8224. read_file(CA_CERT_FILE, cert);
  8225. SSLClient cli("google.com");
  8226. cli.load_ca_cert_store(cert.data(), cert.size());
  8227. const auto res = cli.Get("/");
  8228. ASSERT_TRUE(res);
  8229. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8230. }
  8231. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8232. // clang-format off
  8233. static constexpr char cert[] =
  8234. "GlobalSign Root CA\n"
  8235. "==================\n"
  8236. "-----BEGIN CERTIFICATE-----\n"
  8237. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8238. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8239. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8240. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8241. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8242. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8243. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8244. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8245. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8246. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8247. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8248. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8249. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8250. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8251. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8252. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8253. "-----END CERTIFICATE-----\n";
  8254. // clang-format on
  8255. SSLClient cli("google.com");
  8256. cli.load_ca_cert_store(cert, sizeof(cert));
  8257. const auto res = cli.Get("/");
  8258. ASSERT_TRUE(res);
  8259. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8260. }
  8261. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8262. SSLClient cli("www.youtube.com");
  8263. cli.set_ca_cert_path(CA_CERT_FILE);
  8264. cli.enable_server_certificate_verification(true);
  8265. cli.set_follow_location(true);
  8266. auto res = cli.Get("/");
  8267. ASSERT_TRUE(res);
  8268. ASSERT_EQ(StatusCode::OK_200, res->status);
  8269. }
  8270. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8271. SSLClient cli("wWw.YouTube.Com");
  8272. cli.set_ca_cert_path(CA_CERT_FILE);
  8273. cli.enable_server_certificate_verification(true);
  8274. cli.enable_server_hostname_verification(true);
  8275. cli.set_follow_location(true);
  8276. auto res = cli.Get("/");
  8277. ASSERT_TRUE(res);
  8278. ASSERT_EQ(StatusCode::OK_200, res->status);
  8279. }
  8280. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8281. SSLClient cli("gOoGlE.COm");
  8282. cli.enable_server_certificate_verification(true);
  8283. cli.enable_server_hostname_verification(true);
  8284. cli.set_follow_location(true);
  8285. auto res = cli.Get("/");
  8286. ASSERT_TRUE(res);
  8287. ASSERT_EQ(StatusCode::OK_200, res->status);
  8288. }
  8289. TEST(SSLClientTest, Issue2004_Online) {
  8290. Client client("https://google.com");
  8291. client.set_follow_location(true);
  8292. auto res = client.Get("/");
  8293. ASSERT_TRUE(res);
  8294. ASSERT_EQ(StatusCode::OK_200, res->status);
  8295. auto body = res->body;
  8296. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8297. }
  8298. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8299. // Create SSLClient with invalid cert/key to make is_valid() return false
  8300. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8301. "nonexistent_key.pem");
  8302. // is_valid() should be false due to cert loading failure
  8303. ASSERT_FALSE(cli.is_valid());
  8304. auto res = cli.Get("/");
  8305. ASSERT_FALSE(res);
  8306. EXPECT_EQ(Error::SSLConnection, res.error());
  8307. }
  8308. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8309. // Test for Issue #2251: SSL error not properly reported when client cert
  8310. // and key paths are swapped or mismatched
  8311. // This simulates the scenario where user accidentally swaps the cert and key
  8312. // files
  8313. // Using client cert file as private key and vice versa (completely wrong)
  8314. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8315. // Should fail validation due to cert/key mismatch
  8316. ASSERT_FALSE(cli.is_valid());
  8317. // Attempt to make a request should fail with proper error
  8318. auto res = cli.Get("/");
  8319. ASSERT_FALSE(res);
  8320. EXPECT_EQ(Error::SSLConnection, res.error());
  8321. // SSL error should be recorded in the Result object (this is the key fix for
  8322. // Issue #2251)
  8323. auto backend_error = res.ssl_backend_error();
  8324. EXPECT_NE(0u, backend_error);
  8325. }
  8326. // Tests cert/key mismatch detection at the TLS context level
  8327. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8328. // Test that using mismatched cert/key causes connection failure.
  8329. // We verify this at the SSLClient level rather than through internal
  8330. // TLS API functions.
  8331. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8332. cli.enable_server_certificate_verification(false);
  8333. cli.set_connection_timeout(2);
  8334. // The mismatch should cause a connection or handshake error
  8335. auto res = cli.Get("/test");
  8336. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8337. // Either way, the request should fail
  8338. EXPECT_FALSE(res);
  8339. }
  8340. #endif
  8341. #if 0
  8342. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8343. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8344. ASSERT_TRUE(cli != nullptr);
  8345. cli->set_address_family(AF_INET6);
  8346. cli->set_interface("en0");
  8347. auto res = cli->Get("/get");
  8348. ASSERT_TRUE(res);
  8349. ASSERT_EQ(StatusCode::OK_200, res->status);
  8350. }
  8351. #endif
  8352. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8353. #ifdef CPPHTTPLIB_SSL_ENABLED
  8354. void ClientCertPresent(
  8355. const std::string &client_cert_file,
  8356. const std::string &client_private_key_file,
  8357. const std::string &client_encrypted_private_key_pass = std::string()) {
  8358. using namespace httplib::tls;
  8359. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8360. CLIENT_CA_CERT_DIR);
  8361. ASSERT_TRUE(svr.is_valid());
  8362. svr.Get("/test", [&](const Request &req, Response &res) {
  8363. res.set_content("test", "text/plain");
  8364. auto cert = req.peer_cert();
  8365. ASSERT_TRUE(static_cast<bool>(cert));
  8366. std::string common_name = cert.subject_cn();
  8367. EXPECT_EQ("Common Name", common_name);
  8368. });
  8369. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8370. auto se = detail::scope_exit([&] {
  8371. svr.stop();
  8372. t.join();
  8373. ASSERT_FALSE(svr.is_running());
  8374. });
  8375. svr.wait_until_ready();
  8376. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8377. client_encrypted_private_key_pass);
  8378. cli.enable_server_certificate_verification(false);
  8379. cli.set_connection_timeout(30);
  8380. auto res = cli.Get("/test");
  8381. ASSERT_TRUE(res);
  8382. ASSERT_EQ(StatusCode::OK_200, res->status);
  8383. }
  8384. TEST(SSLClientServerTest, ClientCertPresent) {
  8385. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8386. }
  8387. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8388. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8389. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8390. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8391. }
  8392. // PEM memory-based constructor tests (works with all TLS backends)
  8393. void PemMemoryClientCertPresent(
  8394. const std::string &client_cert_file,
  8395. const std::string &client_private_key_file,
  8396. const std::string &client_encrypted_private_key_pass = std::string()) {
  8397. // Read PEM files into memory
  8398. std::string server_cert_pem, server_key_pem;
  8399. std::string client_ca_pem;
  8400. std::string client_cert_pem, client_key_pem;
  8401. read_file(SERVER_CERT_FILE, server_cert_pem);
  8402. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8403. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8404. read_file(client_cert_file, client_cert_pem);
  8405. read_file(client_private_key_file, client_key_pem);
  8406. // Create server with PEM memory
  8407. SSLServer::PemMemory server_pem = {
  8408. server_cert_pem.c_str(),
  8409. server_cert_pem.size(),
  8410. server_key_pem.c_str(),
  8411. server_key_pem.size(),
  8412. client_ca_pem.c_str(),
  8413. client_ca_pem.size(),
  8414. nullptr // no password for server key
  8415. };
  8416. SSLServer svr(server_pem);
  8417. ASSERT_TRUE(svr.is_valid());
  8418. svr.Get("/test", [&](const Request &, Response &res) {
  8419. res.set_content("test", "text/plain");
  8420. });
  8421. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8422. auto se = detail::scope_exit([&] {
  8423. svr.stop();
  8424. t.join();
  8425. ASSERT_FALSE(svr.is_running());
  8426. });
  8427. svr.wait_until_ready();
  8428. // Create client with PEM memory
  8429. const char *password = client_encrypted_private_key_pass.empty()
  8430. ? nullptr
  8431. : client_encrypted_private_key_pass.c_str();
  8432. SSLClient::PemMemory client_pem = {
  8433. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8434. client_key_pem.size(), password};
  8435. SSLClient cli(HOST, PORT, client_pem);
  8436. cli.enable_server_certificate_verification(false);
  8437. cli.set_connection_timeout(30);
  8438. auto res = cli.Get("/test");
  8439. ASSERT_TRUE(res);
  8440. ASSERT_EQ(StatusCode::OK_200, res->status);
  8441. }
  8442. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8443. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8444. }
  8445. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8446. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8447. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8448. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8449. }
  8450. TEST(SSLClientServerTest, ClientCertMissing) {
  8451. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8452. CLIENT_CA_CERT_DIR);
  8453. ASSERT_TRUE(svr.is_valid());
  8454. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8455. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8456. auto se = detail::scope_exit([&] {
  8457. svr.stop();
  8458. t.join();
  8459. ASSERT_FALSE(svr.is_running());
  8460. });
  8461. svr.wait_until_ready();
  8462. SSLClient cli(HOST, PORT);
  8463. cli.set_connection_timeout(30);
  8464. auto res = cli.Get("/test");
  8465. ASSERT_TRUE(!res);
  8466. // When client cert is missing and server requires it, connection fails
  8467. // Error type depends on backend implementation
  8468. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8469. res.error() == Error::SSLConnection);
  8470. // Verify backend error is captured
  8471. // Note: This test may have different error codes depending on the exact
  8472. // verification failure
  8473. EXPECT_NE(0UL, res.ssl_backend_error());
  8474. }
  8475. TEST(SSLClientServerTest, TrustDirOptional) {
  8476. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8477. ASSERT_TRUE(svr.is_valid());
  8478. svr.Get("/test", [&](const Request &, Response &res) {
  8479. res.set_content("test", "text/plain");
  8480. });
  8481. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8482. auto se = detail::scope_exit([&] {
  8483. svr.stop();
  8484. t.join();
  8485. ASSERT_FALSE(svr.is_running());
  8486. });
  8487. svr.wait_until_ready();
  8488. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8489. cli.enable_server_certificate_verification(false);
  8490. cli.set_connection_timeout(30);
  8491. auto res = cli.Get("/test");
  8492. ASSERT_TRUE(res);
  8493. ASSERT_EQ(StatusCode::OK_200, res->status);
  8494. }
  8495. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8496. class NoListenSSLServer : public SSLServer {
  8497. public:
  8498. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8499. const char *client_ca_cert_file_path,
  8500. const char *client_ca_cert_dir_path = nullptr)
  8501. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8502. client_ca_cert_dir_path),
  8503. stop_(false) {}
  8504. std::atomic_bool stop_;
  8505. private:
  8506. bool process_and_close_socket(socket_t /*sock*/) override {
  8507. // Don't create SSL context
  8508. while (!stop_.load()) {
  8509. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8510. }
  8511. return true;
  8512. }
  8513. };
  8514. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8515. CLIENT_CA_CERT_FILE);
  8516. ASSERT_TRUE(svr.is_valid());
  8517. svr.Get("/test", [&](const Request &, Response &res) {
  8518. res.set_content("test", "text/plain");
  8519. });
  8520. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8521. auto se = detail::scope_exit([&] {
  8522. svr.stop_ = true;
  8523. svr.stop();
  8524. t.join();
  8525. ASSERT_FALSE(svr.is_running());
  8526. });
  8527. svr.wait_until_ready();
  8528. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8529. cli.enable_server_certificate_verification(false);
  8530. cli.set_connection_timeout(1);
  8531. auto res = cli.Get("/test");
  8532. ASSERT_TRUE(!res);
  8533. EXPECT_EQ(Error::SSLConnection, res.error());
  8534. // Timeout results in WantRead error code (maps to backend-specific value)
  8535. EXPECT_NE(0, res.ssl_error());
  8536. }
  8537. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8538. // Test SSLServer with client certificate verification using the standard
  8539. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8540. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8541. CLIENT_CA_CERT_DIR);
  8542. ASSERT_TRUE(svr.is_valid());
  8543. svr.Get("/test", [&](const Request &req, Response &res) {
  8544. res.set_content("test", "text/plain");
  8545. auto cert = req.peer_cert();
  8546. ASSERT_TRUE(static_cast<bool>(cert));
  8547. auto common_name = cert.subject_cn();
  8548. EXPECT_EQ("Common Name", common_name);
  8549. });
  8550. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8551. auto se = detail::scope_exit([&] {
  8552. svr.stop();
  8553. t.join();
  8554. ASSERT_FALSE(svr.is_running());
  8555. });
  8556. svr.wait_until_ready();
  8557. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8558. cli.enable_server_certificate_verification(false);
  8559. cli.set_connection_timeout(30);
  8560. auto res = cli.Get("/test");
  8561. ASSERT_TRUE(res);
  8562. ASSERT_EQ(StatusCode::OK_200, res->status);
  8563. }
  8564. // Test verify_hostname for both OpenSSL and MbedTLS backends
  8565. // Verifies that wildcard matching and exact matching work consistently
  8566. TEST(SSLClientServerTest, TlsVerifyHostname) {
  8567. using namespace httplib::tls;
  8568. // We need a running server to test against
  8569. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8570. ASSERT_TRUE(svr.is_valid());
  8571. svr.Get("/test", [](const Request &, Response &res) {
  8572. res.set_content("ok", "text/plain");
  8573. });
  8574. thread t([&]() { svr.listen(HOST, PORT); });
  8575. auto se = detail::scope_exit([&] {
  8576. svr.stop();
  8577. t.join();
  8578. });
  8579. svr.wait_until_ready();
  8580. bool verify_callback_called = false;
  8581. bool verify_result_wrong = false;
  8582. SSLClient cli(HOST, PORT);
  8583. cli.enable_server_certificate_verification(true);
  8584. cli.set_ca_cert_path(CA_CERT_FILE);
  8585. cli.set_connection_timeout(5);
  8586. // Note: Test certificate has CN="Common Name", not "localhost"
  8587. bool verify_result_cn = false;
  8588. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8589. verify_callback_called = true;
  8590. if (!ctx.cert) return false;
  8591. // Test 1: "Common Name" should match (our test server cert CN)
  8592. verify_result_cn = ctx.check_hostname("Common Name");
  8593. // Test 2: wrong hostname should not match
  8594. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  8595. return true; // Accept for the purpose of this test
  8596. });
  8597. auto res = cli.Get("/test");
  8598. // The request may succeed or fail depending on cert configuration
  8599. // but the callback should have been called
  8600. ASSERT_TRUE(verify_callback_called)
  8601. << "Verify callback should have been called";
  8602. // CN="Common Name" should match our test certificate
  8603. EXPECT_TRUE(verify_result_cn)
  8604. << "verify_hostname should match 'Common Name' (certificate CN)";
  8605. // Wrong hostname should not match
  8606. EXPECT_FALSE(verify_result_wrong)
  8607. << "verify_hostname should not match 'wronghost.example.com'";
  8608. }
  8609. #endif
  8610. // mbedTLS-specific callback constructor test
  8611. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8612. #ifdef CPPHTTPLIB_SSL_ENABLED
  8613. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8614. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8615. ASSERT_TRUE(svr.is_valid());
  8616. // Set up a handler to verify client certificate is present
  8617. bool client_cert_verified = false;
  8618. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8619. // Verify that client certificate was provided
  8620. client_cert_verified = true;
  8621. res.set_content("success", "text/plain");
  8622. });
  8623. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8624. auto se = detail::scope_exit([&] {
  8625. svr.stop();
  8626. t.join();
  8627. ASSERT_FALSE(svr.is_running());
  8628. });
  8629. svr.wait_until_ready();
  8630. // Client with certificate
  8631. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8632. cli.enable_server_certificate_verification(false);
  8633. cli.set_connection_timeout(30);
  8634. auto res = cli.Get("/test");
  8635. ASSERT_TRUE(res);
  8636. ASSERT_EQ(StatusCode::OK_200, res->status);
  8637. ASSERT_TRUE(client_cert_verified);
  8638. EXPECT_EQ("success", res->body);
  8639. }
  8640. #endif
  8641. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  8642. // backends
  8643. #ifdef CPPHTTPLIB_SSL_ENABLED
  8644. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  8645. using namespace httplib::tls;
  8646. // Test that when client CA cert file is provided,
  8647. // the server properly requests and validates client certificates
  8648. // Create a server with client authentication
  8649. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8650. ASSERT_TRUE(svr.is_valid());
  8651. bool handler_called = false;
  8652. svr.Get("/test", [&](const Request &req, Response &res) {
  8653. handler_called = true;
  8654. // Verify that a client certificate was provided
  8655. auto cert = req.peer_cert();
  8656. ASSERT_TRUE(static_cast<bool>(cert));
  8657. // Get the issuer name
  8658. std::string issuer_str = cert.issuer_name();
  8659. ASSERT_FALSE(issuer_str.empty());
  8660. // The client certificate should be issued by our test CA
  8661. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  8662. res.set_content("authenticated", "text/plain");
  8663. });
  8664. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8665. auto se = detail::scope_exit([&] {
  8666. svr.stop();
  8667. t.join();
  8668. ASSERT_FALSE(svr.is_running());
  8669. });
  8670. svr.wait_until_ready();
  8671. // Connect with a client certificate issued by the CA
  8672. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8673. cli.enable_server_certificate_verification(false);
  8674. cli.set_connection_timeout(30);
  8675. auto res = cli.Get("/test");
  8676. ASSERT_TRUE(res);
  8677. ASSERT_EQ(StatusCode::OK_200, res->status);
  8678. ASSERT_TRUE(handler_called);
  8679. EXPECT_EQ("authenticated", res->body);
  8680. }
  8681. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  8682. using namespace httplib::tls;
  8683. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8684. ASSERT_TRUE(svr.is_valid());
  8685. svr.Get("/test", [](const Request &, Response &res) {
  8686. res.set_content("ok", "text/plain");
  8687. });
  8688. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8689. auto se = detail::scope_exit([&] {
  8690. svr.stop();
  8691. t.join();
  8692. });
  8693. svr.wait_until_ready();
  8694. SSLClient cli(HOST, PORT);
  8695. cli.enable_server_certificate_verification(false);
  8696. cli.set_connection_timeout(30);
  8697. bool cert_checked = false;
  8698. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8699. if (ctx.cert) {
  8700. auto sans = ctx.sans();
  8701. // Test certificate may or may not have SANs - just verify the API
  8702. // works If SANs exist, verify the types are valid
  8703. for (const auto &san : sans) {
  8704. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  8705. san.type == SanType::EMAIL || san.type == SanType::URI ||
  8706. san.type == SanType::OTHER);
  8707. EXPECT_FALSE(san.value.empty());
  8708. }
  8709. cert_checked = true;
  8710. }
  8711. return true;
  8712. });
  8713. auto res = cli.Get("/test");
  8714. ASSERT_TRUE(res);
  8715. EXPECT_TRUE(cert_checked);
  8716. }
  8717. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  8718. using namespace httplib::tls;
  8719. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8720. ASSERT_TRUE(svr.is_valid());
  8721. svr.Get("/test", [](const Request &, Response &res) {
  8722. res.set_content("ok", "text/plain");
  8723. });
  8724. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8725. auto se = detail::scope_exit([&] {
  8726. svr.stop();
  8727. t.join();
  8728. });
  8729. svr.wait_until_ready();
  8730. SSLClient cli(HOST, PORT);
  8731. cli.enable_server_certificate_verification(false);
  8732. cli.set_connection_timeout(30);
  8733. bool validity_checked = false;
  8734. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8735. if (ctx.cert) {
  8736. time_t not_before = 0, not_after = 0;
  8737. bool result = ctx.validity(not_before, not_after);
  8738. EXPECT_TRUE(result);
  8739. // Verify that not_before < now < not_after for a valid cert
  8740. time_t now = time(nullptr);
  8741. EXPECT_LT(not_before, now);
  8742. EXPECT_GT(not_after, now);
  8743. validity_checked = true;
  8744. }
  8745. return true;
  8746. });
  8747. auto res = cli.Get("/test");
  8748. ASSERT_TRUE(res);
  8749. EXPECT_TRUE(validity_checked);
  8750. }
  8751. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  8752. using namespace httplib::tls;
  8753. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8754. ASSERT_TRUE(svr.is_valid());
  8755. svr.Get("/test", [](const Request &, Response &res) {
  8756. res.set_content("ok", "text/plain");
  8757. });
  8758. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8759. auto se = detail::scope_exit([&] {
  8760. svr.stop();
  8761. t.join();
  8762. });
  8763. svr.wait_until_ready();
  8764. SSLClient cli(HOST, PORT);
  8765. cli.enable_server_certificate_verification(false);
  8766. cli.set_connection_timeout(30);
  8767. bool serial_checked = false;
  8768. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8769. if (ctx.cert) {
  8770. std::string serial = ctx.serial();
  8771. EXPECT_FALSE(serial.empty());
  8772. // Serial should be a hex string
  8773. for (char c : serial) {
  8774. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  8775. (c >= 'a' && c <= 'f'));
  8776. }
  8777. serial_checked = true;
  8778. }
  8779. return true;
  8780. });
  8781. auto res = cli.Get("/test");
  8782. ASSERT_TRUE(res);
  8783. EXPECT_TRUE(serial_checked);
  8784. }
  8785. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  8786. // Test 1: Valid CA file - no error should be recorded
  8787. {
  8788. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8789. CLIENT_CA_CERT_FILE);
  8790. ASSERT_TRUE(svr.is_valid());
  8791. // With valid setup, last_ssl_error should be 0
  8792. EXPECT_EQ(0, svr.ssl_last_error());
  8793. }
  8794. // Test 2: Invalid CA file content
  8795. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  8796. {
  8797. // Create a temporary file with completely invalid content
  8798. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  8799. {
  8800. std::ofstream ofs(temp_invalid_ca);
  8801. ofs << "This is not a certificate file at all\n";
  8802. ofs << "Just plain text content\n";
  8803. }
  8804. // Create server with invalid CA file
  8805. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  8806. // Clean up temporary file
  8807. std::remove(temp_invalid_ca);
  8808. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  8809. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  8810. // Note: SSL_CTX_load_verify_locations typically fails first,
  8811. // but our error handling code path is still exercised
  8812. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  8813. }
  8814. }
  8815. TEST(VerifyCallbackTest, VerifyContextFields) {
  8816. using namespace httplib::tls;
  8817. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8818. ASSERT_TRUE(svr.is_valid());
  8819. svr.Get("/test", [](const Request &, Response &res) {
  8820. res.set_content("ok", "text/plain");
  8821. });
  8822. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8823. auto se = detail::scope_exit([&] {
  8824. svr.stop();
  8825. t.join();
  8826. });
  8827. svr.wait_until_ready();
  8828. SSLClient cli(HOST, PORT);
  8829. cli.enable_server_certificate_verification(false);
  8830. cli.set_connection_timeout(30);
  8831. int callback_count = 0;
  8832. bool saw_leaf_cert = false;
  8833. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8834. if (ctx.cert) {
  8835. callback_count++;
  8836. // We should see at least one certificate (the leaf)
  8837. std::string cn = ctx.subject_cn();
  8838. if (!cn.empty()) { saw_leaf_cert = true; }
  8839. // Verify context fields are populated
  8840. EXPECT_NE(ctx.session, nullptr);
  8841. EXPECT_GE(ctx.depth, 0);
  8842. }
  8843. return true;
  8844. });
  8845. auto res = cli.Get("/test");
  8846. ASSERT_TRUE(res);
  8847. EXPECT_GT(callback_count, 0);
  8848. EXPECT_TRUE(saw_leaf_cert);
  8849. }
  8850. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  8851. using httplib::tls::TlsError;
  8852. // Test that verify_error_to_string returns empty for success
  8853. std::string success_str = TlsError::verify_error_to_string(0);
  8854. EXPECT_TRUE(success_str.empty());
  8855. // Test that verify_error_to_string returns non-empty for error codes
  8856. // Using a common error code (certificate expired)
  8857. std::string error_str =
  8858. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  8859. EXPECT_FALSE(error_str.empty());
  8860. }
  8861. TEST(SessionVerifierTest, CertificateAccepted) {
  8862. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8863. ASSERT_TRUE(svr.is_valid());
  8864. svr.Get("/test", [](const Request &, Response &res) {
  8865. res.set_content("ok", "text/plain");
  8866. });
  8867. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8868. auto se = detail::scope_exit([&] {
  8869. svr.stop();
  8870. t.join();
  8871. });
  8872. svr.wait_until_ready();
  8873. SSLClient cli(HOST, PORT);
  8874. cli.enable_server_certificate_verification(false);
  8875. cli.set_connection_timeout(30);
  8876. bool callback_called = false;
  8877. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8878. EXPECT_NE(session, nullptr);
  8879. callback_called = true;
  8880. return SSLVerifierResponse::CertificateAccepted;
  8881. });
  8882. auto res = cli.Get("/test");
  8883. ASSERT_TRUE(res);
  8884. EXPECT_EQ(200, res->status);
  8885. EXPECT_TRUE(callback_called);
  8886. }
  8887. TEST(SessionVerifierTest, CertificateRejected) {
  8888. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8889. ASSERT_TRUE(svr.is_valid());
  8890. svr.Get("/test", [](const Request &, Response &res) {
  8891. res.set_content("ok", "text/plain");
  8892. });
  8893. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8894. auto se = detail::scope_exit([&] {
  8895. svr.stop();
  8896. t.join();
  8897. });
  8898. svr.wait_until_ready();
  8899. SSLClient cli(HOST, PORT);
  8900. cli.enable_server_certificate_verification(false);
  8901. cli.set_connection_timeout(30);
  8902. bool callback_called = false;
  8903. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8904. EXPECT_NE(session, nullptr);
  8905. callback_called = true;
  8906. return SSLVerifierResponse::CertificateRejected;
  8907. });
  8908. auto res = cli.Get("/test");
  8909. EXPECT_FALSE(res);
  8910. EXPECT_TRUE(callback_called);
  8911. }
  8912. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  8913. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8914. ASSERT_TRUE(svr.is_valid());
  8915. svr.Get("/test", [](const Request &, Response &res) {
  8916. res.set_content("ok", "text/plain");
  8917. });
  8918. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8919. auto se = detail::scope_exit([&] {
  8920. svr.stop();
  8921. t.join();
  8922. });
  8923. svr.wait_until_ready();
  8924. // NoDecisionMade with verification disabled should succeed (no default check)
  8925. SSLClient cli(HOST, PORT);
  8926. cli.enable_server_certificate_verification(false);
  8927. cli.set_connection_timeout(30);
  8928. bool callback_called = false;
  8929. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8930. EXPECT_NE(session, nullptr);
  8931. callback_called = true;
  8932. return SSLVerifierResponse::NoDecisionMade;
  8933. });
  8934. auto res = cli.Get("/test");
  8935. ASSERT_TRUE(res);
  8936. EXPECT_EQ(200, res->status);
  8937. EXPECT_TRUE(callback_called);
  8938. }
  8939. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  8940. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8941. ASSERT_TRUE(svr.is_valid());
  8942. svr.Get("/test", [](const Request &, Response &res) {
  8943. res.set_content("ok", "text/plain");
  8944. });
  8945. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8946. auto se = detail::scope_exit([&] {
  8947. svr.stop();
  8948. t.join();
  8949. });
  8950. svr.wait_until_ready();
  8951. // NoDecisionMade with verification enabled should fail (self-signed cert).
  8952. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  8953. // so we only check that the request fails, not whether the callback was
  8954. // called.
  8955. SSLClient cli(HOST, PORT);
  8956. cli.enable_server_certificate_verification(true);
  8957. cli.set_connection_timeout(30);
  8958. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8959. EXPECT_NE(session, nullptr);
  8960. return SSLVerifierResponse::NoDecisionMade;
  8961. });
  8962. auto res = cli.Get("/test");
  8963. EXPECT_FALSE(res);
  8964. }
  8965. TEST(SSLClientServerTest, ClientCAListFromPem) {
  8966. // Test SSL server using PemMemory constructor with client CA certificates
  8967. // Read PEM files
  8968. std::string server_cert_pem, server_key_pem, client_ca_pem;
  8969. read_file(SERVER_CERT_FILE, server_cert_pem);
  8970. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8971. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8972. // Create SSLServer with PemMemory constructor including client CA
  8973. SSLServer::PemMemory server_pem = {
  8974. server_cert_pem.c_str(),
  8975. server_cert_pem.size(),
  8976. server_key_pem.c_str(),
  8977. server_key_pem.size(),
  8978. client_ca_pem.c_str(),
  8979. client_ca_pem.size(),
  8980. nullptr // no password for server key
  8981. };
  8982. SSLServer svr(server_pem);
  8983. ASSERT_TRUE(svr.is_valid());
  8984. // No SSL error should be recorded for valid setup
  8985. EXPECT_EQ(0, svr.ssl_last_error());
  8986. // Set up server endpoints
  8987. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  8988. res.set_content("ok", "text/plain");
  8989. });
  8990. // Start server in a thread
  8991. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  8992. svr.wait_until_ready();
  8993. // Connect with client certificate (using constructor with paths)
  8994. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8995. cli.enable_server_certificate_verification(false);
  8996. auto res = cli.Get("/test-pem-ca");
  8997. ASSERT_TRUE(res);
  8998. EXPECT_EQ(200, res->status);
  8999. EXPECT_EQ("ok", res->body);
  9000. svr.stop();
  9001. server_thread.join();
  9002. }
  9003. #endif
  9004. #ifdef _WIN32
  9005. TEST(CleanupTest, WSACleanup) {
  9006. int ret = WSACleanup();
  9007. ASSERT_EQ(0, ret);
  9008. }
  9009. #endif
  9010. #ifndef CPPHTTPLIB_SSL_ENABLED
  9011. TEST(NoSSLSupport, SimpleInterface) {
  9012. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  9013. }
  9014. #endif
  9015. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9016. TEST(InvalidScheme, SimpleInterface) {
  9017. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  9018. }
  9019. #endif
  9020. TEST(NoScheme, SimpleInterface) {
  9021. Client cli("yahoo.com:80");
  9022. ASSERT_TRUE(cli.is_valid());
  9023. }
  9024. TEST(SendAPI, SimpleInterface_Online) {
  9025. Client cli("http://yahoo.com");
  9026. Request req;
  9027. req.method = "GET";
  9028. req.path = "/";
  9029. auto res = cli.send(req);
  9030. ASSERT_TRUE(res);
  9031. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9032. }
  9033. TEST(SendAPI, WithParamsInRequest) {
  9034. Server svr;
  9035. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  9036. EXPECT_TRUE(req.has_param("test"));
  9037. EXPECT_EQ("test_value", req.get_param_value("test"));
  9038. });
  9039. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  9040. auto se = detail::scope_exit([&] {
  9041. svr.stop();
  9042. t.join();
  9043. ASSERT_FALSE(svr.is_running());
  9044. });
  9045. svr.wait_until_ready();
  9046. Client cli(HOST, PORT);
  9047. {
  9048. Request req;
  9049. req.method = "GET";
  9050. req.path = "/";
  9051. req.params.emplace("test", "test_value");
  9052. auto res = cli.send(req);
  9053. ASSERT_TRUE(res);
  9054. }
  9055. {
  9056. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  9057. ASSERT_TRUE(res);
  9058. }
  9059. }
  9060. TEST(ClientImplMethods, GetSocketTest) {
  9061. httplib::Server svr;
  9062. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9063. res.status = StatusCode::OK_200;
  9064. });
  9065. auto port = svr.bind_to_any_port("127.0.0.1");
  9066. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9067. auto se = detail::scope_exit([&] {
  9068. svr.stop();
  9069. thread.join();
  9070. ASSERT_FALSE(svr.is_running());
  9071. });
  9072. svr.wait_until_ready();
  9073. {
  9074. httplib::Client cli("127.0.0.1", port);
  9075. cli.set_keep_alive(true);
  9076. // Use the behavior of cpp-httplib of opening the connection
  9077. // only when the first request happens. If that changes,
  9078. // this test would be obsolete.
  9079. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9080. // This also implicitly tests the server. But other tests would fail much
  9081. // earlier than this one to be considered.
  9082. auto res = cli.Get("/");
  9083. ASSERT_TRUE(res);
  9084. EXPECT_EQ(StatusCode::OK_200, res->status);
  9085. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9086. }
  9087. }
  9088. #ifdef CPPHTTPLIB_SSL_ENABLED
  9089. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9090. Client cli("http://yahoo.com");
  9091. auto res = cli.Get("/");
  9092. ASSERT_TRUE(res);
  9093. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9094. cli.set_follow_location(true);
  9095. res = cli.Get("/");
  9096. ASSERT_TRUE(res);
  9097. EXPECT_EQ(StatusCode::OK_200, res->status);
  9098. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9099. }
  9100. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9101. Client cli("https://yahoo.com");
  9102. auto res = cli.Get("/");
  9103. ASSERT_TRUE(res);
  9104. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9105. cli.set_follow_location(true);
  9106. res = cli.Get("/");
  9107. ASSERT_TRUE(res);
  9108. EXPECT_EQ(StatusCode::OK_200, res->status);
  9109. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9110. }
  9111. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9112. Client cli("https://yahoo.com");
  9113. auto res = cli.Get("/");
  9114. ASSERT_TRUE(res);
  9115. ASSERT_FALSE(!res);
  9116. ASSERT_TRUE(res);
  9117. ASSERT_FALSE(res == nullptr);
  9118. ASSERT_TRUE(res != nullptr);
  9119. EXPECT_EQ(Error::Success, res.error());
  9120. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9121. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9122. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9123. cli.set_follow_location(true);
  9124. res = cli.Get("/");
  9125. ASSERT_TRUE(res);
  9126. EXPECT_EQ(Error::Success, res.error());
  9127. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9128. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9129. EXPECT_EQ(StatusCode::OK_200, res->status);
  9130. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9131. }
  9132. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9133. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9134. Client cli("https://cdnjs.cloudflare.com");
  9135. auto res =
  9136. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9137. ASSERT_TRUE(res);
  9138. EXPECT_EQ(StatusCode::OK_200, res->status);
  9139. EXPECT_EQ(287630U, res->body.size());
  9140. EXPECT_EQ("application/javascript; charset=utf-8",
  9141. res->get_header_value("Content-Type"));
  9142. }
  9143. #endif
  9144. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9145. #undef REDIR_HOST // Silence compiler warning
  9146. #define REDIR_HOST "https://httpbingo.org"
  9147. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9148. Client cli(REDIR_HOST);
  9149. cli.set_follow_location(true);
  9150. auto res =
  9151. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9152. ASSERT_TRUE(res);
  9153. EXPECT_EQ(StatusCode::OK_200, res->status);
  9154. }
  9155. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9156. Client cli(REDIR_HOST);
  9157. cli.set_follow_location(true);
  9158. Params params;
  9159. params.emplace("url", "http://example.com");
  9160. params.emplace("status_code", "302");
  9161. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9162. ASSERT_TRUE(res);
  9163. EXPECT_EQ(StatusCode::OK_200, res->status);
  9164. }
  9165. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9166. Client cli(REDIR_HOST);
  9167. cli.set_follow_location(true);
  9168. Params params;
  9169. params.emplace("url", "http://example.com");
  9170. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9171. ASSERT_TRUE(res);
  9172. EXPECT_EQ(StatusCode::OK_200, res->status);
  9173. }
  9174. TEST(HttpToHttpsRedirectTest, CertFile) {
  9175. auto ssl_port = PORT + 1;
  9176. Server svr;
  9177. ASSERT_TRUE(svr.is_valid());
  9178. svr.Get("/index", [&](const Request &, Response &res) {
  9179. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9180. "/index");
  9181. svr.stop();
  9182. });
  9183. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9184. ASSERT_TRUE(ssl_svr.is_valid());
  9185. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9186. res.set_content("test", "text/plain");
  9187. ssl_svr.stop();
  9188. });
  9189. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9190. thread t2 =
  9191. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9192. auto se = detail::scope_exit([&] {
  9193. t2.join();
  9194. t.join();
  9195. ASSERT_FALSE(svr.is_running());
  9196. });
  9197. svr.wait_until_ready();
  9198. ssl_svr.wait_until_ready();
  9199. Client cli("127.0.0.1", PORT);
  9200. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9201. cli.enable_server_certificate_verification(true);
  9202. cli.set_follow_location(true);
  9203. cli.set_connection_timeout(30);
  9204. auto res = cli.Get("/index");
  9205. ASSERT_TRUE(res);
  9206. ASSERT_EQ(StatusCode::OK_200, res->status);
  9207. }
  9208. TEST(SSLClientRedirectTest, CertFile) {
  9209. auto ssl_port = PORT + 1;
  9210. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9211. ASSERT_TRUE(ssl_svr1.is_valid());
  9212. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9213. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9214. "/index");
  9215. ssl_svr1.stop();
  9216. });
  9217. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9218. ASSERT_TRUE(ssl_svr2.is_valid());
  9219. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9220. res.set_content("test", "text/plain");
  9221. ssl_svr2.stop();
  9222. });
  9223. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9224. thread t2 =
  9225. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9226. auto se = detail::scope_exit([&] {
  9227. t2.join();
  9228. t.join();
  9229. ASSERT_FALSE(ssl_svr1.is_running());
  9230. });
  9231. ssl_svr1.wait_until_ready();
  9232. ssl_svr2.wait_until_ready();
  9233. SSLClient cli("127.0.0.1", PORT);
  9234. std::string cert;
  9235. read_file(SERVER_CERT2_FILE, cert);
  9236. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9237. cli.enable_server_certificate_verification(true);
  9238. cli.set_follow_location(true);
  9239. cli.set_connection_timeout(30);
  9240. auto res = cli.Get("/index");
  9241. ASSERT_TRUE(res);
  9242. ASSERT_EQ(StatusCode::OK_200, res->status);
  9243. }
  9244. #endif
  9245. #ifdef CPPHTTPLIB_SSL_ENABLED
  9246. // Test that set_ca_cert_store() skips system certs (consistent with
  9247. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9248. // should be trusted - system certs should NOT be loaded.
  9249. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9250. // Load a specific cert that is NOT a system CA cert
  9251. std::string cert;
  9252. read_file(SERVER_CERT2_FILE, cert);
  9253. SSLClient cli("google.com");
  9254. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9255. cli.enable_server_certificate_verification(true);
  9256. // This should FAIL because:
  9257. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9258. // 2. System certs should NOT be loaded when custom store is set
  9259. // If system certs WERE loaded, this would succeed
  9260. auto res = cli.Get("/");
  9261. ASSERT_FALSE(res);
  9262. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9263. }
  9264. TEST(MultipartFormDataTest, LargeData) {
  9265. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9266. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9267. const ContentReader &content_reader) {
  9268. if (req.is_multipart_form_data()) {
  9269. std::vector<FormData> items;
  9270. content_reader(
  9271. [&](const FormData &file) {
  9272. items.push_back(file);
  9273. return true;
  9274. },
  9275. [&](const char *data, size_t data_length) {
  9276. items.back().content.append(data, data_length);
  9277. return true;
  9278. });
  9279. EXPECT_TRUE(std::string(items[0].name) == "document");
  9280. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9281. EXPECT_TRUE(items[0].filename == "2MB_data");
  9282. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9283. EXPECT_TRUE(items[1].name == "hello");
  9284. EXPECT_TRUE(items[1].content == "world");
  9285. EXPECT_TRUE(items[1].filename == "");
  9286. EXPECT_TRUE(items[1].content_type == "");
  9287. } else {
  9288. std::string body;
  9289. content_reader([&](const char *data, size_t data_length) {
  9290. body.append(data, data_length);
  9291. return true;
  9292. });
  9293. }
  9294. });
  9295. auto port = svr.bind_to_any_port(HOST);
  9296. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9297. auto se = detail::scope_exit([&] {
  9298. svr.stop();
  9299. t.join();
  9300. ASSERT_FALSE(svr.is_running());
  9301. });
  9302. svr.wait_until_ready();
  9303. {
  9304. std::string data(1024 * 1024 * 2, '.');
  9305. std::stringstream buffer;
  9306. buffer << data;
  9307. SSLClient cli(HOST, port);
  9308. cli.enable_server_certificate_verification(false);
  9309. UploadFormDataItems items{
  9310. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9311. {"hello", "world", "", ""},
  9312. };
  9313. auto res = cli.Post("/post", items);
  9314. ASSERT_TRUE(res);
  9315. ASSERT_EQ(StatusCode::OK_200, res->status);
  9316. }
  9317. }
  9318. TEST(MultipartFormDataTest, DataProviderItems) {
  9319. std::random_device seed_gen;
  9320. std::mt19937 random(seed_gen());
  9321. std::string rand1;
  9322. rand1.resize(1000);
  9323. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9324. std::string rand2;
  9325. rand2.resize(3000);
  9326. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9327. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9328. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9329. const ContentReader &content_reader) {
  9330. ASSERT_FALSE(req.is_multipart_form_data());
  9331. std::string body;
  9332. content_reader([&](const char *data, size_t data_length) {
  9333. body.append(data, data_length);
  9334. return true;
  9335. });
  9336. EXPECT_EQ(body, "");
  9337. });
  9338. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9339. const ContentReader &content_reader) {
  9340. ASSERT_TRUE(req.is_multipart_form_data());
  9341. std::vector<FormData> items;
  9342. content_reader(
  9343. [&](const FormData &file) {
  9344. items.push_back(file);
  9345. return true;
  9346. },
  9347. [&](const char *data, size_t data_length) {
  9348. items.back().content.append(data, data_length);
  9349. return true;
  9350. });
  9351. ASSERT_TRUE(items.size() == 2);
  9352. EXPECT_EQ(std::string(items[0].name), "name1");
  9353. EXPECT_EQ(items[0].content, "Testing123");
  9354. EXPECT_EQ(items[0].filename, "filename1");
  9355. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9356. EXPECT_EQ(items[1].name, "name2");
  9357. EXPECT_EQ(items[1].content, "Testing456");
  9358. EXPECT_EQ(items[1].filename, "");
  9359. EXPECT_EQ(items[1].content_type, "");
  9360. });
  9361. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9362. const ContentReader &content_reader) {
  9363. ASSERT_TRUE(req.is_multipart_form_data());
  9364. std::vector<FormData> items;
  9365. content_reader(
  9366. [&](const FormData &file) {
  9367. items.push_back(file);
  9368. return true;
  9369. },
  9370. [&](const char *data, size_t data_length) {
  9371. items.back().content.append(data, data_length);
  9372. return true;
  9373. });
  9374. ASSERT_TRUE(items.size() == 2);
  9375. EXPECT_EQ(items[0].name, "name3");
  9376. EXPECT_EQ(items[0].content, rand1);
  9377. EXPECT_EQ(items[0].filename, "filename3");
  9378. EXPECT_EQ(items[0].content_type, "");
  9379. EXPECT_EQ(items[1].name, "name4");
  9380. EXPECT_EQ(items[1].content, rand2);
  9381. EXPECT_EQ(items[1].filename, "filename4");
  9382. EXPECT_EQ(items[1].content_type, "");
  9383. });
  9384. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9385. const ContentReader &content_reader) {
  9386. ASSERT_TRUE(req.is_multipart_form_data());
  9387. std::vector<FormData> items;
  9388. content_reader(
  9389. [&](const FormData &file) {
  9390. items.push_back(file);
  9391. return true;
  9392. },
  9393. [&](const char *data, size_t data_length) {
  9394. items.back().content.append(data, data_length);
  9395. return true;
  9396. });
  9397. ASSERT_TRUE(items.size() == 4);
  9398. EXPECT_EQ(std::string(items[0].name), "name1");
  9399. EXPECT_EQ(items[0].content, "Testing123");
  9400. EXPECT_EQ(items[0].filename, "filename1");
  9401. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9402. EXPECT_EQ(items[1].name, "name2");
  9403. EXPECT_EQ(items[1].content, "Testing456");
  9404. EXPECT_EQ(items[1].filename, "");
  9405. EXPECT_EQ(items[1].content_type, "");
  9406. EXPECT_EQ(items[2].name, "name3");
  9407. EXPECT_EQ(items[2].content, rand1);
  9408. EXPECT_EQ(items[2].filename, "filename3");
  9409. EXPECT_EQ(items[2].content_type, "");
  9410. EXPECT_EQ(items[3].name, "name4");
  9411. EXPECT_EQ(items[3].content, rand2);
  9412. EXPECT_EQ(items[3].filename, "filename4");
  9413. EXPECT_EQ(items[3].content_type, "");
  9414. });
  9415. auto port = svr.bind_to_any_port("localhost");
  9416. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9417. auto se = detail::scope_exit([&] {
  9418. svr.stop();
  9419. t.join();
  9420. ASSERT_FALSE(svr.is_running());
  9421. });
  9422. svr.wait_until_ready();
  9423. {
  9424. SSLClient cli("localhost", port);
  9425. cli.enable_server_certificate_verification(false);
  9426. UploadFormDataItems items{
  9427. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9428. {"name2", "Testing456", "", ""}, // not a file
  9429. };
  9430. {
  9431. auto res = cli.Post("/post-none", {}, {}, {});
  9432. ASSERT_TRUE(res);
  9433. ASSERT_EQ(StatusCode::OK_200, res->status);
  9434. }
  9435. FormDataProviderItems providers;
  9436. {
  9437. auto res =
  9438. cli.Post("/post-items", {}, items, providers); // empty providers
  9439. ASSERT_TRUE(res);
  9440. ASSERT_EQ(StatusCode::OK_200, res->status);
  9441. }
  9442. providers.push_back({"name3",
  9443. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9444. // test the offset is given correctly at each step
  9445. if (!offset)
  9446. sink.os.write(rand1.data(), 30);
  9447. else if (offset == 30)
  9448. sink.os.write(rand1.data() + 30, 300);
  9449. else if (offset == 330)
  9450. sink.os.write(rand1.data() + 330, 670);
  9451. else if (offset == rand1.size())
  9452. sink.done();
  9453. return true;
  9454. },
  9455. "filename3",
  9456. {}});
  9457. providers.push_back({"name4",
  9458. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9459. // test the offset is given correctly at each step
  9460. if (!offset)
  9461. sink.os.write(rand2.data(), 2000);
  9462. else if (offset == 2000)
  9463. sink.os.write(rand2.data() + 2000, 1);
  9464. else if (offset == 2001)
  9465. sink.os.write(rand2.data() + 2001, 999);
  9466. else if (offset == rand2.size())
  9467. sink.done();
  9468. return true;
  9469. },
  9470. "filename4",
  9471. {}});
  9472. {
  9473. auto res = cli.Post("/post-providers", {}, {}, providers);
  9474. ASSERT_TRUE(res);
  9475. ASSERT_EQ(StatusCode::OK_200, res->status);
  9476. }
  9477. {
  9478. auto res = cli.Post("/post-both", {}, items, providers);
  9479. ASSERT_TRUE(res);
  9480. ASSERT_EQ(StatusCode::OK_200, res->status);
  9481. }
  9482. }
  9483. }
  9484. TEST(MultipartFormDataTest, BadHeader) {
  9485. Server svr;
  9486. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9487. res.set_content("ok", "text/plain");
  9488. });
  9489. thread t = thread([&] { svr.listen(HOST, PORT); });
  9490. auto se = detail::scope_exit([&] {
  9491. svr.stop();
  9492. t.join();
  9493. ASSERT_FALSE(svr.is_running());
  9494. });
  9495. svr.wait_until_ready();
  9496. const std::string body =
  9497. "This is the preamble. It is to be ignored, though it\r\n"
  9498. "is a handy place for composition agents to include an\r\n"
  9499. "explanatory note to non-MIME conformant readers.\r\n"
  9500. "\r\n"
  9501. "\r\n"
  9502. "--simple boundary\r\n"
  9503. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9504. ": BAD...\r\n"
  9505. "\r\n"
  9506. "value1\r\n"
  9507. "--simple boundary\r\n"
  9508. "Content-Disposition: form-data; name=\"field2\"; "
  9509. "filename=\"example.txt\"\r\n"
  9510. "\r\n"
  9511. "value2\r\n"
  9512. "--simple boundary--\r\n"
  9513. "This is the epilogue. It is also to be ignored.\r\n";
  9514. std::string content_type =
  9515. R"(multipart/form-data; boundary="simple boundary")";
  9516. Client cli(HOST, PORT);
  9517. auto res = cli.Post("/post", body, content_type.c_str());
  9518. ASSERT_TRUE(res);
  9519. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9520. }
  9521. TEST(MultipartFormDataTest, WithPreamble) {
  9522. Server svr;
  9523. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9524. res.set_content("ok", "text/plain");
  9525. });
  9526. thread t = thread([&] { svr.listen(HOST, PORT); });
  9527. auto se = detail::scope_exit([&] {
  9528. svr.stop();
  9529. t.join();
  9530. ASSERT_FALSE(svr.is_running());
  9531. });
  9532. svr.wait_until_ready();
  9533. const std::string body =
  9534. "This is the preamble. It is to be ignored, though it\r\n"
  9535. "is a handy place for composition agents to include an\r\n"
  9536. "explanatory note to non-MIME conformant readers.\r\n"
  9537. "\r\n"
  9538. "\r\n"
  9539. "--simple boundary\r\n"
  9540. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9541. "\r\n"
  9542. "value1\r\n"
  9543. "--simple boundary\r\n"
  9544. "Content-Disposition: form-data; name=\"field2\"; "
  9545. "filename=\"example.txt\"\r\n"
  9546. "\r\n"
  9547. "value2\r\n"
  9548. "--simple boundary--\r\n"
  9549. "This is the epilogue. It is also to be ignored.\r\n";
  9550. std::string content_type =
  9551. R"(multipart/form-data; boundary="simple boundary")";
  9552. Client cli(HOST, PORT);
  9553. auto res = cli.Post("/post", body, content_type.c_str());
  9554. ASSERT_TRUE(res);
  9555. EXPECT_EQ(StatusCode::OK_200, res->status);
  9556. }
  9557. TEST(MultipartFormDataTest, PostCustomBoundary) {
  9558. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9559. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  9560. const ContentReader &content_reader) {
  9561. if (req.is_multipart_form_data()) {
  9562. std::vector<FormData> items;
  9563. content_reader(
  9564. [&](const FormData &file) {
  9565. items.push_back(file);
  9566. return true;
  9567. },
  9568. [&](const char *data, size_t data_length) {
  9569. items.back().content.append(data, data_length);
  9570. return true;
  9571. });
  9572. EXPECT_TRUE(std::string(items[0].name) == "document");
  9573. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9574. EXPECT_TRUE(items[0].filename == "2MB_data");
  9575. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9576. EXPECT_TRUE(items[1].name == "hello");
  9577. EXPECT_TRUE(items[1].content == "world");
  9578. EXPECT_TRUE(items[1].filename == "");
  9579. EXPECT_TRUE(items[1].content_type == "");
  9580. } else {
  9581. std::string body;
  9582. content_reader([&](const char *data, size_t data_length) {
  9583. body.append(data, data_length);
  9584. return true;
  9585. });
  9586. }
  9587. });
  9588. auto port = svr.bind_to_any_port("localhost");
  9589. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9590. auto se = detail::scope_exit([&] {
  9591. svr.stop();
  9592. t.join();
  9593. ASSERT_FALSE(svr.is_running());
  9594. });
  9595. svr.wait_until_ready();
  9596. {
  9597. std::string data(1024 * 1024 * 2, '.');
  9598. std::stringstream buffer;
  9599. buffer << data;
  9600. SSLClient cli("localhost", port);
  9601. cli.enable_server_certificate_verification(false);
  9602. UploadFormDataItems items{
  9603. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9604. {"hello", "world", "", ""},
  9605. };
  9606. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9607. ASSERT_TRUE(res);
  9608. ASSERT_EQ(StatusCode::OK_200, res->status);
  9609. }
  9610. }
  9611. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9612. std::string data(1024 * 1024 * 2, '&');
  9613. std::stringstream buffer;
  9614. buffer << data;
  9615. Client cli("https://localhost:8080");
  9616. UploadFormDataItems items{
  9617. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9618. {"hello", "world", "", ""},
  9619. };
  9620. for (const char &c : " \t\r\n") {
  9621. auto res =
  9622. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9623. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9624. ASSERT_FALSE(res);
  9625. }
  9626. }
  9627. TEST(MultipartFormDataTest, PutFormData) {
  9628. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9629. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9630. const ContentReader &content_reader) {
  9631. if (req.is_multipart_form_data()) {
  9632. std::vector<FormData> items;
  9633. content_reader(
  9634. [&](const FormData &file) {
  9635. items.push_back(file);
  9636. return true;
  9637. },
  9638. [&](const char *data, size_t data_length) {
  9639. items.back().content.append(data, data_length);
  9640. return true;
  9641. });
  9642. EXPECT_TRUE(std::string(items[0].name) == "document");
  9643. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9644. EXPECT_TRUE(items[0].filename == "2MB_data");
  9645. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9646. EXPECT_TRUE(items[1].name == "hello");
  9647. EXPECT_TRUE(items[1].content == "world");
  9648. EXPECT_TRUE(items[1].filename == "");
  9649. EXPECT_TRUE(items[1].content_type == "");
  9650. } else {
  9651. std::string body;
  9652. content_reader([&](const char *data, size_t data_length) {
  9653. body.append(data, data_length);
  9654. return true;
  9655. });
  9656. }
  9657. });
  9658. auto port = svr.bind_to_any_port("localhost");
  9659. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9660. auto se = detail::scope_exit([&] {
  9661. svr.stop();
  9662. t.join();
  9663. ASSERT_FALSE(svr.is_running());
  9664. });
  9665. svr.wait_until_ready();
  9666. {
  9667. std::string data(1024 * 1024 * 2, '&');
  9668. std::stringstream buffer;
  9669. buffer << data;
  9670. SSLClient cli("localhost", port);
  9671. cli.enable_server_certificate_verification(false);
  9672. UploadFormDataItems items{
  9673. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9674. {"hello", "world", "", ""},
  9675. };
  9676. auto res = cli.Put("/put", items);
  9677. ASSERT_TRUE(res);
  9678. ASSERT_EQ(StatusCode::OK_200, res->status);
  9679. }
  9680. }
  9681. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  9682. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9683. svr.Put("/put_customboundary",
  9684. [&](const Request &req, const Response & /*res*/,
  9685. const ContentReader &content_reader) {
  9686. if (req.is_multipart_form_data()) {
  9687. std::vector<FormData> items;
  9688. content_reader(
  9689. [&](const FormData &file) {
  9690. items.push_back(file);
  9691. return true;
  9692. },
  9693. [&](const char *data, size_t data_length) {
  9694. items.back().content.append(data, data_length);
  9695. return true;
  9696. });
  9697. EXPECT_TRUE(std::string(items[0].name) == "document");
  9698. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9699. EXPECT_TRUE(items[0].filename == "2MB_data");
  9700. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9701. EXPECT_TRUE(items[1].name == "hello");
  9702. EXPECT_TRUE(items[1].content == "world");
  9703. EXPECT_TRUE(items[1].filename == "");
  9704. EXPECT_TRUE(items[1].content_type == "");
  9705. } else {
  9706. std::string body;
  9707. content_reader([&](const char *data, size_t data_length) {
  9708. body.append(data, data_length);
  9709. return true;
  9710. });
  9711. }
  9712. });
  9713. auto port = svr.bind_to_any_port("localhost");
  9714. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9715. auto se = detail::scope_exit([&] {
  9716. svr.stop();
  9717. t.join();
  9718. ASSERT_FALSE(svr.is_running());
  9719. });
  9720. svr.wait_until_ready();
  9721. {
  9722. std::string data(1024 * 1024 * 2, '&');
  9723. std::stringstream buffer;
  9724. buffer << data;
  9725. SSLClient cli("localhost", port);
  9726. cli.enable_server_certificate_verification(false);
  9727. UploadFormDataItems items{
  9728. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9729. {"hello", "world", "", ""},
  9730. };
  9731. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  9732. ASSERT_TRUE(res);
  9733. ASSERT_EQ(StatusCode::OK_200, res->status);
  9734. }
  9735. }
  9736. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  9737. std::string data(1024 * 1024 * 2, '&');
  9738. std::stringstream buffer;
  9739. buffer << data;
  9740. Client cli("https://localhost:8080");
  9741. cli.enable_server_certificate_verification(false);
  9742. UploadFormDataItems items{
  9743. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9744. {"hello", "world", "", ""},
  9745. };
  9746. for (const char &c : " \t\r\n") {
  9747. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  9748. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9749. ASSERT_FALSE(res);
  9750. }
  9751. }
  9752. TEST(MultipartFormDataTest, AlternateFilename) {
  9753. auto handled = false;
  9754. Server svr;
  9755. svr.Post("/test", [&](const Request &req, Response &res) {
  9756. ASSERT_EQ(2u, req.form.files.size());
  9757. ASSERT_EQ(1u, req.form.fields.size());
  9758. // Test files
  9759. const auto &file1 = req.form.get_file("file1");
  9760. ASSERT_EQ("file1", file1.name);
  9761. ASSERT_EQ("A.txt", file1.filename);
  9762. ASSERT_EQ("text/plain", file1.content_type);
  9763. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  9764. const auto &file2 = req.form.get_file("file2");
  9765. ASSERT_EQ("file2", file2.name);
  9766. ASSERT_EQ("a.html", file2.filename);
  9767. ASSERT_EQ("text/html", file2.content_type);
  9768. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  9769. file2.content);
  9770. // Test text field
  9771. const auto &text = req.form.get_field("text");
  9772. ASSERT_EQ("text default", text);
  9773. res.set_content("ok", "text/plain");
  9774. handled = true;
  9775. });
  9776. thread t = thread([&] { svr.listen(HOST, PORT); });
  9777. auto se = detail::scope_exit([&] {
  9778. svr.stop();
  9779. t.join();
  9780. ASSERT_FALSE(svr.is_running());
  9781. ASSERT_TRUE(handled);
  9782. });
  9783. svr.wait_until_ready();
  9784. auto req = "POST /test HTTP/1.1\r\n"
  9785. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9786. "Content-Length: 399\r\n"
  9787. "\r\n"
  9788. "----------\r\n"
  9789. "Content-Disposition: form-data; name=\"text\"\r\n"
  9790. "\r\n"
  9791. "text default\r\n"
  9792. "----------\r\n"
  9793. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  9794. "filename=\"a.txt\"; name=\"file1\"\r\n"
  9795. "Content-Type: text/plain\r\n"
  9796. "\r\n"
  9797. "Content of a.txt.\r\n"
  9798. "\r\n"
  9799. "----------\r\n"
  9800. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  9801. "\"a.html\"\r\n"
  9802. "Content-Type: text/html\r\n"
  9803. "\r\n"
  9804. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  9805. "\r\n"
  9806. "------------\r\n";
  9807. ASSERT_TRUE(send_request(1, req));
  9808. }
  9809. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  9810. auto handled = false;
  9811. Server svr;
  9812. svr.Post("/test", [&](const Request &req, Response &res) {
  9813. // Case-insensitive "utf-8''" prefix with a long value
  9814. const auto &file = req.form.get_file("file1");
  9815. ASSERT_EQ("file1", file.name);
  9816. // 8000 chars exercises both the Content-Disposition parser and the
  9817. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  9818. // Prior to the fix, std::regex_match on this header would cause O(N)
  9819. // stack recursion in libstdc++, leading to SIGSEGV.
  9820. std::string expected_filename(8000, 'A');
  9821. ASSERT_EQ(expected_filename, file.filename);
  9822. res.set_content("ok", "text/plain");
  9823. handled = true;
  9824. });
  9825. thread t = thread([&] { svr.listen(HOST, PORT); });
  9826. auto se = detail::scope_exit([&] {
  9827. svr.stop();
  9828. t.join();
  9829. ASSERT_FALSE(svr.is_running());
  9830. ASSERT_TRUE(handled);
  9831. });
  9832. svr.wait_until_ready();
  9833. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  9834. // Regression test for GHSA-qq6v-r583-3h69
  9835. std::string long_filename(8000, 'A');
  9836. std::string body = "----------\r\n"
  9837. "Content-Disposition: form-data; name=\"file1\"; "
  9838. "filename*=\"Utf-8''" +
  9839. long_filename +
  9840. "\"\r\n"
  9841. "\r\n"
  9842. "hello\r\n"
  9843. "------------\r\n";
  9844. auto req = "POST /test HTTP/1.1\r\n"
  9845. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9846. "Content-Length: " +
  9847. std::to_string(body.size()) + "\r\n\r\n" + body;
  9848. ASSERT_TRUE(send_request(1, req));
  9849. }
  9850. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  9851. auto handled = false;
  9852. Server svr;
  9853. svr.Post("/test", [&](const Request &req, Response &) {
  9854. ASSERT_EQ(2u, req.form.fields.size());
  9855. const auto &text1 = req.form.get_field("text1");
  9856. ASSERT_EQ("text1", text1);
  9857. const auto &text2 = req.form.get_field("text2");
  9858. ASSERT_EQ("text2", text2);
  9859. handled = true;
  9860. });
  9861. thread t = thread([&] { svr.listen(HOST, PORT); });
  9862. auto se = detail::scope_exit([&] {
  9863. svr.stop();
  9864. t.join();
  9865. ASSERT_FALSE(svr.is_running());
  9866. ASSERT_TRUE(handled);
  9867. });
  9868. svr.wait_until_ready();
  9869. auto req = "POST /test HTTP/1.1\r\n"
  9870. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9871. "Content-Length: 146\r\n"
  9872. "\r\n----------\r\n"
  9873. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9874. "\r\n"
  9875. "text1"
  9876. "\r\n----------\r\n"
  9877. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9878. "\r\n"
  9879. "text2"
  9880. "\r\n------------";
  9881. std::string response;
  9882. ASSERT_TRUE(send_request(1, req, &response));
  9883. ASSERT_EQ("200", response.substr(9, 3));
  9884. }
  9885. TEST(MultipartFormDataTest, ContentLength) {
  9886. auto handled = false;
  9887. Server svr;
  9888. svr.Post("/test", [&](const Request &req, Response &) {
  9889. ASSERT_EQ(2u, req.form.fields.size());
  9890. const auto &text1 = req.form.get_field("text1");
  9891. ASSERT_EQ("text1", text1);
  9892. const auto &text2 = req.form.get_field("text2");
  9893. ASSERT_EQ("text2", text2);
  9894. handled = true;
  9895. });
  9896. thread t = thread([&] { svr.listen(HOST, PORT); });
  9897. auto se = detail::scope_exit([&] {
  9898. svr.stop();
  9899. t.join();
  9900. ASSERT_FALSE(svr.is_running());
  9901. ASSERT_TRUE(handled);
  9902. });
  9903. svr.wait_until_ready();
  9904. auto req = "POST /test HTTP/1.1\r\n"
  9905. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9906. "Content-Length: 167\r\n"
  9907. "\r\n----------\r\n"
  9908. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9909. "Content-Length: 5\r\n"
  9910. "\r\n"
  9911. "text1"
  9912. "\r\n----------\r\n"
  9913. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9914. "\r\n"
  9915. "text2"
  9916. "\r\n------------\r\n";
  9917. std::string response;
  9918. ASSERT_TRUE(send_request(1, req, &response));
  9919. ASSERT_EQ("200", response.substr(9, 3));
  9920. }
  9921. TEST(MultipartFormDataTest, AccessPartHeaders) {
  9922. auto handled = false;
  9923. Server svr;
  9924. svr.Post("/test", [&](const Request &req, Response &) {
  9925. ASSERT_EQ(2u, req.form.fields.size());
  9926. const auto &text1 = req.form.get_field("text1");
  9927. ASSERT_EQ("text1", text1);
  9928. // TODO: Add header access for text fields if needed
  9929. const auto &text2 = req.form.get_field("text2");
  9930. ASSERT_EQ("text2", text2);
  9931. // TODO: Header access for text fields needs to be implemented
  9932. // auto &headers = it->second.headers;
  9933. // ASSERT_EQ(3U, headers.size());
  9934. // auto custom_header = headers.find("x-whatever");
  9935. // ASSERT_TRUE(custom_header != headers.end());
  9936. // ASSERT_NE("customvalue", custom_header->second);
  9937. // ASSERT_EQ("CustomValue", custom_header->second);
  9938. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  9939. handled = true;
  9940. });
  9941. thread t = thread([&] { svr.listen(HOST, PORT); });
  9942. auto se = detail::scope_exit([&] {
  9943. svr.stop();
  9944. t.join();
  9945. ASSERT_FALSE(svr.is_running());
  9946. ASSERT_TRUE(handled);
  9947. });
  9948. svr.wait_until_ready();
  9949. auto req = "POST /test HTTP/1.1\r\n"
  9950. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9951. "Content-Length: 232\r\n"
  9952. "\r\n----------\r\n"
  9953. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9954. "Content-Length: 5\r\n"
  9955. "X-Test: 1\r\n"
  9956. "\r\n"
  9957. "text1"
  9958. "\r\n----------\r\n"
  9959. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9960. "Content-Type: text/plain\r\n"
  9961. "X-Whatever: CustomValue\r\n"
  9962. "\r\n"
  9963. "text2"
  9964. "\r\n------------\r\n"
  9965. "That should be disregarded. Not even read";
  9966. std::string response;
  9967. ASSERT_TRUE(send_request(1, req, &response));
  9968. ASSERT_EQ("200", response.substr(9, 3));
  9969. }
  9970. TEST(MultipartFormDataTest, LargeHeader) {
  9971. auto handled = false;
  9972. Server svr;
  9973. svr.Post("/test", [&](const Request &req, Response &) {
  9974. ASSERT_EQ(1u, req.form.fields.size());
  9975. const auto &text = req.form.get_field("name1");
  9976. ASSERT_EQ("text1", text);
  9977. handled = true;
  9978. });
  9979. thread t = thread([&] { svr.listen(HOST, PORT); });
  9980. auto se = detail::scope_exit([&] {
  9981. svr.stop();
  9982. t.join();
  9983. ASSERT_FALSE(svr.is_running());
  9984. ASSERT_TRUE(handled);
  9985. });
  9986. svr.wait_until_ready();
  9987. auto boundary = std::string("cpp-httplib-multipart-data");
  9988. std::string content = "--" + boundary +
  9989. "\r\n"
  9990. "Content-Disposition: form-data; name=\"name1\"\r\n"
  9991. "\r\n"
  9992. "text1\r\n"
  9993. "--" +
  9994. boundary + "--\r\n";
  9995. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  9996. "Content-Type: multipart/form-data;boundary=" +
  9997. boundary +
  9998. "\r\n"
  9999. "Content-Length: " +
  10000. std::to_string(content.size()) +
  10001. "\r\n"
  10002. "Dummy-Header: ";
  10003. std::string header_suffix = "\r\n"
  10004. "\r\n";
  10005. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  10006. size_t header_dummy_size =
  10007. read_buff_size -
  10008. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  10009. auto header_dummy = std::string(header_dummy_size, '@');
  10010. auto req = header_prefix + header_dummy + header_suffix + content;
  10011. std::string response;
  10012. ASSERT_TRUE(send_request(1, req, &response));
  10013. ASSERT_EQ("200", response.substr(9, 3));
  10014. }
  10015. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  10016. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  10017. // (not chunked Transfer-Encoding) after the streaming refactor.
  10018. auto handled = false;
  10019. Server svr;
  10020. svr.Post("/upload", [&](const Request &req, Response &res) {
  10021. auto cl_it = req.headers.find("Content-Length");
  10022. EXPECT_TRUE(cl_it != req.headers.end());
  10023. auto te_it = req.headers.find("Transfer-Encoding");
  10024. EXPECT_TRUE(te_it == req.headers.end());
  10025. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  10026. res.set_content("ok", "text/plain");
  10027. handled = true;
  10028. });
  10029. auto port = svr.bind_to_any_port(HOST);
  10030. auto t = thread([&] { svr.listen_after_bind(); });
  10031. auto se = detail::scope_exit([&] {
  10032. svr.stop();
  10033. t.join();
  10034. ASSERT_FALSE(svr.is_running());
  10035. ASSERT_TRUE(handled);
  10036. });
  10037. svr.wait_until_ready();
  10038. UploadFormDataItems items = {
  10039. {"field1", "hello", "", "text/plain"},
  10040. {"file1", "world", "test.txt", "application/octet-stream"},
  10041. };
  10042. Client cli(HOST, port);
  10043. auto res = cli.Post("/upload", {}, items);
  10044. ASSERT_TRUE(res);
  10045. EXPECT_EQ(StatusCode::OK_200, res->status);
  10046. }
  10047. TEST(MultipartFormDataTest, MakeFileProvider) {
  10048. // Verify make_file_provider sends a file's contents correctly.
  10049. const std::string file_content(4096, 'Z');
  10050. const std::string tmp_path = "/tmp/httplib_test_make_file_provider.bin";
  10051. {
  10052. std::ofstream ofs(tmp_path, std::ios::binary);
  10053. ofs.write(file_content.data(),
  10054. static_cast<std::streamsize>(file_content.size()));
  10055. }
  10056. auto handled = false;
  10057. Server svr;
  10058. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  10059. const ContentReader &content_reader) {
  10060. ASSERT_TRUE(req.is_multipart_form_data());
  10061. std::vector<FormData> items;
  10062. content_reader(
  10063. [&](const FormData &file) {
  10064. items.push_back(file);
  10065. return true;
  10066. },
  10067. [&](const char *data, size_t data_length) {
  10068. items.back().content.append(data, data_length);
  10069. return true;
  10070. });
  10071. ASSERT_EQ(1u, items.size());
  10072. EXPECT_EQ("myfile", items[0].name);
  10073. EXPECT_EQ("data.bin", items[0].filename);
  10074. EXPECT_EQ("application/octet-stream", items[0].content_type);
  10075. EXPECT_EQ(file_content, items[0].content);
  10076. handled = true;
  10077. });
  10078. auto port = svr.bind_to_any_port(HOST);
  10079. auto t = thread([&] { svr.listen_after_bind(); });
  10080. auto se = detail::scope_exit([&] {
  10081. svr.stop();
  10082. t.join();
  10083. ASSERT_FALSE(svr.is_running());
  10084. ASSERT_TRUE(handled);
  10085. std::remove(tmp_path.c_str());
  10086. });
  10087. svr.wait_until_ready();
  10088. FormDataProviderItems providers;
  10089. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  10090. "application/octet-stream"));
  10091. Client cli(HOST, port);
  10092. auto res = cli.Post("/upload", {}, {}, providers);
  10093. ASSERT_TRUE(res);
  10094. EXPECT_EQ(StatusCode::OK_200, res->status);
  10095. }
  10096. TEST(MakeFileBodyTest, Basic) {
  10097. const std::string file_content(4096, 'Z');
  10098. const std::string tmp_path = "/tmp/httplib_test_make_file_body.bin";
  10099. {
  10100. std::ofstream ofs(tmp_path, std::ios::binary);
  10101. ofs.write(file_content.data(),
  10102. static_cast<std::streamsize>(file_content.size()));
  10103. }
  10104. auto handled = false;
  10105. Server svr;
  10106. svr.Post("/upload", [&](const Request &req, Response &res) {
  10107. EXPECT_EQ(file_content, req.body);
  10108. handled = true;
  10109. res.status = StatusCode::OK_200;
  10110. });
  10111. auto port = svr.bind_to_any_port(HOST);
  10112. auto t = thread([&] { svr.listen_after_bind(); });
  10113. auto se = detail::scope_exit([&] {
  10114. svr.stop();
  10115. t.join();
  10116. ASSERT_FALSE(svr.is_running());
  10117. ASSERT_TRUE(handled);
  10118. std::remove(tmp_path.c_str());
  10119. });
  10120. svr.wait_until_ready();
  10121. auto fb = make_file_body(tmp_path);
  10122. ASSERT_GT(fb.first, 0u);
  10123. Client cli(HOST, port);
  10124. auto res =
  10125. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  10126. ASSERT_TRUE(res);
  10127. EXPECT_EQ(StatusCode::OK_200, res->status);
  10128. }
  10129. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  10130. static constexpr unsigned int number_of_tasks{1000000};
  10131. std::atomic_uint count{0};
  10132. std::unique_ptr<TaskQueue> task_queue{
  10133. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  10134. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10135. auto queued = task_queue->enqueue(
  10136. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  10137. EXPECT_TRUE(queued);
  10138. }
  10139. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10140. task_queue->shutdown();
  10141. #else
  10142. EXPECT_NO_THROW(task_queue->shutdown());
  10143. #endif
  10144. EXPECT_EQ(number_of_tasks, count.load());
  10145. }
  10146. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  10147. static constexpr unsigned int number_of_tasks{1000000};
  10148. static constexpr unsigned int qlimit{2};
  10149. unsigned int queued_count{0};
  10150. std::atomic_uint count{0};
  10151. std::unique_ptr<TaskQueue> task_queue{
  10152. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  10153. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10154. if (task_queue->enqueue(
  10155. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  10156. queued_count++;
  10157. }
  10158. }
  10159. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10160. task_queue->shutdown();
  10161. #else
  10162. EXPECT_NO_THROW(task_queue->shutdown());
  10163. #endif
  10164. EXPECT_EQ(queued_count, count.load());
  10165. EXPECT_TRUE(queued_count <= number_of_tasks);
  10166. EXPECT_TRUE(queued_count >= qlimit);
  10167. }
  10168. TEST(TaskQueueTest, MaxQueuedRequests) {
  10169. static constexpr unsigned int qlimit{3};
  10170. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  10171. std::condition_variable sem_cv;
  10172. std::mutex sem_mtx;
  10173. int credits = 0;
  10174. bool queued;
  10175. /* Fill up the queue with tasks that will block until we give them credits to
  10176. * complete. */
  10177. for (unsigned int n = 0; n <= qlimit;) {
  10178. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  10179. std::unique_lock<std::mutex> lock(sem_mtx);
  10180. while (credits <= 0) {
  10181. sem_cv.wait(lock);
  10182. }
  10183. /* Consume the credit and signal the test code if they are all gone. */
  10184. if (--credits == 0) { sem_cv.notify_one(); }
  10185. });
  10186. if (n < qlimit) {
  10187. /* The first qlimit enqueues must succeed. */
  10188. EXPECT_TRUE(queued);
  10189. } else {
  10190. /* The last one will succeed only when the worker thread
  10191. * starts and dequeues the first blocking task. Although
  10192. * not necessary for the correctness of this test, we sleep for
  10193. * a short while to avoid busy waiting. */
  10194. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10195. }
  10196. if (queued) { n++; }
  10197. }
  10198. /* Further enqueues must fail since the queue is full. */
  10199. for (auto i = 0; i < 4; i++) {
  10200. queued = task_queue->enqueue([] {});
  10201. EXPECT_FALSE(queued);
  10202. }
  10203. /* Give the credits to allow the previous tasks to complete. */
  10204. {
  10205. std::unique_lock<std::mutex> lock(sem_mtx);
  10206. credits += qlimit + 1;
  10207. }
  10208. sem_cv.notify_all();
  10209. /* Wait for all the credits to be consumed. */
  10210. {
  10211. std::unique_lock<std::mutex> lock(sem_mtx);
  10212. while (credits > 0) {
  10213. sem_cv.wait(lock);
  10214. }
  10215. }
  10216. /* Check that we are able again to enqueue at least qlimit tasks. */
  10217. for (unsigned int i = 0; i < qlimit; i++) {
  10218. queued = task_queue->enqueue([] {});
  10219. EXPECT_TRUE(queued);
  10220. }
  10221. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10222. task_queue->shutdown();
  10223. #else
  10224. EXPECT_NO_THROW(task_queue->shutdown());
  10225. #endif
  10226. }
  10227. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  10228. Server svr;
  10229. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10230. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  10231. });
  10232. svr.Get("/hello", [](const Request &req, Response &res) {
  10233. res.set_content(req.get_param_value("key"), "text/plain");
  10234. });
  10235. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10236. auto se = detail::scope_exit([&] {
  10237. svr.stop();
  10238. thread.join();
  10239. ASSERT_FALSE(svr.is_running());
  10240. });
  10241. svr.wait_until_ready();
  10242. {
  10243. Client cli(HOST, PORT);
  10244. cli.set_follow_location(true);
  10245. auto res = cli.Get("/");
  10246. ASSERT_TRUE(res);
  10247. EXPECT_EQ(StatusCode::OK_200, res->status);
  10248. EXPECT_EQ("val&key2=val2", res->body);
  10249. }
  10250. }
  10251. #endif
  10252. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  10253. Server svr;
  10254. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10255. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  10256. });
  10257. svr.Get("/hello", [](const Request &req, Response &res) {
  10258. res.set_content(req.get_param_value("key"), "text/plain");
  10259. });
  10260. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10261. auto se = detail::scope_exit([&] {
  10262. svr.stop();
  10263. thread.join();
  10264. ASSERT_FALSE(svr.is_running());
  10265. });
  10266. svr.wait_until_ready();
  10267. {
  10268. Client cli(HOST, PORT);
  10269. cli.set_follow_location(true);
  10270. auto res = cli.Get("/");
  10271. ASSERT_TRUE(res);
  10272. EXPECT_EQ(StatusCode::OK_200, res->status);
  10273. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  10274. }
  10275. }
  10276. #ifdef CPPHTTPLIB_SSL_ENABLED
  10277. TEST(RedirectTest, Issue2185_Online) {
  10278. SSLClient client("github.com");
  10279. client.set_follow_location(true);
  10280. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  10281. "Coollab-Windows.zip");
  10282. ASSERT_TRUE(res);
  10283. EXPECT_EQ(StatusCode::OK_200, res->status);
  10284. EXPECT_EQ(9920427U, res->body.size());
  10285. }
  10286. #endif
  10287. TEST(VulnerabilityTest, CRLFInjection) {
  10288. Server svr;
  10289. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  10290. res.set_content("Hello 1", "text/plain");
  10291. });
  10292. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  10293. res.set_content("Hello 2", "text/plain");
  10294. });
  10295. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  10296. res.set_content("Hello 3", "text/plain");
  10297. });
  10298. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  10299. res.set_content("Hello 4", "text/plain");
  10300. });
  10301. svr.set_logger([](const Request &req, const Response & /*res*/) {
  10302. for (const auto &x : req.headers) {
  10303. auto key = x.first;
  10304. EXPECT_STRNE("evil", key.c_str());
  10305. }
  10306. });
  10307. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10308. auto se = detail::scope_exit([&] {
  10309. svr.stop();
  10310. thread.join();
  10311. ASSERT_FALSE(svr.is_running());
  10312. });
  10313. svr.wait_until_ready();
  10314. {
  10315. Client cli(HOST, PORT);
  10316. cli.Post("/test1", "A=B",
  10317. "application/x-www-form-urlencoded\r\nevil: hello1");
  10318. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  10319. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  10320. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  10321. }
  10322. }
  10323. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  10324. auto server_thread = std::thread([] {
  10325. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10326. default_socket_options(srv);
  10327. sockaddr_in addr{};
  10328. addr.sin_family = AF_INET;
  10329. addr.sin_port = htons(PORT + 1);
  10330. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10331. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10332. ::listen(srv, 1);
  10333. sockaddr_in cli_addr{};
  10334. socklen_t cli_len = sizeof(cli_addr);
  10335. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10336. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  10337. std::string buf_all;
  10338. char buf[2048];
  10339. ssize_t n;
  10340. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  10341. buf_all.append(buf, static_cast<size_t>(n));
  10342. size_t pos;
  10343. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  10344. auto request_block = buf_all.substr(0, pos + 4); // include separator
  10345. auto e = request_block.find("\r\n");
  10346. if (e != std::string::npos) {
  10347. auto request_line = request_block.substr(0, e);
  10348. std::string msg =
  10349. "CRLF injection detected in request line: '" + request_line + "'";
  10350. EXPECT_FALSE(true) << msg;
  10351. }
  10352. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  10353. ::send(cli,
  10354. #ifdef _WIN32
  10355. static_cast<const char *>(resp.c_str()),
  10356. static_cast<int>(resp.size()),
  10357. #else
  10358. resp.c_str(), resp.size(),
  10359. #endif
  10360. 0);
  10361. buf_all.erase(0, pos + 4);
  10362. }
  10363. }
  10364. detail::close_socket(cli);
  10365. detail::close_socket(srv);
  10366. });
  10367. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10368. auto cli = Client("127.0.0.1", PORT + 1);
  10369. auto headers = Headers{
  10370. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  10371. {"Connection", "keep-alive"}};
  10372. auto res = cli.Get("/hi", headers);
  10373. EXPECT_FALSE(res);
  10374. EXPECT_EQ(Error::InvalidHeaders, res.error());
  10375. server_thread.join();
  10376. }
  10377. TEST(PathParamsTest, StaticMatch) {
  10378. const auto pattern = "/users/all";
  10379. detail::PathParamsMatcher matcher(pattern);
  10380. Request request;
  10381. request.path = "/users/all";
  10382. ASSERT_TRUE(matcher.match(request));
  10383. std::unordered_map<std::string, std::string> expected_params = {};
  10384. EXPECT_EQ(request.path_params, expected_params);
  10385. }
  10386. TEST(PathParamsTest, StaticMismatch) {
  10387. const auto pattern = "/users/all";
  10388. detail::PathParamsMatcher matcher(pattern);
  10389. Request request;
  10390. request.path = "/users/1";
  10391. ASSERT_FALSE(matcher.match(request));
  10392. }
  10393. TEST(PathParamsTest, SingleParamInTheMiddle) {
  10394. const auto pattern = "/users/:id/subscriptions";
  10395. detail::PathParamsMatcher matcher(pattern);
  10396. Request request;
  10397. request.path = "/users/42/subscriptions";
  10398. ASSERT_TRUE(matcher.match(request));
  10399. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10400. EXPECT_EQ(request.path_params, expected_params);
  10401. }
  10402. TEST(PathParamsTest, SingleParamInTheEnd) {
  10403. const auto pattern = "/users/:id";
  10404. detail::PathParamsMatcher matcher(pattern);
  10405. Request request;
  10406. request.path = "/users/24";
  10407. ASSERT_TRUE(matcher.match(request));
  10408. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  10409. EXPECT_EQ(request.path_params, expected_params);
  10410. }
  10411. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  10412. const auto pattern = "/users/:id/";
  10413. detail::PathParamsMatcher matcher(pattern);
  10414. Request request;
  10415. request.path = "/users/42/";
  10416. ASSERT_TRUE(matcher.match(request));
  10417. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10418. EXPECT_EQ(request.path_params, expected_params);
  10419. }
  10420. TEST(PathParamsTest, EmptyParam) {
  10421. const auto pattern = "/users/:id/";
  10422. detail::PathParamsMatcher matcher(pattern);
  10423. Request request;
  10424. request.path = "/users//";
  10425. ASSERT_TRUE(matcher.match(request));
  10426. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10427. EXPECT_EQ(request.path_params, expected_params);
  10428. }
  10429. TEST(PathParamsTest, FragmentMismatch) {
  10430. const auto pattern = "/users/:id/";
  10431. detail::PathParamsMatcher matcher(pattern);
  10432. Request request;
  10433. request.path = "/admins/24/";
  10434. ASSERT_FALSE(matcher.match(request));
  10435. }
  10436. TEST(PathParamsTest, ExtraFragments) {
  10437. const auto pattern = "/users/:id";
  10438. detail::PathParamsMatcher matcher(pattern);
  10439. Request request;
  10440. request.path = "/users/42/subscriptions";
  10441. ASSERT_FALSE(matcher.match(request));
  10442. }
  10443. TEST(PathParamsTest, MissingTrailingParam) {
  10444. const auto pattern = "/users/:id";
  10445. detail::PathParamsMatcher matcher(pattern);
  10446. Request request;
  10447. request.path = "/users";
  10448. ASSERT_FALSE(matcher.match(request));
  10449. }
  10450. TEST(PathParamsTest, MissingParamInTheMiddle) {
  10451. const auto pattern = "/users/:id/subscriptions";
  10452. detail::PathParamsMatcher matcher(pattern);
  10453. Request request;
  10454. request.path = "/users/subscriptions";
  10455. ASSERT_FALSE(matcher.match(request));
  10456. }
  10457. TEST(PathParamsTest, MultipleParams) {
  10458. const auto pattern = "/users/:userid/subscriptions/:subid";
  10459. detail::PathParamsMatcher matcher(pattern);
  10460. Request request;
  10461. request.path = "/users/42/subscriptions/2";
  10462. ASSERT_TRUE(matcher.match(request));
  10463. std::unordered_map<std::string, std::string> expected_params = {
  10464. {"userid", "42"}, {"subid", "2"}};
  10465. EXPECT_EQ(request.path_params, expected_params);
  10466. }
  10467. TEST(PathParamsTest, SequenceOfParams) {
  10468. const auto pattern = "/values/:x/:y/:z";
  10469. detail::PathParamsMatcher matcher(pattern);
  10470. Request request;
  10471. request.path = "/values/1/2/3";
  10472. ASSERT_TRUE(matcher.match(request));
  10473. std::unordered_map<std::string, std::string> expected_params = {
  10474. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  10475. EXPECT_EQ(request.path_params, expected_params);
  10476. }
  10477. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  10478. const auto pattern = "/prefix:suffix";
  10479. detail::PathParamsMatcher matcher(pattern);
  10480. Request request;
  10481. request.path = "/prefix:suffix";
  10482. ASSERT_TRUE(matcher.match(request));
  10483. const std::unordered_map<std::string, std::string> expected_params = {};
  10484. EXPECT_EQ(request.path_params, expected_params);
  10485. }
  10486. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  10487. // If ipv6 regex working, regex match codepath is taken.
  10488. // else port will default to 80 in Client impl
  10489. int clientImplMagicPort = 80;
  10490. int port = 4321;
  10491. // above ports must be different to avoid false negative
  10492. EXPECT_NE(clientImplMagicPort, port);
  10493. std::string ipV6TestURL = "http://[ff06::c3]";
  10494. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  10495. CLIENT_PRIVATE_KEY_FILE);
  10496. EXPECT_EQ(cli.port(), port);
  10497. }
  10498. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  10499. auto file_path = "./www/dir/index.html";
  10500. auto dir_path = "./www/dir";
  10501. detail::FileStat stat_file(file_path);
  10502. EXPECT_TRUE(stat_file.is_file());
  10503. EXPECT_FALSE(stat_file.is_dir());
  10504. detail::FileStat stat_dir(dir_path);
  10505. EXPECT_FALSE(stat_dir.is_file());
  10506. EXPECT_TRUE(stat_dir.is_dir());
  10507. }
  10508. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  10509. // IPv4 with default HTTP port (80)
  10510. EXPECT_EQ("example.com",
  10511. detail::make_host_and_port_string("example.com", 80, false));
  10512. // IPv4 with default HTTPS port (443)
  10513. EXPECT_EQ("example.com",
  10514. detail::make_host_and_port_string("example.com", 443, true));
  10515. // IPv4 with non-default HTTP port
  10516. EXPECT_EQ("example.com:8080",
  10517. detail::make_host_and_port_string("example.com", 8080, false));
  10518. // IPv4 with non-default HTTPS port
  10519. EXPECT_EQ("example.com:8443",
  10520. detail::make_host_and_port_string("example.com", 8443, true));
  10521. // IPv6 with default HTTP port (80)
  10522. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  10523. // IPv6 with default HTTPS port (443)
  10524. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  10525. // IPv6 with non-default HTTP port
  10526. EXPECT_EQ("[::1]:8080",
  10527. detail::make_host_and_port_string("::1", 8080, false));
  10528. // IPv6 with non-default HTTPS port
  10529. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  10530. // IPv6 full address with default port
  10531. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  10532. detail::make_host_and_port_string(
  10533. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  10534. // IPv6 full address with non-default port
  10535. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  10536. detail::make_host_and_port_string(
  10537. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  10538. // IPv6 localhost with non-default port
  10539. EXPECT_EQ("[::1]:3000",
  10540. detail::make_host_and_port_string("::1", 3000, false));
  10541. // IPv6 with zone ID (link-local address) with default port
  10542. EXPECT_EQ("[fe80::1%eth0]",
  10543. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  10544. // IPv6 with zone ID (link-local address) with non-default port
  10545. EXPECT_EQ("[fe80::1%eth0]:8080",
  10546. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  10547. // Edge case: Port 443 with is_ssl=false (should add port)
  10548. EXPECT_EQ("example.com:443",
  10549. detail::make_host_and_port_string("example.com", 443, false));
  10550. // Edge case: Port 80 with is_ssl=true (should add port)
  10551. EXPECT_EQ("example.com:80",
  10552. detail::make_host_and_port_string("example.com", 80, true));
  10553. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  10554. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  10555. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  10556. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  10557. // Security fix: Already bracketed IPv6 should not get double brackets
  10558. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  10559. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  10560. EXPECT_EQ("[::1]:8080",
  10561. detail::make_host_and_port_string("[::1]", 8080, false));
  10562. EXPECT_EQ("[2001:db8::1]:8080",
  10563. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  10564. EXPECT_EQ("[fe80::1%eth0]",
  10565. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  10566. EXPECT_EQ("[fe80::1%eth0]:8080",
  10567. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  10568. // Edge case: Empty host (should return as-is)
  10569. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  10570. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  10571. // This is a known limitation but shouldn't crash
  10572. EXPECT_EQ("[host:name]",
  10573. detail::make_host_and_port_string("host:name", 80, false));
  10574. // Port number edge cases (no validation, but should not crash)
  10575. EXPECT_EQ("example.com:0",
  10576. detail::make_host_and_port_string("example.com", 0, false));
  10577. EXPECT_EQ("example.com:-1",
  10578. detail::make_host_and_port_string("example.com", -1, false));
  10579. EXPECT_EQ("example.com:65535",
  10580. detail::make_host_and_port_string("example.com", 65535, false));
  10581. EXPECT_EQ("example.com:65536",
  10582. detail::make_host_and_port_string("example.com", 65536, false));
  10583. }
  10584. #ifdef CPPHTTPLIB_SSL_ENABLED
  10585. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  10586. httplib::SSLClient cli("roblox.com", 443);
  10587. cli.set_follow_location(true);
  10588. auto res = cli.Get("/");
  10589. ASSERT_TRUE(res);
  10590. EXPECT_EQ(StatusCode::OK_200, res->status);
  10591. }
  10592. #endif
  10593. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  10594. Server svr;
  10595. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10596. EXPECT_EQ(res.status, 400);
  10597. });
  10598. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10599. auto se = detail::scope_exit([&] {
  10600. svr.stop();
  10601. thread.join();
  10602. ASSERT_FALSE(svr.is_running());
  10603. });
  10604. svr.wait_until_ready();
  10605. Client cli(HOST, PORT);
  10606. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  10607. }
  10608. TEST(InvalidHeaderCharsTest, is_field_name) {
  10609. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  10610. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  10611. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  10612. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  10613. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  10614. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  10615. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  10616. EXPECT_FALSE(detail::fields::is_field_name(""));
  10617. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  10618. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  10619. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  10620. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  10621. }
  10622. TEST(InvalidHeaderCharsTest, is_field_value) {
  10623. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  10624. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  10625. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  10626. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  10627. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  10628. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  10629. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  10630. EXPECT_TRUE(detail::fields::is_field_value(""));
  10631. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  10632. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  10633. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  10634. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  10635. EXPECT_TRUE(detail::fields::is_field_value("0"));
  10636. }
  10637. TEST(InvalidHeaderCharsTest, OnServer) {
  10638. Server svr;
  10639. svr.Get("/test_name", [&](const Request &req, Response &res) {
  10640. std::string header = "Not Set";
  10641. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10642. res.set_header(header, "value");
  10643. res.set_content("Page Content Page Content", "text/plain");
  10644. });
  10645. svr.Get("/test_value", [&](const Request &req, Response &res) {
  10646. std::string header = "Not Set";
  10647. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10648. res.set_header("X-Test", header);
  10649. res.set_content("Page Content Page Content", "text/plain");
  10650. });
  10651. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10652. auto se = detail::scope_exit([&] {
  10653. svr.stop();
  10654. thread.join();
  10655. ASSERT_FALSE(svr.is_running());
  10656. });
  10657. svr.wait_until_ready();
  10658. Client cli(HOST, PORT);
  10659. {
  10660. auto res = cli.Get(
  10661. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10662. ASSERT_TRUE(res);
  10663. EXPECT_EQ("Page Content Page Content", res->body);
  10664. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10665. }
  10666. {
  10667. auto res = cli.Get(
  10668. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10669. ASSERT_TRUE(res);
  10670. EXPECT_EQ("Page Content Page Content", res->body);
  10671. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10672. }
  10673. }
  10674. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  10675. auto handled = false;
  10676. Server svr;
  10677. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10678. thread t = thread([&] { svr.listen(HOST, PORT); });
  10679. auto se = detail::scope_exit([&] {
  10680. svr.stop();
  10681. t.join();
  10682. ASSERT_FALSE(svr.is_running());
  10683. ASSERT_FALSE(handled);
  10684. });
  10685. svr.wait_until_ready();
  10686. auto req = "POST /test HTTP/1.1\r\n"
  10687. "Content-Length: x\r\n"
  10688. "\r\n";
  10689. std::string response;
  10690. ASSERT_TRUE(send_request(1, req, &response));
  10691. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10692. response.substr(0, response.find("\r\n")));
  10693. }
  10694. #ifndef _WIN32
  10695. TEST(Expect100ContinueTest, ServerClosesConnection) {
  10696. static constexpr char reject[] = "Unauthorized";
  10697. static constexpr char accept[] = "Upload accepted";
  10698. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  10699. Server svr;
  10700. svr.set_expect_100_continue_handler(
  10701. [](const Request & /*req*/, Response &res) {
  10702. res.status = StatusCode::Unauthorized_401;
  10703. res.set_content(reject, "text/plain");
  10704. return res.status;
  10705. });
  10706. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  10707. res.set_content(accept, "text/plain");
  10708. });
  10709. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10710. auto se = detail::scope_exit([&] {
  10711. svr.stop();
  10712. thread.join();
  10713. ASSERT_FALSE(svr.is_running());
  10714. });
  10715. svr.wait_until_ready();
  10716. {
  10717. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  10718. curl_easy_init(), &curl_easy_cleanup};
  10719. ASSERT_NE(curl, nullptr);
  10720. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  10721. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  10722. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  10723. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  10724. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  10725. &curl_slist_free_all};
  10726. ASSERT_NE(list, nullptr);
  10727. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  10728. struct read_data {
  10729. size_t read_size;
  10730. size_t total_size;
  10731. } data = {0, total_size};
  10732. using read_callback_t =
  10733. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10734. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  10735. void *userdata) -> size_t {
  10736. read_data *data = (read_data *)userdata;
  10737. if (!userdata || data->read_size >= data->total_size) { return 0; }
  10738. std::fill_n(ptr, size * nmemb, 'A');
  10739. data->read_size += size * nmemb;
  10740. return size * nmemb;
  10741. };
  10742. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  10743. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  10744. std::vector<char> buffer;
  10745. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  10746. using write_callback_t =
  10747. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10748. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  10749. void *userdata) -> size_t {
  10750. std::vector<char> *buffer = (std::vector<char> *)userdata;
  10751. buffer->reserve(buffer->size() + size * nmemb + 1);
  10752. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  10753. return size * nmemb;
  10754. };
  10755. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  10756. {
  10757. const auto res = curl_easy_perform(curl.get());
  10758. ASSERT_EQ(res, CURLE_OK);
  10759. }
  10760. {
  10761. auto response_code = long{};
  10762. const auto res =
  10763. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  10764. ASSERT_EQ(res, CURLE_OK);
  10765. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  10766. }
  10767. {
  10768. auto dl = curl_off_t{};
  10769. const auto res =
  10770. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  10771. ASSERT_EQ(res, CURLE_OK);
  10772. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  10773. }
  10774. {
  10775. buffer.push_back('\0');
  10776. ASSERT_STRCASEEQ(buffer.data(), reject);
  10777. }
  10778. }
  10779. }
  10780. #endif
  10781. template <typename S, typename C>
  10782. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  10783. svr.Get("/stream", [&](const Request &, Response &res) {
  10784. auto data = new std::string("01234567890123456789");
  10785. res.set_content_provider(
  10786. data->size(), "text/plain",
  10787. [&, data](size_t offset, size_t length, DataSink &sink) {
  10788. const size_t DATA_CHUNK_SIZE = 4;
  10789. const auto &d = *data;
  10790. std::this_thread::sleep_for(std::chrono::seconds(1));
  10791. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  10792. return true;
  10793. },
  10794. [data](bool success) {
  10795. EXPECT_FALSE(success);
  10796. delete data;
  10797. });
  10798. });
  10799. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  10800. auto i = new size_t(0);
  10801. res.set_content_provider(
  10802. "text/plain",
  10803. [i](size_t, DataSink &sink) {
  10804. if (*i < 5) {
  10805. std::this_thread::sleep_for(std::chrono::seconds(1));
  10806. sink.write("abcd", 4);
  10807. (*i)++;
  10808. } else {
  10809. sink.done();
  10810. }
  10811. return true;
  10812. },
  10813. [i](bool success) {
  10814. EXPECT_FALSE(success);
  10815. delete i;
  10816. });
  10817. });
  10818. svr.Get("/chunked", [&](const Request &, Response &res) {
  10819. auto i = new size_t(0);
  10820. res.set_chunked_content_provider(
  10821. "text/plain",
  10822. [i](size_t, DataSink &sink) {
  10823. if (*i < 5) {
  10824. std::this_thread::sleep_for(std::chrono::seconds(1));
  10825. sink.os << "abcd";
  10826. (*i)++;
  10827. } else {
  10828. sink.done();
  10829. }
  10830. return true;
  10831. },
  10832. [i](bool success) {
  10833. EXPECT_FALSE(success);
  10834. delete i;
  10835. });
  10836. });
  10837. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10838. auto se = detail::scope_exit([&] {
  10839. svr.stop();
  10840. listen_thread.join();
  10841. ASSERT_FALSE(svr.is_running());
  10842. });
  10843. svr.wait_until_ready();
  10844. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  10845. {
  10846. auto start = std::chrono::steady_clock::now();
  10847. auto res = cli.Get("/stream");
  10848. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10849. std::chrono::steady_clock::now() - start)
  10850. .count();
  10851. ASSERT_FALSE(res);
  10852. EXPECT_EQ(Error::Read, res.error());
  10853. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10854. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10855. }
  10856. {
  10857. auto start = std::chrono::steady_clock::now();
  10858. auto res = cli.Get("/stream_without_length");
  10859. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10860. std::chrono::steady_clock::now() - start)
  10861. .count();
  10862. ASSERT_FALSE(res);
  10863. EXPECT_EQ(Error::Read, res.error());
  10864. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10865. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10866. }
  10867. {
  10868. auto start = std::chrono::steady_clock::now();
  10869. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  10870. EXPECT_EQ("abcd", string(data, data_length));
  10871. return true;
  10872. });
  10873. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10874. std::chrono::steady_clock::now() - start)
  10875. .count();
  10876. ASSERT_FALSE(res);
  10877. EXPECT_EQ(Error::Read, res.error());
  10878. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10879. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10880. }
  10881. }
  10882. TEST(MaxTimeoutTest, ContentStream) {
  10883. time_t timeout = 2000;
  10884. time_t threshold = 200;
  10885. Server svr;
  10886. Client cli("localhost", PORT);
  10887. max_timeout_test(svr, cli, timeout, threshold);
  10888. }
  10889. #ifdef CPPHTTPLIB_SSL_ENABLED
  10890. TEST(MaxTimeoutTest, ContentStreamSSL) {
  10891. time_t timeout = 2000;
  10892. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  10893. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10894. SSLClient cli("localhost", PORT);
  10895. cli.enable_server_certificate_verification(false);
  10896. max_timeout_test(svr, cli, timeout, threshold);
  10897. }
  10898. #endif
  10899. class EventDispatcher {
  10900. public:
  10901. EventDispatcher() {}
  10902. bool wait_event(DataSink *sink) {
  10903. unique_lock<mutex> lk(m_);
  10904. int id = id_;
  10905. // Wait with timeout to prevent hanging if client disconnects
  10906. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  10907. [&] { return cid_ == id; })) {
  10908. return false; // Timeout occurred
  10909. }
  10910. sink->write(message_.data(), message_.size());
  10911. return true;
  10912. }
  10913. void send_event(const string &message) {
  10914. lock_guard<mutex> lk(m_);
  10915. cid_ = id_++;
  10916. message_ = message;
  10917. cv_.notify_all();
  10918. }
  10919. private:
  10920. mutex m_;
  10921. condition_variable cv_;
  10922. atomic_int id_{0};
  10923. atomic_int cid_{-1};
  10924. string message_;
  10925. };
  10926. TEST(ClientInThreadTest, Issue2068) {
  10927. EventDispatcher ed;
  10928. Server svr;
  10929. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  10930. res.set_chunked_content_provider("text/event-stream",
  10931. [&](size_t /*offset*/, DataSink &sink) {
  10932. return ed.wait_event(&sink);
  10933. });
  10934. });
  10935. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10936. svr.wait_until_ready();
  10937. thread event_thread([&] {
  10938. int id = 0;
  10939. while (svr.is_running()) {
  10940. this_thread::sleep_for(chrono::milliseconds(500));
  10941. std::stringstream ss;
  10942. ss << "data: " << id << "\n\n";
  10943. ed.send_event(ss.str());
  10944. id++;
  10945. }
  10946. });
  10947. auto se = detail::scope_exit([&] {
  10948. svr.stop();
  10949. listen_thread.join();
  10950. event_thread.join();
  10951. ASSERT_FALSE(svr.is_running());
  10952. });
  10953. {
  10954. auto client = detail::make_unique<Client>(HOST, PORT);
  10955. client->set_read_timeout(std::chrono::minutes(10));
  10956. std::atomic<bool> stop{false};
  10957. std::thread t([&] {
  10958. client->Get("/event1",
  10959. [&](const char *, size_t) -> bool { return !stop; });
  10960. });
  10961. std::this_thread::sleep_for(std::chrono::seconds(2));
  10962. stop = true;
  10963. client->stop();
  10964. t.join();
  10965. // Reset client after thread has finished
  10966. client.reset();
  10967. }
  10968. }
  10969. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  10970. auto handled = false;
  10971. Server svr;
  10972. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10973. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10974. auto se = detail::scope_exit([&] {
  10975. svr.stop();
  10976. t.join();
  10977. ASSERT_FALSE(svr.is_running());
  10978. ASSERT_FALSE(handled);
  10979. });
  10980. svr.wait_until_ready();
  10981. // Two Content-Length headers with different values — must be rejected
  10982. auto req = "POST /test HTTP/1.1\r\n"
  10983. "Content-Length: 5\r\n"
  10984. "Content-Length: 10\r\n"
  10985. "\r\n"
  10986. "hello";
  10987. std::string response;
  10988. ASSERT_TRUE(send_request(1, req, &response));
  10989. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10990. response.substr(0, response.find("\r\n")));
  10991. }
  10992. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  10993. auto handled = false;
  10994. Server svr;
  10995. svr.Post("/test", [&](const Request &, Response &res) {
  10996. handled = true;
  10997. res.set_content("ok", "text/plain");
  10998. });
  10999. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11000. auto se = detail::scope_exit([&] {
  11001. svr.stop();
  11002. t.join();
  11003. ASSERT_FALSE(svr.is_running());
  11004. ASSERT_TRUE(handled);
  11005. });
  11006. svr.wait_until_ready();
  11007. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  11008. auto req = "POST /test HTTP/1.1\r\n"
  11009. "Content-Length: 5\r\n"
  11010. "Content-Length: 5\r\n"
  11011. "\r\n"
  11012. "hello";
  11013. std::string response;
  11014. ASSERT_TRUE(send_request(1, req, &response));
  11015. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  11016. }
  11017. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  11018. Server svr;
  11019. svr.Get("/", [](const Request &req, Response &res) {
  11020. EXPECT_EQ(2U, req.trailers.size());
  11021. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  11022. // Denied
  11023. EXPECT_FALSE(req.has_trailer("Content-Length"));
  11024. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  11025. // Accepted
  11026. EXPECT_TRUE(req.has_trailer("X-Hello"));
  11027. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  11028. EXPECT_TRUE(req.has_trailer("X-World"));
  11029. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  11030. res.set_content("ok", "text/plain");
  11031. });
  11032. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11033. auto se = detail::scope_exit([&] {
  11034. svr.stop();
  11035. t.join();
  11036. ASSERT_FALSE(svr.is_running());
  11037. });
  11038. svr.wait_until_ready();
  11039. const std::string req = "GET / HTTP/1.1\r\n"
  11040. "Transfer-Encoding: chunked\r\n"
  11041. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  11042. "\r\n"
  11043. "0\r\n"
  11044. "Content-Length: 10\r\n"
  11045. "Host: internal.local\r\n"
  11046. "Content-Type: malicious/content\r\n"
  11047. "Cookie: any\r\n"
  11048. "Set-Cookie: any\r\n"
  11049. "X-Forwarded-For: attacker.com\r\n"
  11050. "X-Real-Ip: 1.1.1.1\r\n"
  11051. "X-Hello: hello\r\n"
  11052. "X-World: world\r\n"
  11053. "\r\n";
  11054. std::string res;
  11055. ASSERT_TRUE(send_request(1, req, &res));
  11056. }
  11057. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  11058. Server svr;
  11059. std::string observed_remote_addr;
  11060. std::string observed_xff;
  11061. svr.Get("/ip", [&](const Request &req, Response &res) {
  11062. observed_remote_addr = req.remote_addr;
  11063. observed_xff = req.get_header_value("X-Forwarded-For");
  11064. res.set_content("ok", "text/plain");
  11065. });
  11066. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11067. auto se = detail::scope_exit([&] {
  11068. svr.stop();
  11069. t.join();
  11070. ASSERT_FALSE(svr.is_running());
  11071. });
  11072. svr.wait_until_ready();
  11073. Client cli(HOST, PORT);
  11074. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  11075. ASSERT_TRUE(res);
  11076. EXPECT_EQ(StatusCode::OK_200, res->status);
  11077. EXPECT_EQ(observed_xff, "203.0.113.66");
  11078. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11079. observed_remote_addr == "127.0.0.1");
  11080. }
  11081. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  11082. Server svr;
  11083. svr.set_trusted_proxies({"203.0.113.66"});
  11084. std::string observed_remote_addr;
  11085. std::string observed_xff;
  11086. svr.Get("/ip", [&](const Request &req, Response &res) {
  11087. observed_remote_addr = req.remote_addr;
  11088. observed_xff = req.get_header_value("X-Forwarded-For");
  11089. res.set_content("ok", "text/plain");
  11090. });
  11091. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11092. auto se = detail::scope_exit([&] {
  11093. svr.stop();
  11094. t.join();
  11095. ASSERT_FALSE(svr.is_running());
  11096. });
  11097. svr.wait_until_ready();
  11098. Client cli(HOST, PORT);
  11099. auto res = cli.Get("/ip");
  11100. ASSERT_TRUE(res);
  11101. EXPECT_EQ(StatusCode::OK_200, res->status);
  11102. EXPECT_EQ(observed_xff, "");
  11103. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11104. observed_remote_addr == "127.0.0.1");
  11105. }
  11106. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  11107. Server svr;
  11108. svr.set_trusted_proxies({"203.0.113.66"});
  11109. std::string observed_remote_addr;
  11110. std::string observed_xff;
  11111. svr.Get("/ip", [&](const Request &req, Response &res) {
  11112. observed_remote_addr = req.remote_addr;
  11113. observed_xff = req.get_header_value("X-Forwarded-For");
  11114. res.set_content("ok", "text/plain");
  11115. });
  11116. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11117. auto se = detail::scope_exit([&] {
  11118. svr.stop();
  11119. t.join();
  11120. ASSERT_FALSE(svr.is_running());
  11121. });
  11122. svr.wait_until_ready();
  11123. Client cli(HOST, PORT);
  11124. auto res =
  11125. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  11126. ASSERT_TRUE(res);
  11127. EXPECT_EQ(StatusCode::OK_200, res->status);
  11128. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  11129. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11130. }
  11131. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  11132. Server svr;
  11133. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  11134. std::string observed_remote_addr;
  11135. std::string observed_xff;
  11136. svr.Get("/ip", [&](const Request &req, Response &res) {
  11137. observed_remote_addr = req.remote_addr;
  11138. observed_xff = req.get_header_value("X-Forwarded-For");
  11139. res.set_content("ok", "text/plain");
  11140. });
  11141. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11142. auto se = detail::scope_exit([&] {
  11143. svr.stop();
  11144. t.join();
  11145. ASSERT_FALSE(svr.is_running());
  11146. });
  11147. svr.wait_until_ready();
  11148. Client cli(HOST, PORT);
  11149. auto res = cli.Get(
  11150. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11151. ASSERT_TRUE(res);
  11152. EXPECT_EQ(StatusCode::OK_200, res->status);
  11153. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11154. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11155. }
  11156. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  11157. Server svr;
  11158. svr.set_trusted_proxies({"192.0.2.45"});
  11159. std::string observed_remote_addr;
  11160. std::string observed_xff;
  11161. svr.Get("/ip", [&](const Request &req, Response &res) {
  11162. observed_remote_addr = req.remote_addr;
  11163. observed_xff = req.get_header_value("X-Forwarded-For");
  11164. res.set_content("ok", "text/plain");
  11165. });
  11166. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11167. auto se = detail::scope_exit([&] {
  11168. svr.stop();
  11169. t.join();
  11170. ASSERT_FALSE(svr.is_running());
  11171. });
  11172. svr.wait_until_ready();
  11173. Client cli(HOST, PORT);
  11174. auto res =
  11175. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  11176. ASSERT_TRUE(res);
  11177. EXPECT_EQ(StatusCode::OK_200, res->status);
  11178. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  11179. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11180. }
  11181. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  11182. Server svr;
  11183. svr.set_trusted_proxies({"192.0.2.45"});
  11184. std::string observed_remote_addr;
  11185. std::string observed_xff;
  11186. svr.Get("/ip", [&](const Request &req, Response &res) {
  11187. observed_remote_addr = req.remote_addr;
  11188. observed_xff = req.get_header_value("X-Forwarded-For");
  11189. res.set_content("ok", "text/plain");
  11190. });
  11191. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11192. auto se = detail::scope_exit([&] {
  11193. svr.stop();
  11194. t.join();
  11195. ASSERT_FALSE(svr.is_running());
  11196. });
  11197. svr.wait_until_ready();
  11198. Client cli(HOST, PORT);
  11199. auto res = cli.Get(
  11200. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11201. ASSERT_TRUE(res);
  11202. EXPECT_EQ(StatusCode::OK_200, res->status);
  11203. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11204. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11205. }
  11206. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  11207. Server svr;
  11208. svr.set_trusted_proxies({"192.0.2.45"});
  11209. std::string observed_remote_addr;
  11210. std::string observed_xff;
  11211. svr.Get("/ip", [&](const Request &req, Response &res) {
  11212. observed_remote_addr = req.remote_addr;
  11213. observed_xff = req.get_header_value("X-Forwarded-For");
  11214. res.set_content("ok", "text/plain");
  11215. });
  11216. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11217. auto se = detail::scope_exit([&] {
  11218. svr.stop();
  11219. t.join();
  11220. ASSERT_FALSE(svr.is_running());
  11221. });
  11222. svr.wait_until_ready();
  11223. std::string raw_req =
  11224. "GET /ip HTTP/1.1\r\n"
  11225. "Host: localhost\r\n"
  11226. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  11227. "Connection: close\r\n"
  11228. "\r\n";
  11229. std::string out;
  11230. ASSERT_TRUE(send_request(5, raw_req, &out));
  11231. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11232. // Header parser trims surrounding whitespace of the header value
  11233. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  11234. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11235. }
  11236. #ifndef _WIN32
  11237. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  11238. Server svr;
  11239. svr.Post("/post", [&](const Request &req, Response &res) {
  11240. res.set_content(req.body, "text/plain");
  11241. });
  11242. svr.Put("/put", [&](const Request &req, Response &res) {
  11243. res.set_content(req.body, "text/plain");
  11244. });
  11245. svr.Patch("/patch", [&](const Request &req, Response &res) {
  11246. res.set_content(req.body, "text/plain");
  11247. });
  11248. svr.Delete("/delete", [&](const Request &req, Response &res) {
  11249. res.set_content(req.body, "text/plain");
  11250. });
  11251. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11252. auto se = detail::scope_exit([&] {
  11253. svr.stop();
  11254. t.join();
  11255. ASSERT_FALSE(svr.is_running());
  11256. });
  11257. svr.wait_until_ready();
  11258. std::string resp;
  11259. // POST without Content-Length
  11260. ASSERT_TRUE(send_request(5,
  11261. "POST /post HTTP/1.1\r\n"
  11262. "Host: localhost\r\n"
  11263. "Connection: close\r\n"
  11264. "\r\n",
  11265. &resp));
  11266. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11267. // PUT without Content-Length
  11268. resp.clear();
  11269. ASSERT_TRUE(send_request(5,
  11270. "PUT /put HTTP/1.1\r\n"
  11271. "Host: localhost\r\n"
  11272. "Connection: close\r\n"
  11273. "\r\n",
  11274. &resp));
  11275. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11276. // PATCH without Content-Length
  11277. resp.clear();
  11278. ASSERT_TRUE(send_request(5,
  11279. "PATCH /patch HTTP/1.1\r\n"
  11280. "Host: localhost\r\n"
  11281. "Connection: close\r\n"
  11282. "\r\n",
  11283. &resp));
  11284. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11285. // DELETE without Content-Length
  11286. resp.clear();
  11287. ASSERT_TRUE(send_request(5,
  11288. "DELETE /delete HTTP/1.1\r\n"
  11289. "Host: localhost\r\n"
  11290. "Connection: close\r\n"
  11291. "\r\n",
  11292. &resp));
  11293. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11294. }
  11295. #endif
  11296. //==============================================================================
  11297. // open_stream() Tests
  11298. //==============================================================================
  11299. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  11300. std::string result;
  11301. char buf[8192];
  11302. ssize_t n;
  11303. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11304. result.append(buf, static_cast<size_t>(n));
  11305. }
  11306. return result;
  11307. }
  11308. // Mock stream for unit tests
  11309. class MockStream : public Stream {
  11310. public:
  11311. std::string data;
  11312. size_t pos = 0;
  11313. ssize_t error_after = -1; // -1 = no error
  11314. explicit MockStream(const std::string &d, ssize_t err = -1)
  11315. : data(d), error_after(err) {}
  11316. bool is_readable() const override { return true; }
  11317. bool wait_readable() const override { return true; }
  11318. bool wait_writable() const override { return true; }
  11319. ssize_t read(char *ptr, size_t size) override {
  11320. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  11321. if (pos >= data.size()) return 0;
  11322. size_t limit =
  11323. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  11324. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  11325. std::memcpy(ptr, data.data() + pos, to_read);
  11326. pos += to_read;
  11327. return static_cast<ssize_t>(to_read);
  11328. }
  11329. ssize_t write(const char *, size_t) override { return -1; }
  11330. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  11331. ip = "127.0.0.1";
  11332. port = 0;
  11333. }
  11334. void get_local_ip_and_port(std::string &ip, int &port) const override {
  11335. ip = "127.0.0.1";
  11336. port = 0;
  11337. }
  11338. socket_t socket() const override { return INVALID_SOCKET; }
  11339. time_t duration() const override { return 0; }
  11340. };
  11341. TEST(StreamHandleTest, Basic) {
  11342. ClientImpl::StreamHandle handle;
  11343. EXPECT_FALSE(handle.is_valid());
  11344. handle.response = detail::make_unique<Response>();
  11345. handle.error = Error::Connection;
  11346. EXPECT_FALSE(handle.is_valid());
  11347. handle.error = Error::Success;
  11348. EXPECT_TRUE(handle.is_valid());
  11349. }
  11350. TEST(BodyReaderTest, Basic) {
  11351. MockStream stream("Hello, World!");
  11352. detail::BodyReader reader;
  11353. reader.stream = &stream;
  11354. reader.content_length = 13;
  11355. char buf[32];
  11356. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  11357. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  11358. EXPECT_TRUE(reader.eof);
  11359. }
  11360. TEST(BodyReaderTest, NoStream) {
  11361. detail::BodyReader reader;
  11362. char buf[32];
  11363. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11364. EXPECT_EQ(Error::Connection, reader.last_error);
  11365. }
  11366. TEST(BodyReaderTest, Error) {
  11367. MockStream stream("Hello, World!", 5);
  11368. detail::BodyReader reader;
  11369. reader.stream = &stream;
  11370. reader.content_length = 13;
  11371. char buf[32];
  11372. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  11373. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11374. EXPECT_EQ(Error::Read, reader.last_error);
  11375. }
  11376. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  11377. // Mock-based StreamHandle tests relying on private internals are removed.
  11378. class OpenStreamTest : public ::testing::Test {
  11379. protected:
  11380. void SetUp() override {
  11381. svr_.Get("/hello", [](const Request &, Response &res) {
  11382. res.set_content("Hello World!", "text/plain");
  11383. });
  11384. svr_.Get("/large", [](const Request &, Response &res) {
  11385. res.set_content(std::string(10000, 'X'), "text/plain");
  11386. });
  11387. svr_.Get("/chunked", [](const Request &, Response &res) {
  11388. res.set_chunked_content_provider("text/plain",
  11389. [](size_t offset, DataSink &sink) {
  11390. if (offset < 15) {
  11391. sink.write("chunk", 5);
  11392. return true;
  11393. }
  11394. sink.done();
  11395. return true;
  11396. });
  11397. });
  11398. svr_.Get("/compressible", [](const Request &, Response &res) {
  11399. res.set_chunked_content_provider("text/plain", [](size_t offset,
  11400. DataSink &sink) {
  11401. if (offset < 100 * 1024) {
  11402. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  11403. sink.write(chunk.data(), chunk.size());
  11404. return true;
  11405. }
  11406. sink.done();
  11407. return true;
  11408. });
  11409. });
  11410. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  11411. [](const Request & /*req*/, Response &res) {
  11412. auto i = new int(0);
  11413. res.set_header("Trailer", "Content-Length, X-Allowed");
  11414. res.set_chunked_content_provider(
  11415. "text/plain",
  11416. [i](size_t /*offset*/, DataSink &sink) {
  11417. switch (*i) {
  11418. case 0: sink.os << "123"; break;
  11419. case 1: sink.os << "456"; break;
  11420. case 2: sink.os << "789"; break;
  11421. case 3: {
  11422. sink.done_with_trailer(
  11423. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  11424. } break;
  11425. }
  11426. (*i)++;
  11427. return true;
  11428. },
  11429. [i](bool success) {
  11430. EXPECT_TRUE(success);
  11431. delete i;
  11432. });
  11433. });
  11434. // Echo headers endpoint for header-related tests
  11435. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  11436. std::string body;
  11437. for (const auto &h : req.headers) {
  11438. body.append(h.first);
  11439. body.push_back(':');
  11440. body.append(h.second);
  11441. body.push_back('\n');
  11442. }
  11443. res.set_content(body, "text/plain");
  11444. });
  11445. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  11446. std::string body;
  11447. for (const auto &h : req.headers) {
  11448. body.append(h.first);
  11449. body.push_back(':');
  11450. body.append(h.second);
  11451. body.push_back('\n');
  11452. }
  11453. res.set_content(body, "text/plain");
  11454. });
  11455. port_ = svr_.bind_to_any_port("127.0.0.1");
  11456. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11457. svr_.wait_until_ready();
  11458. }
  11459. void TearDown() override {
  11460. svr_.stop();
  11461. if (thread_.joinable()) thread_.join();
  11462. }
  11463. Server svr_;
  11464. std::thread thread_;
  11465. int port_ = 0;
  11466. };
  11467. TEST_F(OpenStreamTest, Basic) {
  11468. Client cli("127.0.0.1", port_);
  11469. auto handle = cli.open_stream("GET", "/hello");
  11470. EXPECT_TRUE(handle.is_valid());
  11471. EXPECT_EQ("Hello World!", read_all(handle));
  11472. }
  11473. TEST_F(OpenStreamTest, SmallBuffer) {
  11474. Client cli("127.0.0.1", port_);
  11475. auto handle = cli.open_stream("GET", "/hello");
  11476. std::string result;
  11477. char buf[4];
  11478. ssize_t n;
  11479. while ((n = handle.read(buf, sizeof(buf))) > 0)
  11480. result.append(buf, static_cast<size_t>(n));
  11481. EXPECT_EQ("Hello World!", result);
  11482. }
  11483. TEST_F(OpenStreamTest, DefaultHeaders) {
  11484. Client cli("127.0.0.1", port_);
  11485. // open_stream GET should include Host, User-Agent and Accept-Encoding
  11486. {
  11487. auto handle = cli.open_stream("GET", "/echo-headers");
  11488. ASSERT_TRUE(handle.is_valid());
  11489. auto body = read_all(handle);
  11490. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  11491. std::string::npos);
  11492. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  11493. std::string::npos);
  11494. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  11495. }
  11496. // open_stream POST with body and no explicit content_type should NOT add
  11497. // text/plain Content-Type (behavior differs from non-streaming path), but
  11498. // should include Content-Length
  11499. {
  11500. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  11501. ASSERT_TRUE(handle.is_valid());
  11502. auto body = read_all(handle);
  11503. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  11504. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  11505. }
  11506. // open_stream POST with explicit Content-Type should preserve it
  11507. {
  11508. auto handle = cli.open_stream("POST", "/echo-headers", {},
  11509. {{"Content-Type", "application/custom"}},
  11510. "{}", "application/custom");
  11511. ASSERT_TRUE(handle.is_valid());
  11512. auto body = read_all(handle);
  11513. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  11514. }
  11515. // User-specified User-Agent must not be overwritten for stream API
  11516. {
  11517. auto handle = cli.open_stream("GET", "/echo-headers", {},
  11518. {{"User-Agent", "MyAgent/1.2"}});
  11519. ASSERT_TRUE(handle.is_valid());
  11520. auto body = read_all(handle);
  11521. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  11522. }
  11523. }
  11524. TEST_F(OpenStreamTest, Large) {
  11525. Client cli("127.0.0.1", port_);
  11526. auto handle = cli.open_stream("GET", "/large");
  11527. EXPECT_EQ(10000u, read_all(handle).size());
  11528. }
  11529. TEST_F(OpenStreamTest, ConnectionError) {
  11530. Client cli("127.0.0.1", 9999);
  11531. auto handle = cli.open_stream("GET", "/hello");
  11532. EXPECT_FALSE(handle.is_valid());
  11533. }
  11534. TEST_F(OpenStreamTest, Chunked) {
  11535. Client cli("127.0.0.1", port_);
  11536. auto handle = cli.open_stream("GET", "/chunked");
  11537. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11538. "Transfer-Encoding") == "chunked");
  11539. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  11540. }
  11541. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  11542. Client cli("127.0.0.1", port_);
  11543. auto handle =
  11544. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  11545. ASSERT_TRUE(handle.is_valid());
  11546. // Consume body to allow trailers to be received/parsed
  11547. auto body = read_all(handle);
  11548. // Explicitly parse trailers (ensure trailers are available for assertion)
  11549. handle.parse_trailers_if_needed();
  11550. EXPECT_EQ(std::string("123456789"), body);
  11551. // The response should include a Trailer header declaring both names
  11552. ASSERT_TRUE(handle.response);
  11553. EXPECT_TRUE(handle.response->has_header("Trailer"));
  11554. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  11555. handle.response->get_header_value("Trailer"));
  11556. // Prohibited trailer must not be present
  11557. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  11558. // Allowed trailer should be present
  11559. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  11560. EXPECT_EQ(std::string("yes"),
  11561. handle.response->get_trailer_value("X-Allowed"));
  11562. // Verify trailers are NOT present as regular headers
  11563. EXPECT_EQ(std::string(""),
  11564. handle.response->get_header_value("Content-Length"));
  11565. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  11566. }
  11567. static std::thread serve_single_response(int port,
  11568. const std::string &response) {
  11569. return std::thread([port, response] {
  11570. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11571. default_socket_options(srv);
  11572. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11573. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11574. sockaddr_in addr{};
  11575. addr.sin_family = AF_INET;
  11576. addr.sin_port = htons(static_cast<uint16_t>(port));
  11577. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11578. int opt = 1;
  11579. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11580. #ifdef _WIN32
  11581. reinterpret_cast<const char *>(&opt),
  11582. #else
  11583. &opt,
  11584. #endif
  11585. sizeof(opt));
  11586. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11587. ::listen(srv, 1);
  11588. sockaddr_in cli_addr{};
  11589. socklen_t cli_len = sizeof(cli_addr);
  11590. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11591. if (cli != INVALID_SOCKET) {
  11592. char buf[4096];
  11593. ::recv(cli, buf, sizeof(buf), 0);
  11594. ::send(cli,
  11595. #ifdef _WIN32
  11596. static_cast<const char *>(response.c_str()),
  11597. static_cast<int>(response.size()),
  11598. #else
  11599. response.c_str(), response.size(),
  11600. #endif
  11601. 0);
  11602. detail::close_socket(cli);
  11603. }
  11604. detail::close_socket(srv);
  11605. });
  11606. }
  11607. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  11608. #ifndef _WIN32
  11609. signal(SIGPIPE, SIG_IGN);
  11610. #endif
  11611. auto server_thread =
  11612. serve_single_response(PORT + 2, "HTTP/1.1 200 OK\r\n"
  11613. "Content-Type: text/plain\r\n"
  11614. "Content-Length: not-a-number\r\n"
  11615. "Connection: close\r\n"
  11616. "\r\n"
  11617. "hello");
  11618. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11619. Client cli("127.0.0.1", PORT + 2);
  11620. auto handle = cli.open_stream("GET", "/");
  11621. EXPECT_FALSE(handle.is_valid());
  11622. server_thread.join();
  11623. }
  11624. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  11625. #ifndef _WIN32
  11626. signal(SIGPIPE, SIG_IGN);
  11627. #endif
  11628. auto server_thread = serve_single_response(
  11629. PORT + 2, "HTTP/1.1 200 OK\r\n"
  11630. "Content-Type: text/plain\r\n"
  11631. "Content-Length: 99999999999999999999999999\r\n"
  11632. "Connection: close\r\n"
  11633. "\r\n"
  11634. "hello");
  11635. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11636. // Before the fix, std::stoull would throw std::out_of_range here and
  11637. // crash the process. After the fix, strtoull silently clamps to
  11638. // ULLONG_MAX so the stream opens without crashing. The important thing
  11639. // is that the process does NOT terminate.
  11640. Client cli("127.0.0.1", PORT + 2);
  11641. auto handle = cli.open_stream("GET", "/");
  11642. EXPECT_TRUE(handle.is_valid());
  11643. server_thread.join();
  11644. }
  11645. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11646. TEST_F(OpenStreamTest, Gzip) {
  11647. Client cli("127.0.0.1", port_);
  11648. auto handle = cli.open_stream("GET", "/compressible", {},
  11649. {{"Accept-Encoding", "gzip"}});
  11650. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  11651. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11652. }
  11653. #endif
  11654. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11655. TEST_F(OpenStreamTest, Brotli) {
  11656. Client cli("127.0.0.1", port_);
  11657. auto handle =
  11658. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  11659. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  11660. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11661. }
  11662. #endif
  11663. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11664. TEST_F(OpenStreamTest, Zstd) {
  11665. Client cli("127.0.0.1", port_);
  11666. auto handle = cli.open_stream("GET", "/compressible", {},
  11667. {{"Accept-Encoding", "zstd"}});
  11668. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  11669. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11670. }
  11671. #endif
  11672. #ifdef CPPHTTPLIB_SSL_ENABLED
  11673. class SSLOpenStreamTest : public ::testing::Test {
  11674. protected:
  11675. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  11676. void SetUp() override {
  11677. svr_.Get("/hello", [](const Request &, Response &res) {
  11678. res.set_content("Hello SSL World!", "text/plain");
  11679. });
  11680. svr_.Get("/chunked", [](const Request &, Response &res) {
  11681. res.set_chunked_content_provider("text/plain",
  11682. [](size_t offset, DataSink &sink) {
  11683. if (offset < 15) {
  11684. sink.write("chunk", 5);
  11685. return true;
  11686. }
  11687. sink.done();
  11688. return true;
  11689. });
  11690. });
  11691. svr_.Post("/echo", [](const Request &req, Response &res) {
  11692. res.set_content(req.body, req.get_header_value("Content-Type"));
  11693. });
  11694. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  11695. std::string body = req.body;
  11696. res.set_chunked_content_provider(
  11697. "text/plain", [body](size_t offset, DataSink &sink) {
  11698. if (offset < body.size()) {
  11699. sink.write(body.data() + offset, body.size() - offset);
  11700. }
  11701. sink.done();
  11702. return true;
  11703. });
  11704. });
  11705. port_ = svr_.bind_to_any_port("127.0.0.1");
  11706. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11707. svr_.wait_until_ready();
  11708. }
  11709. void TearDown() override {
  11710. svr_.stop();
  11711. if (thread_.joinable()) thread_.join();
  11712. }
  11713. SSLServer svr_;
  11714. std::thread thread_;
  11715. int port_ = 0;
  11716. };
  11717. TEST_F(SSLOpenStreamTest, Basic) {
  11718. SSLClient cli("127.0.0.1", port_);
  11719. cli.enable_server_certificate_verification(false);
  11720. auto handle = cli.open_stream("GET", "/hello");
  11721. ASSERT_TRUE(handle.is_valid());
  11722. EXPECT_EQ("Hello SSL World!", read_all(handle));
  11723. }
  11724. TEST_F(SSLOpenStreamTest, Chunked) {
  11725. SSLClient cli("127.0.0.1", port_);
  11726. cli.enable_server_certificate_verification(false);
  11727. auto handle = cli.open_stream("GET", "/chunked");
  11728. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11729. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11730. "Transfer-Encoding") == "chunked");
  11731. auto body = read_all(handle);
  11732. EXPECT_EQ("chunkchunkchunk", body);
  11733. }
  11734. TEST_F(SSLOpenStreamTest, Post) {
  11735. SSLClient cli("127.0.0.1", port_);
  11736. cli.enable_server_certificate_verification(false);
  11737. auto handle =
  11738. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  11739. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11740. EXPECT_EQ(200, handle.response->status);
  11741. auto body = read_all(handle);
  11742. EXPECT_EQ("Hello SSL POST", body);
  11743. }
  11744. TEST_F(SSLOpenStreamTest, PostChunked) {
  11745. SSLClient cli("127.0.0.1", port_);
  11746. cli.enable_server_certificate_verification(false);
  11747. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  11748. "Chunked SSL Data", "text/plain");
  11749. ASSERT_TRUE(handle.is_valid());
  11750. EXPECT_EQ(200, handle.response->status);
  11751. auto body = read_all(handle);
  11752. EXPECT_EQ("Chunked SSL Data", body);
  11753. }
  11754. #endif // CPPHTTPLIB_SSL_ENABLED
  11755. //==============================================================================
  11756. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  11757. // results for various scenarios.
  11758. //==============================================================================
  11759. TEST(ParityTest, GetVsOpenStream) {
  11760. Server svr;
  11761. const std::string path = "/parity";
  11762. const std::string content = "Parity test content: hello world";
  11763. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11764. res.set_content(content, "text/plain");
  11765. });
  11766. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11767. auto se = detail::scope_exit([&] {
  11768. svr.stop();
  11769. t.join();
  11770. ASSERT_FALSE(svr.is_running());
  11771. });
  11772. svr.wait_until_ready();
  11773. Client cli(HOST, PORT);
  11774. // Non-stream path
  11775. auto r1 = cli.Get(path);
  11776. ASSERT_TRUE(r1);
  11777. EXPECT_EQ(StatusCode::OK_200, r1->status);
  11778. // Stream path
  11779. auto h = cli.open_stream("GET", path);
  11780. ASSERT_TRUE(h.is_valid());
  11781. EXPECT_EQ(r1->body, read_all(h));
  11782. }
  11783. // Helper to compress data with provided compressor type T
  11784. template <typename Compressor>
  11785. static std::string compress_payload_for_parity(const std::string &in) {
  11786. std::string out;
  11787. Compressor compressor;
  11788. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  11789. [&](const char *data, size_t n) {
  11790. out.append(data, n);
  11791. return true;
  11792. });
  11793. EXPECT_TRUE(ok);
  11794. return out;
  11795. }
  11796. // Helper function for compression parity tests
  11797. template <typename Compressor>
  11798. static void test_compression_parity(const std::string &original,
  11799. const std::string &path,
  11800. const std::string &encoding) {
  11801. const std::string compressed =
  11802. compress_payload_for_parity<Compressor>(original);
  11803. Server svr;
  11804. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11805. res.set_content(compressed, "application/octet-stream");
  11806. res.set_header("Content-Encoding", encoding);
  11807. });
  11808. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  11809. auto se = detail::scope_exit([&] {
  11810. svr.stop();
  11811. t.join();
  11812. ASSERT_FALSE(svr.is_running());
  11813. });
  11814. svr.wait_until_ready();
  11815. Client cli(HOST, PORT);
  11816. // Non-streaming
  11817. {
  11818. auto res = cli.Get(path);
  11819. ASSERT_TRUE(res);
  11820. EXPECT_EQ(StatusCode::OK_200, res->status);
  11821. EXPECT_EQ(original, res->body);
  11822. }
  11823. // Streaming
  11824. {
  11825. auto h = cli.open_stream("GET", path);
  11826. ASSERT_TRUE(h.is_valid());
  11827. EXPECT_EQ(original, read_all(h));
  11828. }
  11829. }
  11830. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11831. TEST(ParityTest, Gzip) {
  11832. test_compression_parity<detail::gzip_compressor>(
  11833. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  11834. }
  11835. #endif
  11836. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11837. TEST(ParityTest, Brotli) {
  11838. test_compression_parity<detail::brotli_compressor>(
  11839. "Hello, brotli parity test payload", "/parity-br", "br");
  11840. }
  11841. #endif
  11842. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11843. TEST(ParityTest, Zstd) {
  11844. test_compression_parity<detail::zstd_compressor>(
  11845. "Zstandard parity test payload", "/parity-zstd", "zstd");
  11846. }
  11847. #endif
  11848. //==============================================================================
  11849. // New Stream API Tests
  11850. //==============================================================================
  11851. inline std::string read_body(httplib::stream::Result &result) {
  11852. std::string body;
  11853. while (result.next()) {
  11854. body.append(result.data(), result.size());
  11855. }
  11856. return body;
  11857. }
  11858. TEST(ClientConnectionTest, Basic) {
  11859. httplib::ClientConnection conn;
  11860. EXPECT_FALSE(conn.is_open());
  11861. conn.sock = 1;
  11862. EXPECT_TRUE(conn.is_open());
  11863. httplib::ClientConnection conn2(std::move(conn));
  11864. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  11865. conn2.sock = INVALID_SOCKET;
  11866. }
  11867. // Unified test server for all stream::* tests
  11868. class StreamApiTest : public ::testing::Test {
  11869. protected:
  11870. void SetUp() override {
  11871. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11872. res.set_content("Hello World!", "text/plain");
  11873. });
  11874. svr_.Get("/echo-params",
  11875. [](const httplib::Request &req, httplib::Response &res) {
  11876. std::string r;
  11877. for (const auto &p : req.params) {
  11878. if (!r.empty()) r += "&";
  11879. r += p.first + "=" + p.second;
  11880. }
  11881. res.set_content(r, "text/plain");
  11882. });
  11883. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11884. res.set_content(req.body, req.get_header_value("Content-Type"));
  11885. });
  11886. svr_.Post("/echo-headers",
  11887. [](const httplib::Request &req, httplib::Response &res) {
  11888. std::string r;
  11889. for (const auto &h : req.headers)
  11890. r += h.first + ": " + h.second + "\n";
  11891. res.set_content(r, "text/plain");
  11892. });
  11893. svr_.Post("/echo-params",
  11894. [](const httplib::Request &req, httplib::Response &res) {
  11895. std::string r = "params:";
  11896. for (const auto &p : req.params)
  11897. r += p.first + "=" + p.second + ";";
  11898. res.set_content(r + " body:" + req.body, "text/plain");
  11899. });
  11900. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  11901. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  11902. });
  11903. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11904. res.set_content("PUT:" + req.body, "text/plain");
  11905. });
  11906. svr_.Patch("/echo",
  11907. [](const httplib::Request &req, httplib::Response &res) {
  11908. res.set_content("PATCH:" + req.body, "text/plain");
  11909. });
  11910. svr_.Delete(
  11911. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  11912. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  11913. "text/plain");
  11914. });
  11915. svr_.Get("/head-test",
  11916. [](const httplib::Request &, httplib::Response &res) {
  11917. res.set_content("body for HEAD", "text/plain");
  11918. });
  11919. svr_.Options("/options",
  11920. [](const httplib::Request &, httplib::Response &res) {
  11921. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  11922. });
  11923. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  11924. svr_.wait_until_ready();
  11925. }
  11926. void TearDown() override {
  11927. svr_.stop();
  11928. if (thread_.joinable()) thread_.join();
  11929. }
  11930. httplib::Server svr_;
  11931. std::thread thread_;
  11932. };
  11933. // stream::Get tests
  11934. TEST_F(StreamApiTest, GetBasic) {
  11935. httplib::Client cli(HOST, PORT);
  11936. auto result = httplib::stream::Get(cli, "/hello");
  11937. ASSERT_TRUE(result.is_valid());
  11938. EXPECT_EQ(200, result.status());
  11939. EXPECT_EQ("Hello World!", read_body(result));
  11940. }
  11941. TEST_F(StreamApiTest, GetWithParams) {
  11942. httplib::Client cli(HOST, PORT);
  11943. httplib::Params params{{"foo", "bar"}};
  11944. auto result = httplib::stream::Get(cli, "/echo-params", params);
  11945. ASSERT_TRUE(result.is_valid());
  11946. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  11947. }
  11948. TEST_F(StreamApiTest, GetConnectionError) {
  11949. httplib::Client cli(HOST, 9999);
  11950. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  11951. }
  11952. TEST_F(StreamApiTest, Get404) {
  11953. httplib::Client cli(HOST, PORT);
  11954. auto result = httplib::stream::Get(cli, "/nonexistent");
  11955. EXPECT_TRUE(result.is_valid());
  11956. EXPECT_EQ(404, result.status());
  11957. }
  11958. // stream::Post tests
  11959. TEST_F(StreamApiTest, PostBasic) {
  11960. httplib::Client cli(HOST, PORT);
  11961. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  11962. "application/json");
  11963. ASSERT_TRUE(result.is_valid());
  11964. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  11965. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  11966. }
  11967. TEST_F(StreamApiTest, PostWithHeaders) {
  11968. httplib::Client cli(HOST, PORT);
  11969. httplib::Headers headers{{"X-Custom", "value"}};
  11970. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  11971. "text/plain");
  11972. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  11973. }
  11974. TEST_F(StreamApiTest, PostWithParams) {
  11975. httplib::Client cli(HOST, PORT);
  11976. httplib::Params params{{"k", "v"}};
  11977. auto result =
  11978. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  11979. auto body = read_body(result);
  11980. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  11981. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  11982. }
  11983. TEST_F(StreamApiTest, PostLarge) {
  11984. httplib::Client cli(HOST, PORT);
  11985. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  11986. size_t total = 0;
  11987. while (result.next()) {
  11988. total += result.size();
  11989. }
  11990. EXPECT_EQ(100u * 1024u, total);
  11991. }
  11992. // stream::Put/Patch tests
  11993. TEST_F(StreamApiTest, PutAndPatch) {
  11994. httplib::Client cli(HOST, PORT);
  11995. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  11996. EXPECT_EQ("PUT:test", read_body(put));
  11997. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  11998. EXPECT_EQ("PATCH:test", read_body(patch));
  11999. }
  12000. // stream::Delete tests
  12001. TEST_F(StreamApiTest, Delete) {
  12002. httplib::Client cli(HOST, PORT);
  12003. auto del1 = httplib::stream::Delete(cli, "/resource");
  12004. EXPECT_EQ("Deleted", read_body(del1));
  12005. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  12006. EXPECT_EQ("Deleted:data", read_body(del2));
  12007. }
  12008. // stream::Head/Options tests
  12009. TEST_F(StreamApiTest, HeadAndOptions) {
  12010. httplib::Client cli(HOST, PORT);
  12011. auto head = httplib::stream::Head(cli, "/head-test");
  12012. EXPECT_TRUE(head.is_valid());
  12013. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  12014. auto opts = httplib::stream::Options(cli, "/options");
  12015. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  12016. }
  12017. // SSL stream::* tests
  12018. #ifdef CPPHTTPLIB_SSL_ENABLED
  12019. class SSLStreamApiTest : public ::testing::Test {
  12020. protected:
  12021. void SetUp() override {
  12022. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12023. res.set_content("Hello SSL!", "text/plain");
  12024. });
  12025. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12026. res.set_content(req.body, "text/plain");
  12027. });
  12028. port_ = svr_.bind_to_any_port("127.0.0.1");
  12029. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12030. svr_.wait_until_ready();
  12031. }
  12032. void TearDown() override {
  12033. svr_.stop();
  12034. if (thread_.joinable()) thread_.join();
  12035. }
  12036. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  12037. std::thread thread_;
  12038. int port_ = 0;
  12039. };
  12040. TEST_F(SSLStreamApiTest, GetAndPost) {
  12041. httplib::SSLClient cli("127.0.0.1", port_);
  12042. cli.enable_server_certificate_verification(false);
  12043. auto get = httplib::stream::Get(cli, "/hello");
  12044. EXPECT_EQ("Hello SSL!", read_body(get));
  12045. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  12046. EXPECT_EQ("test", read_body(post));
  12047. }
  12048. #endif
  12049. // Tests for Error::Timeout and Error::ConnectionClosed error types
  12050. // These errors are set in SocketStream/SSLSocketStream and propagated through
  12051. // BodyReader
  12052. TEST(ErrorHandlingTest, StreamReadTimeout) {
  12053. // Test that read timeout during streaming is detected
  12054. // Use a large content-length response where server delays mid-stream
  12055. Server svr;
  12056. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12057. // Send a large response with delay in the middle
  12058. res.set_content_provider(
  12059. 1000, // content_length
  12060. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  12061. if (offset < 100) {
  12062. // Send first 100 bytes immediately
  12063. std::string data(100, 'A');
  12064. sink.write(data.c_str(), data.size());
  12065. return true;
  12066. }
  12067. // Then delay longer than client timeout
  12068. std::this_thread::sleep_for(std::chrono::seconds(3));
  12069. std::string data(900, 'B');
  12070. sink.write(data.c_str(), data.size());
  12071. return true;
  12072. });
  12073. });
  12074. auto port = 8091;
  12075. std::thread t([&]() { svr.listen("localhost", port); });
  12076. svr.wait_until_ready();
  12077. Client cli("localhost", port);
  12078. cli.set_read_timeout(1, 0); // 1 second timeout
  12079. auto handle = cli.open_stream("GET", "/slow-stream");
  12080. ASSERT_TRUE(handle.is_valid());
  12081. char buf[256];
  12082. ssize_t total = 0;
  12083. ssize_t n;
  12084. bool got_error = false;
  12085. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12086. total += n;
  12087. }
  12088. if (n < 0) {
  12089. got_error = true;
  12090. // Should be timeout or read error
  12091. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12092. handle.get_read_error() == Error::Read)
  12093. << "Actual error: " << to_string(handle.get_read_error());
  12094. }
  12095. // Either we got an error, or we got less data than expected
  12096. EXPECT_TRUE(got_error || total < 1000)
  12097. << "Expected timeout but got all " << total << " bytes";
  12098. svr.stop();
  12099. t.join();
  12100. }
  12101. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  12102. // Test connection closed detection via BodyReader
  12103. Server svr;
  12104. std::atomic<bool> close_now{false};
  12105. svr.Get("/will-close", [&](const Request &, Response &res) {
  12106. res.set_content_provider(
  12107. 10000, // Large content_length that we won't fully send
  12108. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12109. if (offset < 100) {
  12110. std::string data(100, 'X');
  12111. sink.write(data.c_str(), data.size());
  12112. return true;
  12113. }
  12114. // Wait for signal then abort
  12115. while (!close_now) {
  12116. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12117. }
  12118. return false; // Abort - server will close connection
  12119. });
  12120. });
  12121. auto port = 8092;
  12122. std::thread t([&]() { svr.listen("localhost", port); });
  12123. svr.wait_until_ready();
  12124. Client cli("localhost", port);
  12125. auto handle = cli.open_stream("GET", "/will-close");
  12126. ASSERT_TRUE(handle.is_valid());
  12127. char buf[256];
  12128. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12129. EXPECT_GT(n, 0) << "First read should succeed";
  12130. // Signal server to close
  12131. close_now = true;
  12132. // Keep reading until error or EOF
  12133. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12134. // Keep reading
  12135. }
  12136. // Should get an error since content_length wasn't satisfied
  12137. if (n < 0) {
  12138. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12139. handle.get_read_error() == Error::Read)
  12140. << "Actual error: " << to_string(handle.get_read_error());
  12141. }
  12142. svr.stop();
  12143. t.join();
  12144. }
  12145. #ifdef CPPHTTPLIB_SSL_ENABLED
  12146. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  12147. // Test that read timeout during SSL streaming is detected
  12148. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12149. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12150. res.set_content_provider(
  12151. 1000, "text/plain",
  12152. [](size_t offset, size_t /*length*/, DataSink &sink) {
  12153. if (offset < 100) {
  12154. std::string data(100, 'A');
  12155. sink.write(data.c_str(), data.size());
  12156. return true;
  12157. }
  12158. std::this_thread::sleep_for(std::chrono::seconds(3));
  12159. std::string data(900, 'B');
  12160. sink.write(data.c_str(), data.size());
  12161. return true;
  12162. });
  12163. });
  12164. auto port = 8093;
  12165. std::thread t([&]() { svr.listen("localhost", port); });
  12166. svr.wait_until_ready();
  12167. SSLClient cli("localhost", port);
  12168. cli.enable_server_certificate_verification(false);
  12169. cli.set_read_timeout(1, 0); // 1 second timeout
  12170. auto handle = cli.open_stream("GET", "/slow-stream");
  12171. ASSERT_TRUE(handle.is_valid());
  12172. char buf[256];
  12173. ssize_t total = 0;
  12174. ssize_t n;
  12175. bool got_error = false;
  12176. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12177. total += n;
  12178. }
  12179. if (n < 0) {
  12180. got_error = true;
  12181. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12182. handle.get_read_error() == Error::Read)
  12183. << "Actual error: " << to_string(handle.get_read_error());
  12184. }
  12185. EXPECT_TRUE(got_error || total < 1000)
  12186. << "Expected timeout but got all " << total << " bytes";
  12187. svr.stop();
  12188. t.join();
  12189. }
  12190. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  12191. // Test SSL connection closed detection
  12192. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12193. std::atomic<bool> close_now{false};
  12194. svr.Get("/will-close", [&](const Request &, Response &res) {
  12195. res.set_content_provider(
  12196. 10000, "text/plain",
  12197. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12198. if (offset < 100) {
  12199. std::string data(100, 'X');
  12200. sink.write(data.c_str(), data.size());
  12201. return true;
  12202. }
  12203. while (!close_now) {
  12204. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12205. }
  12206. return false;
  12207. });
  12208. });
  12209. auto port = 8094;
  12210. std::thread t([&]() { svr.listen("localhost", port); });
  12211. svr.wait_until_ready();
  12212. SSLClient cli("localhost", port);
  12213. cli.enable_server_certificate_verification(false);
  12214. auto handle = cli.open_stream("GET", "/will-close");
  12215. ASSERT_TRUE(handle.is_valid());
  12216. char buf[256];
  12217. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12218. EXPECT_GT(n, 0);
  12219. // Signal server to close
  12220. close_now = true;
  12221. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12222. // Keep reading
  12223. }
  12224. if (n < 0) {
  12225. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12226. handle.get_read_error() == Error::Read)
  12227. << "Actual error: " << to_string(handle.get_read_error());
  12228. }
  12229. svr.stop();
  12230. t.join();
  12231. }
  12232. #endif
  12233. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  12234. using namespace httplib;
  12235. // Create a test file
  12236. const char *fname = "etag_testfile.txt";
  12237. const char *content = "etag-content";
  12238. {
  12239. std::ofstream ofs(fname);
  12240. ofs << content;
  12241. ASSERT_TRUE(ofs.good());
  12242. }
  12243. Server svr;
  12244. svr.set_mount_point("/static", ".");
  12245. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12246. svr.wait_until_ready();
  12247. Client cli(HOST, PORT);
  12248. // First request: should get 200 with ETag header
  12249. auto res1 = cli.Get("/static/etag_testfile.txt");
  12250. ASSERT_TRUE(res1);
  12251. ASSERT_EQ(200, res1->status);
  12252. ASSERT_TRUE(res1->has_header("ETag"));
  12253. std::string etag = res1->get_header_value("ETag");
  12254. EXPECT_FALSE(etag.empty());
  12255. // Verify ETag format: W/"hex-hex"
  12256. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  12257. EXPECT_EQ('W', etag[0]);
  12258. EXPECT_EQ('/', etag[1]);
  12259. EXPECT_EQ('"', etag[2]);
  12260. EXPECT_EQ('"', etag.back());
  12261. // Exact match: expect 304 Not Modified
  12262. Headers h2 = {{"If-None-Match", etag}};
  12263. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  12264. ASSERT_TRUE(res2);
  12265. EXPECT_EQ(304, res2->status);
  12266. // Wildcard match: expect 304 Not Modified
  12267. Headers h3 = {{"If-None-Match", "*"}};
  12268. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  12269. ASSERT_TRUE(res3);
  12270. EXPECT_EQ(304, res3->status);
  12271. // Non-matching ETag: expect 200
  12272. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  12273. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  12274. ASSERT_TRUE(res4);
  12275. EXPECT_EQ(200, res4->status);
  12276. // Multiple ETags with one matching: expect 304
  12277. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  12278. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  12279. ASSERT_TRUE(res5);
  12280. EXPECT_EQ(304, res5->status);
  12281. svr.stop();
  12282. t.join();
  12283. std::remove(fname);
  12284. }
  12285. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  12286. using namespace httplib;
  12287. Server svr;
  12288. svr.set_mount_point("/static", ".");
  12289. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12290. svr.wait_until_ready();
  12291. Client cli(HOST, PORT);
  12292. // Send If-None-Match: * to a non-existent file
  12293. Headers h = {{"If-None-Match", "*"}};
  12294. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  12295. ASSERT_TRUE(res);
  12296. EXPECT_EQ(404, res->status);
  12297. svr.stop();
  12298. t.join();
  12299. }
  12300. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  12301. using namespace httplib;
  12302. // Create a test file
  12303. const char *fname = "etag_boundary_testfile.txt";
  12304. const char *content = "boundary-test";
  12305. {
  12306. std::ofstream ofs(fname);
  12307. ofs << content;
  12308. ASSERT_TRUE(ofs.good());
  12309. }
  12310. Server svr;
  12311. svr.set_mount_point("/static", ".");
  12312. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12313. svr.wait_until_ready();
  12314. Client cli(HOST, PORT);
  12315. // Get the actual ETag
  12316. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  12317. ASSERT_TRUE(res1);
  12318. ASSERT_EQ(200, res1->status);
  12319. ASSERT_TRUE(res1->has_header("ETag"));
  12320. std::string etag = res1->get_header_value("ETag");
  12321. // Test 1: Very long ETag value (longer than actual ETag)
  12322. // Should NOT match and return 200 (not trigger out-of-bounds read)
  12323. Headers h1 = {{"If-None-Match", "W/"
  12324. "\"very-long-etag-value-that-is-much-longer-"
  12325. "than-the-actual-etag-value\""}};
  12326. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  12327. ASSERT_TRUE(res2);
  12328. EXPECT_EQ(200, res2->status); // Should not match
  12329. // Test 2: Long string followed by wildcard
  12330. // Should match on "*" and return 304 (without out-of-bounds read on the long
  12331. // string)
  12332. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  12333. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  12334. ASSERT_TRUE(res3);
  12335. EXPECT_EQ(304, res3->status); // Should match on "*"
  12336. // Test 3: Wildcard followed by long string
  12337. // Should match on "*" immediately and return 304
  12338. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  12339. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  12340. ASSERT_TRUE(res4);
  12341. EXPECT_EQ(304, res4->status); // Should match on "*"
  12342. // Test 4: Multiple long non-matching values
  12343. // Should NOT match and return 200 (test that all comparisons are safe)
  12344. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  12345. "W/\"second-long-non-matching-value\", "
  12346. "W/\"third-long-non-matching-value\""}};
  12347. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  12348. ASSERT_TRUE(res5);
  12349. EXPECT_EQ(200, res5->status); // Should not match
  12350. // Test 5: Single character that is not "*" (edge case)
  12351. Headers h5 = {{"If-None-Match", "X"}};
  12352. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  12353. ASSERT_TRUE(res6);
  12354. EXPECT_EQ(200, res6->status); // Should not match
  12355. svr.stop();
  12356. t.join();
  12357. std::remove(fname);
  12358. }
  12359. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  12360. using namespace httplib;
  12361. // Create a test file
  12362. const char *fname = "ims_testfile.txt";
  12363. const char *content = "if-modified-since-test";
  12364. {
  12365. std::ofstream ofs(fname);
  12366. ofs << content;
  12367. ASSERT_TRUE(ofs.good());
  12368. }
  12369. Server svr;
  12370. svr.set_mount_point("/static", ".");
  12371. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12372. svr.wait_until_ready();
  12373. Client cli(HOST, PORT);
  12374. // First request: should get 200 with Last-Modified header
  12375. auto res1 = cli.Get("/static/ims_testfile.txt");
  12376. ASSERT_TRUE(res1);
  12377. ASSERT_EQ(200, res1->status);
  12378. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12379. std::string last_modified = res1->get_header_value("Last-Modified");
  12380. EXPECT_FALSE(last_modified.empty());
  12381. // If-Modified-Since with same time: expect 304
  12382. Headers h2 = {{"If-Modified-Since", last_modified}};
  12383. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  12384. ASSERT_TRUE(res2);
  12385. EXPECT_EQ(304, res2->status);
  12386. // If-Modified-Since with future time: expect 304
  12387. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12388. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  12389. ASSERT_TRUE(res3);
  12390. EXPECT_EQ(304, res3->status);
  12391. // If-Modified-Since with past time: expect 200
  12392. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12393. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  12394. ASSERT_TRUE(res4);
  12395. EXPECT_EQ(200, res4->status);
  12396. // If-None-Match takes precedence over If-Modified-Since
  12397. // (send matching ETag with old If-Modified-Since -> should still be 304)
  12398. ASSERT_TRUE(res1->has_header("ETag"));
  12399. std::string etag = res1->get_header_value("ETag");
  12400. Headers h5 = {{"If-None-Match", etag},
  12401. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12402. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  12403. ASSERT_TRUE(res5);
  12404. EXPECT_EQ(304, res5->status);
  12405. svr.stop();
  12406. t.join();
  12407. std::remove(fname);
  12408. }
  12409. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  12410. using namespace httplib;
  12411. Server svr;
  12412. // Endpoint that returns compressible content
  12413. svr.Get("/compressible", [](const Request &, Response &res) {
  12414. // Return a large enough body to trigger compression
  12415. std::string body(1000, 'a');
  12416. res.set_content(body, "text/plain");
  12417. });
  12418. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12419. svr.wait_until_ready();
  12420. Client cli(HOST, PORT);
  12421. // Request with gzip support: should get Vary header when compressed
  12422. cli.set_compress(true);
  12423. auto res1 = cli.Get("/compressible");
  12424. ASSERT_TRUE(res1);
  12425. EXPECT_EQ(200, res1->status);
  12426. // If Content-Encoding is set, Vary should also be set
  12427. if (res1->has_header("Content-Encoding")) {
  12428. EXPECT_TRUE(res1->has_header("Vary"));
  12429. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  12430. }
  12431. // Request without Accept-Encoding header: should not have compression
  12432. Headers h_no_compress;
  12433. auto res2 = cli.Get("/compressible", h_no_compress);
  12434. ASSERT_TRUE(res2);
  12435. EXPECT_EQ(200, res2->status);
  12436. // Verify Vary header is present when compression is applied
  12437. // (the exact behavior depends on server configuration)
  12438. svr.stop();
  12439. t.join();
  12440. }
  12441. TEST(ETagTest, IfRangeWithETag) {
  12442. using namespace httplib;
  12443. // Create a test file with known content
  12444. const char *fname = "if_range_testfile.txt";
  12445. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  12446. {
  12447. std::ofstream ofs(fname);
  12448. ofs << content;
  12449. ASSERT_TRUE(ofs.good());
  12450. }
  12451. Server svr;
  12452. svr.set_mount_point("/static", ".");
  12453. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12454. svr.wait_until_ready();
  12455. Client cli(HOST, PORT);
  12456. // First request: get ETag
  12457. auto res1 = cli.Get("/static/if_range_testfile.txt");
  12458. ASSERT_TRUE(res1);
  12459. ASSERT_EQ(200, res1->status);
  12460. ASSERT_TRUE(res1->has_header("ETag"));
  12461. std::string etag = res1->get_header_value("ETag");
  12462. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  12463. // Since our server generates weak ETags (W/"..."), If-Range with our
  12464. // ETag should NOT result in partial content - it should return full content.
  12465. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  12466. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  12467. ASSERT_TRUE(res2);
  12468. // Weak ETag in If-Range -> full content (200), not partial (206)
  12469. EXPECT_EQ(200, res2->status);
  12470. EXPECT_EQ(content, res2->body);
  12471. EXPECT_FALSE(res2->has_header("Content-Range"));
  12472. // Range request with non-matching If-Range (ETag): should get 200 (full
  12473. // content)
  12474. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  12475. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  12476. ASSERT_TRUE(res3);
  12477. EXPECT_EQ(200, res3->status);
  12478. EXPECT_EQ(content, res3->body);
  12479. EXPECT_FALSE(res3->has_header("Content-Range"));
  12480. // Range request with strong ETag (hypothetical - our server doesn't generate
  12481. // strong ETags, but if client sends a strong ETag that doesn't match, it
  12482. // should return full content)
  12483. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  12484. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  12485. ASSERT_TRUE(res4);
  12486. EXPECT_EQ(200, res4->status);
  12487. EXPECT_EQ(content, res4->body);
  12488. EXPECT_FALSE(res4->has_header("Content-Range"));
  12489. svr.stop();
  12490. t.join();
  12491. std::remove(fname);
  12492. }
  12493. TEST(ETagTest, IfRangeWithDate) {
  12494. using namespace httplib;
  12495. // Create a test file
  12496. const char *fname = "if_range_date_testfile.txt";
  12497. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  12498. {
  12499. std::ofstream ofs(fname);
  12500. ofs << content;
  12501. ASSERT_TRUE(ofs.good());
  12502. }
  12503. Server svr;
  12504. svr.set_mount_point("/static", ".");
  12505. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12506. svr.wait_until_ready();
  12507. Client cli(HOST, PORT);
  12508. // First request: get Last-Modified
  12509. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  12510. ASSERT_TRUE(res1);
  12511. ASSERT_EQ(200, res1->status);
  12512. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12513. std::string last_modified = res1->get_header_value("Last-Modified");
  12514. // Range request with matching If-Range (date): should get 206
  12515. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  12516. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  12517. ASSERT_TRUE(res2);
  12518. EXPECT_EQ(206, res2->status);
  12519. EXPECT_EQ("FGHIJ", res2->body);
  12520. // Range request with old If-Range date: should get 200 (full content)
  12521. Headers h3 = {{"Range", "bytes=5-9"},
  12522. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12523. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  12524. ASSERT_TRUE(res3);
  12525. EXPECT_EQ(200, res3->status);
  12526. EXPECT_EQ(content, res3->body);
  12527. // Range request with future If-Range date: should get 206
  12528. Headers h4 = {{"Range", "bytes=0-4"},
  12529. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12530. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  12531. ASSERT_TRUE(res4);
  12532. EXPECT_EQ(206, res4->status);
  12533. EXPECT_EQ("ABCDE", res4->body);
  12534. svr.stop();
  12535. t.join();
  12536. std::remove(fname);
  12537. }
  12538. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  12539. using namespace httplib;
  12540. const char *fname = "etag_malformed.txt";
  12541. const char *content = "malformed-etag";
  12542. {
  12543. std::ofstream ofs(fname);
  12544. ofs << content;
  12545. ASSERT_TRUE(ofs.good());
  12546. }
  12547. Server svr;
  12548. svr.set_mount_point("/static", ".");
  12549. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12550. svr.wait_until_ready();
  12551. Client cli(HOST, PORT);
  12552. // baseline: should get 200 and an ETag
  12553. auto res1 = cli.Get("/static/etag_malformed.txt");
  12554. ASSERT_TRUE(res1);
  12555. ASSERT_EQ(200, res1->status);
  12556. ASSERT_TRUE(res1->has_header("ETag"));
  12557. // Malformed ETag value (missing quotes) should be treated as non-matching
  12558. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  12559. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  12560. ASSERT_TRUE(res_bad);
  12561. EXPECT_EQ(200, res_bad->status);
  12562. // Whitespace-only header value should be considered invalid / non-matching
  12563. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  12564. "Host: localhost\r\n"
  12565. "If-None-Match: \r\n"
  12566. "Connection: close\r\n"
  12567. "\r\n";
  12568. std::string out;
  12569. ASSERT_TRUE(send_request(5, raw_req, &out));
  12570. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12571. svr.stop();
  12572. t.join();
  12573. std::remove(fname);
  12574. }
  12575. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  12576. using namespace httplib;
  12577. const char *fname = "ims_invalid_format.txt";
  12578. const char *content = "ims-bad-format";
  12579. {
  12580. std::ofstream ofs(fname);
  12581. ofs << content;
  12582. ASSERT_TRUE(ofs.good());
  12583. }
  12584. Server svr;
  12585. svr.set_mount_point("/static", ".");
  12586. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12587. svr.wait_until_ready();
  12588. Client cli(HOST, PORT);
  12589. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  12590. ASSERT_TRUE(res1);
  12591. ASSERT_EQ(200, res1->status);
  12592. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12593. // If-Modified-Since with invalid format should not result in 304
  12594. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  12595. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  12596. ASSERT_TRUE(res_bad);
  12597. EXPECT_EQ(200, res_bad->status);
  12598. // If-Range with invalid date format should be treated as mismatch -> full
  12599. // content (200)
  12600. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  12601. {"If-Range", "invalid-date"}};
  12602. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  12603. ASSERT_TRUE(res_ifrange);
  12604. EXPECT_EQ(200, res_ifrange->status);
  12605. svr.stop();
  12606. t.join();
  12607. std::remove(fname);
  12608. }
  12609. TEST(ETagTest, IfRangeWithMalformedETag) {
  12610. using namespace httplib;
  12611. const char *fname = "ifrange_malformed.txt";
  12612. const std::string content = "0123456789";
  12613. {
  12614. std::ofstream ofs(fname);
  12615. ofs << content;
  12616. ASSERT_TRUE(ofs.good());
  12617. }
  12618. Server svr;
  12619. svr.set_mount_point("/static", ".");
  12620. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12621. svr.wait_until_ready();
  12622. Client cli(HOST, PORT);
  12623. // First request: get ETag
  12624. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  12625. ASSERT_TRUE(res1);
  12626. ASSERT_EQ(200, res1->status);
  12627. ASSERT_TRUE(res1->has_header("ETag"));
  12628. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  12629. // full content (200)
  12630. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  12631. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  12632. ASSERT_TRUE(res2);
  12633. EXPECT_EQ(200, res2->status);
  12634. EXPECT_EQ(content, res2->body);
  12635. svr.stop();
  12636. t.join();
  12637. std::remove(fname);
  12638. }
  12639. TEST(ETagTest, ExtremeLargeDateValues) {
  12640. using namespace httplib;
  12641. const char *fname = "ims_extreme_date.txt";
  12642. const char *content = "ims-extreme-date";
  12643. {
  12644. std::ofstream ofs(fname);
  12645. ofs << content;
  12646. ASSERT_TRUE(ofs.good());
  12647. }
  12648. Server svr;
  12649. svr.set_mount_point("/static", ".");
  12650. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12651. svr.wait_until_ready();
  12652. Client cli(HOST, PORT);
  12653. auto res1 = cli.Get(std::string("/static/") + fname);
  12654. ASSERT_TRUE(res1);
  12655. ASSERT_EQ(200, res1->status);
  12656. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12657. // Extremely large year that may overflow date parsing routines.
  12658. Headers h_large_date = {
  12659. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12660. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  12661. ASSERT_TRUE(res_bad);
  12662. // Expect server to treat this as invalid/mismatch and return full content
  12663. EXPECT_EQ(200, res_bad->status);
  12664. // If-Range with extremely large date should be treated as mismatch -> full
  12665. // content (200)
  12666. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  12667. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12668. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  12669. ASSERT_TRUE(res_ifrange);
  12670. EXPECT_EQ(200, res_ifrange->status);
  12671. svr.stop();
  12672. t.join();
  12673. std::remove(fname);
  12674. }
  12675. TEST(ETagTest, NegativeFileModificationTime) {
  12676. using namespace httplib;
  12677. const char *fname = "ims_negative_mtime.txt";
  12678. const std::string content = "negative-mtime";
  12679. {
  12680. std::ofstream ofs(fname);
  12681. ofs << content;
  12682. ASSERT_TRUE(ofs.good());
  12683. }
  12684. // Try to set file mtime to a negative value. This may fail on some
  12685. // platforms/filesystems; if it fails, the test will still verify server
  12686. // behaves safely by performing a regular conditional request.
  12687. #if defined(__APPLE__) || defined(__linux__)
  12688. bool set_negative = false;
  12689. do {
  12690. struct timeval times[2];
  12691. // access time: now
  12692. times[0].tv_sec = time(nullptr);
  12693. times[0].tv_usec = 0;
  12694. // modification time: negative (e.g., -1)
  12695. times[1].tv_sec = -1;
  12696. times[1].tv_usec = 0;
  12697. if (utimes(fname, times) == 0) { set_negative = true; }
  12698. } while (0);
  12699. #else
  12700. bool set_negative = false;
  12701. #endif
  12702. Server svr;
  12703. svr.set_mount_point("/static", ".");
  12704. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12705. svr.wait_until_ready();
  12706. Client cli(HOST, PORT);
  12707. auto res1 = cli.Get(std::string("/static/") + fname);
  12708. ASSERT_TRUE(res1);
  12709. ASSERT_EQ(200, res1->status);
  12710. bool has_last_modified = res1->has_header("Last-Modified");
  12711. std::string last_modified;
  12712. if (has_last_modified) {
  12713. last_modified = res1->get_header_value("Last-Modified");
  12714. }
  12715. if (set_negative) {
  12716. // If we successfully set a negative mtime, ensure server returns a
  12717. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  12718. // with an old date and ensure server handles it without crash.
  12719. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  12720. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  12721. ASSERT_TRUE(res2);
  12722. // Behavior may vary; at minimum ensure server responds (200 or 304).
  12723. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  12724. } else {
  12725. // Could not set negative mtime on this platform; fall back to verifying
  12726. // that normal invalid/malformed dates are treated safely (non-304).
  12727. Headers h_bad_date = {
  12728. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12729. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  12730. ASSERT_TRUE(res_bad);
  12731. EXPECT_EQ(200, res_bad->status);
  12732. }
  12733. svr.stop();
  12734. t.join();
  12735. std::remove(fname);
  12736. }
  12737. //==============================================================================
  12738. // SSE Parsing Tests
  12739. //==============================================================================
  12740. class SSEParsingTest : public ::testing::Test {
  12741. protected:
  12742. // Test helper that mimics SSE parsing behavior
  12743. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  12744. int &retry_ms) {
  12745. // Blank line signals end of event
  12746. if (line.empty() || line == "\r") { return true; }
  12747. // Lines starting with ':' are comments (ignored)
  12748. if (!line.empty() && line[0] == ':') { return false; }
  12749. // Find the colon separator
  12750. auto colon_pos = line.find(':');
  12751. if (colon_pos == std::string::npos) {
  12752. // Line with no colon is treated as field name with empty value
  12753. return false;
  12754. }
  12755. std::string field = line.substr(0, colon_pos);
  12756. std::string value;
  12757. // Value starts after colon, skip optional single space
  12758. if (colon_pos + 1 < line.size()) {
  12759. size_t value_start = colon_pos + 1;
  12760. if (line[value_start] == ' ') { value_start++; }
  12761. value = line.substr(value_start);
  12762. // Remove trailing \r if present
  12763. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  12764. }
  12765. // Handle known fields
  12766. if (field == "event") {
  12767. msg.event = value;
  12768. } else if (field == "data") {
  12769. // Multiple data lines are concatenated with newlines
  12770. if (!msg.data.empty()) { msg.data += "\n"; }
  12771. msg.data += value;
  12772. } else if (field == "id") {
  12773. // Empty id is valid (clears the last event ID)
  12774. msg.id = value;
  12775. } else if (field == "retry") {
  12776. // Parse retry interval in milliseconds
  12777. {
  12778. int v = 0;
  12779. auto res =
  12780. detail::from_chars(value.data(), value.data() + value.size(), v);
  12781. if (res.ec == std::errc{}) { retry_ms = v; }
  12782. }
  12783. }
  12784. // Unknown fields are ignored per SSE spec
  12785. return false;
  12786. }
  12787. };
  12788. // Test: Single-line data
  12789. TEST_F(SSEParsingTest, SingleLineData) {
  12790. sse::SSEMessage msg;
  12791. int retry_ms = 3000;
  12792. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  12793. EXPECT_EQ(msg.data, "hello");
  12794. EXPECT_EQ(msg.event, "message");
  12795. // Blank line ends event
  12796. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12797. }
  12798. // Test: Multi-line data
  12799. TEST_F(SSEParsingTest, MultiLineData) {
  12800. sse::SSEMessage msg;
  12801. int retry_ms = 3000;
  12802. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  12803. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  12804. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  12805. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  12806. }
  12807. // Test: Custom event types
  12808. TEST_F(SSEParsingTest, CustomEventType) {
  12809. sse::SSEMessage msg;
  12810. int retry_ms = 3000;
  12811. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  12812. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  12813. EXPECT_EQ(msg.event, "update");
  12814. EXPECT_EQ(msg.data, "payload");
  12815. }
  12816. // Test: Event ID handling
  12817. TEST_F(SSEParsingTest, EventIdHandling) {
  12818. sse::SSEMessage msg;
  12819. int retry_ms = 3000;
  12820. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  12821. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  12822. EXPECT_EQ(msg.id, "12345");
  12823. }
  12824. // Test: Empty event ID (clears last event ID)
  12825. TEST_F(SSEParsingTest, EmptyEventId) {
  12826. sse::SSEMessage msg;
  12827. msg.id = "previous";
  12828. int retry_ms = 3000;
  12829. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  12830. EXPECT_EQ(msg.id, "");
  12831. }
  12832. // Test: Retry field parsing
  12833. TEST_F(SSEParsingTest, RetryFieldParsing) {
  12834. sse::SSEMessage msg;
  12835. int retry_ms = 3000;
  12836. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  12837. EXPECT_EQ(retry_ms, 5000);
  12838. }
  12839. // Test: Invalid retry value
  12840. TEST_F(SSEParsingTest, InvalidRetryValue) {
  12841. sse::SSEMessage msg;
  12842. int retry_ms = 3000;
  12843. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  12844. EXPECT_EQ(retry_ms, 3000); // Unchanged
  12845. }
  12846. // Test: Comments (lines starting with :)
  12847. TEST_F(SSEParsingTest, CommentsIgnored) {
  12848. sse::SSEMessage msg;
  12849. int retry_ms = 3000;
  12850. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  12851. EXPECT_EQ(msg.data, "");
  12852. EXPECT_EQ(msg.event, "message");
  12853. }
  12854. // Test: Colon in value
  12855. TEST_F(SSEParsingTest, ColonInValue) {
  12856. sse::SSEMessage msg;
  12857. int retry_ms = 3000;
  12858. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  12859. EXPECT_EQ(msg.data, "hello:world:test");
  12860. }
  12861. // Test: Line with no colon (field name only)
  12862. TEST_F(SSEParsingTest, FieldNameOnly) {
  12863. sse::SSEMessage msg;
  12864. int retry_ms = 3000;
  12865. // According to SSE spec, this is treated as field name with empty value
  12866. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  12867. // Since we don't recognize "data" without colon, data should be empty
  12868. EXPECT_EQ(msg.data, "");
  12869. }
  12870. // Test: Trailing \r handling
  12871. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  12872. sse::SSEMessage msg;
  12873. int retry_ms = 3000;
  12874. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  12875. EXPECT_EQ(msg.data, "hello");
  12876. }
  12877. // Test: Unknown fields ignored
  12878. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  12879. sse::SSEMessage msg;
  12880. int retry_ms = 3000;
  12881. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  12882. EXPECT_EQ(msg.data, "");
  12883. EXPECT_EQ(msg.event, "message");
  12884. }
  12885. // Test: Space after colon is optional
  12886. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  12887. sse::SSEMessage msg1, msg2;
  12888. int retry_ms = 3000;
  12889. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  12890. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  12891. EXPECT_EQ(msg1.data, "hello");
  12892. EXPECT_EQ(msg2.data, "hello");
  12893. }
  12894. // Test: SSEMessage clear
  12895. TEST_F(SSEParsingTest, MessageClear) {
  12896. sse::SSEMessage msg;
  12897. msg.event = "custom";
  12898. msg.data = "some data";
  12899. msg.id = "123";
  12900. msg.clear();
  12901. EXPECT_EQ(msg.event, "message");
  12902. EXPECT_EQ(msg.data, "");
  12903. EXPECT_EQ(msg.id, "");
  12904. }
  12905. // Test: Complete event parsing
  12906. TEST_F(SSEParsingTest, CompleteEventParsing) {
  12907. sse::SSEMessage msg;
  12908. int retry_ms = 3000;
  12909. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  12910. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  12911. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  12912. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  12913. // Blank line ends event
  12914. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12915. EXPECT_EQ(msg.event, "notification");
  12916. EXPECT_EQ(msg.id, "evt-42");
  12917. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  12918. EXPECT_EQ(retry_ms, 1000);
  12919. }
  12920. //==============================================================================
  12921. // Integration Tests with Server
  12922. //==============================================================================
  12923. class SSEIntegrationTest : public ::testing::Test {
  12924. protected:
  12925. void SetUp() override {
  12926. stop_server_.store(false);
  12927. events_.clear();
  12928. server_ = httplib::detail::make_unique<Server>();
  12929. setup_server();
  12930. start_server();
  12931. }
  12932. void TearDown() override {
  12933. stop_server_.store(true);
  12934. event_cv_.notify_all();
  12935. server_->stop();
  12936. if (server_thread_.joinable()) { server_thread_.join(); }
  12937. }
  12938. void setup_server() {
  12939. // Simple SSE endpoint
  12940. server_->Get("/events", [this](const Request &req, Response &res) {
  12941. auto last_id = req.get_header_value("Last-Event-ID");
  12942. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  12943. res.set_chunked_content_provider(
  12944. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  12945. std::unique_lock<std::mutex> lock(event_mutex_);
  12946. if (event_cv_.wait_for(
  12947. lock, std::chrono::milliseconds(200), [this] {
  12948. return !events_.empty() || stop_server_.load();
  12949. })) {
  12950. if (stop_server_.load()) { return false; }
  12951. if (!events_.empty()) {
  12952. std::string event = events_.front();
  12953. events_.erase(events_.begin());
  12954. sink.write(event.data(), event.size());
  12955. return true;
  12956. }
  12957. }
  12958. return !stop_server_.load();
  12959. });
  12960. });
  12961. // Endpoint that returns error
  12962. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  12963. res.status = 500;
  12964. res.set_content("Internal Server Error", "text/plain");
  12965. });
  12966. // Endpoint for custom event types
  12967. server_->Get("/custom-events", [](const Request &, Response &res) {
  12968. res.set_chunked_content_provider(
  12969. "text/event-stream", [](size_t offset, DataSink &sink) {
  12970. if (offset == 0) {
  12971. std::string event = "event: update\ndata: updated\n\n"
  12972. "event: delete\ndata: deleted\n\n";
  12973. sink.write(event.data(), event.size());
  12974. }
  12975. return false; // End stream after sending
  12976. });
  12977. });
  12978. }
  12979. void start_server() {
  12980. port_ = server_->bind_to_any_port(HOST);
  12981. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  12982. // Wait for server to start
  12983. while (!server_->is_running()) {
  12984. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12985. }
  12986. }
  12987. int get_port() const { return port_; }
  12988. void send_event(const std::string &event) {
  12989. std::lock_guard<std::mutex> lock(event_mutex_);
  12990. events_.push_back(event);
  12991. event_cv_.notify_all();
  12992. }
  12993. std::unique_ptr<Server> server_;
  12994. std::thread server_thread_;
  12995. std::mutex event_mutex_;
  12996. std::condition_variable event_cv_;
  12997. std::vector<std::string> events_;
  12998. std::atomic<bool> stop_server_{false};
  12999. std::string last_received_event_id_;
  13000. int port_ = 0;
  13001. };
  13002. // Test: Successful connection and on_open callback
  13003. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  13004. // Add a simple endpoint that sends one event and closes
  13005. server_->Get("/simple-event", [](const Request &, Response &res) {
  13006. res.set_chunked_content_provider(
  13007. "text/event-stream", [](size_t offset, DataSink &sink) {
  13008. if (offset == 0) {
  13009. std::string event = "data: hello\n\n";
  13010. sink.write(event.data(), event.size());
  13011. }
  13012. return false; // Close stream after sending
  13013. });
  13014. });
  13015. Client client("localhost", get_port());
  13016. sse::SSEClient sse(client, "/simple-event");
  13017. std::atomic<bool> open_called{false};
  13018. std::atomic<bool> message_received{false};
  13019. sse.on_open([&open_called]() { open_called.store(true); });
  13020. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  13021. if (msg.data == "hello") { message_received.store(true); }
  13022. });
  13023. sse.set_reconnect_interval(100);
  13024. sse.set_max_reconnect_attempts(1);
  13025. // Start async
  13026. sse.start_async();
  13027. // Wait for message to be processed
  13028. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13029. sse.stop();
  13030. EXPECT_TRUE(open_called.load());
  13031. EXPECT_TRUE(message_received.load());
  13032. }
  13033. // Test: on_message callback
  13034. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  13035. // Endpoint that sends multiple events then closes
  13036. server_->Get("/multi-event", [](const Request &, Response &res) {
  13037. res.set_chunked_content_provider(
  13038. "text/event-stream", [](size_t offset, DataSink &sink) {
  13039. if (offset == 0) {
  13040. std::string events = "data: message1\n\ndata: message2\n\n";
  13041. sink.write(events.data(), events.size());
  13042. }
  13043. return false;
  13044. });
  13045. });
  13046. Client client("localhost", get_port());
  13047. sse::SSEClient sse(client, "/multi-event");
  13048. std::vector<std::string> received_messages;
  13049. std::mutex messages_mutex;
  13050. sse.on_message([&](const sse::SSEMessage &msg) {
  13051. std::lock_guard<std::mutex> lock(messages_mutex);
  13052. received_messages.push_back(msg.data);
  13053. });
  13054. sse.set_reconnect_interval(100);
  13055. sse.set_max_reconnect_attempts(1);
  13056. sse.start_async();
  13057. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13058. sse.stop();
  13059. std::lock_guard<std::mutex> lock(messages_mutex);
  13060. EXPECT_GE(received_messages.size(), 2u);
  13061. if (received_messages.size() >= 2) {
  13062. EXPECT_EQ(received_messages[0], "message1");
  13063. EXPECT_EQ(received_messages[1], "message2");
  13064. }
  13065. }
  13066. // Test: on_event for specific types
  13067. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  13068. Client client("localhost", get_port());
  13069. sse::SSEClient sse(client, "/custom-events");
  13070. std::atomic<bool> update_received{false};
  13071. std::atomic<bool> delete_received{false};
  13072. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  13073. if (msg.data == "updated") { update_received.store(true); }
  13074. });
  13075. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  13076. if (msg.data == "deleted") { delete_received.store(true); }
  13077. });
  13078. sse.set_max_reconnect_attempts(1);
  13079. sse.start_async();
  13080. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  13081. sse.stop();
  13082. EXPECT_TRUE(update_received.load());
  13083. EXPECT_TRUE(delete_received.load());
  13084. }
  13085. // Test: on_error callback on connection failure
  13086. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  13087. // Connect to a non-existent port
  13088. Client client("localhost", 59999);
  13089. sse::SSEClient sse(client, "/events");
  13090. std::atomic<bool> error_called{false};
  13091. Error received_error = Error::Success;
  13092. sse.on_error([&](Error err) {
  13093. error_called.store(true);
  13094. received_error = err;
  13095. });
  13096. sse.set_reconnect_interval(50);
  13097. sse.set_max_reconnect_attempts(1);
  13098. sse.start_async();
  13099. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13100. sse.stop();
  13101. EXPECT_TRUE(error_called.load());
  13102. EXPECT_NE(received_error, Error::Success);
  13103. }
  13104. // Test: Last-Event-ID header sent on reconnect
  13105. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  13106. // Endpoint that sends event with ID
  13107. server_->Get("/event-with-id", [](const Request &, Response &res) {
  13108. res.set_chunked_content_provider(
  13109. "text/event-stream", [](size_t offset, DataSink &sink) {
  13110. if (offset == 0) {
  13111. std::string event = "id: evt-123\ndata: test\n\n";
  13112. sink.write(event.data(), event.size());
  13113. }
  13114. return false;
  13115. });
  13116. });
  13117. Client client("localhost", get_port());
  13118. sse::SSEClient sse(client, "/event-with-id");
  13119. std::atomic<bool> id_received{false};
  13120. sse.on_message([&](const sse::SSEMessage &msg) {
  13121. if (!msg.id.empty()) { id_received.store(true); }
  13122. });
  13123. sse.set_reconnect_interval(100);
  13124. sse.set_max_reconnect_attempts(1);
  13125. sse.start_async();
  13126. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13127. sse.stop();
  13128. EXPECT_TRUE(id_received.load());
  13129. EXPECT_EQ(sse.last_event_id(), "evt-123");
  13130. }
  13131. // Test: Manual stop
  13132. TEST_F(SSEIntegrationTest, ManualStop) {
  13133. // Endpoint that sends one event and stays open briefly
  13134. std::atomic<bool> handler_running{true};
  13135. server_->Get("/stay-open", [&handler_running](const Request &,
  13136. Response &res) {
  13137. res.set_chunked_content_provider(
  13138. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  13139. if (offset == 0) {
  13140. std::string event = "data: connected\n\n";
  13141. sink.write(event.data(), event.size());
  13142. }
  13143. // Keep connection open while handler_running is true
  13144. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  13145. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13146. }
  13147. return false;
  13148. });
  13149. });
  13150. Client client("localhost", get_port());
  13151. sse::SSEClient sse(client, "/stay-open");
  13152. std::atomic<bool> connected{false};
  13153. sse.on_open([&connected]() { connected.store(true); });
  13154. sse.set_reconnect_interval(100);
  13155. sse.set_max_reconnect_attempts(1);
  13156. sse.start_async();
  13157. // Wait for connection to establish
  13158. for (int i = 0; i < 20 && !connected.load(); ++i) {
  13159. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13160. }
  13161. EXPECT_TRUE(connected.load());
  13162. EXPECT_TRUE(sse.is_connected());
  13163. // Signal handler to stop
  13164. handler_running.store(false);
  13165. // Stop SSE client
  13166. sse.stop();
  13167. EXPECT_FALSE(sse.is_connected());
  13168. }
  13169. // Test: SSEClient with custom headers
  13170. TEST_F(SSEIntegrationTest, CustomHeaders) {
  13171. // Setup a server endpoint that checks for custom header
  13172. std::atomic<bool> header_received{false};
  13173. server_->Get("/header-check", [&](const Request &req, Response &res) {
  13174. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  13175. header_received.store(true);
  13176. }
  13177. res.set_chunked_content_provider("text/event-stream",
  13178. [](size_t, DataSink &) { return false; });
  13179. });
  13180. Client client("localhost", get_port());
  13181. Headers headers = {{"X-Custom-Header", "custom-value"}};
  13182. sse::SSEClient sse(client, "/header-check", headers);
  13183. sse.set_max_reconnect_attempts(1);
  13184. sse.start_async();
  13185. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13186. sse.stop();
  13187. EXPECT_TRUE(header_received.load());
  13188. }
  13189. // Test: Reconnect interval configuration
  13190. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  13191. Client client("localhost", get_port());
  13192. sse::SSEClient sse(client, "/events");
  13193. auto &result = sse.set_reconnect_interval(500);
  13194. // Builder pattern should return reference to self
  13195. EXPECT_EQ(&result, &sse);
  13196. }
  13197. // Test: Max reconnect attempts
  13198. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  13199. // Connect to non-existent port to force reconnects
  13200. Client client("localhost", 59998);
  13201. sse::SSEClient sse(client, "/events");
  13202. std::atomic<int> error_count{0};
  13203. sse.on_error([&](Error) { error_count.fetch_add(1); });
  13204. sse.set_reconnect_interval(50);
  13205. sse.set_max_reconnect_attempts(2);
  13206. auto start = std::chrono::steady_clock::now();
  13207. sse.start(); // Blocking call
  13208. auto end = std::chrono::steady_clock::now();
  13209. // Should have stopped after 2 failed attempts
  13210. EXPECT_GE(error_count.load(), 2);
  13211. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  13212. auto duration =
  13213. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  13214. #ifdef _WIN32
  13215. // Windows is much slower for socket connection failures
  13216. EXPECT_LT(duration.count(), 7000);
  13217. #else
  13218. EXPECT_LT(duration.count(), 1000);
  13219. #endif
  13220. }
  13221. // Test: Multi-line data in integration
  13222. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  13223. // Endpoint with multi-line data
  13224. server_->Get("/multiline-data", [](const Request &, Response &res) {
  13225. res.set_chunked_content_provider(
  13226. "text/event-stream", [](size_t offset, DataSink &sink) {
  13227. if (offset == 0) {
  13228. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  13229. sink.write(event.data(), event.size());
  13230. }
  13231. return false;
  13232. });
  13233. });
  13234. Client client("localhost", get_port());
  13235. sse::SSEClient sse(client, "/multiline-data");
  13236. std::string received_data;
  13237. std::mutex data_mutex;
  13238. sse.on_message([&](const sse::SSEMessage &msg) {
  13239. std::lock_guard<std::mutex> lock(data_mutex);
  13240. received_data = msg.data;
  13241. });
  13242. sse.set_reconnect_interval(100);
  13243. sse.set_max_reconnect_attempts(1);
  13244. sse.start_async();
  13245. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13246. sse.stop();
  13247. std::lock_guard<std::mutex> lock(data_mutex);
  13248. EXPECT_EQ(received_data, "line1\nline2\nline3");
  13249. }
  13250. // Test: Auto-reconnect after server disconnection
  13251. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  13252. std::atomic<int> connection_count{0};
  13253. std::atomic<int> message_count{0};
  13254. // Endpoint that sends one event and closes, forcing reconnect
  13255. server_->Get("/reconnect-test",
  13256. [&connection_count](const Request &, Response &res) {
  13257. connection_count.fetch_add(1);
  13258. res.set_chunked_content_provider(
  13259. "text/event-stream", [](size_t offset, DataSink &sink) {
  13260. if (offset == 0) {
  13261. std::string event = "data: hello\n\n";
  13262. sink.write(event.data(), event.size());
  13263. }
  13264. return false; // Close connection after sending
  13265. });
  13266. });
  13267. Client client("localhost", get_port());
  13268. sse::SSEClient sse(client, "/reconnect-test");
  13269. sse.on_message([&message_count](const sse::SSEMessage &) {
  13270. message_count.fetch_add(1);
  13271. });
  13272. sse.set_reconnect_interval(100);
  13273. sse.set_max_reconnect_attempts(3);
  13274. sse.start_async();
  13275. // Wait long enough for multiple reconnects
  13276. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13277. sse.stop();
  13278. // Should have connected multiple times (initial + reconnects)
  13279. EXPECT_GE(connection_count.load(), 2);
  13280. // Should have received messages from multiple connections
  13281. EXPECT_GE(message_count.load(), 2);
  13282. }
  13283. // Test: Last-Event-ID sent on reconnect
  13284. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  13285. std::atomic<int> connection_count{0};
  13286. std::vector<std::string> received_last_event_ids;
  13287. std::mutex id_mutex;
  13288. // Endpoint that checks Last-Event-ID header and sends event with ID
  13289. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  13290. int conn = connection_count.fetch_add(1);
  13291. // Capture the Last-Event-ID header from each connection
  13292. {
  13293. std::lock_guard<std::mutex> lock(id_mutex);
  13294. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  13295. }
  13296. res.set_chunked_content_provider(
  13297. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  13298. if (offset == 0) {
  13299. std::string event =
  13300. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  13301. sink.write(event.data(), event.size());
  13302. }
  13303. return false;
  13304. });
  13305. });
  13306. Client client("localhost", get_port());
  13307. sse::SSEClient sse(client, "/reconnect-with-id");
  13308. sse.set_reconnect_interval(100);
  13309. sse.set_max_reconnect_attempts(3);
  13310. sse.start_async();
  13311. // Wait for at least 2 connections
  13312. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13313. sse.stop();
  13314. // Verify behavior
  13315. std::lock_guard<std::mutex> lock(id_mutex);
  13316. EXPECT_GE(received_last_event_ids.size(), 2u);
  13317. // First connection should have no Last-Event-ID
  13318. if (!received_last_event_ids.empty()) {
  13319. EXPECT_EQ(received_last_event_ids[0], "");
  13320. }
  13321. // Second connection should have Last-Event-ID from first connection
  13322. if (received_last_event_ids.size() >= 2) {
  13323. EXPECT_EQ(received_last_event_ids[1], "event-0");
  13324. }
  13325. }
  13326. TEST(Issue2318Test, EmptyHostString) {
  13327. {
  13328. httplib::Client cli_empty("", PORT);
  13329. auto res = cli_empty.Get("/");
  13330. ASSERT_FALSE(res);
  13331. EXPECT_EQ(httplib::Error::Connection, res.error());
  13332. }
  13333. {
  13334. httplib::Client cli(" ", PORT);
  13335. auto res = cli.Get("/");
  13336. ASSERT_FALSE(res);
  13337. EXPECT_EQ(httplib::Error::Connection, res.error());
  13338. }
  13339. }
  13340. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13341. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  13342. Server svr;
  13343. // Set a small payload limit (1KB)
  13344. svr.set_payload_max_length(1024);
  13345. svr.Post("/test", [&](const Request &req, Response &res) {
  13346. res.set_content("Body size: " + std::to_string(req.body.size()),
  13347. "text/plain");
  13348. });
  13349. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13350. auto se = detail::scope_exit([&] {
  13351. svr.stop();
  13352. listen_thread.join();
  13353. });
  13354. svr.wait_until_ready();
  13355. // Create data that compresses well but exceeds limit when decompressed
  13356. // 8KB of repeated null bytes compresses to a very small size
  13357. std::string original_data(8 * 1024, '\0');
  13358. // Compress the data using gzip
  13359. std::string compressed_data;
  13360. detail::gzip_compressor compressor;
  13361. compressor.compress(original_data.data(), original_data.size(), true,
  13362. [&](const char *data, size_t size) {
  13363. compressed_data.append(data, size);
  13364. return true;
  13365. });
  13366. // Verify compression worked (compressed should be much smaller)
  13367. ASSERT_LT(compressed_data.size(), original_data.size());
  13368. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  13369. // Send compressed data with Content-Encoding: gzip
  13370. Client cli(HOST, PORT);
  13371. Headers headers = {{"Content-Encoding", "gzip"}};
  13372. auto res =
  13373. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  13374. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  13375. ASSERT_TRUE(res);
  13376. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13377. }
  13378. #endif
  13379. // ============================================================================
  13380. // OpenSSL-Specific Tests
  13381. // ============================================================================
  13382. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13383. X509 *readCertificate(const std::string &strFileName) {
  13384. std::ifstream inStream(strFileName);
  13385. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  13386. std::istreambuf_iterator<char>());
  13387. if (strCertPEM.empty()) return (nullptr);
  13388. BIO *pbCert = BIO_new(BIO_s_mem());
  13389. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  13390. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  13391. BIO_free(pbCert);
  13392. return (pCert);
  13393. }
  13394. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  13395. std::ifstream inStream(strFileName);
  13396. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  13397. std::istreambuf_iterator<char>());
  13398. if (strPrivateKeyPEM.empty()) return (nullptr);
  13399. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  13400. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  13401. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  13402. BIO_free(pbPrivKey);
  13403. return (pPrivateKey);
  13404. }
  13405. TEST(BindServerTest, UpdateCerts) {
  13406. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13407. int port = svr.bind_to_any_port("0.0.0.0");
  13408. ASSERT_TRUE(svr.is_valid());
  13409. ASSERT_TRUE(port > 0);
  13410. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13411. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13412. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13413. ASSERT_TRUE(cert != nullptr);
  13414. ASSERT_TRUE(ca_cert != nullptr);
  13415. ASSERT_TRUE(key != nullptr);
  13416. X509_STORE *cert_store = X509_STORE_new();
  13417. X509_STORE_add_cert(cert_store, ca_cert);
  13418. // svr.update_certs(cert, key, cert_store); // deprecated
  13419. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13420. CLIENT_CA_CERT_FILE);
  13421. ASSERT_TRUE(svr.is_valid());
  13422. svr.stop();
  13423. X509_STORE_free(cert_store);
  13424. X509_free(cert);
  13425. X509_free(ca_cert);
  13426. EVP_PKEY_free(key);
  13427. }
  13428. // Test that SSLServer(X509*, EVP_PKEY*, X509_STORE*) constructor sets
  13429. // client CA list correctly for TLS handshake
  13430. TEST(SSLClientServerTest, X509ConstructorSetsClientCAList) {
  13431. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13432. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13433. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13434. ASSERT_TRUE(cert != nullptr);
  13435. ASSERT_TRUE(ca_cert != nullptr);
  13436. ASSERT_TRUE(key != nullptr);
  13437. X509_STORE *cert_store = X509_STORE_new();
  13438. X509_STORE_add_cert(cert_store, ca_cert);
  13439. // Use X509-based constructor (deprecated but should still work correctly)
  13440. #pragma GCC diagnostic push
  13441. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  13442. SSLServer svr(cert, key, cert_store);
  13443. #pragma GCC diagnostic pop
  13444. ASSERT_TRUE(svr.is_valid());
  13445. // Verify that client CA list is set in SSL_CTX
  13446. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13447. ASSERT_TRUE(ssl_ctx != nullptr);
  13448. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13449. ASSERT_TRUE(ca_list != nullptr);
  13450. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13451. X509_free(cert);
  13452. X509_free(ca_cert);
  13453. EVP_PKEY_free(key);
  13454. }
  13455. // Test that update_certs() updates client CA list correctly
  13456. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  13457. // Start with file-based constructor
  13458. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13459. ASSERT_TRUE(svr.is_valid());
  13460. // Initially no client CA list should be set
  13461. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13462. ASSERT_TRUE(ssl_ctx != nullptr);
  13463. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  13464. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  13465. EXPECT_EQ(0, count_before);
  13466. // Now update with client CA (PEM string)
  13467. std::string cert_pem, key_pem, ca_pem;
  13468. read_file(SERVER_CERT_FILE, cert_pem);
  13469. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13470. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13471. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  13472. ASSERT_TRUE(svr.is_valid());
  13473. // Now client CA list should be set
  13474. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  13475. ASSERT_TRUE(ca_list_after != nullptr);
  13476. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  13477. }
  13478. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  13479. // Test that the file-path SSLServer constructor properly sets the client CA
  13480. // list that is sent to clients during the TLS handshake (CertificateRequest)
  13481. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13482. ASSERT_TRUE(svr.is_valid());
  13483. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13484. ASSERT_TRUE(ssl_ctx != nullptr);
  13485. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13486. ASSERT_TRUE(ca_list != nullptr);
  13487. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13488. }
  13489. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  13490. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  13491. // prepare large data
  13492. std::random_device seed_gen;
  13493. std::mt19937 random(seed_gen());
  13494. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  13495. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  13496. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  13497. // server
  13498. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13499. ASSERT_TRUE(svr.is_valid());
  13500. svr.Post("/binary", [&](const Request &req, Response &res) {
  13501. EXPECT_EQ(large_size_byte, req.body.size());
  13502. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  13503. res.set_content(req.body, "application/octet-stream");
  13504. });
  13505. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  13506. auto se = detail::scope_exit([&] {
  13507. svr.stop();
  13508. listen_thread.join();
  13509. ASSERT_FALSE(svr.is_running());
  13510. });
  13511. svr.wait_until_ready();
  13512. // client POST
  13513. SSLClient cli("localhost", PORT);
  13514. cli.enable_server_certificate_verification(false);
  13515. cli.set_read_timeout(std::chrono::seconds(100));
  13516. cli.set_write_timeout(std::chrono::seconds(100));
  13517. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  13518. large_size_byte, "application/octet-stream");
  13519. // compare
  13520. EXPECT_EQ(StatusCode::OK_200, res->status);
  13521. EXPECT_EQ(large_size_byte, res->body.size());
  13522. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  13523. }
  13524. #endif
  13525. // ============================================================================
  13526. // MbedTLS-Specific Tests
  13527. // ============================================================================
  13528. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  13529. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  13530. using namespace httplib::tls;
  13531. // Track if callback was invoked
  13532. bool callback_invoked = false;
  13533. // The callback receives void* ctx which is actually MbedTlsContext*
  13534. // We can access the mbedtls_ssl_config via the context
  13535. auto setup_callback = [&callback_invoked](void *ctx) {
  13536. callback_invoked = true;
  13537. // Cast to MbedTlsContext* to access the ssl config
  13538. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  13539. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  13540. // Use static variables to hold certificate data (simplified for test)
  13541. static mbedtls_x509_crt own_cert;
  13542. static mbedtls_pk_context own_key;
  13543. static mbedtls_x509_crt ca_chain;
  13544. static bool initialized = false;
  13545. if (!initialized) {
  13546. mbedtls_x509_crt_init(&own_cert);
  13547. mbedtls_pk_init(&own_key);
  13548. mbedtls_x509_crt_init(&ca_chain);
  13549. // Load server certificate
  13550. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  13551. return false;
  13552. }
  13553. // Load server private key
  13554. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  13555. #if MBEDTLS_VERSION_MAJOR >= 3
  13556. ,
  13557. mbedtls_ctr_drbg_random, nullptr
  13558. #endif
  13559. ) != 0) {
  13560. return false;
  13561. }
  13562. // Load CA chain for client verification
  13563. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  13564. return false;
  13565. }
  13566. initialized = true;
  13567. }
  13568. // Configure the SSL config
  13569. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  13570. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  13571. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  13572. // Set minimum TLS version using mbedTLS native API
  13573. #if MBEDTLS_VERSION_MAJOR >= 3
  13574. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  13575. #else
  13576. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  13577. MBEDTLS_SSL_MINOR_VERSION_3);
  13578. #endif
  13579. return true;
  13580. };
  13581. SSLServer svr(setup_callback);
  13582. ASSERT_TRUE(svr.is_valid());
  13583. ASSERT_TRUE(callback_invoked);
  13584. svr.Get("/test", [&](const Request &req, Response &res) {
  13585. res.set_content("test", "text/plain");
  13586. auto cert = req.peer_cert();
  13587. ASSERT_TRUE(static_cast<bool>(cert));
  13588. auto common_name = cert.subject_cn();
  13589. EXPECT_EQ("Common Name", common_name);
  13590. });
  13591. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13592. auto se = detail::scope_exit([&] {
  13593. svr.stop();
  13594. t.join();
  13595. ASSERT_FALSE(svr.is_running());
  13596. });
  13597. svr.wait_until_ready();
  13598. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13599. cli.enable_server_certificate_verification(false);
  13600. cli.set_connection_timeout(30);
  13601. auto res = cli.Get("/test");
  13602. ASSERT_TRUE(res);
  13603. ASSERT_EQ(StatusCode::OK_200, res->status);
  13604. }
  13605. #endif
  13606. // WebSocket Tests
  13607. TEST(WebSocketTest, RSVBitsMustBeZero) {
  13608. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  13609. // defining the meaning of these bits has been negotiated.
  13610. auto make_frame = [](uint8_t first_byte) {
  13611. std::string frame;
  13612. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  13613. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  13614. frame += "Hello";
  13615. return frame;
  13616. };
  13617. // RSV1 set (0x40)
  13618. {
  13619. detail::BufferStream strm;
  13620. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  13621. ws::Opcode opcode;
  13622. std::string payload;
  13623. bool fin;
  13624. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13625. false, 1024));
  13626. }
  13627. // RSV2 set (0x20)
  13628. {
  13629. detail::BufferStream strm;
  13630. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  13631. ws::Opcode opcode;
  13632. std::string payload;
  13633. bool fin;
  13634. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13635. false, 1024));
  13636. }
  13637. // RSV3 set (0x10)
  13638. {
  13639. detail::BufferStream strm;
  13640. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  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. // No RSV bits set - should succeed
  13648. {
  13649. detail::BufferStream strm;
  13650. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  13651. ws::Opcode opcode;
  13652. std::string payload;
  13653. bool fin;
  13654. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13655. false, 1024));
  13656. EXPECT_EQ(ws::Opcode::Text, opcode);
  13657. EXPECT_EQ("Hello", payload);
  13658. EXPECT_TRUE(fin);
  13659. }
  13660. }
  13661. TEST(WebSocketTest, ControlFrameValidation) {
  13662. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  13663. // payload length <= 125.
  13664. // Ping with FIN=0 - must be rejected
  13665. {
  13666. detail::BufferStream strm;
  13667. std::string frame;
  13668. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  13669. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13670. strm.write(frame.data(), frame.size());
  13671. ws::Opcode opcode;
  13672. std::string payload;
  13673. bool fin;
  13674. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13675. false, 1024));
  13676. }
  13677. // Close with FIN=0 - must be rejected
  13678. {
  13679. detail::BufferStream strm;
  13680. std::string frame;
  13681. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  13682. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13683. strm.write(frame.data(), frame.size());
  13684. ws::Opcode opcode;
  13685. std::string payload;
  13686. bool fin;
  13687. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13688. false, 1024));
  13689. }
  13690. // Ping with payload_len=126 (extended length) - must be rejected
  13691. {
  13692. detail::BufferStream strm;
  13693. std::string frame;
  13694. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13695. frame += static_cast<char>(126); // payload_len=126 (>125)
  13696. frame += static_cast<char>(0x00); // extended length high byte
  13697. frame += static_cast<char>(126); // extended length low byte
  13698. frame += std::string(126, 'x');
  13699. strm.write(frame.data(), frame.size());
  13700. ws::Opcode opcode;
  13701. std::string payload;
  13702. bool fin;
  13703. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13704. false, 1024));
  13705. }
  13706. // Ping with FIN=1 and payload_len=125 - should succeed
  13707. {
  13708. detail::BufferStream strm;
  13709. std::string frame;
  13710. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13711. frame += static_cast<char>(125); // payload_len=125
  13712. frame += std::string(125, 'x');
  13713. strm.write(frame.data(), frame.size());
  13714. ws::Opcode opcode;
  13715. std::string payload;
  13716. bool fin;
  13717. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13718. false, 1024));
  13719. EXPECT_EQ(ws::Opcode::Ping, opcode);
  13720. EXPECT_EQ(125u, payload.size());
  13721. EXPECT_TRUE(fin);
  13722. }
  13723. }
  13724. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  13725. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  13726. // length MUST be 0.
  13727. // MSB set - must be rejected
  13728. {
  13729. detail::BufferStream strm;
  13730. std::string frame;
  13731. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13732. frame += static_cast<char>(127); // 64-bit extended length
  13733. frame += static_cast<char>(0x80); // MSB set (invalid)
  13734. frame += std::string(7, '\0'); // remaining 7 bytes of length
  13735. strm.write(frame.data(), frame.size());
  13736. ws::Opcode opcode;
  13737. std::string payload;
  13738. bool fin;
  13739. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13740. false, 1024));
  13741. }
  13742. // MSB clear - should pass length parsing (will be rejected by max_len,
  13743. // but that's a different check; use a small length to verify)
  13744. {
  13745. detail::BufferStream strm;
  13746. std::string frame;
  13747. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13748. frame += static_cast<char>(127); // 64-bit extended length
  13749. frame += std::string(7, '\0'); // high bytes = 0
  13750. frame += static_cast<char>(0x03); // length = 3
  13751. frame += "abc";
  13752. strm.write(frame.data(), frame.size());
  13753. ws::Opcode opcode;
  13754. std::string payload;
  13755. bool fin;
  13756. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13757. false, 1024));
  13758. EXPECT_EQ(ws::Opcode::Text, opcode);
  13759. EXPECT_EQ("abc", payload);
  13760. }
  13761. }
  13762. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  13763. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  13764. // Valid UTF-8
  13765. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  13766. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  13767. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  13768. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  13769. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  13770. // Invalid UTF-8
  13771. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  13772. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  13773. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  13774. EXPECT_FALSE(
  13775. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  13776. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  13777. }
  13778. TEST(WebSocketTest, ConnectAndDisconnect) {
  13779. Server svr;
  13780. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  13781. std::string msg;
  13782. while (ws.read(msg)) {}
  13783. });
  13784. auto port = svr.bind_to_any_port(HOST);
  13785. std::thread t([&]() { svr.listen_after_bind(); });
  13786. svr.wait_until_ready();
  13787. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  13788. ASSERT_TRUE(client.connect());
  13789. EXPECT_TRUE(client.is_open());
  13790. client.close();
  13791. EXPECT_FALSE(client.is_open());
  13792. svr.stop();
  13793. t.join();
  13794. }
  13795. TEST(WebSocketTest, ValidURL) {
  13796. ws::WebSocketClient ws1("ws://localhost:8080/path");
  13797. EXPECT_TRUE(ws1.is_valid());
  13798. ws::WebSocketClient ws2("ws://example.com/path");
  13799. EXPECT_TRUE(ws2.is_valid());
  13800. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  13801. EXPECT_TRUE(ws3.is_valid());
  13802. #ifdef CPPHTTPLIB_SSL_ENABLED
  13803. ws::WebSocketClient wss1("wss://example.com/path");
  13804. EXPECT_TRUE(wss1.is_valid());
  13805. ws::WebSocketClient wss2("wss://example.com:443/path");
  13806. EXPECT_TRUE(wss2.is_valid());
  13807. #endif
  13808. }
  13809. TEST(WebSocketTest, InvalidURL) {
  13810. // No scheme
  13811. ws::WebSocketClient ws1("localhost:8080/path");
  13812. EXPECT_FALSE(ws1.is_valid());
  13813. // No path
  13814. ws::WebSocketClient ws2("ws://localhost:8080");
  13815. EXPECT_FALSE(ws2.is_valid());
  13816. // Empty string
  13817. ws::WebSocketClient ws3("");
  13818. EXPECT_FALSE(ws3.is_valid());
  13819. // Missing host
  13820. ws::WebSocketClient ws4("ws://:8080/path");
  13821. EXPECT_FALSE(ws4.is_valid());
  13822. // Port number overflow — should not crash
  13823. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  13824. EXPECT_FALSE(ws5.is_valid());
  13825. // Port out of range
  13826. ws::WebSocketClient ws6("ws://localhost:99999/path");
  13827. EXPECT_FALSE(ws6.is_valid());
  13828. }
  13829. TEST(WebSocketTest, UnsupportedScheme) {
  13830. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13831. ws::WebSocketClient ws1("http://localhost:8080/path");
  13832. EXPECT_FALSE(ws1.is_valid());
  13833. ws::WebSocketClient ws2("https://localhost:8080/path");
  13834. EXPECT_FALSE(ws2.is_valid());
  13835. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  13836. EXPECT_FALSE(ws3.is_valid());
  13837. #else
  13838. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  13839. std::invalid_argument);
  13840. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  13841. std::invalid_argument);
  13842. #endif
  13843. }
  13844. TEST(WebSocketTest, ConnectWhenInvalid) {
  13845. ws::WebSocketClient ws("not a valid url");
  13846. EXPECT_FALSE(ws.is_valid());
  13847. EXPECT_FALSE(ws.connect());
  13848. }
  13849. TEST(WebSocketTest, DefaultPort) {
  13850. ws::WebSocketClient ws1("ws://example.com/path");
  13851. EXPECT_TRUE(ws1.is_valid());
  13852. // ws:// defaults to port 80 (verified by successful parse)
  13853. #ifdef CPPHTTPLIB_SSL_ENABLED
  13854. ws::WebSocketClient ws2("wss://example.com/path");
  13855. EXPECT_TRUE(ws2.is_valid());
  13856. // wss:// defaults to port 443 (verified by successful parse)
  13857. #endif
  13858. }
  13859. TEST(WebSocketTest, IPv6LiteralAddress) {
  13860. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  13861. EXPECT_TRUE(ws1.is_valid());
  13862. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  13863. EXPECT_TRUE(ws2.is_valid());
  13864. }
  13865. TEST(WebSocketTest, ComplexPath) {
  13866. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  13867. EXPECT_TRUE(ws1.is_valid());
  13868. ws::WebSocketClient ws2("ws://localhost:8080/");
  13869. EXPECT_TRUE(ws2.is_valid());
  13870. }
  13871. class WebSocketIntegrationTest : public ::testing::Test {
  13872. protected:
  13873. void SetUp() override {
  13874. server_ = httplib::detail::make_unique<Server>();
  13875. setup_server();
  13876. start_server();
  13877. }
  13878. void TearDown() override {
  13879. server_->stop();
  13880. if (server_thread_.joinable()) { server_thread_.join(); }
  13881. }
  13882. void setup_server() {
  13883. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  13884. std::string msg;
  13885. ws::ReadResult ret;
  13886. while ((ret = ws.read(msg))) {
  13887. if (ret == ws::Binary) {
  13888. ws.send(msg.data(), msg.size());
  13889. } else {
  13890. ws.send(msg);
  13891. }
  13892. }
  13893. });
  13894. server_->WebSocket("/ws-echo-string",
  13895. [](const Request &, ws::WebSocket &ws) {
  13896. std::string msg;
  13897. while (ws.read(msg)) {
  13898. ws.send("echo: " + msg);
  13899. }
  13900. });
  13901. server_->WebSocket(
  13902. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  13903. // Echo back request metadata
  13904. ws.send("path:" + req.path);
  13905. ws.send("header:" + req.get_header_value("X-Test-Header"));
  13906. std::string msg;
  13907. while (ws.read(msg)) {}
  13908. });
  13909. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  13910. std::string msg;
  13911. ws.read(msg); // wait for a message
  13912. ws.close();
  13913. });
  13914. server_->WebSocket("/ws-close-status",
  13915. [](const Request &, ws::WebSocket &ws) {
  13916. std::string msg;
  13917. ws.read(msg); // wait for a message
  13918. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  13919. });
  13920. server_->WebSocket(
  13921. "/ws-subprotocol",
  13922. [](const Request &, ws::WebSocket &ws) {
  13923. std::string msg;
  13924. while (ws.read(msg)) {
  13925. ws.send(msg);
  13926. }
  13927. },
  13928. [](const std::vector<std::string> &protocols) -> std::string {
  13929. for (const auto &p : protocols) {
  13930. if (p == "graphql-ws") { return p; }
  13931. }
  13932. return "";
  13933. });
  13934. }
  13935. void start_server() {
  13936. port_ = server_->bind_to_any_port(HOST);
  13937. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13938. server_->wait_until_ready();
  13939. }
  13940. std::unique_ptr<Server> server_;
  13941. std::thread server_thread_;
  13942. int port_ = 0;
  13943. };
  13944. TEST_F(WebSocketIntegrationTest, TextEcho) {
  13945. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13946. "/ws-echo");
  13947. ASSERT_TRUE(client.connect());
  13948. ASSERT_TRUE(client.is_open());
  13949. ASSERT_TRUE(client.send("Hello WebSocket"));
  13950. std::string msg;
  13951. EXPECT_EQ(ws::Text, client.read(msg));
  13952. EXPECT_EQ("Hello WebSocket", msg);
  13953. client.close();
  13954. }
  13955. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  13956. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13957. "/ws-echo");
  13958. ASSERT_TRUE(client.connect());
  13959. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  13960. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  13961. std::string msg;
  13962. EXPECT_EQ(ws::Binary, client.read(msg));
  13963. EXPECT_EQ(binary_data, msg);
  13964. client.close();
  13965. }
  13966. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  13967. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13968. "/ws-echo");
  13969. ASSERT_TRUE(client.connect());
  13970. for (int i = 0; i < 10; i++) {
  13971. auto text = "message " + std::to_string(i);
  13972. ASSERT_TRUE(client.send(text));
  13973. std::string msg;
  13974. ASSERT_TRUE(client.read(msg));
  13975. EXPECT_EQ(text, msg);
  13976. }
  13977. client.close();
  13978. }
  13979. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  13980. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13981. "/ws-close");
  13982. ASSERT_TRUE(client.connect());
  13983. // Send a message to trigger the server to close
  13984. ASSERT_TRUE(client.send("trigger close"));
  13985. // The server will close, so read should return false
  13986. std::string msg;
  13987. EXPECT_FALSE(client.read(msg));
  13988. EXPECT_FALSE(client.is_open());
  13989. }
  13990. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  13991. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13992. "/ws-echo");
  13993. ASSERT_TRUE(client.connect());
  13994. // 128KB message
  13995. std::string large_data(128 * 1024, 'X');
  13996. ASSERT_TRUE(client.send(large_data));
  13997. std::string msg;
  13998. ASSERT_TRUE(client.read(msg));
  13999. EXPECT_EQ(large_data, msg);
  14000. client.close();
  14001. }
  14002. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  14003. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14004. "/ws-echo");
  14005. ASSERT_TRUE(client.connect());
  14006. const int num_threads = 4;
  14007. std::vector<std::thread> threads;
  14008. std::atomic<int> send_count{0};
  14009. for (int t = 0; t < num_threads; t++) {
  14010. threads.emplace_back([&client, &send_count, t]() {
  14011. for (int i = 0; i < 5; i++) {
  14012. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  14013. if (client.send(text)) { send_count++; }
  14014. }
  14015. });
  14016. }
  14017. for (auto &th : threads) {
  14018. th.join();
  14019. }
  14020. int received = 0;
  14021. std::string msg;
  14022. while (received < send_count.load()) {
  14023. if (!client.read(msg)) { break; }
  14024. received++;
  14025. }
  14026. EXPECT_EQ(send_count.load(), received);
  14027. client.close();
  14028. }
  14029. TEST_F(WebSocketIntegrationTest, ReadString) {
  14030. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14031. "/ws-echo-string");
  14032. ASSERT_TRUE(client.connect());
  14033. ASSERT_TRUE(client.send("hello"));
  14034. std::string msg;
  14035. ASSERT_TRUE(client.read(msg));
  14036. EXPECT_EQ("echo: hello", msg);
  14037. ASSERT_TRUE(client.send("world"));
  14038. ASSERT_TRUE(client.read(msg));
  14039. EXPECT_EQ("echo: world", msg);
  14040. client.close();
  14041. }
  14042. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  14043. Headers headers = {{"X-Test-Header", "test-value"}};
  14044. ws::WebSocketClient client(
  14045. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  14046. ASSERT_TRUE(client.connect());
  14047. std::string msg;
  14048. ASSERT_TRUE(client.read(msg));
  14049. EXPECT_EQ("path:/ws-request-info", msg);
  14050. ASSERT_TRUE(client.read(msg));
  14051. EXPECT_EQ("header:test-value", msg);
  14052. client.close();
  14053. }
  14054. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  14055. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14056. "/ws-echo");
  14057. client.set_read_timeout(1, 0); // 1 second
  14058. ASSERT_TRUE(client.connect());
  14059. // Don't send anything — server echo handler waits for a message,
  14060. // so read() should time out and return false.
  14061. std::string msg;
  14062. EXPECT_FALSE(client.read(msg));
  14063. }
  14064. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  14065. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14066. "/ws-echo");
  14067. client.set_read_timeout(5, 0);
  14068. ASSERT_TRUE(client.connect());
  14069. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14070. // The server should reject it and close the connection.
  14071. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  14072. client.send(oversized);
  14073. // The server's read() should have failed due to payload limit,
  14074. // so our read() should return false (connection closed).
  14075. std::string msg;
  14076. EXPECT_FALSE(client.read(msg));
  14077. }
  14078. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  14079. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14080. "/ws-echo");
  14081. client.set_read_timeout(10, 0);
  14082. ASSERT_TRUE(client.connect());
  14083. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14084. // This should succeed.
  14085. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  14086. ASSERT_TRUE(client.send(at_limit));
  14087. std::string msg;
  14088. ASSERT_TRUE(client.read(msg));
  14089. EXPECT_EQ(at_limit.size(), msg.size());
  14090. client.close();
  14091. }
  14092. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  14093. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14094. "/nonexistent");
  14095. EXPECT_FALSE(client.connect());
  14096. EXPECT_FALSE(client.is_open());
  14097. }
  14098. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  14099. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14100. "/ws-echo");
  14101. ASSERT_TRUE(client.connect());
  14102. ASSERT_TRUE(client.send(""));
  14103. std::string msg;
  14104. EXPECT_EQ(ws::Text, client.read(msg));
  14105. EXPECT_EQ("", msg);
  14106. client.close();
  14107. }
  14108. TEST_F(WebSocketIntegrationTest, Reconnect) {
  14109. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14110. "/ws-echo");
  14111. // First connection
  14112. ASSERT_TRUE(client.connect());
  14113. ASSERT_TRUE(client.send("first"));
  14114. std::string msg;
  14115. ASSERT_TRUE(client.read(msg));
  14116. EXPECT_EQ("first", msg);
  14117. client.close();
  14118. EXPECT_FALSE(client.is_open());
  14119. // Reconnect using the same client object
  14120. ASSERT_TRUE(client.connect());
  14121. ASSERT_TRUE(client.is_open());
  14122. ASSERT_TRUE(client.send("second"));
  14123. ASSERT_TRUE(client.read(msg));
  14124. EXPECT_EQ("second", msg);
  14125. client.close();
  14126. }
  14127. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  14128. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14129. "/ws-close-status");
  14130. ASSERT_TRUE(client.connect());
  14131. // Trigger the server to close with GoingAway status
  14132. ASSERT_TRUE(client.send("trigger"));
  14133. // read() should return false after receiving the close frame
  14134. std::string msg;
  14135. EXPECT_FALSE(client.read(msg));
  14136. EXPECT_FALSE(client.is_open());
  14137. }
  14138. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  14139. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14140. "/ws-echo");
  14141. ASSERT_TRUE(client.connect());
  14142. client.close(ws::CloseStatus::GoingAway, "client leaving");
  14143. EXPECT_FALSE(client.is_open());
  14144. }
  14145. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  14146. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  14147. ws::WebSocketClient client(
  14148. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14149. ASSERT_TRUE(client.connect());
  14150. // Server should have selected graphql-ws
  14151. EXPECT_EQ("graphql-ws", client.subprotocol());
  14152. client.close();
  14153. }
  14154. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  14155. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  14156. ws::WebSocketClient client(
  14157. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14158. ASSERT_TRUE(client.connect());
  14159. // Server should not have selected any subprotocol
  14160. EXPECT_TRUE(client.subprotocol().empty());
  14161. client.close();
  14162. }
  14163. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  14164. // Connect without requesting any subprotocol
  14165. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14166. "/ws-subprotocol");
  14167. ASSERT_TRUE(client.connect());
  14168. EXPECT_TRUE(client.subprotocol().empty());
  14169. client.close();
  14170. }
  14171. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  14172. Server svr;
  14173. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  14174. if (!req.has_header("Authorization")) {
  14175. res.status = StatusCode::Unauthorized_401;
  14176. res.set_content("Unauthorized", "text/plain");
  14177. return Server::HandlerResponse::Handled;
  14178. }
  14179. return Server::HandlerResponse::Unhandled;
  14180. });
  14181. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14182. std::string msg;
  14183. while (ws.read(msg)) {
  14184. ws.send(msg);
  14185. }
  14186. });
  14187. auto port = svr.bind_to_any_port("localhost");
  14188. std::thread t([&]() { svr.listen_after_bind(); });
  14189. svr.wait_until_ready();
  14190. // Without Authorization header - should be rejected before upgrade
  14191. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  14192. EXPECT_FALSE(client1.connect());
  14193. // With Authorization header - should succeed
  14194. Headers headers = {{"Authorization", "Bearer token123"}};
  14195. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  14196. headers);
  14197. ASSERT_TRUE(client2.connect());
  14198. ASSERT_TRUE(client2.send("hello"));
  14199. std::string msg;
  14200. ASSERT_TRUE(client2.read(msg));
  14201. EXPECT_EQ("hello", msg);
  14202. client2.close();
  14203. svr.stop();
  14204. t.join();
  14205. }
  14206. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14207. class WebSocketSSLIntegrationTest : public ::testing::Test {
  14208. protected:
  14209. void SetUp() override {
  14210. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  14211. SERVER_PRIVATE_KEY_FILE);
  14212. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14213. std::string msg;
  14214. ws::ReadResult ret;
  14215. while ((ret = ws.read(msg))) {
  14216. if (ret == ws::Binary) {
  14217. ws.send(msg.data(), msg.size());
  14218. } else {
  14219. ws.send(msg);
  14220. }
  14221. }
  14222. });
  14223. port_ = server_->bind_to_any_port(HOST);
  14224. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14225. server_->wait_until_ready();
  14226. }
  14227. void TearDown() override {
  14228. server_->stop();
  14229. if (server_thread_.joinable()) { server_thread_.join(); }
  14230. }
  14231. std::unique_ptr<SSLServer> server_;
  14232. std::thread server_thread_;
  14233. int port_ = 0;
  14234. };
  14235. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  14236. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  14237. "/ws-echo");
  14238. client.enable_server_certificate_verification(false);
  14239. ASSERT_TRUE(client.connect());
  14240. ASSERT_TRUE(client.is_open());
  14241. ASSERT_TRUE(client.send("Hello WSS"));
  14242. std::string msg;
  14243. EXPECT_EQ(ws::Text, client.read(msg));
  14244. EXPECT_EQ("Hello WSS", msg);
  14245. client.close();
  14246. }
  14247. #endif
  14248. #if !defined(_WIN32)
  14249. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  14250. auto secret_dir = std::string("./symlink_test_secret");
  14251. auto served_dir = std::string("./symlink_test_served");
  14252. auto secret_file = secret_dir + "/secret.txt";
  14253. auto symlink_path = served_dir + "/escape";
  14254. // Setup: create directories and files
  14255. mkdir(secret_dir.c_str(), 0755);
  14256. mkdir(served_dir.c_str(), 0755);
  14257. {
  14258. std::ofstream ofs(secret_file);
  14259. ofs << "SECRET_DATA";
  14260. }
  14261. // Create symlink using absolute path so it resolves correctly
  14262. char abs_secret[PATH_MAX];
  14263. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  14264. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  14265. auto se = detail::scope_exit([&] {
  14266. unlink(symlink_path.c_str());
  14267. unlink(secret_file.c_str());
  14268. rmdir(served_dir.c_str());
  14269. rmdir(secret_dir.c_str());
  14270. });
  14271. Server svr;
  14272. svr.set_mount_point("/", served_dir);
  14273. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  14274. auto se2 = detail::scope_exit([&] {
  14275. svr.stop();
  14276. listen_thread.join();
  14277. });
  14278. svr.wait_until_ready();
  14279. Client cli("localhost", PORT);
  14280. // Symlink pointing outside base dir should be blocked
  14281. auto res = cli.Get("/escape/secret.txt");
  14282. ASSERT_TRUE(res);
  14283. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  14284. }
  14285. #endif