test.cc 524 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #if __cplusplus >= 202002L
  28. inline std::string u8_to_string(const char8_t *s) {
  29. return std::string(reinterpret_cast<const char *>(s));
  30. }
  31. #define U8(x) u8_to_string(u8##x)
  32. #else
  33. #define U8(x) u8##x
  34. #endif
  35. #define SERVER_CERT_FILE "./cert.pem"
  36. #define SERVER_CERT2_FILE "./cert2.pem"
  37. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  38. #define CA_CERT_FILE "./ca-bundle.crt"
  39. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  40. #define CLIENT_CA_CERT_DIR "."
  41. #define CLIENT_CERT_FILE "./client.cert.pem"
  42. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  43. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  44. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  45. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  46. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  47. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  48. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  49. using namespace std;
  50. using namespace httplib;
  51. const char *HOST = "localhost";
  52. static int get_base_port() {
  53. const char *shard = getenv("GTEST_SHARD_INDEX");
  54. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  55. }
  56. 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. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4846. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  4847. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  4848. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4849. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4850. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  4851. #endif
  4852. }
  4853. TEST_F(ServerTest, PutContentWithDeflate) {
  4854. cli_.set_compress(false);
  4855. Headers headers;
  4856. headers.emplace("Content-Encoding", "deflate");
  4857. // PUT in deflate format:
  4858. auto res = cli_.Put("/put", headers,
  4859. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4860. ASSERT_TRUE(res);
  4861. EXPECT_EQ(StatusCode::OK_200, res->status);
  4862. EXPECT_EQ("PUT", res->body);
  4863. }
  4864. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4865. Headers headers;
  4866. headers.emplace("Accept-Encoding", "gzip, deflate");
  4867. auto res = cli_.Get("/streamed-chunked", headers);
  4868. ASSERT_TRUE(res);
  4869. EXPECT_EQ(StatusCode::OK_200, res->status);
  4870. EXPECT_EQ(std::string("123456789"), res->body);
  4871. }
  4872. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4873. Headers headers;
  4874. headers.emplace("Accept-Encoding", "gzip, deflate");
  4875. auto res = cli_.Get("/streamed-chunked2", headers);
  4876. ASSERT_TRUE(res);
  4877. EXPECT_EQ(StatusCode::OK_200, res->status);
  4878. EXPECT_EQ(std::string("123456789"), res->body);
  4879. }
  4880. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4881. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4882. ASSERT_TRUE(res);
  4883. EXPECT_EQ(StatusCode::OK_200, res->status);
  4884. }
  4885. TEST(GzipDecompressor, ChunkedDecompression) {
  4886. std::string data;
  4887. for (size_t i = 0; i < 32 * 1024; ++i) {
  4888. data.push_back(static_cast<char>('a' + i % 26));
  4889. }
  4890. std::string compressed_data;
  4891. {
  4892. httplib::detail::gzip_compressor compressor;
  4893. bool result = compressor.compress(
  4894. data.data(), data.size(),
  4895. /*last=*/true,
  4896. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4897. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4898. compressed_data_size);
  4899. return true;
  4900. });
  4901. ASSERT_TRUE(result);
  4902. }
  4903. std::string decompressed_data;
  4904. {
  4905. httplib::detail::gzip_decompressor decompressor;
  4906. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4907. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4908. size_t chunk_size = 130;
  4909. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4910. chunk_begin += chunk_size) {
  4911. size_t current_chunk_size =
  4912. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4913. bool result = decompressor.decompress(
  4914. compressed_data.data() + chunk_begin, current_chunk_size,
  4915. [&](const char *decompressed_data_chunk,
  4916. size_t decompressed_data_chunk_size) {
  4917. decompressed_data.insert(decompressed_data.size(),
  4918. decompressed_data_chunk,
  4919. decompressed_data_chunk_size);
  4920. return true;
  4921. });
  4922. ASSERT_TRUE(result);
  4923. }
  4924. }
  4925. ASSERT_EQ(data, decompressed_data);
  4926. }
  4927. TEST(GzipDecompressor, DeflateDecompression) {
  4928. std::string original_text = "Raw deflate without gzip";
  4929. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4930. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4931. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4932. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4933. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4934. std::string decompressed_data;
  4935. {
  4936. httplib::detail::gzip_decompressor decompressor;
  4937. bool result = decompressor.decompress(
  4938. compressed_data.data(), compressed_data.size(),
  4939. [&](const char *decompressed_data_chunk,
  4940. size_t decompressed_data_chunk_size) {
  4941. decompressed_data.insert(decompressed_data.size(),
  4942. decompressed_data_chunk,
  4943. decompressed_data_chunk_size);
  4944. return true;
  4945. });
  4946. ASSERT_TRUE(result);
  4947. }
  4948. ASSERT_EQ(original_text, decompressed_data);
  4949. }
  4950. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4951. std::string original_text = "Raw deflate without gzip";
  4952. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4953. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4954. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4955. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4956. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4957. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4958. std::string decompressed_data;
  4959. {
  4960. httplib::detail::gzip_decompressor decompressor;
  4961. bool result = decompressor.decompress(
  4962. compressed_data.data(), compressed_data.size(),
  4963. [&](const char *decompressed_data_chunk,
  4964. size_t decompressed_data_chunk_size) {
  4965. decompressed_data.insert(decompressed_data.size(),
  4966. decompressed_data_chunk,
  4967. decompressed_data_chunk_size);
  4968. return true;
  4969. });
  4970. ASSERT_TRUE(result);
  4971. }
  4972. ASSERT_EQ(original_text, decompressed_data);
  4973. }
  4974. #endif
  4975. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4976. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4977. Headers headers;
  4978. headers.emplace("Accept-Encoding", "br");
  4979. auto res = cli_.Get("/streamed-chunked", headers);
  4980. ASSERT_TRUE(res);
  4981. EXPECT_EQ(StatusCode::OK_200, res->status);
  4982. EXPECT_EQ(std::string("123456789"), res->body);
  4983. }
  4984. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4985. Headers headers;
  4986. headers.emplace("Accept-Encoding", "br");
  4987. auto res = cli_.Get("/streamed-chunked2", headers);
  4988. ASSERT_TRUE(res);
  4989. EXPECT_EQ(StatusCode::OK_200, res->status);
  4990. EXPECT_EQ(std::string("123456789"), res->body);
  4991. }
  4992. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  4993. cli_.set_compress(true);
  4994. auto res = cli_.Put(
  4995. "/put", 3,
  4996. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4997. sink.os << "PUT";
  4998. return true;
  4999. },
  5000. "text/plain");
  5001. ASSERT_TRUE(res);
  5002. EXPECT_EQ(StatusCode::OK_200, res->status);
  5003. EXPECT_EQ("PUT", res->body);
  5004. }
  5005. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5006. cli_.set_compress(true);
  5007. auto res = cli_.Put(
  5008. "/put",
  5009. [](size_t /*offset*/, DataSink &sink) {
  5010. sink.os << "PUT";
  5011. sink.done();
  5012. return true;
  5013. },
  5014. "text/plain");
  5015. ASSERT_TRUE(res);
  5016. EXPECT_EQ(StatusCode::OK_200, res->status);
  5017. EXPECT_EQ("PUT", res->body);
  5018. }
  5019. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5020. cli_.set_compress(true);
  5021. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5022. ASSERT_TRUE(res);
  5023. EXPECT_EQ(StatusCode::OK_200, res->status);
  5024. EXPECT_EQ(LARGE_DATA, res->body);
  5025. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5026. }
  5027. #endif
  5028. TEST_F(ServerTest, Patch) {
  5029. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5030. ASSERT_TRUE(res);
  5031. EXPECT_EQ(StatusCode::OK_200, res->status);
  5032. EXPECT_EQ("PATCH", res->body);
  5033. }
  5034. TEST_F(ServerTest, Delete) {
  5035. auto res = cli_.Delete("/delete");
  5036. ASSERT_TRUE(res);
  5037. EXPECT_EQ(StatusCode::OK_200, res->status);
  5038. EXPECT_EQ("DELETE", res->body);
  5039. }
  5040. TEST_F(ServerTest, DeleteContentReceiver) {
  5041. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5042. ASSERT_TRUE(res);
  5043. EXPECT_EQ(StatusCode::OK_200, res->status);
  5044. EXPECT_EQ("content", res->body);
  5045. }
  5046. TEST_F(ServerTest, Options) {
  5047. auto res = cli_.Options("*");
  5048. ASSERT_TRUE(res);
  5049. EXPECT_EQ(StatusCode::OK_200, res->status);
  5050. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5051. EXPECT_TRUE(res->body.empty());
  5052. }
  5053. TEST_F(ServerTest, URL) {
  5054. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5055. ASSERT_TRUE(res);
  5056. EXPECT_EQ(StatusCode::OK_200, res->status);
  5057. }
  5058. TEST_F(ServerTest, ArrayParam) {
  5059. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5060. ASSERT_TRUE(res);
  5061. EXPECT_EQ(StatusCode::OK_200, res->status);
  5062. }
  5063. TEST_F(ServerTest, NoMultipleHeaders) {
  5064. Headers headers = {{"Content-Length", "5"}};
  5065. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5066. "text/plain");
  5067. ASSERT_TRUE(res);
  5068. EXPECT_EQ(StatusCode::OK_200, res->status);
  5069. }
  5070. TEST_F(ServerTest, PostContentReceiver) {
  5071. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5072. ASSERT_TRUE(res);
  5073. ASSERT_EQ(StatusCode::OK_200, res->status);
  5074. ASSERT_EQ("content", res->body);
  5075. }
  5076. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5077. UploadFormDataItems items = {
  5078. {"text1", "text default", "", ""},
  5079. {"text2", "aωb", "", ""},
  5080. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5081. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5082. {"file3", "", "", "application/octet-stream"},
  5083. };
  5084. auto res = cli_.Post("/content_receiver", items);
  5085. ASSERT_TRUE(res);
  5086. EXPECT_EQ(StatusCode::OK_200, res->status);
  5087. }
  5088. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5089. UploadFormDataItems items = {
  5090. {"text1", "text default", "", ""},
  5091. {"text2", "aωb", "", ""},
  5092. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5093. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5094. {"file3", "", "", "application/octet-stream"},
  5095. };
  5096. auto boundary = std::string("+++++");
  5097. std::string body;
  5098. for (const auto &item : items) {
  5099. body += "--" + boundary + "\r\n";
  5100. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5101. if (!item.filename.empty()) {
  5102. body += "; filename=\"" + item.filename + "\"";
  5103. }
  5104. body += "\r\n";
  5105. if (!item.content_type.empty()) {
  5106. body += "Content-Type: " + item.content_type + "\r\n";
  5107. }
  5108. body += "\r\n";
  5109. body += item.content + "\r\n";
  5110. }
  5111. body += "--" + boundary + "--\r\n";
  5112. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5113. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5114. ASSERT_TRUE(res);
  5115. EXPECT_EQ(StatusCode::OK_200, res->status);
  5116. }
  5117. TEST_F(ServerTest, PostContentReceiverGzip) {
  5118. cli_.set_compress(true);
  5119. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5120. ASSERT_TRUE(res);
  5121. ASSERT_EQ(StatusCode::OK_200, res->status);
  5122. ASSERT_EQ("content", res->body);
  5123. }
  5124. TEST_F(ServerTest, PutContentReceiver) {
  5125. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5126. ASSERT_TRUE(res);
  5127. ASSERT_EQ(StatusCode::OK_200, res->status);
  5128. ASSERT_EQ("content", res->body);
  5129. }
  5130. TEST_F(ServerTest, PatchContentReceiver) {
  5131. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5132. ASSERT_TRUE(res);
  5133. ASSERT_EQ(StatusCode::OK_200, res->status);
  5134. ASSERT_EQ("content", res->body);
  5135. }
  5136. template <typename ClientType>
  5137. void TestWithHeadersAndContentReceiver(
  5138. ClientType &cli,
  5139. std::function<Result(ClientType &, const std::string &, const Headers &,
  5140. const std::string &, const std::string &,
  5141. ContentReceiver, DownloadProgress)>
  5142. request_func) {
  5143. Headers headers;
  5144. headers.emplace("X-Custom-Header", "test-value");
  5145. std::string received_body;
  5146. auto res = request_func(
  5147. cli, "/content_receiver", headers, "content", "application/json",
  5148. [&](const char *data, size_t data_length) {
  5149. received_body.append(data, data_length);
  5150. return true;
  5151. },
  5152. nullptr);
  5153. ASSERT_TRUE(res);
  5154. EXPECT_EQ(StatusCode::OK_200, res->status);
  5155. EXPECT_EQ("content", received_body);
  5156. }
  5157. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5158. #ifdef CPPHTTPLIB_SSL_ENABLED
  5159. using ClientT = SSLClient;
  5160. #else
  5161. using ClientT = Client;
  5162. #endif
  5163. TestWithHeadersAndContentReceiver<ClientT>(
  5164. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5165. const std::string &body, const std::string &content_type,
  5166. ContentReceiver receiver, DownloadProgress progress) {
  5167. return cli.Post(path, headers, body, content_type, receiver, progress);
  5168. });
  5169. }
  5170. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5171. #ifdef CPPHTTPLIB_SSL_ENABLED
  5172. using ClientT = SSLClient;
  5173. #else
  5174. using ClientT = Client;
  5175. #endif
  5176. TestWithHeadersAndContentReceiver<ClientT>(
  5177. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5178. const std::string &body, const std::string &content_type,
  5179. ContentReceiver receiver, DownloadProgress progress) {
  5180. return cli.Put(path, headers, body, content_type, receiver, progress);
  5181. });
  5182. }
  5183. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5184. #ifdef CPPHTTPLIB_SSL_ENABLED
  5185. using ClientT = SSLClient;
  5186. #else
  5187. using ClientT = Client;
  5188. #endif
  5189. TestWithHeadersAndContentReceiver<ClientT>(
  5190. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5191. const std::string &body, const std::string &content_type,
  5192. ContentReceiver receiver, DownloadProgress progress) {
  5193. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5194. });
  5195. }
  5196. template <typename ClientType>
  5197. void TestWithHeadersAndContentReceiverWithProgress(
  5198. ClientType &cli,
  5199. std::function<Result(ClientType &, const std::string &, const Headers &,
  5200. const std::string &, const std::string &,
  5201. ContentReceiver, DownloadProgress)>
  5202. request_func) {
  5203. Headers headers;
  5204. headers.emplace("X-Test-Header", "progress-test");
  5205. std::string received_body;
  5206. auto progress_called = false;
  5207. auto res = request_func(
  5208. cli, "/content_receiver", headers, "content", "text/plain",
  5209. [&](const char *data, size_t data_length) {
  5210. received_body.append(data, data_length);
  5211. return true;
  5212. },
  5213. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5214. progress_called = true;
  5215. return true;
  5216. });
  5217. ASSERT_TRUE(res);
  5218. EXPECT_EQ(StatusCode::OK_200, res->status);
  5219. EXPECT_EQ("content", received_body);
  5220. EXPECT_TRUE(progress_called);
  5221. }
  5222. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5223. #ifdef CPPHTTPLIB_SSL_ENABLED
  5224. using ClientT = SSLClient;
  5225. #else
  5226. using ClientT = Client;
  5227. #endif
  5228. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5229. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5230. const std::string &body, const std::string &content_type,
  5231. ContentReceiver receiver, DownloadProgress progress) {
  5232. return cli.Post(path, headers, body, content_type, receiver, progress);
  5233. });
  5234. }
  5235. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5236. #ifdef CPPHTTPLIB_SSL_ENABLED
  5237. using ClientT = SSLClient;
  5238. #else
  5239. using ClientT = Client;
  5240. #endif
  5241. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5242. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5243. const std::string &body, const std::string &content_type,
  5244. ContentReceiver receiver, DownloadProgress progress) {
  5245. return cli.Put(path, headers, body, content_type, receiver, progress);
  5246. });
  5247. }
  5248. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5249. #ifdef CPPHTTPLIB_SSL_ENABLED
  5250. using ClientT = SSLClient;
  5251. #else
  5252. using ClientT = Client;
  5253. #endif
  5254. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5255. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5256. const std::string &body, const std::string &content_type,
  5257. ContentReceiver receiver, DownloadProgress progress) {
  5258. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5259. });
  5260. }
  5261. template <typename ClientType>
  5262. void TestWithHeadersAndContentReceiverError(
  5263. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5264. const Headers &, const std::string &,
  5265. const std::string &, ContentReceiver)>
  5266. request_func) {
  5267. Headers headers;
  5268. headers.emplace("X-Error-Test", "true");
  5269. std::string received_body;
  5270. auto receiver_failed = false;
  5271. auto res =
  5272. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5273. [&](const char *data, size_t data_length) {
  5274. received_body.append(data, data_length);
  5275. receiver_failed = true;
  5276. return false;
  5277. });
  5278. ASSERT_FALSE(res);
  5279. EXPECT_TRUE(receiver_failed);
  5280. }
  5281. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5282. #ifdef CPPHTTPLIB_SSL_ENABLED
  5283. using ClientT = SSLClient;
  5284. #else
  5285. using ClientT = Client;
  5286. #endif
  5287. TestWithHeadersAndContentReceiverError<ClientT>(
  5288. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5289. const std::string &body, const std::string &content_type,
  5290. ContentReceiver receiver) {
  5291. return cli.Post(path, headers, body, content_type, receiver);
  5292. });
  5293. }
  5294. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5295. #ifdef CPPHTTPLIB_SSL_ENABLED
  5296. using ClientT = SSLClient;
  5297. #else
  5298. using ClientT = Client;
  5299. #endif
  5300. TestWithHeadersAndContentReceiverError<ClientT>(
  5301. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5302. const std::string &body, const std::string &content_type,
  5303. ContentReceiver receiver) {
  5304. return cli.Put(path, headers, body, content_type, receiver);
  5305. });
  5306. }
  5307. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5308. #ifdef CPPHTTPLIB_SSL_ENABLED
  5309. using ClientT = SSLClient;
  5310. #else
  5311. using ClientT = Client;
  5312. #endif
  5313. TestWithHeadersAndContentReceiverError<ClientT>(
  5314. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5315. const std::string &body, const std::string &content_type,
  5316. ContentReceiver receiver) {
  5317. return cli.Patch(path, headers, body, content_type, receiver);
  5318. });
  5319. }
  5320. TEST_F(ServerTest, PostQueryStringAndBody) {
  5321. auto res =
  5322. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5323. ASSERT_TRUE(res);
  5324. ASSERT_EQ(StatusCode::OK_200, res->status);
  5325. }
  5326. TEST_F(ServerTest, HTTP2Magic) {
  5327. Request req;
  5328. req.method = "PRI";
  5329. req.path = "*";
  5330. req.body = "SM";
  5331. auto res = std::make_shared<Response>();
  5332. auto error = Error::Success;
  5333. auto ret = cli_.send(req, *res, error);
  5334. ASSERT_TRUE(ret);
  5335. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5336. }
  5337. TEST_F(ServerTest, KeepAlive) {
  5338. auto res = cli_.Get("/hi");
  5339. ASSERT_TRUE(res);
  5340. EXPECT_EQ(StatusCode::OK_200, res->status);
  5341. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5342. EXPECT_EQ("Hello World!", res->body);
  5343. res = cli_.Get("/hi");
  5344. ASSERT_TRUE(res);
  5345. EXPECT_EQ(StatusCode::OK_200, res->status);
  5346. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5347. EXPECT_EQ("Hello World!", res->body);
  5348. res = cli_.Get("/hi");
  5349. ASSERT_TRUE(res);
  5350. EXPECT_EQ(StatusCode::OK_200, res->status);
  5351. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5352. EXPECT_EQ("Hello World!", res->body);
  5353. res = cli_.Get("/not-exist");
  5354. ASSERT_TRUE(res);
  5355. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5356. res = cli_.Post("/empty", "", "text/plain");
  5357. ASSERT_TRUE(res);
  5358. EXPECT_EQ(StatusCode::OK_200, res->status);
  5359. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5360. EXPECT_EQ("empty", res->body);
  5361. EXPECT_EQ("close", res->get_header_value("Connection"));
  5362. res = cli_.Post(
  5363. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5364. "text/plain");
  5365. ASSERT_TRUE(res);
  5366. EXPECT_EQ(StatusCode::OK_200, res->status);
  5367. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5368. EXPECT_EQ("empty", res->body);
  5369. cli_.set_keep_alive(false);
  5370. res = cli_.Get("/last-request");
  5371. ASSERT_TRUE(res);
  5372. EXPECT_EQ(StatusCode::OK_200, res->status);
  5373. EXPECT_EQ("close", res->get_header_value("Connection"));
  5374. }
  5375. TEST_F(ServerTest, TooManyRedirect) {
  5376. cli_.set_follow_location(true);
  5377. auto res = cli_.Get("/redirect/0");
  5378. ASSERT_TRUE(!res);
  5379. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5380. }
  5381. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5382. Request req;
  5383. req.method = "FOOBAR";
  5384. req.path = "/hi";
  5385. cli_.set_keep_alive(true);
  5386. auto res = cli_.send(req);
  5387. ASSERT_TRUE(res);
  5388. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5389. EXPECT_EQ("close", res->get_header_value("Connection"));
  5390. EXPECT_FALSE(cli_.is_socket_open());
  5391. }
  5392. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5393. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5394. TEST_F(ServerTest, Gzip) {
  5395. Headers headers;
  5396. headers.emplace("Accept-Encoding", "gzip, deflate");
  5397. auto res = cli_.Get("/compress", headers);
  5398. ASSERT_TRUE(res);
  5399. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5400. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5401. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5402. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5403. "7890123456789012345678901234567890",
  5404. res->body);
  5405. EXPECT_EQ(StatusCode::OK_200, res->status);
  5406. }
  5407. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5408. Headers headers;
  5409. headers.emplace("Accept-Encoding", "gzip, deflate");
  5410. auto res = cli_.Get("/compress-with-charset", headers);
  5411. ASSERT_TRUE(res);
  5412. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5413. EXPECT_EQ("application/json; charset=utf-8",
  5414. res->get_header_value("Content-Type"));
  5415. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5416. "7890123456789012345678901234567890",
  5417. res->body);
  5418. EXPECT_EQ(StatusCode::OK_200, res->status);
  5419. }
  5420. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5421. Headers headers;
  5422. headers.emplace("Accept-Encoding", "");
  5423. auto res = cli_.Get("/compress", headers);
  5424. ASSERT_TRUE(res);
  5425. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5426. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5427. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5428. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5429. "7890123456789012345678901234567890",
  5430. res->body);
  5431. EXPECT_EQ(StatusCode::OK_200, res->status);
  5432. }
  5433. TEST_F(ServerTest, GzipWithContentReceiver) {
  5434. Headers headers;
  5435. headers.emplace("Accept-Encoding", "gzip, deflate");
  5436. std::string body;
  5437. auto res = cli_.Get("/compress", headers,
  5438. [&](const char *data, uint64_t data_length) {
  5439. EXPECT_EQ(100U, data_length);
  5440. body.append(data, data_length);
  5441. return true;
  5442. });
  5443. ASSERT_TRUE(res);
  5444. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5445. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5446. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5447. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5448. "7890123456789012345678901234567890",
  5449. body);
  5450. EXPECT_EQ(StatusCode::OK_200, res->status);
  5451. }
  5452. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5453. Headers headers;
  5454. headers.emplace("Accept-Encoding", "gzip, deflate");
  5455. cli_.set_decompress(false);
  5456. auto res = cli_.Get("/compress", headers);
  5457. ASSERT_TRUE(res);
  5458. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5459. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5460. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5461. EXPECT_EQ(33U, res->body.size());
  5462. EXPECT_EQ(StatusCode::OK_200, res->status);
  5463. }
  5464. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5465. Headers headers;
  5466. headers.emplace("Accept-Encoding", "");
  5467. std::string body;
  5468. auto res = cli_.Get("/compress", headers,
  5469. [&](const char *data, uint64_t data_length) {
  5470. EXPECT_EQ(100U, data_length);
  5471. body.append(data, data_length);
  5472. return true;
  5473. });
  5474. ASSERT_TRUE(res);
  5475. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5476. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5477. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5478. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5479. "7890123456789012345678901234567890",
  5480. body);
  5481. EXPECT_EQ(StatusCode::OK_200, res->status);
  5482. }
  5483. TEST_F(ServerTest, NoGzip) {
  5484. Headers headers;
  5485. headers.emplace("Accept-Encoding", "gzip, deflate");
  5486. auto res = cli_.Get("/nocompress", headers);
  5487. ASSERT_TRUE(res);
  5488. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5489. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5490. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5491. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5492. "7890123456789012345678901234567890",
  5493. res->body);
  5494. EXPECT_EQ(StatusCode::OK_200, res->status);
  5495. }
  5496. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5497. Headers headers;
  5498. headers.emplace("Accept-Encoding", "gzip, deflate");
  5499. std::string body;
  5500. auto res = cli_.Get("/nocompress", headers,
  5501. [&](const char *data, uint64_t data_length) {
  5502. EXPECT_EQ(100U, data_length);
  5503. body.append(data, data_length);
  5504. return true;
  5505. });
  5506. ASSERT_TRUE(res);
  5507. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5508. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5509. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5510. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5511. "7890123456789012345678901234567890",
  5512. body);
  5513. EXPECT_EQ(StatusCode::OK_200, res->status);
  5514. }
  5515. TEST_F(ServerTest, MultipartFormDataGzip) {
  5516. UploadFormDataItems items = {
  5517. {"key1", "test", "", ""},
  5518. {"key2", "--abcdefg123", "", ""},
  5519. };
  5520. cli_.set_compress(true);
  5521. auto res = cli_.Post("/compress-multipart", items);
  5522. ASSERT_TRUE(res);
  5523. EXPECT_EQ(StatusCode::OK_200, res->status);
  5524. }
  5525. #endif
  5526. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5527. TEST_F(ServerTest, Brotli) {
  5528. Headers headers;
  5529. headers.emplace("Accept-Encoding", "br");
  5530. auto res = cli_.Get("/compress", headers);
  5531. ASSERT_TRUE(res);
  5532. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5533. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5534. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5535. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5536. "7890123456789012345678901234567890",
  5537. res->body);
  5538. EXPECT_EQ(StatusCode::OK_200, res->status);
  5539. }
  5540. #endif
  5541. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5542. TEST_F(ServerTest, Zstd) {
  5543. Headers headers;
  5544. headers.emplace("Accept-Encoding", "zstd");
  5545. auto res = cli_.Get("/compress", headers);
  5546. ASSERT_TRUE(res);
  5547. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5548. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5549. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5550. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5551. "7890123456789012345678901234567890",
  5552. res->body);
  5553. EXPECT_EQ(StatusCode::OK_200, res->status);
  5554. }
  5555. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5556. Headers headers;
  5557. headers.emplace("Accept-Encoding", "");
  5558. auto res = cli_.Get("/compress", headers);
  5559. ASSERT_TRUE(res);
  5560. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5561. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5562. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5563. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5564. "7890123456789012345678901234567890",
  5565. res->body);
  5566. EXPECT_EQ(StatusCode::OK_200, res->status);
  5567. }
  5568. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5569. Headers headers;
  5570. headers.emplace("Accept-Encoding", "zstd");
  5571. std::string body;
  5572. auto res = cli_.Get("/compress", headers,
  5573. [&](const char *data, uint64_t data_length) {
  5574. EXPECT_EQ(100U, data_length);
  5575. body.append(data, data_length);
  5576. return true;
  5577. });
  5578. ASSERT_TRUE(res);
  5579. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5580. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5581. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5582. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5583. "7890123456789012345678901234567890",
  5584. body);
  5585. EXPECT_EQ(StatusCode::OK_200, res->status);
  5586. }
  5587. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5588. Headers headers;
  5589. headers.emplace("Accept-Encoding", "zstd");
  5590. cli_.set_decompress(false);
  5591. auto res = cli_.Get("/compress", headers);
  5592. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5593. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5594. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5595. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5596. ASSERT_TRUE(res);
  5597. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5598. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5599. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5600. EXPECT_EQ(StatusCode::OK_200, res->status);
  5601. ASSERT_EQ(26U, res->body.size());
  5602. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5603. 0);
  5604. }
  5605. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5606. Headers headers;
  5607. headers.emplace("Accept-Encoding", "");
  5608. std::string body;
  5609. auto res = cli_.Get("/compress", headers,
  5610. [&](const char *data, uint64_t data_length) {
  5611. EXPECT_EQ(100U, data_length);
  5612. body.append(data, data_length);
  5613. return true;
  5614. });
  5615. ASSERT_TRUE(res);
  5616. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5617. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5618. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5619. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5620. "7890123456789012345678901234567890",
  5621. body);
  5622. EXPECT_EQ(StatusCode::OK_200, res->status);
  5623. }
  5624. TEST_F(ServerTest, NoZstd) {
  5625. Headers headers;
  5626. headers.emplace("Accept-Encoding", "zstd");
  5627. auto res = cli_.Get("/nocompress", headers);
  5628. ASSERT_TRUE(res);
  5629. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5630. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5631. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5632. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5633. "7890123456789012345678901234567890",
  5634. res->body);
  5635. EXPECT_EQ(StatusCode::OK_200, res->status);
  5636. }
  5637. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5638. Headers headers;
  5639. headers.emplace("Accept-Encoding", "zstd");
  5640. std::string body;
  5641. auto res = cli_.Get("/nocompress", headers,
  5642. [&](const char *data, uint64_t data_length) {
  5643. EXPECT_EQ(100U, data_length);
  5644. body.append(data, data_length);
  5645. return true;
  5646. });
  5647. ASSERT_TRUE(res);
  5648. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5649. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5650. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5651. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5652. "7890123456789012345678901234567890",
  5653. body);
  5654. EXPECT_EQ(StatusCode::OK_200, res->status);
  5655. }
  5656. // TODO: How to enable zstd ??
  5657. TEST_F(ServerTest, MultipartFormDataZstd) {
  5658. UploadFormDataItems items = {
  5659. {"key1", "test", "", ""},
  5660. {"key2", "--abcdefg123", "", ""},
  5661. };
  5662. Headers headers;
  5663. headers.emplace("Accept-Encoding", "zstd");
  5664. cli_.set_compress(true);
  5665. auto res = cli_.Post("/compress-multipart", headers, items);
  5666. ASSERT_TRUE(res);
  5667. EXPECT_EQ(StatusCode::OK_200, res->status);
  5668. }
  5669. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5670. Headers headers;
  5671. headers.emplace("Accept-Encoding", "zstd");
  5672. cli_.set_compress(true);
  5673. auto res = cli_.Put(
  5674. "/put", headers, 3,
  5675. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5676. sink.os << "PUT";
  5677. return true;
  5678. },
  5679. "text/plain");
  5680. ASSERT_TRUE(res);
  5681. EXPECT_EQ(StatusCode::OK_200, res->status);
  5682. EXPECT_EQ("PUT", res->body);
  5683. }
  5684. // Pre-compression logging tests
  5685. TEST_F(ServerTest, PreCompressionLogging) {
  5686. // Test data for compression (matches the actual /compress endpoint content)
  5687. const std::string test_content =
  5688. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5689. "3456789012345678901234567890";
  5690. // Variables to capture logging data
  5691. std::string pre_compression_body;
  5692. std::string pre_compression_content_type;
  5693. std::string pre_compression_content_encoding;
  5694. std::string post_compression_body;
  5695. std::string post_compression_content_type;
  5696. std::string post_compression_content_encoding;
  5697. // Set up pre-compression logger
  5698. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5699. const Response &res) {
  5700. pre_compression_body = res.body;
  5701. pre_compression_content_type = res.get_header_value("Content-Type");
  5702. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5703. });
  5704. // Set up post-compression logger
  5705. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5706. post_compression_body = res.body;
  5707. post_compression_content_type = res.get_header_value("Content-Type");
  5708. post_compression_content_encoding =
  5709. res.get_header_value("Content-Encoding");
  5710. });
  5711. // Test with gzip compression
  5712. Headers headers;
  5713. headers.emplace("Accept-Encoding", "gzip");
  5714. auto res = cli_.Get("/compress", headers);
  5715. // Verify response was compressed
  5716. ASSERT_TRUE(res);
  5717. EXPECT_EQ(StatusCode::OK_200, res->status);
  5718. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5719. // Verify pre-compression logger captured uncompressed content
  5720. EXPECT_EQ(test_content, pre_compression_body);
  5721. EXPECT_EQ("text/plain", pre_compression_content_type);
  5722. EXPECT_TRUE(pre_compression_content_encoding
  5723. .empty()); // No encoding header before compression
  5724. // Verify post-compression logger captured compressed content
  5725. EXPECT_NE(test_content,
  5726. post_compression_body); // Should be different after compression
  5727. EXPECT_EQ("text/plain", post_compression_content_type);
  5728. EXPECT_EQ("gzip", post_compression_content_encoding);
  5729. // Verify compressed content is smaller
  5730. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5731. }
  5732. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5733. const std::string test_content =
  5734. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5735. "3456789012345678901234567890";
  5736. std::string pre_compression_body;
  5737. std::string post_compression_body;
  5738. svr_.set_pre_compression_logger(
  5739. [&](const Request & /*req*/, const Response &res) {
  5740. pre_compression_body = res.body;
  5741. });
  5742. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5743. post_compression_body = res.body;
  5744. });
  5745. Headers headers;
  5746. headers.emplace("Accept-Encoding", "br");
  5747. auto res = cli_.Get("/compress", headers);
  5748. ASSERT_TRUE(res);
  5749. EXPECT_EQ(StatusCode::OK_200, res->status);
  5750. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5751. // Verify pre-compression content is uncompressed
  5752. EXPECT_EQ(test_content, pre_compression_body);
  5753. // Verify post-compression content is compressed
  5754. EXPECT_NE(test_content, post_compression_body);
  5755. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5756. }
  5757. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5758. const std::string test_content =
  5759. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5760. "3456789012345678901234567890";
  5761. std::string pre_compression_body;
  5762. std::string post_compression_body;
  5763. svr_.set_pre_compression_logger(
  5764. [&](const Request & /*req*/, const Response &res) {
  5765. pre_compression_body = res.body;
  5766. });
  5767. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5768. post_compression_body = res.body;
  5769. });
  5770. // Request without compression (use /nocompress endpoint)
  5771. Headers headers;
  5772. auto res = cli_.Get("/nocompress", headers);
  5773. ASSERT_TRUE(res);
  5774. EXPECT_EQ(StatusCode::OK_200, res->status);
  5775. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5776. // Pre-compression logger should not be called when no compression is applied
  5777. EXPECT_TRUE(
  5778. pre_compression_body.empty()); // Pre-compression logger not called
  5779. EXPECT_EQ(
  5780. test_content,
  5781. post_compression_body); // Post-compression logger captures final content
  5782. }
  5783. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5784. const std::string test_content =
  5785. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5786. "3456789012345678901234567890";
  5787. std::string pre_compression_body;
  5788. bool pre_logger_called = false;
  5789. // Set only pre-compression logger
  5790. svr_.set_pre_compression_logger(
  5791. [&](const Request & /*req*/, const Response &res) {
  5792. pre_compression_body = res.body;
  5793. pre_logger_called = true;
  5794. });
  5795. Headers headers;
  5796. headers.emplace("Accept-Encoding", "gzip");
  5797. auto res = cli_.Get("/compress", headers);
  5798. ASSERT_TRUE(res);
  5799. EXPECT_EQ(StatusCode::OK_200, res->status);
  5800. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5801. // Verify pre-compression logger was called
  5802. EXPECT_TRUE(pre_logger_called);
  5803. EXPECT_EQ(test_content, pre_compression_body);
  5804. }
  5805. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5806. {
  5807. // Test with Expect: 100-continue header - success case
  5808. // Server returns 100 Continue, client sends body, server returns 200 OK
  5809. Request req;
  5810. req.method = "POST";
  5811. req.path = "/post-large";
  5812. req.set_header("Expect", "100-continue");
  5813. req.body = LARGE_DATA;
  5814. Response res;
  5815. auto error = Error::Success;
  5816. cli_.set_keep_alive(true);
  5817. auto ret = cli_.send(req, res, error);
  5818. EXPECT_TRUE(ret);
  5819. EXPECT_EQ(StatusCode::OK_200, res.status);
  5820. EXPECT_EQ(LARGE_DATA, res.body);
  5821. }
  5822. {
  5823. // Test with Expect: 100-continue header - error case
  5824. // Client should not send the body when server returns an error
  5825. Request req;
  5826. req.method = "POST";
  5827. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5828. req.set_header("Expect", "100-continue");
  5829. req.body = LARGE_DATA;
  5830. Response res;
  5831. auto error = Error::Success;
  5832. auto start = std::chrono::high_resolution_clock::now();
  5833. cli_.set_keep_alive(true);
  5834. auto ret = cli_.send(req, res, error);
  5835. auto end = std::chrono::high_resolution_clock::now();
  5836. auto elapsed =
  5837. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5838. .count();
  5839. // With Expect: 100-continue, request completes successfully but with error
  5840. EXPECT_TRUE(ret);
  5841. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5842. EXPECT_EQ("close", res.get_header_value("Connection"));
  5843. EXPECT_FALSE(cli_.is_socket_open());
  5844. EXPECT_LE(elapsed, 200);
  5845. }
  5846. {
  5847. // Send an extra GET request to ensure error recovery without hanging
  5848. Request req;
  5849. req.method = "GET";
  5850. req.path = "/hi";
  5851. auto start = std::chrono::high_resolution_clock::now();
  5852. auto res = cli_.send(req);
  5853. auto end = std::chrono::high_resolution_clock::now();
  5854. auto elapsed =
  5855. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5856. .count();
  5857. ASSERT_TRUE(res);
  5858. EXPECT_EQ(StatusCode::OK_200, res->status);
  5859. EXPECT_EQ("Hello World!", res->body);
  5860. EXPECT_LE(elapsed, 500);
  5861. }
  5862. }
  5863. TEST(ZstdDecompressor, ChunkedDecompression) {
  5864. std::string data;
  5865. for (size_t i = 0; i < 32 * 1024; ++i) {
  5866. data.push_back(static_cast<char>('a' + i % 26));
  5867. }
  5868. std::string compressed_data;
  5869. {
  5870. httplib::detail::zstd_compressor compressor;
  5871. bool result = compressor.compress(
  5872. data.data(), data.size(),
  5873. /*last=*/true,
  5874. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5875. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5876. compressed_data_size);
  5877. return true;
  5878. });
  5879. ASSERT_TRUE(result);
  5880. }
  5881. std::string decompressed_data;
  5882. {
  5883. httplib::detail::zstd_decompressor decompressor;
  5884. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5885. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5886. size_t chunk_size = 130;
  5887. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5888. chunk_begin += chunk_size) {
  5889. size_t current_chunk_size =
  5890. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5891. bool result = decompressor.decompress(
  5892. compressed_data.data() + chunk_begin, current_chunk_size,
  5893. [&](const char *decompressed_data_chunk,
  5894. size_t decompressed_data_chunk_size) {
  5895. decompressed_data.insert(decompressed_data.size(),
  5896. decompressed_data_chunk,
  5897. decompressed_data_chunk_size);
  5898. return true;
  5899. });
  5900. ASSERT_TRUE(result);
  5901. }
  5902. }
  5903. ASSERT_EQ(data, decompressed_data);
  5904. }
  5905. TEST(ZstdDecompressor, Decompress) {
  5906. std::string original_text = "Compressed with ZSTD";
  5907. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5908. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5909. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5910. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5911. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5912. std::string decompressed_data;
  5913. {
  5914. httplib::detail::zstd_decompressor decompressor;
  5915. bool result = decompressor.decompress(
  5916. compressed_data.data(), compressed_data.size(),
  5917. [&](const char *decompressed_data_chunk,
  5918. size_t decompressed_data_chunk_size) {
  5919. decompressed_data.insert(decompressed_data.size(),
  5920. decompressed_data_chunk,
  5921. decompressed_data_chunk_size);
  5922. return true;
  5923. });
  5924. ASSERT_TRUE(result);
  5925. }
  5926. ASSERT_EQ(original_text, decompressed_data);
  5927. }
  5928. #endif
  5929. // Sends a raw request to a server listening at HOST:PORT.
  5930. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5931. std::string *resp = nullptr) {
  5932. auto error = Error::Success;
  5933. auto client_sock = detail::create_client_socket(
  5934. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5935. /*connection_timeout_sec=*/5, 0,
  5936. /*read_timeout_sec=*/5, 0,
  5937. /*write_timeout_sec=*/5, 0, std::string(), error);
  5938. if (client_sock == INVALID_SOCKET) { return false; }
  5939. auto ret = detail::process_client_socket(
  5940. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5941. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5942. if (req.size() !=
  5943. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5944. return false;
  5945. }
  5946. char buf[512];
  5947. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5948. while (line_reader.getline()) {
  5949. if (resp) { *resp += line_reader.ptr(); }
  5950. }
  5951. return true;
  5952. });
  5953. detail::close_socket(client_sock);
  5954. return ret;
  5955. }
  5956. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5957. Server svr;
  5958. std::string header_value;
  5959. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5960. header_value = req.get_header_value("foo");
  5961. res.set_content("ok", "text/plain");
  5962. });
  5963. thread t = thread([&] { svr.listen(HOST, PORT); });
  5964. auto se = detail::scope_exit([&] {
  5965. svr.stop();
  5966. t.join();
  5967. ASSERT_FALSE(svr.is_running());
  5968. });
  5969. svr.wait_until_ready();
  5970. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5971. // like characters are not treated the same - use vertical tab and escape.
  5972. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5973. "foo: \t \v bar \x1B\t \r\n"
  5974. "Connection: close\r\n"
  5975. "\r\n";
  5976. std::string res;
  5977. ASSERT_TRUE(send_request(5, req, &res));
  5978. EXPECT_EQ(header_value, "");
  5979. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5980. }
  5981. // Sends a raw request and verifies that there isn't a crash or exception.
  5982. static void test_raw_request(const std::string &req,
  5983. std::string *out = nullptr) {
  5984. Server svr;
  5985. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5986. res.set_content("ok", "text/plain");
  5987. });
  5988. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5989. res.set_content("ok", "text/plain");
  5990. });
  5991. svr.Get("/header_field_value_check",
  5992. [&](const Request & /*req*/, Response &res) {
  5993. res.set_content("ok", "text/plain");
  5994. });
  5995. // Server read timeout must be longer than the client read timeout for the
  5996. // bug to reproduce, probably to force the server to process a request
  5997. // without a trailing blank line.
  5998. const time_t client_read_timeout_sec = 1;
  5999. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  6000. bool listen_thread_ok = false;
  6001. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  6002. auto se = detail::scope_exit([&] {
  6003. svr.stop();
  6004. t.join();
  6005. ASSERT_FALSE(svr.is_running());
  6006. EXPECT_TRUE(listen_thread_ok);
  6007. });
  6008. svr.wait_until_ready();
  6009. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  6010. }
  6011. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  6012. // A certain header line causes an exception if the header property is parsed
  6013. // naively with a single regex. This occurs with libc++ but not libstdc++.
  6014. test_raw_request(
  6015. "GET /hi HTTP/1.1\r\n"
  6016. " : "
  6017. " "
  6018. " ");
  6019. }
  6020. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6021. // A certain header line causes an exception if the header property *name* is
  6022. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6023. // greedy matcher and requires backtracking when there are a lot of ":"
  6024. // characters.
  6025. // This occurs with libc++ but not libstdc++.
  6026. test_raw_request(
  6027. "GET /hi HTTP/1.1\r\n"
  6028. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6029. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6030. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6031. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6032. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6033. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6034. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6035. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6036. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6037. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6038. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6039. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6040. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6041. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6042. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6043. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6044. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6045. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6046. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6047. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6048. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6049. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6050. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6051. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6052. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6053. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6054. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6055. "&&&%%%");
  6056. }
  6057. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6058. // Make sure this doesn't crash the server.
  6059. // In a previous version of the header line regex, the "\r" rendered the line
  6060. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6061. // a new position where the leading white space ended and the field value
  6062. // began.
  6063. // The crash occurs with libc++ but not libstdc++.
  6064. test_raw_request("GET /hi HTTP/1.1\r\n"
  6065. "a:" +
  6066. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6067. "\r\n"
  6068. "\r\n");
  6069. }
  6070. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6071. std::string out;
  6072. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6073. "Content-Type: text/plain\r\n"
  6074. "Transfer-Encoding: chunked\r\n"
  6075. "\r\n"
  6076. "nothex\r\n",
  6077. &out);
  6078. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6079. }
  6080. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6081. std::string out;
  6082. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6083. "Content-Type: text/plain\r\n"
  6084. "Transfer-Encoding: chunked\r\n"
  6085. "\r\n"
  6086. "3\r\n"
  6087. "xyz\r\n"
  6088. "NaN\r\n",
  6089. &out);
  6090. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6091. }
  6092. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6093. std::string out;
  6094. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6095. "Content-Type: text/plain\r\n"
  6096. "Transfer-Encoding: chunked\r\n"
  6097. "\r\n"
  6098. // Length is too large for 64 bits.
  6099. "1ffffffffffffffff\r\n"
  6100. "xyz\r\n",
  6101. &out);
  6102. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6103. }
  6104. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6105. test_raw_request("GET /hi HTTP/1.1\r\n"
  6106. "Content-Type: text/plain\r\n\r");
  6107. }
  6108. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6109. std::string out;
  6110. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6111. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6112. }
  6113. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6114. Server svr;
  6115. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6116. EXPECT_TRUE(!req.remote_addr.empty());
  6117. });
  6118. thread t = thread([&] { svr.listen(HOST, PORT); });
  6119. auto se = detail::scope_exit([&] {
  6120. svr.stop();
  6121. t.join();
  6122. ASSERT_FALSE(svr.is_running());
  6123. });
  6124. svr.wait_until_ready();
  6125. // Send an invalid request line to trigger Bad Request
  6126. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6127. std::string out;
  6128. ASSERT_TRUE(send_request(5, bad_req, &out));
  6129. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6130. }
  6131. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6132. std::string out;
  6133. std::string request(
  6134. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6135. test_raw_request(request, &out);
  6136. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6137. }
  6138. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6139. std::string out;
  6140. std::string request(
  6141. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6142. test_raw_request(request, &out);
  6143. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6144. }
  6145. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6146. std::string out;
  6147. std::string request(
  6148. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6149. test_raw_request(request, &out);
  6150. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6151. }
  6152. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6153. std::string out;
  6154. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6155. "Test: \r\n\r\n",
  6156. &out);
  6157. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6158. }
  6159. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6160. Server svr;
  6161. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6162. res.set_header("Cache-Control", "no-cache");
  6163. res.set_chunked_content_provider(
  6164. "text/event-stream", [](size_t offset, DataSink &sink) {
  6165. std::string s = "data:";
  6166. s += std::to_string(offset);
  6167. s += "\n\n";
  6168. auto ret = sink.write(s.data(), s.size());
  6169. EXPECT_TRUE(ret);
  6170. std::this_thread::sleep_for(std::chrono::seconds(1));
  6171. return true;
  6172. });
  6173. });
  6174. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6175. svr.wait_until_ready();
  6176. Client client(HOST, PORT);
  6177. const Headers headers = {{"Accept", "text/event-stream"}};
  6178. auto get_thread = std::thread([&client, &headers]() {
  6179. auto res = client.Get(
  6180. "/events", headers,
  6181. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6182. });
  6183. auto se = detail::scope_exit([&] {
  6184. svr.stop();
  6185. get_thread.join();
  6186. listen_thread.join();
  6187. ASSERT_FALSE(svr.is_running());
  6188. });
  6189. // Give GET time to get a few messages.
  6190. std::this_thread::sleep_for(std::chrono::seconds(2));
  6191. }
  6192. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6193. httplib::Server svr;
  6194. svr.Post("/hi",
  6195. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6196. res.status = StatusCode::OK_200;
  6197. });
  6198. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6199. svr.wait_until_ready();
  6200. Client cli(HOST, PORT);
  6201. auto res = cli.Post("/hi", "data", "text/plain");
  6202. ASSERT_TRUE(res);
  6203. EXPECT_EQ(StatusCode::OK_200, res->status);
  6204. svr.stop();
  6205. thread.join();
  6206. ASSERT_FALSE(svr.is_running());
  6207. res = cli.Post("/hi", "data", "text/plain");
  6208. ASSERT_FALSE(res);
  6209. }
  6210. TEST(ServerStopTest, ListenFailure) {
  6211. Server svr;
  6212. auto t = thread([&]() {
  6213. auto ret = svr.listen("????", PORT);
  6214. EXPECT_FALSE(ret);
  6215. });
  6216. svr.wait_until_ready();
  6217. svr.stop();
  6218. t.join();
  6219. }
  6220. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6221. TEST(ServerStopTest, Decommision) {
  6222. Server svr;
  6223. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6224. for (int i = 0; i < 4; i++) {
  6225. auto is_even = !(i % 2);
  6226. std::thread t{[&] {
  6227. try {
  6228. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6229. if (is_even) {
  6230. throw std::runtime_error("Some thing that happens to go wrong.");
  6231. }
  6232. svr.listen(HOST, PORT);
  6233. } catch (...) { svr.decommission(); }
  6234. }};
  6235. svr.wait_until_ready();
  6236. // Server is up
  6237. {
  6238. Client cli(HOST, PORT);
  6239. auto res = cli.Get("/hi");
  6240. if (is_even) {
  6241. EXPECT_FALSE(res);
  6242. } else {
  6243. EXPECT_TRUE(res);
  6244. EXPECT_EQ("hi...", res->body);
  6245. }
  6246. }
  6247. svr.stop();
  6248. t.join();
  6249. // Server is down...
  6250. {
  6251. Client cli(HOST, PORT);
  6252. auto res = cli.Get("/hi");
  6253. EXPECT_FALSE(res);
  6254. }
  6255. }
  6256. }
  6257. #endif
  6258. // Helper function for string body upload progress tests
  6259. template <typename SetupHandler, typename ClientCall>
  6260. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6261. ClientCall &&client_call,
  6262. const string &body) {
  6263. Server svr;
  6264. setup_handler(svr);
  6265. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6266. auto se = detail::scope_exit([&] {
  6267. svr.stop();
  6268. t.join();
  6269. });
  6270. svr.wait_until_ready();
  6271. Client cli(HOST, PORT);
  6272. vector<uint64_t> progress_values;
  6273. bool progress_called = false;
  6274. auto res =
  6275. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6276. progress_values.push_back(current);
  6277. progress_called = true;
  6278. return true;
  6279. });
  6280. ASSERT_TRUE(res);
  6281. EXPECT_EQ(200, res->status);
  6282. EXPECT_TRUE(progress_called);
  6283. }
  6284. TEST(UploadProgressTest, PostStringBodyBasic) {
  6285. TestStringBodyUploadProgress(
  6286. [](Server &svr) {
  6287. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6288. res.set_content("received", "text/plain");
  6289. });
  6290. },
  6291. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6292. return cli.Post("/test", body, "text/plain", progress_callback);
  6293. },
  6294. "test data for upload progress");
  6295. }
  6296. TEST(UploadProgressTest, PutStringBodyBasic) {
  6297. TestStringBodyUploadProgress(
  6298. [](Server &svr) {
  6299. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6300. res.set_content("put received", "text/plain");
  6301. });
  6302. },
  6303. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6304. return cli.Put("/test", body, "text/plain", progress_callback);
  6305. },
  6306. "put test data for upload progress");
  6307. }
  6308. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6309. TestStringBodyUploadProgress(
  6310. [](Server &svr) {
  6311. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6312. res.set_content("patch received", "text/plain");
  6313. });
  6314. },
  6315. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6316. return cli.Patch("/test", body, "text/plain", progress_callback);
  6317. },
  6318. "patch test data for upload progress");
  6319. }
  6320. // Helper function for content provider upload progress tests
  6321. template <typename SetupHandler, typename ClientCall>
  6322. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6323. ClientCall &&client_call) {
  6324. Server svr;
  6325. setup_handler(svr);
  6326. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6327. auto se = detail::scope_exit([&] {
  6328. svr.stop();
  6329. t.join();
  6330. });
  6331. svr.wait_until_ready();
  6332. Client cli(HOST, PORT);
  6333. vector<uint64_t> progress_values;
  6334. auto res =
  6335. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6336. progress_values.push_back(current);
  6337. return true;
  6338. });
  6339. ASSERT_TRUE(res);
  6340. EXPECT_EQ(200, res->status);
  6341. EXPECT_FALSE(progress_values.empty());
  6342. }
  6343. TEST(UploadProgressTest, PostContentProviderProgress) {
  6344. TestContentProviderUploadProgress(
  6345. [](Server &svr) {
  6346. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6347. res.set_content("provider received", "text/plain");
  6348. });
  6349. },
  6350. [](Client &cli, UploadProgress progress_callback) {
  6351. return cli.Post(
  6352. "/test", 10,
  6353. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6354. sink.os << "test data";
  6355. return true;
  6356. },
  6357. "text/plain", progress_callback);
  6358. });
  6359. }
  6360. // Helper function for multipart upload progress tests
  6361. template <typename SetupHandler, typename ClientCall>
  6362. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6363. ClientCall &&client_call,
  6364. const string &endpoint) {
  6365. Server svr;
  6366. setup_handler(svr);
  6367. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6368. auto se = detail::scope_exit([&] {
  6369. svr.stop();
  6370. t.join();
  6371. });
  6372. svr.wait_until_ready();
  6373. Client cli(HOST, PORT);
  6374. vector<uint64_t> progress_values;
  6375. UploadFormDataItems items = {
  6376. {"field1", "value1", "", ""},
  6377. {"field2", "longer value for progress tracking test", "", ""},
  6378. {"file1", "file content data for upload progress", "test.txt",
  6379. "text/plain"}};
  6380. auto res = client_call(cli, endpoint, items,
  6381. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6382. progress_values.push_back(current);
  6383. return true;
  6384. });
  6385. ASSERT_TRUE(res);
  6386. EXPECT_EQ(200, res->status);
  6387. EXPECT_FALSE(progress_values.empty());
  6388. }
  6389. TEST(UploadProgressTest, PostMultipartProgress) {
  6390. TestMultipartUploadProgress(
  6391. [](Server &svr) {
  6392. svr.Post("/multipart", [](const Request &req, Response &res) {
  6393. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6394. res.set_content("multipart received", "text/plain");
  6395. });
  6396. },
  6397. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6398. UploadProgress progress_callback) {
  6399. return cli.Post(endpoint, items, progress_callback);
  6400. },
  6401. "/multipart");
  6402. }
  6403. // Helper function for basic download progress tests
  6404. template <typename SetupHandler, typename ClientCall>
  6405. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6406. ClientCall &&client_call, const string &endpoint,
  6407. size_t expected_content_size) {
  6408. Server svr;
  6409. setup_handler(svr);
  6410. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6411. auto se = detail::scope_exit([&] {
  6412. svr.stop();
  6413. t.join();
  6414. });
  6415. svr.wait_until_ready();
  6416. Client cli(HOST, PORT);
  6417. vector<uint64_t> progress_values;
  6418. auto res = client_call(cli, endpoint,
  6419. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6420. progress_values.push_back(current);
  6421. return true;
  6422. });
  6423. ASSERT_TRUE(res);
  6424. EXPECT_EQ(200, res->status);
  6425. EXPECT_FALSE(progress_values.empty());
  6426. EXPECT_EQ(expected_content_size, res->body.size());
  6427. }
  6428. TEST(DownloadProgressTest, GetBasic) {
  6429. TestBasicDownloadProgress(
  6430. [](Server &svr) {
  6431. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6432. string content(1000, 'D');
  6433. res.set_content(content, "text/plain");
  6434. });
  6435. },
  6436. [](Client &cli, const string &endpoint,
  6437. DownloadProgress progress_callback) {
  6438. return cli.Get(endpoint, progress_callback);
  6439. },
  6440. "/download", 1000u);
  6441. }
  6442. // Helper function for content receiver download progress tests
  6443. template <typename SetupHandler, typename ClientCall>
  6444. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6445. ClientCall &&client_call,
  6446. const string &endpoint,
  6447. size_t expected_content_size) {
  6448. Server svr;
  6449. setup_handler(svr);
  6450. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6451. auto se = detail::scope_exit([&] {
  6452. svr.stop();
  6453. t.join();
  6454. });
  6455. svr.wait_until_ready();
  6456. Client cli(HOST, PORT);
  6457. vector<uint64_t> progress_values;
  6458. string received_body;
  6459. auto res = client_call(
  6460. cli, endpoint,
  6461. [&](const char *data, size_t data_length) -> bool {
  6462. received_body.append(data, data_length);
  6463. return true;
  6464. },
  6465. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6466. progress_values.push_back(current);
  6467. return true;
  6468. });
  6469. ASSERT_TRUE(res);
  6470. EXPECT_EQ(200, res->status);
  6471. EXPECT_FALSE(progress_values.empty());
  6472. EXPECT_EQ(expected_content_size, received_body.size());
  6473. EXPECT_TRUE(res->body.empty());
  6474. }
  6475. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6476. TestContentReceiverDownloadProgress(
  6477. [](Server &svr) {
  6478. svr.Get("/download-receiver",
  6479. [](const Request & /*req*/, Response &res) {
  6480. string content(2000, 'R');
  6481. res.set_content(content, "text/plain");
  6482. });
  6483. },
  6484. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6485. DownloadProgress progress_callback) {
  6486. return cli.Get(endpoint, content_receiver, progress_callback);
  6487. },
  6488. "/download-receiver", 2000u);
  6489. }
  6490. TEST(StreamingTest, NoContentLengthStreaming) {
  6491. Server svr;
  6492. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6493. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6494. if (offset < 6) {
  6495. sink.os << (offset < 3 ? "a" : "b");
  6496. } else {
  6497. sink.done();
  6498. }
  6499. return true;
  6500. });
  6501. });
  6502. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6503. auto listen_se = detail::scope_exit([&] {
  6504. svr.stop();
  6505. listen_thread.join();
  6506. ASSERT_FALSE(svr.is_running());
  6507. });
  6508. svr.wait_until_ready();
  6509. Client client(HOST, PORT);
  6510. auto get_thread = std::thread([&client]() {
  6511. std::string s;
  6512. auto res =
  6513. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6514. s += std::string(data, len);
  6515. return true;
  6516. });
  6517. ASSERT_TRUE(res);
  6518. EXPECT_EQ(StatusCode::OK_200, res->status);
  6519. EXPECT_EQ("aaabbb", s);
  6520. });
  6521. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6522. // Give GET time to get a few messages.
  6523. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6524. }
  6525. TEST(MountTest, Unmount) {
  6526. Server svr;
  6527. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6528. auto se = detail::scope_exit([&] {
  6529. svr.stop();
  6530. listen_thread.join();
  6531. ASSERT_FALSE(svr.is_running());
  6532. });
  6533. svr.wait_until_ready();
  6534. Client cli("localhost", PORT);
  6535. svr.set_mount_point("/mount2", "./www2");
  6536. auto res = cli.Get("/");
  6537. ASSERT_TRUE(res);
  6538. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6539. res = cli.Get("/mount2/dir/test.html");
  6540. ASSERT_TRUE(res);
  6541. EXPECT_EQ(StatusCode::OK_200, res->status);
  6542. svr.set_mount_point("/", "./www");
  6543. res = cli.Get("/dir/");
  6544. ASSERT_TRUE(res);
  6545. EXPECT_EQ(StatusCode::OK_200, res->status);
  6546. svr.remove_mount_point("/");
  6547. res = cli.Get("/dir/");
  6548. ASSERT_TRUE(res);
  6549. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6550. svr.remove_mount_point("/mount2");
  6551. res = cli.Get("/mount2/dir/test.html");
  6552. ASSERT_TRUE(res);
  6553. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6554. }
  6555. TEST(MountTest, Redicect) {
  6556. Server svr;
  6557. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6558. auto se = detail::scope_exit([&] {
  6559. svr.stop();
  6560. listen_thread.join();
  6561. ASSERT_FALSE(svr.is_running());
  6562. });
  6563. svr.set_mount_point("/", "./www");
  6564. svr.wait_until_ready();
  6565. Client cli("localhost", PORT);
  6566. auto res = cli.Get("/dir/");
  6567. ASSERT_TRUE(res);
  6568. EXPECT_EQ(StatusCode::OK_200, res->status);
  6569. res = cli.Get("/dir");
  6570. ASSERT_TRUE(res);
  6571. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6572. res = cli.Get("/file");
  6573. ASSERT_TRUE(res);
  6574. EXPECT_EQ(StatusCode::OK_200, res->status);
  6575. res = cli.Get("/file/");
  6576. ASSERT_TRUE(res);
  6577. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6578. cli.set_follow_location(true);
  6579. res = cli.Get("/dir");
  6580. ASSERT_TRUE(res);
  6581. EXPECT_EQ(StatusCode::OK_200, res->status);
  6582. }
  6583. TEST(MountTest, MultibytesPathName) {
  6584. Server svr;
  6585. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6586. auto se = detail::scope_exit([&] {
  6587. svr.stop();
  6588. listen_thread.join();
  6589. ASSERT_FALSE(svr.is_running());
  6590. });
  6591. svr.set_mount_point("/", "./www");
  6592. svr.wait_until_ready();
  6593. Client cli("localhost", PORT);
  6594. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6595. ASSERT_TRUE(res);
  6596. EXPECT_EQ(StatusCode::OK_200, res->status);
  6597. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6598. }
  6599. TEST(KeepAliveTest, ReadTimeout) {
  6600. Server svr;
  6601. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6602. std::this_thread::sleep_for(std::chrono::seconds(2));
  6603. res.set_content("a", "text/plain");
  6604. });
  6605. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6606. res.set_content("b", "text/plain");
  6607. });
  6608. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6609. auto se = detail::scope_exit([&] {
  6610. svr.stop();
  6611. listen_thread.join();
  6612. ASSERT_FALSE(svr.is_running());
  6613. });
  6614. svr.wait_until_ready();
  6615. Client cli("localhost", PORT);
  6616. cli.set_keep_alive(true);
  6617. cli.set_read_timeout(std::chrono::seconds(1));
  6618. auto resa = cli.Get("/a");
  6619. ASSERT_FALSE(resa);
  6620. EXPECT_EQ(Error::Read, resa.error());
  6621. auto resb = cli.Get("/b");
  6622. ASSERT_TRUE(resb);
  6623. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6624. EXPECT_EQ("b", resb->body);
  6625. }
  6626. TEST(KeepAliveTest, MaxCount) {
  6627. size_t keep_alive_max_count = 3;
  6628. Server svr;
  6629. svr.set_keep_alive_max_count(keep_alive_max_count);
  6630. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6631. res.set_content("Hello World!", "text/plain");
  6632. });
  6633. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6634. auto se = detail::scope_exit([&] {
  6635. svr.stop();
  6636. listen_thread.join();
  6637. ASSERT_FALSE(svr.is_running());
  6638. });
  6639. svr.wait_until_ready();
  6640. Client cli(HOST, PORT);
  6641. cli.set_keep_alive(true);
  6642. for (size_t i = 0; i < 5; i++) {
  6643. auto result = cli.Get("/hi");
  6644. ASSERT_TRUE(result);
  6645. EXPECT_EQ(StatusCode::OK_200, result->status);
  6646. if (i == keep_alive_max_count - 1) {
  6647. EXPECT_EQ("close", result->get_header_value("Connection"));
  6648. } else {
  6649. EXPECT_FALSE(result->has_header("Connection"));
  6650. }
  6651. }
  6652. }
  6653. TEST(KeepAliveTest, Issue1041) {
  6654. Server svr;
  6655. svr.set_keep_alive_timeout(3);
  6656. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6657. res.set_content("Hello World!", "text/plain");
  6658. });
  6659. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6660. auto se = detail::scope_exit([&] {
  6661. svr.stop();
  6662. listen_thread.join();
  6663. ASSERT_FALSE(svr.is_running());
  6664. });
  6665. svr.wait_until_ready();
  6666. Client cli(HOST, PORT);
  6667. cli.set_keep_alive(true);
  6668. auto result = cli.Get("/hi");
  6669. ASSERT_TRUE(result);
  6670. EXPECT_EQ(StatusCode::OK_200, result->status);
  6671. std::this_thread::sleep_for(std::chrono::seconds(5));
  6672. result = cli.Get("/hi");
  6673. ASSERT_TRUE(result);
  6674. EXPECT_EQ(StatusCode::OK_200, result->status);
  6675. }
  6676. TEST(KeepAliveTest, Issue1959) {
  6677. Server svr;
  6678. svr.set_keep_alive_timeout(5);
  6679. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6680. res.set_content("a", "text/plain");
  6681. });
  6682. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6683. auto se = detail::scope_exit([&] {
  6684. if (!svr.is_running()) return;
  6685. svr.stop();
  6686. listen_thread.join();
  6687. ASSERT_FALSE(svr.is_running());
  6688. });
  6689. svr.wait_until_ready();
  6690. Client cli("localhost", PORT);
  6691. cli.set_keep_alive(true);
  6692. using namespace std::chrono;
  6693. auto start = steady_clock::now();
  6694. cli.Get("/a");
  6695. svr.stop();
  6696. listen_thread.join();
  6697. auto end = steady_clock::now();
  6698. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6699. EXPECT_LT(elapsed, 5000);
  6700. }
  6701. #ifdef CPPHTTPLIB_SSL_ENABLED
  6702. TEST(KeepAliveTest, SSLClientReconnection) {
  6703. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6704. ASSERT_TRUE(svr.is_valid());
  6705. svr.set_keep_alive_timeout(1);
  6706. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6707. res.set_content("Hello World!", "text/plain");
  6708. });
  6709. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6710. auto se = detail::scope_exit([&] {
  6711. svr.stop();
  6712. listen_thread.join();
  6713. ASSERT_FALSE(svr.is_running());
  6714. });
  6715. svr.wait_until_ready();
  6716. SSLClient cli(HOST, PORT);
  6717. cli.enable_server_certificate_verification(false);
  6718. cli.set_keep_alive(true);
  6719. auto result = cli.Get("/hi");
  6720. ASSERT_TRUE(result);
  6721. EXPECT_EQ(StatusCode::OK_200, result->status);
  6722. result = cli.Get("/hi");
  6723. ASSERT_TRUE(result);
  6724. EXPECT_EQ(StatusCode::OK_200, result->status);
  6725. std::this_thread::sleep_for(std::chrono::seconds(2));
  6726. // Recoonect
  6727. result = cli.Get("/hi");
  6728. ASSERT_TRUE(result);
  6729. EXPECT_EQ(StatusCode::OK_200, result->status);
  6730. result = cli.Get("/hi");
  6731. ASSERT_TRUE(result);
  6732. EXPECT_EQ(StatusCode::OK_200, result->status);
  6733. }
  6734. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6735. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6736. ASSERT_TRUE(svr.is_valid());
  6737. svr.set_keep_alive_timeout(1);
  6738. std::string content = "reconnect";
  6739. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6740. res.set_content("Hello World!", "text/plain");
  6741. });
  6742. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6743. auto se = detail::scope_exit([&] {
  6744. svr.stop();
  6745. listen_thread.join();
  6746. ASSERT_FALSE(svr.is_running());
  6747. });
  6748. svr.wait_until_ready();
  6749. SSLClient cli(HOST, PORT);
  6750. cli.enable_server_certificate_verification(false);
  6751. cli.set_keep_alive(true);
  6752. auto result = cli.Post(
  6753. "/hi", content.size(),
  6754. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6755. sink.write(content.c_str(), content.size());
  6756. return true;
  6757. },
  6758. "text/plain");
  6759. ASSERT_TRUE(result);
  6760. EXPECT_EQ(200, result->status);
  6761. std::this_thread::sleep_for(std::chrono::seconds(2));
  6762. // Recoonect
  6763. result = cli.Post(
  6764. "/hi", content.size(),
  6765. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6766. sink.write(content.c_str(), content.size());
  6767. return true;
  6768. },
  6769. "text/plain");
  6770. ASSERT_TRUE(result);
  6771. EXPECT_EQ(200, result->status);
  6772. result = cli.Post(
  6773. "/hi", content.size(),
  6774. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6775. sink.write(content.c_str(), content.size());
  6776. return true;
  6777. },
  6778. "text/plain");
  6779. ASSERT_TRUE(result);
  6780. EXPECT_EQ(200, result->status);
  6781. }
  6782. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6783. using namespace httplib::tls;
  6784. {
  6785. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6786. ASSERT_TRUE(svr.is_valid());
  6787. svr.Get("/sni", [&](const Request &req, Response &res) {
  6788. std::string expected = req.sni();
  6789. EXPECT_EQ(expected, req.get_param_value("expected"));
  6790. res.set_content("ok", "text/plain");
  6791. });
  6792. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6793. auto se = detail::scope_exit([&] {
  6794. svr.stop();
  6795. listen_thread.join();
  6796. ASSERT_FALSE(svr.is_running());
  6797. });
  6798. svr.wait_until_ready();
  6799. {
  6800. SSLClient cli("localhost", PORT);
  6801. cli.enable_server_certificate_verification(false);
  6802. auto res = cli.Get("/sni?expected=localhost");
  6803. ASSERT_TRUE(res);
  6804. }
  6805. {
  6806. SSLClient cli("::1", PORT);
  6807. cli.enable_server_certificate_verification(false);
  6808. auto res = cli.Get("/sni?expected=");
  6809. // NOTE: This may fail if the server is listening on IPv4 only
  6810. // (e.g., when localhost resolves to 127.0.0.1 only)
  6811. if (res) {
  6812. EXPECT_EQ(StatusCode::OK_200, res->status);
  6813. } else {
  6814. EXPECT_EQ(Error::Connection, res.error());
  6815. }
  6816. }
  6817. }
  6818. }
  6819. #endif
  6820. TEST(ClientProblemDetectionTest, ContentProvider) {
  6821. Server svr;
  6822. size_t content_length = 1024 * 1024;
  6823. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6824. res.set_content_provider(
  6825. content_length, "text/plain",
  6826. [&](size_t offset, size_t length, DataSink &sink) {
  6827. auto out_len = std::min(length, static_cast<size_t>(1024));
  6828. std::string out(out_len, '@');
  6829. sink.write(out.data(), out_len);
  6830. return offset < 4096;
  6831. },
  6832. [](bool success) { ASSERT_FALSE(success); });
  6833. });
  6834. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6835. res.set_content_provider(
  6836. 0, "text/plain",
  6837. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6838. EXPECT_TRUE(false);
  6839. return true;
  6840. },
  6841. [](bool success) { ASSERT_FALSE(success); });
  6842. });
  6843. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6844. auto se = detail::scope_exit([&] {
  6845. svr.stop();
  6846. listen_thread.join();
  6847. ASSERT_FALSE(svr.is_running());
  6848. });
  6849. svr.wait_until_ready();
  6850. Client cli("localhost", PORT);
  6851. {
  6852. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6853. size_t /*data_length*/) { return false; });
  6854. ASSERT_FALSE(res);
  6855. }
  6856. {
  6857. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6858. size_t /*data_length*/) { return false; });
  6859. ASSERT_TRUE(res);
  6860. }
  6861. }
  6862. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6863. Server svr;
  6864. svr.set_error_handler([](Request const &, Response &res) -> void {
  6865. res.set_chunked_content_provider(
  6866. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6867. sink.os << "hello";
  6868. sink.os << "world";
  6869. sink.done();
  6870. return true;
  6871. });
  6872. });
  6873. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6874. auto se = detail::scope_exit([&] {
  6875. svr.stop();
  6876. listen_thread.join();
  6877. ASSERT_FALSE(svr.is_running());
  6878. });
  6879. svr.wait_until_ready();
  6880. Client cli("localhost", PORT);
  6881. auto res = cli.Get("/");
  6882. ASSERT_TRUE(res);
  6883. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6884. EXPECT_EQ("helloworld", res->body);
  6885. }
  6886. TEST(LongPollingTest, ClientCloseDetection) {
  6887. Server svr;
  6888. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6889. res.set_chunked_content_provider(
  6890. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6891. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6892. sink.os << "hello";
  6893. auto count = 10;
  6894. while (count > 0 && sink.is_writable()) {
  6895. this_thread::sleep_for(chrono::milliseconds(10));
  6896. count--;
  6897. }
  6898. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6899. return true;
  6900. });
  6901. });
  6902. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6903. auto se = detail::scope_exit([&] {
  6904. svr.stop();
  6905. listen_thread.join();
  6906. ASSERT_FALSE(svr.is_running());
  6907. });
  6908. svr.wait_until_ready();
  6909. Client cli("localhost", PORT);
  6910. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6911. EXPECT_EQ("hello", string(data, data_length));
  6912. return false; // close the socket immediately.
  6913. });
  6914. ASSERT_FALSE(res);
  6915. }
  6916. TEST(GetWithParametersTest, GetWithParameters) {
  6917. Server svr;
  6918. svr.Get("/", [&](const Request &req, Response &) {
  6919. EXPECT_EQ("world", req.get_param_value("hello"));
  6920. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6921. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6922. });
  6923. svr.Get("/params", [&](const Request &req, Response &) {
  6924. EXPECT_EQ("world", req.get_param_value("hello"));
  6925. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6926. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6927. });
  6928. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6929. EXPECT_EQ("resource-id", req.matches[1]);
  6930. EXPECT_EQ("foo", req.get_param_value("param1"));
  6931. EXPECT_EQ("bar", req.get_param_value("param2"));
  6932. });
  6933. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6934. EXPECT_EQ("user-id", req.path_params.at("id"));
  6935. EXPECT_EQ("foo", req.get_param_value("param1"));
  6936. EXPECT_EQ("bar", req.get_param_value("param2"));
  6937. });
  6938. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6939. auto se = detail::scope_exit([&] {
  6940. svr.stop();
  6941. listen_thread.join();
  6942. ASSERT_FALSE(svr.is_running());
  6943. });
  6944. svr.wait_until_ready();
  6945. {
  6946. Client cli(HOST, PORT);
  6947. Params params;
  6948. params.emplace("hello", "world");
  6949. params.emplace("hello2", "world2");
  6950. params.emplace("hello3", "world3");
  6951. auto res = cli.Get("/", params, Headers{});
  6952. ASSERT_TRUE(res);
  6953. EXPECT_EQ(StatusCode::OK_200, res->status);
  6954. }
  6955. {
  6956. Client cli(HOST, PORT);
  6957. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6958. ASSERT_TRUE(res);
  6959. EXPECT_EQ(StatusCode::OK_200, res->status);
  6960. }
  6961. {
  6962. Client cli(HOST, PORT);
  6963. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6964. ASSERT_TRUE(res);
  6965. EXPECT_EQ(StatusCode::OK_200, res->status);
  6966. }
  6967. {
  6968. Client cli(HOST, PORT);
  6969. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6970. ASSERT_TRUE(res);
  6971. EXPECT_EQ(StatusCode::OK_200, res->status);
  6972. }
  6973. }
  6974. TEST(GetWithParametersTest, GetWithParameters2) {
  6975. Server svr;
  6976. svr.Get("/", [&](const Request &req, Response &res) {
  6977. auto text = req.get_param_value("hello");
  6978. res.set_content(text, "text/plain");
  6979. });
  6980. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6981. auto se = detail::scope_exit([&] {
  6982. svr.stop();
  6983. listen_thread.join();
  6984. ASSERT_FALSE(svr.is_running());
  6985. });
  6986. svr.wait_until_ready();
  6987. Client cli("localhost", PORT);
  6988. Params params;
  6989. params.emplace("hello", "world");
  6990. std::string body;
  6991. auto res = cli.Get("/", params, Headers{},
  6992. [&](const char *data, size_t data_length) {
  6993. body.append(data, data_length);
  6994. return true;
  6995. });
  6996. ASSERT_TRUE(res);
  6997. EXPECT_EQ(StatusCode::OK_200, res->status);
  6998. EXPECT_EQ("world", body);
  6999. }
  7000. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  7001. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7002. auto host = "httpcan.org";
  7003. auto path = std::string{"/range/32"};
  7004. #else
  7005. auto host = "nghttp2.org";
  7006. auto path = std::string{"/httpbin/range/32"};
  7007. #endif
  7008. #ifdef CPPHTTPLIB_SSL_ENABLED
  7009. SSLClient cli(host);
  7010. #else
  7011. Client cli(host);
  7012. #endif
  7013. cli.set_default_headers({make_range_header({{1, 10}})});
  7014. cli.set_connection_timeout(5);
  7015. {
  7016. auto res = cli.Get(path);
  7017. ASSERT_TRUE(res);
  7018. EXPECT_EQ("bcdefghijk", res->body);
  7019. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7020. }
  7021. {
  7022. auto res = cli.Get(path);
  7023. ASSERT_TRUE(res);
  7024. EXPECT_EQ("bcdefghijk", res->body);
  7025. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7026. }
  7027. }
  7028. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7029. Server svr;
  7030. svr.set_default_headers({{"Hello", "World"}});
  7031. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7032. res.set_content("ok", "text/plain");
  7033. });
  7034. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7035. auto se = detail::scope_exit([&] {
  7036. svr.stop();
  7037. listen_thread.join();
  7038. ASSERT_FALSE(svr.is_running());
  7039. });
  7040. svr.wait_until_ready();
  7041. Client cli("localhost", PORT);
  7042. auto res = cli.Get("/");
  7043. ASSERT_TRUE(res);
  7044. EXPECT_EQ(StatusCode::OK_200, res->status);
  7045. EXPECT_EQ("ok", res->body);
  7046. EXPECT_EQ("World", res->get_header_value("Hello"));
  7047. }
  7048. #ifdef CPPHTTPLIB_SSL_ENABLED
  7049. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7050. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7051. ASSERT_TRUE(svr.is_valid());
  7052. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7053. std::this_thread::sleep_for(std::chrono::seconds(2));
  7054. res.set_content("a", "text/plain");
  7055. });
  7056. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7057. res.set_content("b", "text/plain");
  7058. });
  7059. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7060. auto se = detail::scope_exit([&] {
  7061. svr.stop();
  7062. listen_thread.join();
  7063. ASSERT_FALSE(svr.is_running());
  7064. });
  7065. svr.wait_until_ready();
  7066. SSLClient cli("localhost", PORT);
  7067. cli.enable_server_certificate_verification(false);
  7068. cli.set_keep_alive(true);
  7069. cli.set_read_timeout(std::chrono::seconds(1));
  7070. auto resa = cli.Get("/a");
  7071. ASSERT_TRUE(!resa);
  7072. EXPECT_EQ(Error::Read, resa.error());
  7073. auto resb = cli.Get("/b");
  7074. ASSERT_TRUE(resb);
  7075. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7076. EXPECT_EQ("b", resb->body);
  7077. }
  7078. #endif
  7079. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7080. protected:
  7081. ServerTestWithAI_PASSIVE()
  7082. : cli_(HOST, PORT)
  7083. #ifdef CPPHTTPLIB_SSL_ENABLED
  7084. ,
  7085. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7086. #endif
  7087. {
  7088. #ifdef CPPHTTPLIB_SSL_ENABLED
  7089. cli_.enable_server_certificate_verification(false);
  7090. #endif
  7091. }
  7092. virtual void SetUp() {
  7093. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7094. res.set_content("Hello World!", "text/plain");
  7095. });
  7096. t_ = thread(
  7097. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7098. svr_.wait_until_ready();
  7099. }
  7100. virtual void TearDown() {
  7101. svr_.stop();
  7102. t_.join();
  7103. }
  7104. #ifdef CPPHTTPLIB_SSL_ENABLED
  7105. SSLClient cli_;
  7106. SSLServer svr_;
  7107. #else
  7108. Client cli_;
  7109. Server svr_;
  7110. #endif
  7111. thread t_;
  7112. };
  7113. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7114. auto res = cli_.Get("/hi");
  7115. ASSERT_TRUE(res);
  7116. EXPECT_EQ(StatusCode::OK_200, res->status);
  7117. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7118. EXPECT_EQ("Hello World!", res->body);
  7119. }
  7120. class ServerUpDownTest : public ::testing::Test {
  7121. protected:
  7122. ServerUpDownTest() : cli_(HOST, PORT) {}
  7123. virtual void SetUp() {
  7124. t_ = thread([&]() {
  7125. svr_.bind_to_any_port(HOST);
  7126. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7127. ASSERT_TRUE(svr_.listen_after_bind());
  7128. });
  7129. svr_.wait_until_ready();
  7130. }
  7131. virtual void TearDown() {
  7132. svr_.stop();
  7133. t_.join();
  7134. }
  7135. Client cli_;
  7136. Server svr_;
  7137. thread t_;
  7138. };
  7139. TEST_F(ServerUpDownTest, QuickStartStop) {
  7140. // Should not crash, especially when run with
  7141. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7142. }
  7143. class PayloadMaxLengthTest : public ::testing::Test {
  7144. protected:
  7145. PayloadMaxLengthTest()
  7146. : cli_(HOST, PORT)
  7147. #ifdef CPPHTTPLIB_SSL_ENABLED
  7148. ,
  7149. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7150. #endif
  7151. {
  7152. #ifdef CPPHTTPLIB_SSL_ENABLED
  7153. cli_.enable_server_certificate_verification(false);
  7154. #endif
  7155. }
  7156. virtual void SetUp() {
  7157. svr_.set_payload_max_length(8);
  7158. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7159. res.set_content("test", "text/plain");
  7160. });
  7161. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7162. svr_.wait_until_ready();
  7163. }
  7164. virtual void TearDown() {
  7165. svr_.stop();
  7166. t_.join();
  7167. }
  7168. #ifdef CPPHTTPLIB_SSL_ENABLED
  7169. SSLClient cli_;
  7170. SSLServer svr_;
  7171. #else
  7172. Client cli_;
  7173. Server svr_;
  7174. #endif
  7175. thread t_;
  7176. };
  7177. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7178. auto res = cli_.Post("/test", "123456789", "text/plain");
  7179. ASSERT_TRUE(res);
  7180. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7181. res = cli_.Post("/test", "12345678", "text/plain");
  7182. ASSERT_TRUE(res);
  7183. EXPECT_EQ(StatusCode::OK_200, res->status);
  7184. }
  7185. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7186. // Test chunked encoding with payload exceeding the 8-byte limit
  7187. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7188. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7189. ASSERT_TRUE(res);
  7190. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7191. }
  7192. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7193. // Test chunked encoding with payload within the 8-byte limit
  7194. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7195. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7196. ASSERT_TRUE(res);
  7197. EXPECT_EQ(StatusCode::OK_200, res->status);
  7198. }
  7199. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7200. // Test using send_request to send chunked data exceeding payload limit
  7201. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7202. "Host: " +
  7203. std::string(HOST) + ":" + std::to_string(PORT) +
  7204. "\r\n"
  7205. "Transfer-Encoding: chunked\r\n"
  7206. "Connection: close\r\n"
  7207. "\r\n"
  7208. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7209. "0123456789\r\n"
  7210. "0\r\n" // End chunk
  7211. "\r\n";
  7212. std::string response;
  7213. bool result = send_request(1, chunked_request, &response);
  7214. if (!result) {
  7215. // If send_request fails, it might be because the server closed the
  7216. // connection due to payload limit enforcement, which is acceptable
  7217. SUCCEED()
  7218. << "Server rejected oversized chunked request (connection closed)";
  7219. } else {
  7220. // If we got a response, check if it's an error response or connection was
  7221. // closed early Short response length indicates connection was closed due to
  7222. // payload limit
  7223. if (response.length() <= 10) {
  7224. SUCCEED() << "Server closed connection for oversized chunked request";
  7225. } else {
  7226. // Check for error status codes
  7227. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7228. response.find("Payload Too Large") != std::string::npos ||
  7229. response.find("400") != std::string::npos);
  7230. }
  7231. }
  7232. }
  7233. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7234. // Test request without Content-Length header exceeding payload limit
  7235. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7236. "Host: " +
  7237. std::string(HOST) + ":" +
  7238. std::to_string(PORT) +
  7239. "\r\n"
  7240. "Connection: close\r\n"
  7241. "\r\n";
  7242. // Add payload exceeding the 8-byte limit
  7243. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7244. request_without_content_length += large_payload;
  7245. std::string response;
  7246. bool result = send_request(1, request_without_content_length, &response);
  7247. if (!result) {
  7248. // If send_request fails, server likely closed connection due to payload
  7249. // limit
  7250. SUCCEED() << "Server rejected oversized request without Content-Length "
  7251. "(connection closed)";
  7252. } else {
  7253. // Check if server responded with error or closed connection early
  7254. if (response.length() <= 10) {
  7255. SUCCEED() << "Server closed connection for oversized request without "
  7256. "Content-Length";
  7257. } else {
  7258. // Check for error status codes
  7259. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7260. response.find("Payload Too Large") != std::string::npos ||
  7261. response.find("400") != std::string::npos);
  7262. }
  7263. }
  7264. }
  7265. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7266. // Test request without Content-Length header within payload limit
  7267. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7268. "Host: " +
  7269. std::string(HOST) + ":" +
  7270. std::to_string(PORT) +
  7271. "\r\n"
  7272. "Connection: close\r\n"
  7273. "\r\n";
  7274. // Add payload within the 8-byte limit
  7275. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7276. request_without_content_length += small_payload;
  7277. std::string response;
  7278. bool result = send_request(1, request_without_content_length, &response);
  7279. // For requests without Content-Length, the server may have different behavior
  7280. // The key is that it should not reject due to payload limit for small
  7281. // payloads
  7282. if (result) {
  7283. // Check for any HTTP response (success or error, but not connection closed)
  7284. if (response.length() > 10) {
  7285. SUCCEED()
  7286. << "Server processed request without Content-Length within limit";
  7287. } else {
  7288. // Short response might indicate connection closed, which is acceptable
  7289. SUCCEED() << "Server closed connection for request without "
  7290. "Content-Length (acceptable behavior)";
  7291. }
  7292. } else {
  7293. // Connection failure might be due to protocol requirements
  7294. SUCCEED() << "Connection issue with request without Content-Length "
  7295. "(environment-specific)";
  7296. }
  7297. }
  7298. class LargePayloadMaxLengthTest : public ::testing::Test {
  7299. protected:
  7300. LargePayloadMaxLengthTest()
  7301. : cli_(HOST, PORT)
  7302. #ifdef CPPHTTPLIB_SSL_ENABLED
  7303. ,
  7304. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7305. #endif
  7306. {
  7307. #ifdef CPPHTTPLIB_SSL_ENABLED
  7308. cli_.enable_server_certificate_verification(false);
  7309. #endif
  7310. }
  7311. virtual void SetUp() {
  7312. // Set 10MB payload limit
  7313. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7314. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7315. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7316. res.set_content("Large payload test", "text/plain");
  7317. });
  7318. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7319. svr_.wait_until_ready();
  7320. }
  7321. virtual void TearDown() {
  7322. svr_.stop();
  7323. t_.join();
  7324. }
  7325. #ifdef CPPHTTPLIB_SSL_ENABLED
  7326. SSLClient cli_;
  7327. SSLServer svr_;
  7328. #else
  7329. Client cli_;
  7330. Server svr_;
  7331. #endif
  7332. thread t_;
  7333. };
  7334. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7335. // Test chunked encoding with payload within 10MB limit
  7336. std::string medium_payload(5 * 1024 * 1024,
  7337. 'A'); // 5MB payload, within 10MB limit
  7338. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7339. ASSERT_TRUE(res);
  7340. EXPECT_EQ(StatusCode::OK_200, res->status);
  7341. }
  7342. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7343. // Test chunked encoding with payload exceeding 10MB limit
  7344. std::string large_payload(12 * 1024 * 1024,
  7345. 'B'); // 12MB payload, exceeds 10MB limit
  7346. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7347. // Server may either return 413 or close the connection
  7348. if (res) {
  7349. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7350. } else {
  7351. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7352. }
  7353. }
  7354. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7355. // Test request without Content-Length header within 10MB limit
  7356. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7357. "Host: " +
  7358. std::string(HOST) + ":" +
  7359. std::to_string(PORT) +
  7360. "\r\n"
  7361. "Connection: close\r\n"
  7362. "\r\n";
  7363. // Add 1MB payload (within 10MB limit)
  7364. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7365. request_without_content_length += medium_payload;
  7366. std::string response;
  7367. bool result = send_request(5, request_without_content_length, &response);
  7368. if (result) {
  7369. // Should get a proper HTTP response for payloads within limit
  7370. if (response.length() > 10) {
  7371. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7372. "10MB limit";
  7373. } else {
  7374. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7375. "Content-Length)";
  7376. }
  7377. } else {
  7378. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7379. }
  7380. }
  7381. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7382. // Test request without Content-Length header exceeding 10MB limit
  7383. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7384. "Host: " +
  7385. std::string(HOST) + ":" +
  7386. std::to_string(PORT) +
  7387. "\r\n"
  7388. "Connection: close\r\n"
  7389. "\r\n";
  7390. // Add 12MB payload (exceeds 10MB limit)
  7391. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7392. request_without_content_length += large_payload;
  7393. std::string response;
  7394. bool result = send_request(10, request_without_content_length, &response);
  7395. if (!result) {
  7396. // Server should close connection due to payload limit
  7397. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7398. "(connection closed)";
  7399. } else {
  7400. // Check for error response
  7401. if (response.length() <= 10) {
  7402. SUCCEED()
  7403. << "Server closed connection for 12MB request exceeding 10MB limit";
  7404. } else {
  7405. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7406. response.find("Payload Too Large") != std::string::npos ||
  7407. response.find("400") != std::string::npos);
  7408. }
  7409. }
  7410. }
  7411. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7412. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7413. // path.
  7414. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7415. Server svr;
  7416. const size_t LIMIT = 64 * 1024; // 64KB
  7417. svr.set_payload_max_length(LIMIT);
  7418. size_t total = 0;
  7419. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7420. const ContentReader &content_reader) {
  7421. content_reader([&](const char * /*data*/, size_t len) {
  7422. total += len;
  7423. return true;
  7424. });
  7425. res.status = 200;
  7426. res.set_content("stream_ok", "text/plain");
  7427. });
  7428. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7429. auto se = detail::scope_exit([&] {
  7430. svr.stop();
  7431. thread.join();
  7432. ASSERT_FALSE(svr.is_running());
  7433. });
  7434. svr.wait_until_ready();
  7435. // Prepare 256KB raw data and gzip-compress it
  7436. std::string raw(256 * 1024, 'A');
  7437. std::string gz;
  7438. {
  7439. z_stream zs{};
  7440. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7441. Z_DEFAULT_STRATEGY);
  7442. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7443. zs.avail_in = static_cast<uInt>(raw.size());
  7444. char outbuf[4096];
  7445. int ret;
  7446. do {
  7447. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7448. zs.avail_out = sizeof(outbuf);
  7449. ret = deflate(&zs, Z_FINISH);
  7450. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7451. } while (ret != Z_STREAM_END);
  7452. deflateEnd(&zs);
  7453. }
  7454. Client cli(HOST, PORT);
  7455. cli.set_connection_timeout(std::chrono::seconds(5));
  7456. Headers headers = {{"Content-Encoding", "gzip"}};
  7457. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7458. "application/octet-stream");
  7459. ASSERT_TRUE(res);
  7460. // Server must reject oversized decompressed payloads with 413.
  7461. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7462. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7463. EXPECT_LE(total, LIMIT);
  7464. }
  7465. #endif
  7466. // Regression test for DoS vulnerability: a malicious server sending a response
  7467. // without Content-Length header must not cause unbounded memory consumption on
  7468. // the client side. The client should stop reading after a reasonable limit,
  7469. // similar to the server-side set_payload_max_length protection.
  7470. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7471. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7472. #ifndef _WIN32
  7473. signal(SIGPIPE, SIG_IGN);
  7474. #endif
  7475. auto server_thread = std::thread([] {
  7476. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7477. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7478. default_socket_options(srv);
  7479. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7480. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7481. sockaddr_in addr{};
  7482. addr.sin_family = AF_INET;
  7483. addr.sin_port = htons(PORT + 2);
  7484. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7485. int opt = 1;
  7486. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7487. #ifdef _WIN32
  7488. reinterpret_cast<const char *>(&opt),
  7489. #else
  7490. &opt,
  7491. #endif
  7492. sizeof(opt));
  7493. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7494. ::listen(srv, 1);
  7495. sockaddr_in cli_addr{};
  7496. socklen_t cli_len = sizeof(cli_addr);
  7497. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7498. if (cli != INVALID_SOCKET) {
  7499. char buf[4096];
  7500. ::recv(cli, buf, sizeof(buf), 0);
  7501. // Malicious response: no Content-Length, no chunked encoding
  7502. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7503. "Connection: close\r\n"
  7504. "\r\n";
  7505. ::send(cli,
  7506. #ifdef _WIN32
  7507. static_cast<const char *>(response_header.c_str()),
  7508. static_cast<int>(response_header.size()),
  7509. #else
  7510. response_header.c_str(), response_header.size(),
  7511. #endif
  7512. 0);
  7513. // Send 10MB of data
  7514. std::string chunk(64 * 1024, 'A');
  7515. size_t total_sent = 0;
  7516. while (total_sent < MALICIOUS_DATA_SIZE) {
  7517. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7518. auto sent = ::send(cli,
  7519. #ifdef _WIN32
  7520. static_cast<const char *>(chunk.c_str()),
  7521. static_cast<int>(to_send),
  7522. #else
  7523. chunk.c_str(), to_send,
  7524. #endif
  7525. 0);
  7526. if (sent <= 0) break;
  7527. total_sent += static_cast<size_t>(sent);
  7528. }
  7529. detail::close_socket(cli);
  7530. }
  7531. detail::close_socket(srv);
  7532. });
  7533. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7534. size_t total_read = 0;
  7535. {
  7536. Client cli("127.0.0.1", PORT + 2);
  7537. cli.set_read_timeout(5, 0);
  7538. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7539. auto stream = cli.open_stream("GET", "/malicious");
  7540. ASSERT_TRUE(stream.is_valid());
  7541. char buffer[64 * 1024];
  7542. ssize_t n;
  7543. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7544. total_read += static_cast<size_t>(n);
  7545. }
  7546. } // StreamHandle and Client destroyed here, closing the socket
  7547. server_thread.join();
  7548. // With set_payload_max_length, the client must stop reading before consuming
  7549. // all 10MB. The read loop should be cut off at or near the configured limit.
  7550. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7551. << "Client read " << total_read << " bytes, exceeding the configured "
  7552. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7553. }
  7554. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7555. // the entire response body without truncation.
  7556. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7557. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7558. #ifndef _WIN32
  7559. signal(SIGPIPE, SIG_IGN);
  7560. #endif
  7561. auto server_thread = std::thread([] {
  7562. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7563. default_socket_options(srv);
  7564. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7565. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7566. sockaddr_in addr{};
  7567. addr.sin_family = AF_INET;
  7568. addr.sin_port = htons(PORT + 2);
  7569. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7570. int opt = 1;
  7571. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7572. #ifdef _WIN32
  7573. reinterpret_cast<const char *>(&opt),
  7574. #else
  7575. &opt,
  7576. #endif
  7577. sizeof(opt));
  7578. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7579. ::listen(srv, 1);
  7580. sockaddr_in cli_addr{};
  7581. socklen_t cli_len = sizeof(cli_addr);
  7582. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7583. if (cli != INVALID_SOCKET) {
  7584. char buf[4096];
  7585. ::recv(cli, buf, sizeof(buf), 0);
  7586. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7587. "Connection: close\r\n"
  7588. "\r\n";
  7589. ::send(cli,
  7590. #ifdef _WIN32
  7591. static_cast<const char *>(response_header.c_str()),
  7592. static_cast<int>(response_header.size()),
  7593. #else
  7594. response_header.c_str(), response_header.size(),
  7595. #endif
  7596. 0);
  7597. std::string chunk(64 * 1024, 'A');
  7598. size_t total_sent = 0;
  7599. while (total_sent < DATA_SIZE) {
  7600. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7601. auto sent = ::send(cli,
  7602. #ifdef _WIN32
  7603. static_cast<const char *>(chunk.c_str()),
  7604. static_cast<int>(to_send),
  7605. #else
  7606. chunk.c_str(), to_send,
  7607. #endif
  7608. 0);
  7609. if (sent <= 0) break;
  7610. total_sent += static_cast<size_t>(sent);
  7611. }
  7612. #ifdef _WIN32
  7613. ::shutdown(cli, SD_SEND);
  7614. #else
  7615. ::shutdown(cli, SHUT_WR);
  7616. #endif
  7617. // Drain until the client closes its end, ensuring all data is delivered
  7618. char drain[1024];
  7619. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7620. detail::close_socket(cli);
  7621. }
  7622. detail::close_socket(srv);
  7623. });
  7624. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7625. size_t total_read = 0;
  7626. {
  7627. Client cli("127.0.0.1", PORT + 2);
  7628. cli.set_read_timeout(5, 0);
  7629. cli.set_payload_max_length(0); // 0 means no limit
  7630. auto stream = cli.open_stream("GET", "/data");
  7631. ASSERT_TRUE(stream.is_valid());
  7632. char buffer[64 * 1024];
  7633. ssize_t n;
  7634. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7635. total_read += static_cast<size_t>(n);
  7636. }
  7637. }
  7638. server_thread.join();
  7639. EXPECT_EQ(total_read, DATA_SIZE)
  7640. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7641. << " bytes without truncation, but only read " << total_read << " bytes.";
  7642. }
  7643. // Verify that content_receiver bypasses the default payload_max_length,
  7644. // allowing streaming downloads larger than 100MB without requiring an explicit
  7645. // set_payload_max_length call.
  7646. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  7647. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7648. #ifndef _WIN32
  7649. signal(SIGPIPE, SIG_IGN);
  7650. #endif
  7651. auto server_thread = std::thread([] {
  7652. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7653. default_socket_options(srv);
  7654. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7655. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7656. sockaddr_in addr{};
  7657. addr.sin_family = AF_INET;
  7658. addr.sin_port = htons(PORT + 2);
  7659. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7660. int opt = 1;
  7661. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7662. #ifdef _WIN32
  7663. reinterpret_cast<const char *>(&opt),
  7664. #else
  7665. &opt,
  7666. #endif
  7667. sizeof(opt));
  7668. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7669. ::listen(srv, 1);
  7670. sockaddr_in cli_addr{};
  7671. socklen_t cli_len = sizeof(cli_addr);
  7672. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7673. if (cli != INVALID_SOCKET) {
  7674. char buf[4096];
  7675. ::recv(cli, buf, sizeof(buf), 0);
  7676. // Response with Content-Length larger than default 100MB limit
  7677. auto content_length = std::to_string(DATA_SIZE);
  7678. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7679. "Content-Length: " +
  7680. content_length +
  7681. "\r\n"
  7682. "Connection: close\r\n"
  7683. "\r\n";
  7684. ::send(cli,
  7685. #ifdef _WIN32
  7686. static_cast<const char *>(response_header.c_str()),
  7687. static_cast<int>(response_header.size()),
  7688. #else
  7689. response_header.c_str(), response_header.size(),
  7690. #endif
  7691. 0);
  7692. std::string chunk(64 * 1024, 'A');
  7693. size_t total_sent = 0;
  7694. while (total_sent < DATA_SIZE) {
  7695. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7696. auto sent = ::send(cli,
  7697. #ifdef _WIN32
  7698. static_cast<const char *>(chunk.c_str()),
  7699. static_cast<int>(to_send),
  7700. #else
  7701. chunk.c_str(), to_send,
  7702. #endif
  7703. 0);
  7704. if (sent <= 0) break;
  7705. total_sent += static_cast<size_t>(sent);
  7706. }
  7707. detail::close_socket(cli);
  7708. }
  7709. detail::close_socket(srv);
  7710. });
  7711. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7712. size_t total_received = 0;
  7713. {
  7714. Client cli("127.0.0.1", PORT + 2);
  7715. cli.set_read_timeout(10, 0);
  7716. // Do NOT call set_payload_max_length — use the default 100MB limit
  7717. auto res =
  7718. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7719. total_received += data_length;
  7720. return true;
  7721. });
  7722. ASSERT_TRUE(res);
  7723. EXPECT_EQ(StatusCode::OK_200, res->status);
  7724. }
  7725. server_thread.join();
  7726. EXPECT_EQ(total_received, DATA_SIZE)
  7727. << "With content_receiver, the client should read all " << DATA_SIZE
  7728. << " bytes despite the default 100MB payload_max_length, but only read "
  7729. << total_received << " bytes.";
  7730. }
  7731. // Verify that an explicit set_payload_max_length smaller than the response is
  7732. // enforced even when a content_receiver is used.
  7733. TEST(ClientVulnerabilityTest,
  7734. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  7735. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7736. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  7737. #ifndef _WIN32
  7738. signal(SIGPIPE, SIG_IGN);
  7739. #endif
  7740. auto server_thread = std::thread([] {
  7741. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7742. default_socket_options(srv);
  7743. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7744. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7745. sockaddr_in addr{};
  7746. addr.sin_family = AF_INET;
  7747. addr.sin_port = htons(PORT + 2);
  7748. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7749. int opt = 1;
  7750. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7751. #ifdef _WIN32
  7752. reinterpret_cast<const char *>(&opt),
  7753. #else
  7754. &opt,
  7755. #endif
  7756. sizeof(opt));
  7757. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7758. ::listen(srv, 1);
  7759. sockaddr_in cli_addr{};
  7760. socklen_t cli_len = sizeof(cli_addr);
  7761. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7762. if (cli != INVALID_SOCKET) {
  7763. char buf[4096];
  7764. ::recv(cli, buf, sizeof(buf), 0);
  7765. auto content_length = std::to_string(DATA_SIZE);
  7766. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7767. "Content-Length: " +
  7768. content_length +
  7769. "\r\n"
  7770. "Connection: close\r\n"
  7771. "\r\n";
  7772. ::send(cli,
  7773. #ifdef _WIN32
  7774. static_cast<const char *>(response_header.c_str()),
  7775. static_cast<int>(response_header.size()),
  7776. #else
  7777. response_header.c_str(), response_header.size(),
  7778. #endif
  7779. 0);
  7780. std::string chunk(64 * 1024, 'A');
  7781. size_t total_sent = 0;
  7782. while (total_sent < DATA_SIZE) {
  7783. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7784. auto sent = ::send(cli,
  7785. #ifdef _WIN32
  7786. static_cast<const char *>(chunk.c_str()),
  7787. static_cast<int>(to_send),
  7788. #else
  7789. chunk.c_str(), to_send,
  7790. #endif
  7791. 0);
  7792. if (sent <= 0) break;
  7793. total_sent += static_cast<size_t>(sent);
  7794. }
  7795. detail::close_socket(cli);
  7796. }
  7797. detail::close_socket(srv);
  7798. });
  7799. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7800. size_t total_received = 0;
  7801. {
  7802. Client cli("127.0.0.1", PORT + 2);
  7803. cli.set_read_timeout(10, 0);
  7804. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  7805. auto res =
  7806. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7807. total_received += data_length;
  7808. return true;
  7809. });
  7810. // Should fail because 200MB exceeds the explicit 150MB limit
  7811. EXPECT_FALSE(res);
  7812. }
  7813. server_thread.join();
  7814. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  7815. << "Client with content_receiver should respect the explicit "
  7816. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  7817. << total_received << " bytes.";
  7818. }
  7819. // Verify that an explicit set_payload_max_length larger than the response
  7820. // allows the content_receiver to read all data successfully.
  7821. TEST(ClientVulnerabilityTest,
  7822. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  7823. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7824. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  7825. #ifndef _WIN32
  7826. signal(SIGPIPE, SIG_IGN);
  7827. #endif
  7828. auto server_thread = std::thread([] {
  7829. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7830. default_socket_options(srv);
  7831. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7832. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7833. sockaddr_in addr{};
  7834. addr.sin_family = AF_INET;
  7835. addr.sin_port = htons(PORT + 2);
  7836. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7837. int opt = 1;
  7838. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7839. #ifdef _WIN32
  7840. reinterpret_cast<const char *>(&opt),
  7841. #else
  7842. &opt,
  7843. #endif
  7844. sizeof(opt));
  7845. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7846. ::listen(srv, 1);
  7847. sockaddr_in cli_addr{};
  7848. socklen_t cli_len = sizeof(cli_addr);
  7849. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7850. if (cli != INVALID_SOCKET) {
  7851. char buf[4096];
  7852. ::recv(cli, buf, sizeof(buf), 0);
  7853. auto content_length = std::to_string(DATA_SIZE);
  7854. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7855. "Content-Length: " +
  7856. content_length +
  7857. "\r\n"
  7858. "Connection: close\r\n"
  7859. "\r\n";
  7860. ::send(cli,
  7861. #ifdef _WIN32
  7862. static_cast<const char *>(response_header.c_str()),
  7863. static_cast<int>(response_header.size()),
  7864. #else
  7865. response_header.c_str(), response_header.size(),
  7866. #endif
  7867. 0);
  7868. std::string chunk(64 * 1024, 'A');
  7869. size_t total_sent = 0;
  7870. while (total_sent < DATA_SIZE) {
  7871. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7872. auto sent = ::send(cli,
  7873. #ifdef _WIN32
  7874. static_cast<const char *>(chunk.c_str()),
  7875. static_cast<int>(to_send),
  7876. #else
  7877. chunk.c_str(), to_send,
  7878. #endif
  7879. 0);
  7880. if (sent <= 0) break;
  7881. total_sent += static_cast<size_t>(sent);
  7882. }
  7883. #ifdef _WIN32
  7884. ::shutdown(cli, SD_SEND);
  7885. #else
  7886. ::shutdown(cli, SHUT_WR);
  7887. #endif
  7888. char drain[1024];
  7889. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7890. detail::close_socket(cli);
  7891. }
  7892. detail::close_socket(srv);
  7893. });
  7894. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7895. size_t total_received = 0;
  7896. {
  7897. Client cli("127.0.0.1", PORT + 2);
  7898. cli.set_read_timeout(10, 0);
  7899. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  7900. auto res =
  7901. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7902. total_received += data_length;
  7903. return true;
  7904. });
  7905. ASSERT_TRUE(res);
  7906. EXPECT_EQ(StatusCode::OK_200, res->status);
  7907. }
  7908. server_thread.join();
  7909. EXPECT_EQ(total_received, DATA_SIZE)
  7910. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  7911. << " bytes (larger than " << DATA_SIZE
  7912. << " bytes response), content_receiver should read all data, but only "
  7913. "read "
  7914. << total_received << " bytes.";
  7915. }
  7916. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  7917. // Regression test for "zip bomb" attack on the client side: a malicious server
  7918. // sends a small gzip-compressed response that decompresses to a huge payload.
  7919. // The client must enforce payload_max_length on the decompressed size.
  7920. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  7921. constexpr size_t DECOMPRESSED_SIZE =
  7922. 10 * 1024 * 1024; // 10MB after decompression
  7923. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7924. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  7925. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  7926. std::string compressed;
  7927. {
  7928. httplib::detail::gzip_compressor compressor;
  7929. bool ok =
  7930. compressor.compress(uncompressed.data(), uncompressed.size(),
  7931. /*last=*/true, [&](const char *buf, size_t len) {
  7932. compressed.append(buf, len);
  7933. return true;
  7934. });
  7935. ASSERT_TRUE(ok);
  7936. }
  7937. // Sanity: compressed data should be much smaller than the decompressed size
  7938. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  7939. #ifndef _WIN32
  7940. signal(SIGPIPE, SIG_IGN);
  7941. #endif
  7942. // Set up the listening socket in the main thread so the server is guaranteed
  7943. // to be ready before the client connects (eliminates race condition).
  7944. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7945. default_socket_options(srv);
  7946. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7947. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7948. sockaddr_in addr{};
  7949. addr.sin_family = AF_INET;
  7950. addr.sin_port = htons(PORT + 3);
  7951. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7952. int opt = 1;
  7953. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7954. #ifdef _WIN32
  7955. reinterpret_cast<const char *>(&opt),
  7956. #else
  7957. &opt,
  7958. #endif
  7959. sizeof(opt));
  7960. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  7961. ASSERT_EQ(0, ::listen(srv, 1));
  7962. auto server_thread = std::thread([&compressed, srv] {
  7963. sockaddr_in cli_addr{};
  7964. socklen_t cli_len = sizeof(cli_addr);
  7965. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7966. if (cli != INVALID_SOCKET) {
  7967. // Read the full HTTP request (until \r\n\r\n)
  7968. char buf[4096];
  7969. size_t total = 0;
  7970. while (total < sizeof(buf)) {
  7971. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  7972. if (n <= 0) break;
  7973. total += static_cast<size_t>(n);
  7974. // Check for end of headers
  7975. if (total >= 4) {
  7976. std::string req(buf, total);
  7977. if (req.find("\r\n\r\n") != std::string::npos) break;
  7978. }
  7979. }
  7980. // Malicious response: gzip-compressed body, no Content-Length
  7981. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7982. "Content-Encoding: gzip\r\n"
  7983. "Connection: close\r\n"
  7984. "\r\n";
  7985. ::send(cli,
  7986. #ifdef _WIN32
  7987. static_cast<const char *>(response_header.c_str()),
  7988. static_cast<int>(response_header.size()),
  7989. #else
  7990. response_header.c_str(), response_header.size(),
  7991. #endif
  7992. 0);
  7993. // Send the compressed payload (small on the wire, huge when decompressed)
  7994. size_t total_sent = 0;
  7995. while (total_sent < compressed.size()) {
  7996. auto to_send = std::min(compressed.size() - total_sent,
  7997. static_cast<size_t>(64 * 1024));
  7998. auto sent =
  7999. ::send(cli,
  8000. #ifdef _WIN32
  8001. static_cast<const char *>(compressed.c_str() + total_sent),
  8002. static_cast<int>(to_send),
  8003. #else
  8004. compressed.c_str() + total_sent, to_send,
  8005. #endif
  8006. 0);
  8007. if (sent <= 0) break;
  8008. total_sent += static_cast<size_t>(sent);
  8009. }
  8010. detail::close_socket(cli);
  8011. }
  8012. });
  8013. auto se = detail::scope_exit([&] {
  8014. detail::close_socket(srv);
  8015. server_thread.join();
  8016. });
  8017. size_t total_decompressed = 0;
  8018. {
  8019. Client cli("127.0.0.1", PORT + 3);
  8020. cli.set_read_timeout(5, 0);
  8021. cli.set_decompress(true);
  8022. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8023. auto stream = cli.open_stream("GET", "/zipbomb");
  8024. ASSERT_TRUE(stream.is_valid());
  8025. char buffer[64 * 1024];
  8026. ssize_t n;
  8027. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8028. total_decompressed += static_cast<size_t>(n);
  8029. }
  8030. }
  8031. // The decompressed size must be capped by payload_max_length. Without
  8032. // protection, the client would decompress the full 10MB from a tiny
  8033. // compressed payload, enabling a zip bomb DoS attack.
  8034. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8035. << "Client decompressed " << total_decompressed
  8036. << " bytes from a gzip response. The decompressed size should be "
  8037. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8038. }
  8039. #endif
  8040. TEST(HostAndPortPropertiesTest, NoSSL) {
  8041. httplib::Client cli("www.google.com", 1234);
  8042. ASSERT_EQ("www.google.com", cli.host());
  8043. ASSERT_EQ(1234, cli.port());
  8044. }
  8045. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8046. httplib::Client cli("www.google.com:1234");
  8047. ASSERT_EQ("www.google.com", cli.host());
  8048. ASSERT_EQ(1234, cli.port());
  8049. }
  8050. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8051. // Port number that overflows int — should not crash, client becomes invalid
  8052. httplib::Client cli("http://www.google.com:99999999999999999999");
  8053. ASSERT_FALSE(cli.is_valid());
  8054. }
  8055. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8056. // Port 99999 exceeds valid range (1-65535) — should not crash
  8057. httplib::Client cli("http://www.google.com:99999");
  8058. ASSERT_FALSE(cli.is_valid());
  8059. }
  8060. #ifdef CPPHTTPLIB_SSL_ENABLED
  8061. TEST(HostAndPortPropertiesTest, SSL) {
  8062. httplib::SSLClient cli("www.google.com");
  8063. ASSERT_EQ("www.google.com", cli.host());
  8064. ASSERT_EQ(443, cli.port());
  8065. }
  8066. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8067. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8068. std::string cert;
  8069. read_file(CA_CERT_FILE, cert);
  8070. httplib::SSLClient httplib_client("www.google.com");
  8071. // Load CA store first time
  8072. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8073. // Load CA store second time (update)
  8074. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8075. // Verify client is still valid and can make connections
  8076. httplib_client.enable_server_certificate_verification(true);
  8077. auto res = httplib_client.Get("/");
  8078. ASSERT_TRUE(res);
  8079. // Google may return 200 or 301 depending on various factors
  8080. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8081. res->status == StatusCode::MovedPermanently_301);
  8082. }
  8083. TEST(SSLClientTest, ServerNameIndication_Online) {
  8084. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  8085. auto host = "httpcan.org";
  8086. auto path = std::string{"/get"};
  8087. #else
  8088. auto host = "nghttp2.org";
  8089. auto path = std::string{"/httpbin/get"};
  8090. #endif
  8091. SSLClient cli(host, 443);
  8092. auto res = cli.Get(path);
  8093. ASSERT_TRUE(res);
  8094. ASSERT_EQ(StatusCode::OK_200, res->status);
  8095. }
  8096. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8097. // Use a site that will cause SSL verification failure due to self-signed cert
  8098. SSLClient cli("self-signed.badssl.com", 443);
  8099. cli.enable_server_certificate_verification(true);
  8100. auto res = cli.Get("/");
  8101. ASSERT_TRUE(!res);
  8102. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8103. // Verify backend error is captured for SSLServerVerification
  8104. // This occurs when certificate verification fails
  8105. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8106. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8107. EXPECT_NE(0UL, res.ssl_backend_error());
  8108. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8109. // For OpenSSL, ssl_error is 0 for verification errors
  8110. EXPECT_EQ(0, res.ssl_error());
  8111. #if !defined(_WIN32) || \
  8112. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8113. // On non-Windows or when Windows Schannel is disabled, the error comes
  8114. // from OpenSSL's verification
  8115. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8116. res.ssl_backend_error());
  8117. #endif
  8118. #endif
  8119. }
  8120. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8121. // Use a site where hostname doesn't match the certificate
  8122. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8123. SSLClient cli("wrong.host.badssl.com", 443);
  8124. cli.enable_server_certificate_verification(true);
  8125. cli.enable_server_hostname_verification(true);
  8126. auto res = cli.Get("/");
  8127. ASSERT_TRUE(!res);
  8128. // The error type depends on when hostname verification occurs:
  8129. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8130. // - Mbed TLS: SSLServerVerification (during handshake)
  8131. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8132. res.error() == Error::SSLServerVerification);
  8133. // Verify backend error is captured for hostname verification failure
  8134. EXPECT_NE(0UL, res.ssl_backend_error());
  8135. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8136. // For OpenSSL, ssl_error is 0 for verification errors
  8137. EXPECT_EQ(0, res.ssl_error());
  8138. #if !defined(_WIN32) || \
  8139. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8140. // On non-Windows or when Windows Schannel is disabled, the error comes
  8141. // from OpenSSL's hostname verification
  8142. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8143. res.ssl_backend_error());
  8144. #endif
  8145. #endif
  8146. }
  8147. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8148. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8149. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8150. SSLClient cli("www.google.com", 443);
  8151. cli.enable_server_certificate_verification(true);
  8152. auto res = cli.Get("/");
  8153. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8154. }
  8155. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8156. SSLClient cli("www.google.com", 443);
  8157. cli.enable_server_certificate_verification(true);
  8158. cli.enable_windows_certificate_verification(false);
  8159. auto res = cli.Get("/");
  8160. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8161. }
  8162. #endif
  8163. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8164. Client cli("https://google.com");
  8165. auto res = cli.Get("/");
  8166. ASSERT_TRUE(res);
  8167. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8168. }
  8169. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8170. SSLClient cli("google.com");
  8171. cli.set_ca_cert_path(CA_CERT_FILE);
  8172. auto res = cli.Get("/");
  8173. ASSERT_TRUE(res);
  8174. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8175. }
  8176. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8177. SSLClient cli("google.com");
  8178. cli.enable_server_certificate_verification(true);
  8179. cli.set_ca_cert_path("hello");
  8180. auto res = cli.Get("/");
  8181. ASSERT_TRUE(!res);
  8182. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8183. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8184. // should be set
  8185. EXPECT_EQ(0, res.ssl_error());
  8186. // Verify backend error is captured for SSLLoadingCerts
  8187. // This error occurs when loading CA certificates fails
  8188. EXPECT_NE(0UL, res.ssl_backend_error());
  8189. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8190. // OpenSSL specific error codes:
  8191. // > openssl errstr 0x80000002
  8192. // error:80000002:system library::No such file or directory
  8193. // > openssl errstr 0xA000126
  8194. // error:0A000126:SSL routines::unexpected eof while reading
  8195. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8196. res.ssl_backend_error() == 0xA000126);
  8197. #endif
  8198. }
  8199. TEST(SSLClientTest, ServerCertificateVerification4) {
  8200. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8201. ASSERT_TRUE(svr.is_valid());
  8202. svr.Get("/test", [&](const Request &, Response &res) {
  8203. res.set_content("test", "text/plain");
  8204. svr.stop();
  8205. ASSERT_TRUE(true);
  8206. });
  8207. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8208. auto se = detail::scope_exit([&] {
  8209. t.join();
  8210. ASSERT_FALSE(svr.is_running());
  8211. });
  8212. svr.wait_until_ready();
  8213. SSLClient cli("127.0.0.1", PORT);
  8214. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8215. cli.enable_server_certificate_verification(true);
  8216. cli.set_connection_timeout(30);
  8217. auto res = cli.Get("/test");
  8218. ASSERT_TRUE(res);
  8219. ASSERT_EQ(StatusCode::OK_200, res->status);
  8220. }
  8221. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8222. std::string cert;
  8223. read_file(CA_CERT_FILE, cert);
  8224. SSLClient cli("google.com");
  8225. cli.load_ca_cert_store(cert.data(), cert.size());
  8226. const auto res = cli.Get("/");
  8227. ASSERT_TRUE(res);
  8228. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8229. }
  8230. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8231. // clang-format off
  8232. static constexpr char cert[] =
  8233. "GlobalSign Root CA\n"
  8234. "==================\n"
  8235. "-----BEGIN CERTIFICATE-----\n"
  8236. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8237. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8238. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8239. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8240. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8241. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8242. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8243. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8244. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8245. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8246. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8247. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8248. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8249. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8250. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8251. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8252. "-----END CERTIFICATE-----\n";
  8253. // clang-format on
  8254. SSLClient cli("google.com");
  8255. cli.load_ca_cert_store(cert, sizeof(cert));
  8256. const auto res = cli.Get("/");
  8257. ASSERT_TRUE(res);
  8258. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8259. }
  8260. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8261. SSLClient cli("www.youtube.com");
  8262. cli.set_ca_cert_path(CA_CERT_FILE);
  8263. cli.enable_server_certificate_verification(true);
  8264. cli.set_follow_location(true);
  8265. auto res = cli.Get("/");
  8266. ASSERT_TRUE(res);
  8267. ASSERT_EQ(StatusCode::OK_200, res->status);
  8268. }
  8269. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8270. SSLClient cli("wWw.YouTube.Com");
  8271. cli.set_ca_cert_path(CA_CERT_FILE);
  8272. cli.enable_server_certificate_verification(true);
  8273. cli.enable_server_hostname_verification(true);
  8274. cli.set_follow_location(true);
  8275. auto res = cli.Get("/");
  8276. ASSERT_TRUE(res);
  8277. ASSERT_EQ(StatusCode::OK_200, res->status);
  8278. }
  8279. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8280. SSLClient cli("gOoGlE.COm");
  8281. cli.enable_server_certificate_verification(true);
  8282. cli.enable_server_hostname_verification(true);
  8283. cli.set_follow_location(true);
  8284. auto res = cli.Get("/");
  8285. ASSERT_TRUE(res);
  8286. ASSERT_EQ(StatusCode::OK_200, res->status);
  8287. }
  8288. TEST(SSLClientTest, Issue2004_Online) {
  8289. Client client("https://google.com");
  8290. client.set_follow_location(true);
  8291. auto res = client.Get("/");
  8292. ASSERT_TRUE(res);
  8293. ASSERT_EQ(StatusCode::OK_200, res->status);
  8294. auto body = res->body;
  8295. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8296. }
  8297. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8298. // Create SSLClient with invalid cert/key to make is_valid() return false
  8299. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8300. "nonexistent_key.pem");
  8301. // is_valid() should be false due to cert loading failure
  8302. ASSERT_FALSE(cli.is_valid());
  8303. auto res = cli.Get("/");
  8304. ASSERT_FALSE(res);
  8305. EXPECT_EQ(Error::SSLConnection, res.error());
  8306. }
  8307. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8308. // Test for Issue #2251: SSL error not properly reported when client cert
  8309. // and key paths are swapped or mismatched
  8310. // This simulates the scenario where user accidentally swaps the cert and key
  8311. // files
  8312. // Using client cert file as private key and vice versa (completely wrong)
  8313. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8314. // Should fail validation due to cert/key mismatch
  8315. ASSERT_FALSE(cli.is_valid());
  8316. // Attempt to make a request should fail with proper error
  8317. auto res = cli.Get("/");
  8318. ASSERT_FALSE(res);
  8319. EXPECT_EQ(Error::SSLConnection, res.error());
  8320. // SSL error should be recorded in the Result object (this is the key fix for
  8321. // Issue #2251)
  8322. auto backend_error = res.ssl_backend_error();
  8323. EXPECT_NE(0u, backend_error);
  8324. }
  8325. // Tests cert/key mismatch detection at the TLS context level
  8326. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8327. // Test that using mismatched cert/key causes connection failure.
  8328. // We verify this at the SSLClient level rather than through internal
  8329. // TLS API functions.
  8330. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8331. cli.enable_server_certificate_verification(false);
  8332. cli.set_connection_timeout(2);
  8333. // The mismatch should cause a connection or handshake error
  8334. auto res = cli.Get("/test");
  8335. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8336. // Either way, the request should fail
  8337. EXPECT_FALSE(res);
  8338. }
  8339. #endif
  8340. #if 0
  8341. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8342. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8343. ASSERT_TRUE(cli != nullptr);
  8344. cli->set_address_family(AF_INET6);
  8345. cli->set_interface("en0");
  8346. auto res = cli->Get("/get");
  8347. ASSERT_TRUE(res);
  8348. ASSERT_EQ(StatusCode::OK_200, res->status);
  8349. }
  8350. #endif
  8351. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8352. #ifdef CPPHTTPLIB_SSL_ENABLED
  8353. void ClientCertPresent(
  8354. const std::string &client_cert_file,
  8355. const std::string &client_private_key_file,
  8356. const std::string &client_encrypted_private_key_pass = std::string()) {
  8357. using namespace httplib::tls;
  8358. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8359. CLIENT_CA_CERT_DIR);
  8360. ASSERT_TRUE(svr.is_valid());
  8361. svr.Get("/test", [&](const Request &req, Response &res) {
  8362. res.set_content("test", "text/plain");
  8363. auto cert = req.peer_cert();
  8364. ASSERT_TRUE(static_cast<bool>(cert));
  8365. std::string common_name = cert.subject_cn();
  8366. EXPECT_EQ("Common Name", common_name);
  8367. });
  8368. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8369. auto se = detail::scope_exit([&] {
  8370. svr.stop();
  8371. t.join();
  8372. ASSERT_FALSE(svr.is_running());
  8373. });
  8374. svr.wait_until_ready();
  8375. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8376. client_encrypted_private_key_pass);
  8377. cli.enable_server_certificate_verification(false);
  8378. cli.set_connection_timeout(30);
  8379. auto res = cli.Get("/test");
  8380. ASSERT_TRUE(res);
  8381. ASSERT_EQ(StatusCode::OK_200, res->status);
  8382. }
  8383. TEST(SSLClientServerTest, ClientCertPresent) {
  8384. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8385. }
  8386. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8387. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8388. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8389. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8390. }
  8391. // PEM memory-based constructor tests (works with all TLS backends)
  8392. void PemMemoryClientCertPresent(
  8393. const std::string &client_cert_file,
  8394. const std::string &client_private_key_file,
  8395. const std::string &client_encrypted_private_key_pass = std::string()) {
  8396. // Read PEM files into memory
  8397. std::string server_cert_pem, server_key_pem;
  8398. std::string client_ca_pem;
  8399. std::string client_cert_pem, client_key_pem;
  8400. read_file(SERVER_CERT_FILE, server_cert_pem);
  8401. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8402. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8403. read_file(client_cert_file, client_cert_pem);
  8404. read_file(client_private_key_file, client_key_pem);
  8405. // Create server with PEM memory
  8406. SSLServer::PemMemory server_pem = {
  8407. server_cert_pem.c_str(),
  8408. server_cert_pem.size(),
  8409. server_key_pem.c_str(),
  8410. server_key_pem.size(),
  8411. client_ca_pem.c_str(),
  8412. client_ca_pem.size(),
  8413. nullptr // no password for server key
  8414. };
  8415. SSLServer svr(server_pem);
  8416. ASSERT_TRUE(svr.is_valid());
  8417. svr.Get("/test", [&](const Request &, Response &res) {
  8418. res.set_content("test", "text/plain");
  8419. });
  8420. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8421. auto se = detail::scope_exit([&] {
  8422. svr.stop();
  8423. t.join();
  8424. ASSERT_FALSE(svr.is_running());
  8425. });
  8426. svr.wait_until_ready();
  8427. // Create client with PEM memory
  8428. const char *password = client_encrypted_private_key_pass.empty()
  8429. ? nullptr
  8430. : client_encrypted_private_key_pass.c_str();
  8431. SSLClient::PemMemory client_pem = {
  8432. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8433. client_key_pem.size(), password};
  8434. SSLClient cli(HOST, PORT, client_pem);
  8435. cli.enable_server_certificate_verification(false);
  8436. cli.set_connection_timeout(30);
  8437. auto res = cli.Get("/test");
  8438. ASSERT_TRUE(res);
  8439. ASSERT_EQ(StatusCode::OK_200, res->status);
  8440. }
  8441. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8442. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8443. }
  8444. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8445. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8446. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8447. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8448. }
  8449. TEST(SSLClientServerTest, ClientCertMissing) {
  8450. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8451. CLIENT_CA_CERT_DIR);
  8452. ASSERT_TRUE(svr.is_valid());
  8453. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8454. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8455. auto se = detail::scope_exit([&] {
  8456. svr.stop();
  8457. t.join();
  8458. ASSERT_FALSE(svr.is_running());
  8459. });
  8460. svr.wait_until_ready();
  8461. SSLClient cli(HOST, PORT);
  8462. cli.set_connection_timeout(30);
  8463. auto res = cli.Get("/test");
  8464. ASSERT_TRUE(!res);
  8465. // When client cert is missing and server requires it, connection fails
  8466. // Error type depends on backend implementation
  8467. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8468. res.error() == Error::SSLConnection);
  8469. // Verify backend error is captured
  8470. // Note: This test may have different error codes depending on the exact
  8471. // verification failure
  8472. EXPECT_NE(0UL, res.ssl_backend_error());
  8473. }
  8474. TEST(SSLClientServerTest, TrustDirOptional) {
  8475. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8476. ASSERT_TRUE(svr.is_valid());
  8477. svr.Get("/test", [&](const Request &, Response &res) {
  8478. res.set_content("test", "text/plain");
  8479. });
  8480. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8481. auto se = detail::scope_exit([&] {
  8482. svr.stop();
  8483. t.join();
  8484. ASSERT_FALSE(svr.is_running());
  8485. });
  8486. svr.wait_until_ready();
  8487. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8488. cli.enable_server_certificate_verification(false);
  8489. cli.set_connection_timeout(30);
  8490. auto res = cli.Get("/test");
  8491. ASSERT_TRUE(res);
  8492. ASSERT_EQ(StatusCode::OK_200, res->status);
  8493. }
  8494. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8495. class NoListenSSLServer : public SSLServer {
  8496. public:
  8497. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8498. const char *client_ca_cert_file_path,
  8499. const char *client_ca_cert_dir_path = nullptr)
  8500. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8501. client_ca_cert_dir_path),
  8502. stop_(false) {}
  8503. std::atomic_bool stop_;
  8504. private:
  8505. bool process_and_close_socket(socket_t /*sock*/) override {
  8506. // Don't create SSL context
  8507. while (!stop_.load()) {
  8508. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8509. }
  8510. return true;
  8511. }
  8512. };
  8513. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8514. CLIENT_CA_CERT_FILE);
  8515. ASSERT_TRUE(svr.is_valid());
  8516. svr.Get("/test", [&](const Request &, Response &res) {
  8517. res.set_content("test", "text/plain");
  8518. });
  8519. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8520. auto se = detail::scope_exit([&] {
  8521. svr.stop_ = true;
  8522. svr.stop();
  8523. t.join();
  8524. ASSERT_FALSE(svr.is_running());
  8525. });
  8526. svr.wait_until_ready();
  8527. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8528. cli.enable_server_certificate_verification(false);
  8529. cli.set_connection_timeout(1);
  8530. auto res = cli.Get("/test");
  8531. ASSERT_TRUE(!res);
  8532. EXPECT_EQ(Error::SSLConnection, res.error());
  8533. // Timeout results in WantRead error code (maps to backend-specific value)
  8534. EXPECT_NE(0, res.ssl_error());
  8535. }
  8536. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8537. // Test SSLServer with client certificate verification using the standard
  8538. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8539. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8540. CLIENT_CA_CERT_DIR);
  8541. ASSERT_TRUE(svr.is_valid());
  8542. svr.Get("/test", [&](const Request &req, Response &res) {
  8543. res.set_content("test", "text/plain");
  8544. auto cert = req.peer_cert();
  8545. ASSERT_TRUE(static_cast<bool>(cert));
  8546. auto common_name = cert.subject_cn();
  8547. EXPECT_EQ("Common Name", common_name);
  8548. });
  8549. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8550. auto se = detail::scope_exit([&] {
  8551. svr.stop();
  8552. t.join();
  8553. ASSERT_FALSE(svr.is_running());
  8554. });
  8555. svr.wait_until_ready();
  8556. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8557. cli.enable_server_certificate_verification(false);
  8558. cli.set_connection_timeout(30);
  8559. auto res = cli.Get("/test");
  8560. ASSERT_TRUE(res);
  8561. ASSERT_EQ(StatusCode::OK_200, res->status);
  8562. }
  8563. // Test verify_hostname for both OpenSSL and MbedTLS backends
  8564. // Verifies that wildcard matching and exact matching work consistently
  8565. TEST(SSLClientServerTest, TlsVerifyHostname) {
  8566. using namespace httplib::tls;
  8567. // We need a running server to test against
  8568. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8569. ASSERT_TRUE(svr.is_valid());
  8570. svr.Get("/test", [](const Request &, Response &res) {
  8571. res.set_content("ok", "text/plain");
  8572. });
  8573. thread t([&]() { svr.listen(HOST, PORT); });
  8574. auto se = detail::scope_exit([&] {
  8575. svr.stop();
  8576. t.join();
  8577. });
  8578. svr.wait_until_ready();
  8579. bool verify_callback_called = false;
  8580. bool verify_result_wrong = false;
  8581. SSLClient cli(HOST, PORT);
  8582. cli.enable_server_certificate_verification(true);
  8583. cli.set_ca_cert_path(CA_CERT_FILE);
  8584. cli.set_connection_timeout(5);
  8585. // Note: Test certificate has CN="Common Name", not "localhost"
  8586. bool verify_result_cn = false;
  8587. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8588. verify_callback_called = true;
  8589. if (!ctx.cert) return false;
  8590. // Test 1: "Common Name" should match (our test server cert CN)
  8591. verify_result_cn = ctx.check_hostname("Common Name");
  8592. // Test 2: wrong hostname should not match
  8593. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  8594. return true; // Accept for the purpose of this test
  8595. });
  8596. auto res = cli.Get("/test");
  8597. // The request may succeed or fail depending on cert configuration
  8598. // but the callback should have been called
  8599. ASSERT_TRUE(verify_callback_called)
  8600. << "Verify callback should have been called";
  8601. // CN="Common Name" should match our test certificate
  8602. EXPECT_TRUE(verify_result_cn)
  8603. << "verify_hostname should match 'Common Name' (certificate CN)";
  8604. // Wrong hostname should not match
  8605. EXPECT_FALSE(verify_result_wrong)
  8606. << "verify_hostname should not match 'wronghost.example.com'";
  8607. }
  8608. #endif
  8609. // mbedTLS-specific callback constructor test
  8610. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8611. #ifdef CPPHTTPLIB_SSL_ENABLED
  8612. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8613. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8614. ASSERT_TRUE(svr.is_valid());
  8615. // Set up a handler to verify client certificate is present
  8616. bool client_cert_verified = false;
  8617. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8618. // Verify that client certificate was provided
  8619. client_cert_verified = true;
  8620. res.set_content("success", "text/plain");
  8621. });
  8622. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8623. auto se = detail::scope_exit([&] {
  8624. svr.stop();
  8625. t.join();
  8626. ASSERT_FALSE(svr.is_running());
  8627. });
  8628. svr.wait_until_ready();
  8629. // Client with certificate
  8630. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8631. cli.enable_server_certificate_verification(false);
  8632. cli.set_connection_timeout(30);
  8633. auto res = cli.Get("/test");
  8634. ASSERT_TRUE(res);
  8635. ASSERT_EQ(StatusCode::OK_200, res->status);
  8636. ASSERT_TRUE(client_cert_verified);
  8637. EXPECT_EQ("success", res->body);
  8638. }
  8639. #endif
  8640. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  8641. // backends
  8642. #ifdef CPPHTTPLIB_SSL_ENABLED
  8643. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  8644. using namespace httplib::tls;
  8645. // Test that when client CA cert file is provided,
  8646. // the server properly requests and validates client certificates
  8647. // Create a server with client authentication
  8648. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8649. ASSERT_TRUE(svr.is_valid());
  8650. bool handler_called = false;
  8651. svr.Get("/test", [&](const Request &req, Response &res) {
  8652. handler_called = true;
  8653. // Verify that a client certificate was provided
  8654. auto cert = req.peer_cert();
  8655. ASSERT_TRUE(static_cast<bool>(cert));
  8656. // Get the issuer name
  8657. std::string issuer_str = cert.issuer_name();
  8658. ASSERT_FALSE(issuer_str.empty());
  8659. // The client certificate should be issued by our test CA
  8660. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  8661. res.set_content("authenticated", "text/plain");
  8662. });
  8663. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8664. auto se = detail::scope_exit([&] {
  8665. svr.stop();
  8666. t.join();
  8667. ASSERT_FALSE(svr.is_running());
  8668. });
  8669. svr.wait_until_ready();
  8670. // Connect with a client certificate issued by the CA
  8671. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8672. cli.enable_server_certificate_verification(false);
  8673. cli.set_connection_timeout(30);
  8674. auto res = cli.Get("/test");
  8675. ASSERT_TRUE(res);
  8676. ASSERT_EQ(StatusCode::OK_200, res->status);
  8677. ASSERT_TRUE(handler_called);
  8678. EXPECT_EQ("authenticated", res->body);
  8679. }
  8680. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  8681. using namespace httplib::tls;
  8682. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8683. ASSERT_TRUE(svr.is_valid());
  8684. svr.Get("/test", [](const Request &, Response &res) {
  8685. res.set_content("ok", "text/plain");
  8686. });
  8687. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8688. auto se = detail::scope_exit([&] {
  8689. svr.stop();
  8690. t.join();
  8691. });
  8692. svr.wait_until_ready();
  8693. SSLClient cli(HOST, PORT);
  8694. cli.enable_server_certificate_verification(false);
  8695. cli.set_connection_timeout(30);
  8696. bool cert_checked = false;
  8697. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8698. if (ctx.cert) {
  8699. auto sans = ctx.sans();
  8700. // Test certificate may or may not have SANs - just verify the API
  8701. // works If SANs exist, verify the types are valid
  8702. for (const auto &san : sans) {
  8703. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  8704. san.type == SanType::EMAIL || san.type == SanType::URI ||
  8705. san.type == SanType::OTHER);
  8706. EXPECT_FALSE(san.value.empty());
  8707. }
  8708. cert_checked = true;
  8709. }
  8710. return true;
  8711. });
  8712. auto res = cli.Get("/test");
  8713. ASSERT_TRUE(res);
  8714. EXPECT_TRUE(cert_checked);
  8715. }
  8716. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  8717. using namespace httplib::tls;
  8718. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8719. ASSERT_TRUE(svr.is_valid());
  8720. svr.Get("/test", [](const Request &, Response &res) {
  8721. res.set_content("ok", "text/plain");
  8722. });
  8723. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8724. auto se = detail::scope_exit([&] {
  8725. svr.stop();
  8726. t.join();
  8727. });
  8728. svr.wait_until_ready();
  8729. SSLClient cli(HOST, PORT);
  8730. cli.enable_server_certificate_verification(false);
  8731. cli.set_connection_timeout(30);
  8732. bool validity_checked = false;
  8733. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8734. if (ctx.cert) {
  8735. time_t not_before = 0, not_after = 0;
  8736. bool result = ctx.validity(not_before, not_after);
  8737. EXPECT_TRUE(result);
  8738. // Verify that not_before < now < not_after for a valid cert
  8739. time_t now = time(nullptr);
  8740. EXPECT_LT(not_before, now);
  8741. EXPECT_GT(not_after, now);
  8742. validity_checked = true;
  8743. }
  8744. return true;
  8745. });
  8746. auto res = cli.Get("/test");
  8747. ASSERT_TRUE(res);
  8748. EXPECT_TRUE(validity_checked);
  8749. }
  8750. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  8751. using namespace httplib::tls;
  8752. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8753. ASSERT_TRUE(svr.is_valid());
  8754. svr.Get("/test", [](const Request &, Response &res) {
  8755. res.set_content("ok", "text/plain");
  8756. });
  8757. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8758. auto se = detail::scope_exit([&] {
  8759. svr.stop();
  8760. t.join();
  8761. });
  8762. svr.wait_until_ready();
  8763. SSLClient cli(HOST, PORT);
  8764. cli.enable_server_certificate_verification(false);
  8765. cli.set_connection_timeout(30);
  8766. bool serial_checked = false;
  8767. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8768. if (ctx.cert) {
  8769. std::string serial = ctx.serial();
  8770. EXPECT_FALSE(serial.empty());
  8771. // Serial should be a hex string
  8772. for (char c : serial) {
  8773. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  8774. (c >= 'a' && c <= 'f'));
  8775. }
  8776. serial_checked = true;
  8777. }
  8778. return true;
  8779. });
  8780. auto res = cli.Get("/test");
  8781. ASSERT_TRUE(res);
  8782. EXPECT_TRUE(serial_checked);
  8783. }
  8784. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  8785. // Test 1: Valid CA file - no error should be recorded
  8786. {
  8787. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8788. CLIENT_CA_CERT_FILE);
  8789. ASSERT_TRUE(svr.is_valid());
  8790. // With valid setup, last_ssl_error should be 0
  8791. EXPECT_EQ(0, svr.ssl_last_error());
  8792. }
  8793. // Test 2: Invalid CA file content
  8794. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  8795. {
  8796. // Create a temporary file with completely invalid content
  8797. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  8798. {
  8799. std::ofstream ofs(temp_invalid_ca);
  8800. ofs << "This is not a certificate file at all\n";
  8801. ofs << "Just plain text content\n";
  8802. }
  8803. // Create server with invalid CA file
  8804. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  8805. // Clean up temporary file
  8806. std::remove(temp_invalid_ca);
  8807. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  8808. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  8809. // Note: SSL_CTX_load_verify_locations typically fails first,
  8810. // but our error handling code path is still exercised
  8811. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  8812. }
  8813. }
  8814. TEST(VerifyCallbackTest, VerifyContextFields) {
  8815. using namespace httplib::tls;
  8816. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8817. ASSERT_TRUE(svr.is_valid());
  8818. svr.Get("/test", [](const Request &, Response &res) {
  8819. res.set_content("ok", "text/plain");
  8820. });
  8821. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8822. auto se = detail::scope_exit([&] {
  8823. svr.stop();
  8824. t.join();
  8825. });
  8826. svr.wait_until_ready();
  8827. SSLClient cli(HOST, PORT);
  8828. cli.enable_server_certificate_verification(false);
  8829. cli.set_connection_timeout(30);
  8830. int callback_count = 0;
  8831. bool saw_leaf_cert = false;
  8832. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8833. if (ctx.cert) {
  8834. callback_count++;
  8835. // We should see at least one certificate (the leaf)
  8836. std::string cn = ctx.subject_cn();
  8837. if (!cn.empty()) { saw_leaf_cert = true; }
  8838. // Verify context fields are populated
  8839. EXPECT_NE(ctx.session, nullptr);
  8840. EXPECT_GE(ctx.depth, 0);
  8841. }
  8842. return true;
  8843. });
  8844. auto res = cli.Get("/test");
  8845. ASSERT_TRUE(res);
  8846. EXPECT_GT(callback_count, 0);
  8847. EXPECT_TRUE(saw_leaf_cert);
  8848. }
  8849. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  8850. using httplib::tls::TlsError;
  8851. // Test that verify_error_to_string returns empty for success
  8852. std::string success_str = TlsError::verify_error_to_string(0);
  8853. EXPECT_TRUE(success_str.empty());
  8854. // Test that verify_error_to_string returns non-empty for error codes
  8855. // Using a common error code (certificate expired)
  8856. std::string error_str =
  8857. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  8858. EXPECT_FALSE(error_str.empty());
  8859. }
  8860. TEST(SessionVerifierTest, CertificateAccepted) {
  8861. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8862. ASSERT_TRUE(svr.is_valid());
  8863. svr.Get("/test", [](const Request &, Response &res) {
  8864. res.set_content("ok", "text/plain");
  8865. });
  8866. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8867. auto se = detail::scope_exit([&] {
  8868. svr.stop();
  8869. t.join();
  8870. });
  8871. svr.wait_until_ready();
  8872. SSLClient cli(HOST, PORT);
  8873. cli.enable_server_certificate_verification(false);
  8874. cli.set_connection_timeout(30);
  8875. bool callback_called = false;
  8876. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8877. EXPECT_NE(session, nullptr);
  8878. callback_called = true;
  8879. return SSLVerifierResponse::CertificateAccepted;
  8880. });
  8881. auto res = cli.Get("/test");
  8882. ASSERT_TRUE(res);
  8883. EXPECT_EQ(200, res->status);
  8884. EXPECT_TRUE(callback_called);
  8885. }
  8886. TEST(SessionVerifierTest, CertificateRejected) {
  8887. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8888. ASSERT_TRUE(svr.is_valid());
  8889. svr.Get("/test", [](const Request &, Response &res) {
  8890. res.set_content("ok", "text/plain");
  8891. });
  8892. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8893. auto se = detail::scope_exit([&] {
  8894. svr.stop();
  8895. t.join();
  8896. });
  8897. svr.wait_until_ready();
  8898. SSLClient cli(HOST, PORT);
  8899. cli.enable_server_certificate_verification(false);
  8900. cli.set_connection_timeout(30);
  8901. bool callback_called = false;
  8902. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8903. EXPECT_NE(session, nullptr);
  8904. callback_called = true;
  8905. return SSLVerifierResponse::CertificateRejected;
  8906. });
  8907. auto res = cli.Get("/test");
  8908. EXPECT_FALSE(res);
  8909. EXPECT_TRUE(callback_called);
  8910. }
  8911. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  8912. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8913. ASSERT_TRUE(svr.is_valid());
  8914. svr.Get("/test", [](const Request &, Response &res) {
  8915. res.set_content("ok", "text/plain");
  8916. });
  8917. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8918. auto se = detail::scope_exit([&] {
  8919. svr.stop();
  8920. t.join();
  8921. });
  8922. svr.wait_until_ready();
  8923. // NoDecisionMade with verification disabled should succeed (no default check)
  8924. SSLClient cli(HOST, PORT);
  8925. cli.enable_server_certificate_verification(false);
  8926. cli.set_connection_timeout(30);
  8927. bool callback_called = false;
  8928. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8929. EXPECT_NE(session, nullptr);
  8930. callback_called = true;
  8931. return SSLVerifierResponse::NoDecisionMade;
  8932. });
  8933. auto res = cli.Get("/test");
  8934. ASSERT_TRUE(res);
  8935. EXPECT_EQ(200, res->status);
  8936. EXPECT_TRUE(callback_called);
  8937. }
  8938. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  8939. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8940. ASSERT_TRUE(svr.is_valid());
  8941. svr.Get("/test", [](const Request &, Response &res) {
  8942. res.set_content("ok", "text/plain");
  8943. });
  8944. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8945. auto se = detail::scope_exit([&] {
  8946. svr.stop();
  8947. t.join();
  8948. });
  8949. svr.wait_until_ready();
  8950. // NoDecisionMade with verification enabled should fail (self-signed cert).
  8951. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  8952. // so we only check that the request fails, not whether the callback was
  8953. // called.
  8954. SSLClient cli(HOST, PORT);
  8955. cli.enable_server_certificate_verification(true);
  8956. cli.set_connection_timeout(30);
  8957. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8958. EXPECT_NE(session, nullptr);
  8959. return SSLVerifierResponse::NoDecisionMade;
  8960. });
  8961. auto res = cli.Get("/test");
  8962. EXPECT_FALSE(res);
  8963. }
  8964. TEST(SSLClientServerTest, ClientCAListFromPem) {
  8965. // Test SSL server using PemMemory constructor with client CA certificates
  8966. // Read PEM files
  8967. std::string server_cert_pem, server_key_pem, client_ca_pem;
  8968. read_file(SERVER_CERT_FILE, server_cert_pem);
  8969. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8970. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8971. // Create SSLServer with PemMemory constructor including client CA
  8972. SSLServer::PemMemory server_pem = {
  8973. server_cert_pem.c_str(),
  8974. server_cert_pem.size(),
  8975. server_key_pem.c_str(),
  8976. server_key_pem.size(),
  8977. client_ca_pem.c_str(),
  8978. client_ca_pem.size(),
  8979. nullptr // no password for server key
  8980. };
  8981. SSLServer svr(server_pem);
  8982. ASSERT_TRUE(svr.is_valid());
  8983. // No SSL error should be recorded for valid setup
  8984. EXPECT_EQ(0, svr.ssl_last_error());
  8985. // Set up server endpoints
  8986. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  8987. res.set_content("ok", "text/plain");
  8988. });
  8989. // Start server in a thread
  8990. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  8991. svr.wait_until_ready();
  8992. // Connect with client certificate (using constructor with paths)
  8993. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8994. cli.enable_server_certificate_verification(false);
  8995. auto res = cli.Get("/test-pem-ca");
  8996. ASSERT_TRUE(res);
  8997. EXPECT_EQ(200, res->status);
  8998. EXPECT_EQ("ok", res->body);
  8999. svr.stop();
  9000. server_thread.join();
  9001. }
  9002. #endif
  9003. #ifdef _WIN32
  9004. TEST(CleanupTest, WSACleanup) {
  9005. int ret = WSACleanup();
  9006. ASSERT_EQ(0, ret);
  9007. }
  9008. #endif
  9009. #ifndef CPPHTTPLIB_SSL_ENABLED
  9010. TEST(NoSSLSupport, SimpleInterface) {
  9011. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  9012. }
  9013. #endif
  9014. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9015. TEST(InvalidScheme, SimpleInterface) {
  9016. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  9017. }
  9018. #endif
  9019. TEST(NoScheme, SimpleInterface) {
  9020. Client cli("yahoo.com:80");
  9021. ASSERT_TRUE(cli.is_valid());
  9022. }
  9023. TEST(SendAPI, SimpleInterface_Online) {
  9024. Client cli("http://yahoo.com");
  9025. Request req;
  9026. req.method = "GET";
  9027. req.path = "/";
  9028. auto res = cli.send(req);
  9029. ASSERT_TRUE(res);
  9030. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9031. }
  9032. TEST(SendAPI, WithParamsInRequest) {
  9033. Server svr;
  9034. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  9035. EXPECT_TRUE(req.has_param("test"));
  9036. EXPECT_EQ("test_value", req.get_param_value("test"));
  9037. });
  9038. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  9039. auto se = detail::scope_exit([&] {
  9040. svr.stop();
  9041. t.join();
  9042. ASSERT_FALSE(svr.is_running());
  9043. });
  9044. svr.wait_until_ready();
  9045. Client cli(HOST, PORT);
  9046. {
  9047. Request req;
  9048. req.method = "GET";
  9049. req.path = "/";
  9050. req.params.emplace("test", "test_value");
  9051. auto res = cli.send(req);
  9052. ASSERT_TRUE(res);
  9053. }
  9054. {
  9055. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  9056. ASSERT_TRUE(res);
  9057. }
  9058. }
  9059. TEST(ClientImplMethods, GetSocketTest) {
  9060. httplib::Server svr;
  9061. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9062. res.status = StatusCode::OK_200;
  9063. });
  9064. auto port = svr.bind_to_any_port("127.0.0.1");
  9065. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9066. auto se = detail::scope_exit([&] {
  9067. svr.stop();
  9068. thread.join();
  9069. ASSERT_FALSE(svr.is_running());
  9070. });
  9071. svr.wait_until_ready();
  9072. {
  9073. httplib::Client cli("127.0.0.1", port);
  9074. cli.set_keep_alive(true);
  9075. // Use the behavior of cpp-httplib of opening the connection
  9076. // only when the first request happens. If that changes,
  9077. // this test would be obsolete.
  9078. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9079. // This also implicitly tests the server. But other tests would fail much
  9080. // earlier than this one to be considered.
  9081. auto res = cli.Get("/");
  9082. ASSERT_TRUE(res);
  9083. EXPECT_EQ(StatusCode::OK_200, res->status);
  9084. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9085. }
  9086. }
  9087. #ifdef CPPHTTPLIB_SSL_ENABLED
  9088. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9089. Client cli("http://yahoo.com");
  9090. auto res = cli.Get("/");
  9091. ASSERT_TRUE(res);
  9092. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9093. cli.set_follow_location(true);
  9094. res = cli.Get("/");
  9095. ASSERT_TRUE(res);
  9096. EXPECT_EQ(StatusCode::OK_200, res->status);
  9097. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9098. }
  9099. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9100. Client cli("https://yahoo.com");
  9101. auto res = cli.Get("/");
  9102. ASSERT_TRUE(res);
  9103. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9104. cli.set_follow_location(true);
  9105. res = cli.Get("/");
  9106. ASSERT_TRUE(res);
  9107. EXPECT_EQ(StatusCode::OK_200, res->status);
  9108. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9109. }
  9110. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9111. Client cli("https://yahoo.com");
  9112. auto res = cli.Get("/");
  9113. ASSERT_TRUE(res);
  9114. ASSERT_FALSE(!res);
  9115. ASSERT_TRUE(res);
  9116. ASSERT_FALSE(res == nullptr);
  9117. ASSERT_TRUE(res != nullptr);
  9118. EXPECT_EQ(Error::Success, res.error());
  9119. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9120. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9121. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9122. cli.set_follow_location(true);
  9123. res = cli.Get("/");
  9124. ASSERT_TRUE(res);
  9125. EXPECT_EQ(Error::Success, res.error());
  9126. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9127. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9128. EXPECT_EQ(StatusCode::OK_200, res->status);
  9129. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9130. }
  9131. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9132. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9133. Client cli("https://cdnjs.cloudflare.com");
  9134. auto res =
  9135. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9136. ASSERT_TRUE(res);
  9137. EXPECT_EQ(StatusCode::OK_200, res->status);
  9138. EXPECT_EQ(287630U, res->body.size());
  9139. EXPECT_EQ("application/javascript; charset=utf-8",
  9140. res->get_header_value("Content-Type"));
  9141. }
  9142. #endif
  9143. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9144. #undef REDIR_HOST // Silence compiler warning
  9145. #define REDIR_HOST "https://httpbingo.org"
  9146. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9147. Client cli(REDIR_HOST);
  9148. cli.set_follow_location(true);
  9149. auto res =
  9150. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9151. ASSERT_TRUE(res);
  9152. EXPECT_EQ(StatusCode::OK_200, res->status);
  9153. }
  9154. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9155. Client cli(REDIR_HOST);
  9156. cli.set_follow_location(true);
  9157. Params params;
  9158. params.emplace("url", "http://example.com");
  9159. params.emplace("status_code", "302");
  9160. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9161. ASSERT_TRUE(res);
  9162. EXPECT_EQ(StatusCode::OK_200, res->status);
  9163. }
  9164. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9165. Client cli(REDIR_HOST);
  9166. cli.set_follow_location(true);
  9167. Params params;
  9168. params.emplace("url", "http://example.com");
  9169. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9170. ASSERT_TRUE(res);
  9171. EXPECT_EQ(StatusCode::OK_200, res->status);
  9172. }
  9173. TEST(HttpToHttpsRedirectTest, CertFile) {
  9174. auto ssl_port = PORT + 1;
  9175. Server svr;
  9176. ASSERT_TRUE(svr.is_valid());
  9177. svr.Get("/index", [&](const Request &, Response &res) {
  9178. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9179. "/index");
  9180. svr.stop();
  9181. });
  9182. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9183. ASSERT_TRUE(ssl_svr.is_valid());
  9184. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9185. res.set_content("test", "text/plain");
  9186. ssl_svr.stop();
  9187. });
  9188. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9189. thread t2 =
  9190. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9191. auto se = detail::scope_exit([&] {
  9192. t2.join();
  9193. t.join();
  9194. ASSERT_FALSE(svr.is_running());
  9195. });
  9196. svr.wait_until_ready();
  9197. ssl_svr.wait_until_ready();
  9198. Client cli("127.0.0.1", PORT);
  9199. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9200. cli.enable_server_certificate_verification(true);
  9201. cli.set_follow_location(true);
  9202. cli.set_connection_timeout(30);
  9203. auto res = cli.Get("/index");
  9204. ASSERT_TRUE(res);
  9205. ASSERT_EQ(StatusCode::OK_200, res->status);
  9206. }
  9207. TEST(SSLClientRedirectTest, CertFile) {
  9208. auto ssl_port = PORT + 1;
  9209. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9210. ASSERT_TRUE(ssl_svr1.is_valid());
  9211. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9212. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9213. "/index");
  9214. ssl_svr1.stop();
  9215. });
  9216. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9217. ASSERT_TRUE(ssl_svr2.is_valid());
  9218. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9219. res.set_content("test", "text/plain");
  9220. ssl_svr2.stop();
  9221. });
  9222. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9223. thread t2 =
  9224. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9225. auto se = detail::scope_exit([&] {
  9226. t2.join();
  9227. t.join();
  9228. ASSERT_FALSE(ssl_svr1.is_running());
  9229. });
  9230. ssl_svr1.wait_until_ready();
  9231. ssl_svr2.wait_until_ready();
  9232. SSLClient cli("127.0.0.1", PORT);
  9233. std::string cert;
  9234. read_file(SERVER_CERT2_FILE, cert);
  9235. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9236. cli.enable_server_certificate_verification(true);
  9237. cli.set_follow_location(true);
  9238. cli.set_connection_timeout(30);
  9239. auto res = cli.Get("/index");
  9240. ASSERT_TRUE(res);
  9241. ASSERT_EQ(StatusCode::OK_200, res->status);
  9242. }
  9243. #endif
  9244. #ifdef CPPHTTPLIB_SSL_ENABLED
  9245. // Test that set_ca_cert_store() skips system certs (consistent with
  9246. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9247. // should be trusted - system certs should NOT be loaded.
  9248. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9249. // Load a specific cert that is NOT a system CA cert
  9250. std::string cert;
  9251. read_file(SERVER_CERT2_FILE, cert);
  9252. SSLClient cli("google.com");
  9253. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9254. cli.enable_server_certificate_verification(true);
  9255. // This should FAIL because:
  9256. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9257. // 2. System certs should NOT be loaded when custom store is set
  9258. // If system certs WERE loaded, this would succeed
  9259. auto res = cli.Get("/");
  9260. ASSERT_FALSE(res);
  9261. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9262. }
  9263. TEST(MultipartFormDataTest, LargeData) {
  9264. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9265. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9266. const ContentReader &content_reader) {
  9267. if (req.is_multipart_form_data()) {
  9268. std::vector<FormData> items;
  9269. content_reader(
  9270. [&](const FormData &file) {
  9271. items.push_back(file);
  9272. return true;
  9273. },
  9274. [&](const char *data, size_t data_length) {
  9275. items.back().content.append(data, data_length);
  9276. return true;
  9277. });
  9278. EXPECT_TRUE(std::string(items[0].name) == "document");
  9279. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9280. EXPECT_TRUE(items[0].filename == "2MB_data");
  9281. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9282. EXPECT_TRUE(items[1].name == "hello");
  9283. EXPECT_TRUE(items[1].content == "world");
  9284. EXPECT_TRUE(items[1].filename == "");
  9285. EXPECT_TRUE(items[1].content_type == "");
  9286. } else {
  9287. std::string body;
  9288. content_reader([&](const char *data, size_t data_length) {
  9289. body.append(data, data_length);
  9290. return true;
  9291. });
  9292. }
  9293. });
  9294. auto port = svr.bind_to_any_port(HOST);
  9295. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9296. auto se = detail::scope_exit([&] {
  9297. svr.stop();
  9298. t.join();
  9299. ASSERT_FALSE(svr.is_running());
  9300. });
  9301. svr.wait_until_ready();
  9302. {
  9303. std::string data(1024 * 1024 * 2, '.');
  9304. std::stringstream buffer;
  9305. buffer << data;
  9306. SSLClient cli(HOST, port);
  9307. cli.enable_server_certificate_verification(false);
  9308. UploadFormDataItems items{
  9309. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9310. {"hello", "world", "", ""},
  9311. };
  9312. auto res = cli.Post("/post", items);
  9313. ASSERT_TRUE(res);
  9314. ASSERT_EQ(StatusCode::OK_200, res->status);
  9315. }
  9316. }
  9317. TEST(MultipartFormDataTest, DataProviderItems) {
  9318. std::random_device seed_gen;
  9319. std::mt19937 random(seed_gen());
  9320. std::string rand1;
  9321. rand1.resize(1000);
  9322. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9323. std::string rand2;
  9324. rand2.resize(3000);
  9325. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9326. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9327. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9328. const ContentReader &content_reader) {
  9329. ASSERT_FALSE(req.is_multipart_form_data());
  9330. std::string body;
  9331. content_reader([&](const char *data, size_t data_length) {
  9332. body.append(data, data_length);
  9333. return true;
  9334. });
  9335. EXPECT_EQ(body, "");
  9336. });
  9337. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9338. const ContentReader &content_reader) {
  9339. ASSERT_TRUE(req.is_multipart_form_data());
  9340. std::vector<FormData> items;
  9341. content_reader(
  9342. [&](const FormData &file) {
  9343. items.push_back(file);
  9344. return true;
  9345. },
  9346. [&](const char *data, size_t data_length) {
  9347. items.back().content.append(data, data_length);
  9348. return true;
  9349. });
  9350. ASSERT_TRUE(items.size() == 2);
  9351. EXPECT_EQ(std::string(items[0].name), "name1");
  9352. EXPECT_EQ(items[0].content, "Testing123");
  9353. EXPECT_EQ(items[0].filename, "filename1");
  9354. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9355. EXPECT_EQ(items[1].name, "name2");
  9356. EXPECT_EQ(items[1].content, "Testing456");
  9357. EXPECT_EQ(items[1].filename, "");
  9358. EXPECT_EQ(items[1].content_type, "");
  9359. });
  9360. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9361. const ContentReader &content_reader) {
  9362. ASSERT_TRUE(req.is_multipart_form_data());
  9363. std::vector<FormData> items;
  9364. content_reader(
  9365. [&](const FormData &file) {
  9366. items.push_back(file);
  9367. return true;
  9368. },
  9369. [&](const char *data, size_t data_length) {
  9370. items.back().content.append(data, data_length);
  9371. return true;
  9372. });
  9373. ASSERT_TRUE(items.size() == 2);
  9374. EXPECT_EQ(items[0].name, "name3");
  9375. EXPECT_EQ(items[0].content, rand1);
  9376. EXPECT_EQ(items[0].filename, "filename3");
  9377. EXPECT_EQ(items[0].content_type, "");
  9378. EXPECT_EQ(items[1].name, "name4");
  9379. EXPECT_EQ(items[1].content, rand2);
  9380. EXPECT_EQ(items[1].filename, "filename4");
  9381. EXPECT_EQ(items[1].content_type, "");
  9382. });
  9383. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9384. const ContentReader &content_reader) {
  9385. ASSERT_TRUE(req.is_multipart_form_data());
  9386. std::vector<FormData> items;
  9387. content_reader(
  9388. [&](const FormData &file) {
  9389. items.push_back(file);
  9390. return true;
  9391. },
  9392. [&](const char *data, size_t data_length) {
  9393. items.back().content.append(data, data_length);
  9394. return true;
  9395. });
  9396. ASSERT_TRUE(items.size() == 4);
  9397. EXPECT_EQ(std::string(items[0].name), "name1");
  9398. EXPECT_EQ(items[0].content, "Testing123");
  9399. EXPECT_EQ(items[0].filename, "filename1");
  9400. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9401. EXPECT_EQ(items[1].name, "name2");
  9402. EXPECT_EQ(items[1].content, "Testing456");
  9403. EXPECT_EQ(items[1].filename, "");
  9404. EXPECT_EQ(items[1].content_type, "");
  9405. EXPECT_EQ(items[2].name, "name3");
  9406. EXPECT_EQ(items[2].content, rand1);
  9407. EXPECT_EQ(items[2].filename, "filename3");
  9408. EXPECT_EQ(items[2].content_type, "");
  9409. EXPECT_EQ(items[3].name, "name4");
  9410. EXPECT_EQ(items[3].content, rand2);
  9411. EXPECT_EQ(items[3].filename, "filename4");
  9412. EXPECT_EQ(items[3].content_type, "");
  9413. });
  9414. auto port = svr.bind_to_any_port("localhost");
  9415. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9416. auto se = detail::scope_exit([&] {
  9417. svr.stop();
  9418. t.join();
  9419. ASSERT_FALSE(svr.is_running());
  9420. });
  9421. svr.wait_until_ready();
  9422. {
  9423. SSLClient cli("localhost", port);
  9424. cli.enable_server_certificate_verification(false);
  9425. UploadFormDataItems items{
  9426. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9427. {"name2", "Testing456", "", ""}, // not a file
  9428. };
  9429. {
  9430. auto res = cli.Post("/post-none", {}, {}, {});
  9431. ASSERT_TRUE(res);
  9432. ASSERT_EQ(StatusCode::OK_200, res->status);
  9433. }
  9434. FormDataProviderItems providers;
  9435. {
  9436. auto res =
  9437. cli.Post("/post-items", {}, items, providers); // empty providers
  9438. ASSERT_TRUE(res);
  9439. ASSERT_EQ(StatusCode::OK_200, res->status);
  9440. }
  9441. providers.push_back({"name3",
  9442. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9443. // test the offset is given correctly at each step
  9444. if (!offset)
  9445. sink.os.write(rand1.data(), 30);
  9446. else if (offset == 30)
  9447. sink.os.write(rand1.data() + 30, 300);
  9448. else if (offset == 330)
  9449. sink.os.write(rand1.data() + 330, 670);
  9450. else if (offset == rand1.size())
  9451. sink.done();
  9452. return true;
  9453. },
  9454. "filename3",
  9455. {}});
  9456. providers.push_back({"name4",
  9457. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9458. // test the offset is given correctly at each step
  9459. if (!offset)
  9460. sink.os.write(rand2.data(), 2000);
  9461. else if (offset == 2000)
  9462. sink.os.write(rand2.data() + 2000, 1);
  9463. else if (offset == 2001)
  9464. sink.os.write(rand2.data() + 2001, 999);
  9465. else if (offset == rand2.size())
  9466. sink.done();
  9467. return true;
  9468. },
  9469. "filename4",
  9470. {}});
  9471. {
  9472. auto res = cli.Post("/post-providers", {}, {}, providers);
  9473. ASSERT_TRUE(res);
  9474. ASSERT_EQ(StatusCode::OK_200, res->status);
  9475. }
  9476. {
  9477. auto res = cli.Post("/post-both", {}, items, providers);
  9478. ASSERT_TRUE(res);
  9479. ASSERT_EQ(StatusCode::OK_200, res->status);
  9480. }
  9481. }
  9482. }
  9483. TEST(MultipartFormDataTest, BadHeader) {
  9484. Server svr;
  9485. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9486. res.set_content("ok", "text/plain");
  9487. });
  9488. thread t = thread([&] { svr.listen(HOST, PORT); });
  9489. auto se = detail::scope_exit([&] {
  9490. svr.stop();
  9491. t.join();
  9492. ASSERT_FALSE(svr.is_running());
  9493. });
  9494. svr.wait_until_ready();
  9495. const std::string body =
  9496. "This is the preamble. It is to be ignored, though it\r\n"
  9497. "is a handy place for composition agents to include an\r\n"
  9498. "explanatory note to non-MIME conformant readers.\r\n"
  9499. "\r\n"
  9500. "\r\n"
  9501. "--simple boundary\r\n"
  9502. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9503. ": BAD...\r\n"
  9504. "\r\n"
  9505. "value1\r\n"
  9506. "--simple boundary\r\n"
  9507. "Content-Disposition: form-data; name=\"field2\"; "
  9508. "filename=\"example.txt\"\r\n"
  9509. "\r\n"
  9510. "value2\r\n"
  9511. "--simple boundary--\r\n"
  9512. "This is the epilogue. It is also to be ignored.\r\n";
  9513. std::string content_type =
  9514. R"(multipart/form-data; boundary="simple boundary")";
  9515. Client cli(HOST, PORT);
  9516. auto res = cli.Post("/post", body, content_type.c_str());
  9517. ASSERT_TRUE(res);
  9518. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9519. }
  9520. TEST(MultipartFormDataTest, WithPreamble) {
  9521. Server svr;
  9522. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9523. res.set_content("ok", "text/plain");
  9524. });
  9525. thread t = thread([&] { svr.listen(HOST, PORT); });
  9526. auto se = detail::scope_exit([&] {
  9527. svr.stop();
  9528. t.join();
  9529. ASSERT_FALSE(svr.is_running());
  9530. });
  9531. svr.wait_until_ready();
  9532. const std::string body =
  9533. "This is the preamble. It is to be ignored, though it\r\n"
  9534. "is a handy place for composition agents to include an\r\n"
  9535. "explanatory note to non-MIME conformant readers.\r\n"
  9536. "\r\n"
  9537. "\r\n"
  9538. "--simple boundary\r\n"
  9539. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9540. "\r\n"
  9541. "value1\r\n"
  9542. "--simple boundary\r\n"
  9543. "Content-Disposition: form-data; name=\"field2\"; "
  9544. "filename=\"example.txt\"\r\n"
  9545. "\r\n"
  9546. "value2\r\n"
  9547. "--simple boundary--\r\n"
  9548. "This is the epilogue. It is also to be ignored.\r\n";
  9549. std::string content_type =
  9550. R"(multipart/form-data; boundary="simple boundary")";
  9551. Client cli(HOST, PORT);
  9552. auto res = cli.Post("/post", body, content_type.c_str());
  9553. ASSERT_TRUE(res);
  9554. EXPECT_EQ(StatusCode::OK_200, res->status);
  9555. }
  9556. TEST(MultipartFormDataTest, PostCustomBoundary) {
  9557. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9558. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  9559. const ContentReader &content_reader) {
  9560. if (req.is_multipart_form_data()) {
  9561. std::vector<FormData> items;
  9562. content_reader(
  9563. [&](const FormData &file) {
  9564. items.push_back(file);
  9565. return true;
  9566. },
  9567. [&](const char *data, size_t data_length) {
  9568. items.back().content.append(data, data_length);
  9569. return true;
  9570. });
  9571. EXPECT_TRUE(std::string(items[0].name) == "document");
  9572. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9573. EXPECT_TRUE(items[0].filename == "2MB_data");
  9574. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9575. EXPECT_TRUE(items[1].name == "hello");
  9576. EXPECT_TRUE(items[1].content == "world");
  9577. EXPECT_TRUE(items[1].filename == "");
  9578. EXPECT_TRUE(items[1].content_type == "");
  9579. } else {
  9580. std::string body;
  9581. content_reader([&](const char *data, size_t data_length) {
  9582. body.append(data, data_length);
  9583. return true;
  9584. });
  9585. }
  9586. });
  9587. auto port = svr.bind_to_any_port("localhost");
  9588. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9589. auto se = detail::scope_exit([&] {
  9590. svr.stop();
  9591. t.join();
  9592. ASSERT_FALSE(svr.is_running());
  9593. });
  9594. svr.wait_until_ready();
  9595. {
  9596. std::string data(1024 * 1024 * 2, '.');
  9597. std::stringstream buffer;
  9598. buffer << data;
  9599. SSLClient cli("localhost", port);
  9600. cli.enable_server_certificate_verification(false);
  9601. UploadFormDataItems items{
  9602. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9603. {"hello", "world", "", ""},
  9604. };
  9605. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9606. ASSERT_TRUE(res);
  9607. ASSERT_EQ(StatusCode::OK_200, res->status);
  9608. }
  9609. }
  9610. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9611. std::string data(1024 * 1024 * 2, '&');
  9612. std::stringstream buffer;
  9613. buffer << data;
  9614. Client cli("https://localhost:8080");
  9615. UploadFormDataItems items{
  9616. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9617. {"hello", "world", "", ""},
  9618. };
  9619. for (const char &c : " \t\r\n") {
  9620. auto res =
  9621. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9622. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9623. ASSERT_FALSE(res);
  9624. }
  9625. }
  9626. TEST(MultipartFormDataTest, PutFormData) {
  9627. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9628. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9629. const ContentReader &content_reader) {
  9630. if (req.is_multipart_form_data()) {
  9631. std::vector<FormData> items;
  9632. content_reader(
  9633. [&](const FormData &file) {
  9634. items.push_back(file);
  9635. return true;
  9636. },
  9637. [&](const char *data, size_t data_length) {
  9638. items.back().content.append(data, data_length);
  9639. return true;
  9640. });
  9641. EXPECT_TRUE(std::string(items[0].name) == "document");
  9642. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9643. EXPECT_TRUE(items[0].filename == "2MB_data");
  9644. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9645. EXPECT_TRUE(items[1].name == "hello");
  9646. EXPECT_TRUE(items[1].content == "world");
  9647. EXPECT_TRUE(items[1].filename == "");
  9648. EXPECT_TRUE(items[1].content_type == "");
  9649. } else {
  9650. std::string body;
  9651. content_reader([&](const char *data, size_t data_length) {
  9652. body.append(data, data_length);
  9653. return true;
  9654. });
  9655. }
  9656. });
  9657. auto port = svr.bind_to_any_port("localhost");
  9658. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9659. auto se = detail::scope_exit([&] {
  9660. svr.stop();
  9661. t.join();
  9662. ASSERT_FALSE(svr.is_running());
  9663. });
  9664. svr.wait_until_ready();
  9665. {
  9666. std::string data(1024 * 1024 * 2, '&');
  9667. std::stringstream buffer;
  9668. buffer << data;
  9669. SSLClient cli("localhost", port);
  9670. cli.enable_server_certificate_verification(false);
  9671. UploadFormDataItems items{
  9672. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9673. {"hello", "world", "", ""},
  9674. };
  9675. auto res = cli.Put("/put", items);
  9676. ASSERT_TRUE(res);
  9677. ASSERT_EQ(StatusCode::OK_200, res->status);
  9678. }
  9679. }
  9680. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  9681. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9682. svr.Put("/put_customboundary",
  9683. [&](const Request &req, const Response & /*res*/,
  9684. const ContentReader &content_reader) {
  9685. if (req.is_multipart_form_data()) {
  9686. std::vector<FormData> items;
  9687. content_reader(
  9688. [&](const FormData &file) {
  9689. items.push_back(file);
  9690. return true;
  9691. },
  9692. [&](const char *data, size_t data_length) {
  9693. items.back().content.append(data, data_length);
  9694. return true;
  9695. });
  9696. EXPECT_TRUE(std::string(items[0].name) == "document");
  9697. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9698. EXPECT_TRUE(items[0].filename == "2MB_data");
  9699. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9700. EXPECT_TRUE(items[1].name == "hello");
  9701. EXPECT_TRUE(items[1].content == "world");
  9702. EXPECT_TRUE(items[1].filename == "");
  9703. EXPECT_TRUE(items[1].content_type == "");
  9704. } else {
  9705. std::string body;
  9706. content_reader([&](const char *data, size_t data_length) {
  9707. body.append(data, data_length);
  9708. return true;
  9709. });
  9710. }
  9711. });
  9712. auto port = svr.bind_to_any_port("localhost");
  9713. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9714. auto se = detail::scope_exit([&] {
  9715. svr.stop();
  9716. t.join();
  9717. ASSERT_FALSE(svr.is_running());
  9718. });
  9719. svr.wait_until_ready();
  9720. {
  9721. std::string data(1024 * 1024 * 2, '&');
  9722. std::stringstream buffer;
  9723. buffer << data;
  9724. SSLClient cli("localhost", port);
  9725. cli.enable_server_certificate_verification(false);
  9726. UploadFormDataItems items{
  9727. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9728. {"hello", "world", "", ""},
  9729. };
  9730. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  9731. ASSERT_TRUE(res);
  9732. ASSERT_EQ(StatusCode::OK_200, res->status);
  9733. }
  9734. }
  9735. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  9736. std::string data(1024 * 1024 * 2, '&');
  9737. std::stringstream buffer;
  9738. buffer << data;
  9739. Client cli("https://localhost:8080");
  9740. cli.enable_server_certificate_verification(false);
  9741. UploadFormDataItems items{
  9742. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9743. {"hello", "world", "", ""},
  9744. };
  9745. for (const char &c : " \t\r\n") {
  9746. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  9747. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9748. ASSERT_FALSE(res);
  9749. }
  9750. }
  9751. TEST(MultipartFormDataTest, AlternateFilename) {
  9752. auto handled = false;
  9753. Server svr;
  9754. svr.Post("/test", [&](const Request &req, Response &res) {
  9755. ASSERT_EQ(2u, req.form.files.size());
  9756. ASSERT_EQ(1u, req.form.fields.size());
  9757. // Test files
  9758. const auto &file1 = req.form.get_file("file1");
  9759. ASSERT_EQ("file1", file1.name);
  9760. ASSERT_EQ("A.txt", file1.filename);
  9761. ASSERT_EQ("text/plain", file1.content_type);
  9762. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  9763. const auto &file2 = req.form.get_file("file2");
  9764. ASSERT_EQ("file2", file2.name);
  9765. ASSERT_EQ("a.html", file2.filename);
  9766. ASSERT_EQ("text/html", file2.content_type);
  9767. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  9768. file2.content);
  9769. // Test text field
  9770. const auto &text = req.form.get_field("text");
  9771. ASSERT_EQ("text default", text);
  9772. res.set_content("ok", "text/plain");
  9773. handled = true;
  9774. });
  9775. thread t = thread([&] { svr.listen(HOST, PORT); });
  9776. auto se = detail::scope_exit([&] {
  9777. svr.stop();
  9778. t.join();
  9779. ASSERT_FALSE(svr.is_running());
  9780. ASSERT_TRUE(handled);
  9781. });
  9782. svr.wait_until_ready();
  9783. auto req = "POST /test HTTP/1.1\r\n"
  9784. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9785. "Content-Length: 399\r\n"
  9786. "\r\n"
  9787. "----------\r\n"
  9788. "Content-Disposition: form-data; name=\"text\"\r\n"
  9789. "\r\n"
  9790. "text default\r\n"
  9791. "----------\r\n"
  9792. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  9793. "filename=\"a.txt\"; name=\"file1\"\r\n"
  9794. "Content-Type: text/plain\r\n"
  9795. "\r\n"
  9796. "Content of a.txt.\r\n"
  9797. "\r\n"
  9798. "----------\r\n"
  9799. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  9800. "\"a.html\"\r\n"
  9801. "Content-Type: text/html\r\n"
  9802. "\r\n"
  9803. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  9804. "\r\n"
  9805. "------------\r\n";
  9806. ASSERT_TRUE(send_request(1, req));
  9807. }
  9808. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  9809. auto handled = false;
  9810. Server svr;
  9811. svr.Post("/test", [&](const Request &req, Response &res) {
  9812. // Case-insensitive "utf-8''" prefix with a long value
  9813. const auto &file = req.form.get_file("file1");
  9814. ASSERT_EQ("file1", file.name);
  9815. // 8000 chars exercises both the Content-Disposition parser and the
  9816. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  9817. // Prior to the fix, std::regex_match on this header would cause O(N)
  9818. // stack recursion in libstdc++, leading to SIGSEGV.
  9819. std::string expected_filename(8000, 'A');
  9820. ASSERT_EQ(expected_filename, file.filename);
  9821. res.set_content("ok", "text/plain");
  9822. handled = true;
  9823. });
  9824. thread t = thread([&] { svr.listen(HOST, PORT); });
  9825. auto se = detail::scope_exit([&] {
  9826. svr.stop();
  9827. t.join();
  9828. ASSERT_FALSE(svr.is_running());
  9829. ASSERT_TRUE(handled);
  9830. });
  9831. svr.wait_until_ready();
  9832. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  9833. // Regression test for GHSA-qq6v-r583-3h69
  9834. std::string long_filename(8000, 'A');
  9835. std::string body = "----------\r\n"
  9836. "Content-Disposition: form-data; name=\"file1\"; "
  9837. "filename*=\"Utf-8''" +
  9838. long_filename +
  9839. "\"\r\n"
  9840. "\r\n"
  9841. "hello\r\n"
  9842. "------------\r\n";
  9843. auto req = "POST /test HTTP/1.1\r\n"
  9844. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9845. "Content-Length: " +
  9846. std::to_string(body.size()) + "\r\n\r\n" + body;
  9847. ASSERT_TRUE(send_request(1, req));
  9848. }
  9849. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  9850. auto handled = false;
  9851. Server svr;
  9852. svr.Post("/test", [&](const Request &req, Response &) {
  9853. ASSERT_EQ(2u, req.form.fields.size());
  9854. const auto &text1 = req.form.get_field("text1");
  9855. ASSERT_EQ("text1", text1);
  9856. const auto &text2 = req.form.get_field("text2");
  9857. ASSERT_EQ("text2", text2);
  9858. handled = true;
  9859. });
  9860. thread t = thread([&] { svr.listen(HOST, PORT); });
  9861. auto se = detail::scope_exit([&] {
  9862. svr.stop();
  9863. t.join();
  9864. ASSERT_FALSE(svr.is_running());
  9865. ASSERT_TRUE(handled);
  9866. });
  9867. svr.wait_until_ready();
  9868. auto req = "POST /test HTTP/1.1\r\n"
  9869. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9870. "Content-Length: 146\r\n"
  9871. "\r\n----------\r\n"
  9872. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9873. "\r\n"
  9874. "text1"
  9875. "\r\n----------\r\n"
  9876. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9877. "\r\n"
  9878. "text2"
  9879. "\r\n------------";
  9880. std::string response;
  9881. ASSERT_TRUE(send_request(1, req, &response));
  9882. ASSERT_EQ("200", response.substr(9, 3));
  9883. }
  9884. TEST(MultipartFormDataTest, ContentLength) {
  9885. auto handled = false;
  9886. Server svr;
  9887. svr.Post("/test", [&](const Request &req, Response &) {
  9888. ASSERT_EQ(2u, req.form.fields.size());
  9889. const auto &text1 = req.form.get_field("text1");
  9890. ASSERT_EQ("text1", text1);
  9891. const auto &text2 = req.form.get_field("text2");
  9892. ASSERT_EQ("text2", text2);
  9893. handled = true;
  9894. });
  9895. thread t = thread([&] { svr.listen(HOST, PORT); });
  9896. auto se = detail::scope_exit([&] {
  9897. svr.stop();
  9898. t.join();
  9899. ASSERT_FALSE(svr.is_running());
  9900. ASSERT_TRUE(handled);
  9901. });
  9902. svr.wait_until_ready();
  9903. auto req = "POST /test HTTP/1.1\r\n"
  9904. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9905. "Content-Length: 167\r\n"
  9906. "\r\n----------\r\n"
  9907. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9908. "Content-Length: 5\r\n"
  9909. "\r\n"
  9910. "text1"
  9911. "\r\n----------\r\n"
  9912. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9913. "\r\n"
  9914. "text2"
  9915. "\r\n------------\r\n";
  9916. std::string response;
  9917. ASSERT_TRUE(send_request(1, req, &response));
  9918. ASSERT_EQ("200", response.substr(9, 3));
  9919. }
  9920. TEST(MultipartFormDataTest, AccessPartHeaders) {
  9921. auto handled = false;
  9922. Server svr;
  9923. svr.Post("/test", [&](const Request &req, Response &) {
  9924. ASSERT_EQ(2u, req.form.fields.size());
  9925. const auto &text1 = req.form.get_field("text1");
  9926. ASSERT_EQ("text1", text1);
  9927. // TODO: Add header access for text fields if needed
  9928. const auto &text2 = req.form.get_field("text2");
  9929. ASSERT_EQ("text2", text2);
  9930. // TODO: Header access for text fields needs to be implemented
  9931. // auto &headers = it->second.headers;
  9932. // ASSERT_EQ(3U, headers.size());
  9933. // auto custom_header = headers.find("x-whatever");
  9934. // ASSERT_TRUE(custom_header != headers.end());
  9935. // ASSERT_NE("customvalue", custom_header->second);
  9936. // ASSERT_EQ("CustomValue", custom_header->second);
  9937. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  9938. handled = true;
  9939. });
  9940. thread t = thread([&] { svr.listen(HOST, PORT); });
  9941. auto se = detail::scope_exit([&] {
  9942. svr.stop();
  9943. t.join();
  9944. ASSERT_FALSE(svr.is_running());
  9945. ASSERT_TRUE(handled);
  9946. });
  9947. svr.wait_until_ready();
  9948. auto req = "POST /test HTTP/1.1\r\n"
  9949. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9950. "Content-Length: 232\r\n"
  9951. "\r\n----------\r\n"
  9952. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9953. "Content-Length: 5\r\n"
  9954. "X-Test: 1\r\n"
  9955. "\r\n"
  9956. "text1"
  9957. "\r\n----------\r\n"
  9958. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9959. "Content-Type: text/plain\r\n"
  9960. "X-Whatever: CustomValue\r\n"
  9961. "\r\n"
  9962. "text2"
  9963. "\r\n------------\r\n"
  9964. "That should be disregarded. Not even read";
  9965. std::string response;
  9966. ASSERT_TRUE(send_request(1, req, &response));
  9967. ASSERT_EQ("200", response.substr(9, 3));
  9968. }
  9969. TEST(MultipartFormDataTest, LargeHeader) {
  9970. auto handled = false;
  9971. Server svr;
  9972. svr.Post("/test", [&](const Request &req, Response &) {
  9973. ASSERT_EQ(1u, req.form.fields.size());
  9974. const auto &text = req.form.get_field("name1");
  9975. ASSERT_EQ("text1", text);
  9976. handled = true;
  9977. });
  9978. thread t = thread([&] { svr.listen(HOST, PORT); });
  9979. auto se = detail::scope_exit([&] {
  9980. svr.stop();
  9981. t.join();
  9982. ASSERT_FALSE(svr.is_running());
  9983. ASSERT_TRUE(handled);
  9984. });
  9985. svr.wait_until_ready();
  9986. auto boundary = std::string("cpp-httplib-multipart-data");
  9987. std::string content = "--" + boundary +
  9988. "\r\n"
  9989. "Content-Disposition: form-data; name=\"name1\"\r\n"
  9990. "\r\n"
  9991. "text1\r\n"
  9992. "--" +
  9993. boundary + "--\r\n";
  9994. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  9995. "Content-Type: multipart/form-data;boundary=" +
  9996. boundary +
  9997. "\r\n"
  9998. "Content-Length: " +
  9999. std::to_string(content.size()) +
  10000. "\r\n"
  10001. "Dummy-Header: ";
  10002. std::string header_suffix = "\r\n"
  10003. "\r\n";
  10004. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  10005. size_t header_dummy_size =
  10006. read_buff_size -
  10007. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  10008. auto header_dummy = std::string(header_dummy_size, '@');
  10009. auto req = header_prefix + header_dummy + header_suffix + content;
  10010. std::string response;
  10011. ASSERT_TRUE(send_request(1, req, &response));
  10012. ASSERT_EQ("200", response.substr(9, 3));
  10013. }
  10014. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  10015. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  10016. // (not chunked Transfer-Encoding) after the streaming refactor.
  10017. auto handled = false;
  10018. Server svr;
  10019. svr.Post("/upload", [&](const Request &req, Response &res) {
  10020. auto cl_it = req.headers.find("Content-Length");
  10021. EXPECT_TRUE(cl_it != req.headers.end());
  10022. auto te_it = req.headers.find("Transfer-Encoding");
  10023. EXPECT_TRUE(te_it == req.headers.end());
  10024. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  10025. res.set_content("ok", "text/plain");
  10026. handled = true;
  10027. });
  10028. auto port = svr.bind_to_any_port(HOST);
  10029. auto t = thread([&] { svr.listen_after_bind(); });
  10030. auto se = detail::scope_exit([&] {
  10031. svr.stop();
  10032. t.join();
  10033. ASSERT_FALSE(svr.is_running());
  10034. ASSERT_TRUE(handled);
  10035. });
  10036. svr.wait_until_ready();
  10037. UploadFormDataItems items = {
  10038. {"field1", "hello", "", "text/plain"},
  10039. {"file1", "world", "test.txt", "application/octet-stream"},
  10040. };
  10041. Client cli(HOST, port);
  10042. auto res = cli.Post("/upload", {}, items);
  10043. ASSERT_TRUE(res);
  10044. EXPECT_EQ(StatusCode::OK_200, res->status);
  10045. }
  10046. TEST(MultipartFormDataTest, MakeFileProvider) {
  10047. // Verify make_file_provider sends a file's contents correctly.
  10048. const std::string file_content(4096, 'Z');
  10049. const std::string tmp_path = "/tmp/httplib_test_make_file_provider.bin";
  10050. {
  10051. std::ofstream ofs(tmp_path, std::ios::binary);
  10052. ofs.write(file_content.data(),
  10053. static_cast<std::streamsize>(file_content.size()));
  10054. }
  10055. auto handled = false;
  10056. Server svr;
  10057. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  10058. const ContentReader &content_reader) {
  10059. ASSERT_TRUE(req.is_multipart_form_data());
  10060. std::vector<FormData> items;
  10061. content_reader(
  10062. [&](const FormData &file) {
  10063. items.push_back(file);
  10064. return true;
  10065. },
  10066. [&](const char *data, size_t data_length) {
  10067. items.back().content.append(data, data_length);
  10068. return true;
  10069. });
  10070. ASSERT_EQ(1u, items.size());
  10071. EXPECT_EQ("myfile", items[0].name);
  10072. EXPECT_EQ("data.bin", items[0].filename);
  10073. EXPECT_EQ("application/octet-stream", items[0].content_type);
  10074. EXPECT_EQ(file_content, items[0].content);
  10075. handled = true;
  10076. });
  10077. auto port = svr.bind_to_any_port(HOST);
  10078. auto t = thread([&] { svr.listen_after_bind(); });
  10079. auto se = detail::scope_exit([&] {
  10080. svr.stop();
  10081. t.join();
  10082. ASSERT_FALSE(svr.is_running());
  10083. ASSERT_TRUE(handled);
  10084. std::remove(tmp_path.c_str());
  10085. });
  10086. svr.wait_until_ready();
  10087. FormDataProviderItems providers;
  10088. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  10089. "application/octet-stream"));
  10090. Client cli(HOST, port);
  10091. auto res = cli.Post("/upload", {}, {}, providers);
  10092. ASSERT_TRUE(res);
  10093. EXPECT_EQ(StatusCode::OK_200, res->status);
  10094. }
  10095. TEST(MakeFileBodyTest, Basic) {
  10096. const std::string file_content(4096, 'Z');
  10097. const std::string tmp_path = "/tmp/httplib_test_make_file_body.bin";
  10098. {
  10099. std::ofstream ofs(tmp_path, std::ios::binary);
  10100. ofs.write(file_content.data(),
  10101. static_cast<std::streamsize>(file_content.size()));
  10102. }
  10103. auto handled = false;
  10104. Server svr;
  10105. svr.Post("/upload", [&](const Request &req, Response &res) {
  10106. EXPECT_EQ(file_content, req.body);
  10107. handled = true;
  10108. res.status = StatusCode::OK_200;
  10109. });
  10110. auto port = svr.bind_to_any_port(HOST);
  10111. auto t = thread([&] { svr.listen_after_bind(); });
  10112. auto se = detail::scope_exit([&] {
  10113. svr.stop();
  10114. t.join();
  10115. ASSERT_FALSE(svr.is_running());
  10116. ASSERT_TRUE(handled);
  10117. std::remove(tmp_path.c_str());
  10118. });
  10119. svr.wait_until_ready();
  10120. auto fb = make_file_body(tmp_path);
  10121. ASSERT_GT(fb.first, 0u);
  10122. Client cli(HOST, port);
  10123. auto res =
  10124. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  10125. ASSERT_TRUE(res);
  10126. EXPECT_EQ(StatusCode::OK_200, res->status);
  10127. }
  10128. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  10129. static constexpr unsigned int number_of_tasks{1000000};
  10130. std::atomic_uint count{0};
  10131. std::unique_ptr<TaskQueue> task_queue{
  10132. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  10133. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10134. auto queued = task_queue->enqueue(
  10135. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  10136. EXPECT_TRUE(queued);
  10137. }
  10138. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10139. task_queue->shutdown();
  10140. #else
  10141. EXPECT_NO_THROW(task_queue->shutdown());
  10142. #endif
  10143. EXPECT_EQ(number_of_tasks, count.load());
  10144. }
  10145. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  10146. static constexpr unsigned int number_of_tasks{1000000};
  10147. static constexpr unsigned int qlimit{2};
  10148. unsigned int queued_count{0};
  10149. std::atomic_uint count{0};
  10150. std::unique_ptr<TaskQueue> task_queue{
  10151. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  10152. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10153. if (task_queue->enqueue(
  10154. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  10155. queued_count++;
  10156. }
  10157. }
  10158. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10159. task_queue->shutdown();
  10160. #else
  10161. EXPECT_NO_THROW(task_queue->shutdown());
  10162. #endif
  10163. EXPECT_EQ(queued_count, count.load());
  10164. EXPECT_TRUE(queued_count <= number_of_tasks);
  10165. EXPECT_TRUE(queued_count >= qlimit);
  10166. }
  10167. TEST(TaskQueueTest, MaxQueuedRequests) {
  10168. static constexpr unsigned int qlimit{3};
  10169. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  10170. std::condition_variable sem_cv;
  10171. std::mutex sem_mtx;
  10172. int credits = 0;
  10173. bool queued;
  10174. /* Fill up the queue with tasks that will block until we give them credits to
  10175. * complete. */
  10176. for (unsigned int n = 0; n <= qlimit;) {
  10177. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  10178. std::unique_lock<std::mutex> lock(sem_mtx);
  10179. while (credits <= 0) {
  10180. sem_cv.wait(lock);
  10181. }
  10182. /* Consume the credit and signal the test code if they are all gone. */
  10183. if (--credits == 0) { sem_cv.notify_one(); }
  10184. });
  10185. if (n < qlimit) {
  10186. /* The first qlimit enqueues must succeed. */
  10187. EXPECT_TRUE(queued);
  10188. } else {
  10189. /* The last one will succeed only when the worker thread
  10190. * starts and dequeues the first blocking task. Although
  10191. * not necessary for the correctness of this test, we sleep for
  10192. * a short while to avoid busy waiting. */
  10193. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10194. }
  10195. if (queued) { n++; }
  10196. }
  10197. /* Further enqueues must fail since the queue is full. */
  10198. for (auto i = 0; i < 4; i++) {
  10199. queued = task_queue->enqueue([] {});
  10200. EXPECT_FALSE(queued);
  10201. }
  10202. /* Give the credits to allow the previous tasks to complete. */
  10203. {
  10204. std::unique_lock<std::mutex> lock(sem_mtx);
  10205. credits += qlimit + 1;
  10206. }
  10207. sem_cv.notify_all();
  10208. /* Wait for all the credits to be consumed. */
  10209. {
  10210. std::unique_lock<std::mutex> lock(sem_mtx);
  10211. while (credits > 0) {
  10212. sem_cv.wait(lock);
  10213. }
  10214. }
  10215. /* Check that we are able again to enqueue at least qlimit tasks. */
  10216. for (unsigned int i = 0; i < qlimit; i++) {
  10217. queued = task_queue->enqueue([] {});
  10218. EXPECT_TRUE(queued);
  10219. }
  10220. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10221. task_queue->shutdown();
  10222. #else
  10223. EXPECT_NO_THROW(task_queue->shutdown());
  10224. #endif
  10225. }
  10226. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  10227. Server svr;
  10228. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10229. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  10230. });
  10231. svr.Get("/hello", [](const Request &req, Response &res) {
  10232. res.set_content(req.get_param_value("key"), "text/plain");
  10233. });
  10234. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10235. auto se = detail::scope_exit([&] {
  10236. svr.stop();
  10237. thread.join();
  10238. ASSERT_FALSE(svr.is_running());
  10239. });
  10240. svr.wait_until_ready();
  10241. {
  10242. Client cli(HOST, PORT);
  10243. cli.set_follow_location(true);
  10244. auto res = cli.Get("/");
  10245. ASSERT_TRUE(res);
  10246. EXPECT_EQ(StatusCode::OK_200, res->status);
  10247. EXPECT_EQ("val&key2=val2", res->body);
  10248. }
  10249. }
  10250. #endif
  10251. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  10252. Server svr;
  10253. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10254. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  10255. });
  10256. svr.Get("/hello", [](const Request &req, Response &res) {
  10257. res.set_content(req.get_param_value("key"), "text/plain");
  10258. });
  10259. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10260. auto se = detail::scope_exit([&] {
  10261. svr.stop();
  10262. thread.join();
  10263. ASSERT_FALSE(svr.is_running());
  10264. });
  10265. svr.wait_until_ready();
  10266. {
  10267. Client cli(HOST, PORT);
  10268. cli.set_follow_location(true);
  10269. auto res = cli.Get("/");
  10270. ASSERT_TRUE(res);
  10271. EXPECT_EQ(StatusCode::OK_200, res->status);
  10272. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  10273. }
  10274. }
  10275. #ifdef CPPHTTPLIB_SSL_ENABLED
  10276. TEST(RedirectTest, Issue2185_Online) {
  10277. SSLClient client("github.com");
  10278. client.set_follow_location(true);
  10279. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  10280. "Coollab-Windows.zip");
  10281. ASSERT_TRUE(res);
  10282. EXPECT_EQ(StatusCode::OK_200, res->status);
  10283. EXPECT_EQ(9920427U, res->body.size());
  10284. }
  10285. #endif
  10286. TEST(VulnerabilityTest, CRLFInjection) {
  10287. Server svr;
  10288. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  10289. res.set_content("Hello 1", "text/plain");
  10290. });
  10291. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  10292. res.set_content("Hello 2", "text/plain");
  10293. });
  10294. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  10295. res.set_content("Hello 3", "text/plain");
  10296. });
  10297. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  10298. res.set_content("Hello 4", "text/plain");
  10299. });
  10300. svr.set_logger([](const Request &req, const Response & /*res*/) {
  10301. for (const auto &x : req.headers) {
  10302. auto key = x.first;
  10303. EXPECT_STRNE("evil", key.c_str());
  10304. }
  10305. });
  10306. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10307. auto se = detail::scope_exit([&] {
  10308. svr.stop();
  10309. thread.join();
  10310. ASSERT_FALSE(svr.is_running());
  10311. });
  10312. svr.wait_until_ready();
  10313. {
  10314. Client cli(HOST, PORT);
  10315. cli.Post("/test1", "A=B",
  10316. "application/x-www-form-urlencoded\r\nevil: hello1");
  10317. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  10318. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  10319. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  10320. }
  10321. }
  10322. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  10323. auto server_thread = std::thread([] {
  10324. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10325. default_socket_options(srv);
  10326. sockaddr_in addr{};
  10327. addr.sin_family = AF_INET;
  10328. addr.sin_port = htons(PORT + 1);
  10329. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10330. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10331. ::listen(srv, 1);
  10332. sockaddr_in cli_addr{};
  10333. socklen_t cli_len = sizeof(cli_addr);
  10334. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10335. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  10336. std::string buf_all;
  10337. char buf[2048];
  10338. ssize_t n;
  10339. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  10340. buf_all.append(buf, static_cast<size_t>(n));
  10341. size_t pos;
  10342. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  10343. auto request_block = buf_all.substr(0, pos + 4); // include separator
  10344. auto e = request_block.find("\r\n");
  10345. if (e != std::string::npos) {
  10346. auto request_line = request_block.substr(0, e);
  10347. std::string msg =
  10348. "CRLF injection detected in request line: '" + request_line + "'";
  10349. EXPECT_FALSE(true) << msg;
  10350. }
  10351. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  10352. ::send(cli,
  10353. #ifdef _WIN32
  10354. static_cast<const char *>(resp.c_str()),
  10355. static_cast<int>(resp.size()),
  10356. #else
  10357. resp.c_str(), resp.size(),
  10358. #endif
  10359. 0);
  10360. buf_all.erase(0, pos + 4);
  10361. }
  10362. }
  10363. detail::close_socket(cli);
  10364. detail::close_socket(srv);
  10365. });
  10366. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10367. auto cli = Client("127.0.0.1", PORT + 1);
  10368. auto headers = Headers{
  10369. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  10370. {"Connection", "keep-alive"}};
  10371. auto res = cli.Get("/hi", headers);
  10372. EXPECT_FALSE(res);
  10373. EXPECT_EQ(Error::InvalidHeaders, res.error());
  10374. server_thread.join();
  10375. }
  10376. TEST(PathParamsTest, StaticMatch) {
  10377. const auto pattern = "/users/all";
  10378. detail::PathParamsMatcher matcher(pattern);
  10379. Request request;
  10380. request.path = "/users/all";
  10381. ASSERT_TRUE(matcher.match(request));
  10382. std::unordered_map<std::string, std::string> expected_params = {};
  10383. EXPECT_EQ(request.path_params, expected_params);
  10384. }
  10385. TEST(PathParamsTest, StaticMismatch) {
  10386. const auto pattern = "/users/all";
  10387. detail::PathParamsMatcher matcher(pattern);
  10388. Request request;
  10389. request.path = "/users/1";
  10390. ASSERT_FALSE(matcher.match(request));
  10391. }
  10392. TEST(PathParamsTest, SingleParamInTheMiddle) {
  10393. const auto pattern = "/users/:id/subscriptions";
  10394. detail::PathParamsMatcher matcher(pattern);
  10395. Request request;
  10396. request.path = "/users/42/subscriptions";
  10397. ASSERT_TRUE(matcher.match(request));
  10398. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10399. EXPECT_EQ(request.path_params, expected_params);
  10400. }
  10401. TEST(PathParamsTest, SingleParamInTheEnd) {
  10402. const auto pattern = "/users/:id";
  10403. detail::PathParamsMatcher matcher(pattern);
  10404. Request request;
  10405. request.path = "/users/24";
  10406. ASSERT_TRUE(matcher.match(request));
  10407. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  10408. EXPECT_EQ(request.path_params, expected_params);
  10409. }
  10410. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  10411. const auto pattern = "/users/:id/";
  10412. detail::PathParamsMatcher matcher(pattern);
  10413. Request request;
  10414. request.path = "/users/42/";
  10415. ASSERT_TRUE(matcher.match(request));
  10416. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10417. EXPECT_EQ(request.path_params, expected_params);
  10418. }
  10419. TEST(PathParamsTest, EmptyParam) {
  10420. const auto pattern = "/users/:id/";
  10421. detail::PathParamsMatcher matcher(pattern);
  10422. Request request;
  10423. request.path = "/users//";
  10424. ASSERT_TRUE(matcher.match(request));
  10425. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10426. EXPECT_EQ(request.path_params, expected_params);
  10427. }
  10428. TEST(PathParamsTest, FragmentMismatch) {
  10429. const auto pattern = "/users/:id/";
  10430. detail::PathParamsMatcher matcher(pattern);
  10431. Request request;
  10432. request.path = "/admins/24/";
  10433. ASSERT_FALSE(matcher.match(request));
  10434. }
  10435. TEST(PathParamsTest, ExtraFragments) {
  10436. const auto pattern = "/users/:id";
  10437. detail::PathParamsMatcher matcher(pattern);
  10438. Request request;
  10439. request.path = "/users/42/subscriptions";
  10440. ASSERT_FALSE(matcher.match(request));
  10441. }
  10442. TEST(PathParamsTest, MissingTrailingParam) {
  10443. const auto pattern = "/users/:id";
  10444. detail::PathParamsMatcher matcher(pattern);
  10445. Request request;
  10446. request.path = "/users";
  10447. ASSERT_FALSE(matcher.match(request));
  10448. }
  10449. TEST(PathParamsTest, MissingParamInTheMiddle) {
  10450. const auto pattern = "/users/:id/subscriptions";
  10451. detail::PathParamsMatcher matcher(pattern);
  10452. Request request;
  10453. request.path = "/users/subscriptions";
  10454. ASSERT_FALSE(matcher.match(request));
  10455. }
  10456. TEST(PathParamsTest, MultipleParams) {
  10457. const auto pattern = "/users/:userid/subscriptions/:subid";
  10458. detail::PathParamsMatcher matcher(pattern);
  10459. Request request;
  10460. request.path = "/users/42/subscriptions/2";
  10461. ASSERT_TRUE(matcher.match(request));
  10462. std::unordered_map<std::string, std::string> expected_params = {
  10463. {"userid", "42"}, {"subid", "2"}};
  10464. EXPECT_EQ(request.path_params, expected_params);
  10465. }
  10466. TEST(PathParamsTest, SequenceOfParams) {
  10467. const auto pattern = "/values/:x/:y/:z";
  10468. detail::PathParamsMatcher matcher(pattern);
  10469. Request request;
  10470. request.path = "/values/1/2/3";
  10471. ASSERT_TRUE(matcher.match(request));
  10472. std::unordered_map<std::string, std::string> expected_params = {
  10473. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  10474. EXPECT_EQ(request.path_params, expected_params);
  10475. }
  10476. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  10477. const auto pattern = "/prefix:suffix";
  10478. detail::PathParamsMatcher matcher(pattern);
  10479. Request request;
  10480. request.path = "/prefix:suffix";
  10481. ASSERT_TRUE(matcher.match(request));
  10482. const std::unordered_map<std::string, std::string> expected_params = {};
  10483. EXPECT_EQ(request.path_params, expected_params);
  10484. }
  10485. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  10486. // If ipv6 regex working, regex match codepath is taken.
  10487. // else port will default to 80 in Client impl
  10488. int clientImplMagicPort = 80;
  10489. int port = 4321;
  10490. // above ports must be different to avoid false negative
  10491. EXPECT_NE(clientImplMagicPort, port);
  10492. std::string ipV6TestURL = "http://[ff06::c3]";
  10493. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  10494. CLIENT_PRIVATE_KEY_FILE);
  10495. EXPECT_EQ(cli.port(), port);
  10496. }
  10497. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  10498. auto file_path = "./www/dir/index.html";
  10499. auto dir_path = "./www/dir";
  10500. detail::FileStat stat_file(file_path);
  10501. EXPECT_TRUE(stat_file.is_file());
  10502. EXPECT_FALSE(stat_file.is_dir());
  10503. detail::FileStat stat_dir(dir_path);
  10504. EXPECT_FALSE(stat_dir.is_file());
  10505. EXPECT_TRUE(stat_dir.is_dir());
  10506. }
  10507. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  10508. // IPv4 with default HTTP port (80)
  10509. EXPECT_EQ("example.com",
  10510. detail::make_host_and_port_string("example.com", 80, false));
  10511. // IPv4 with default HTTPS port (443)
  10512. EXPECT_EQ("example.com",
  10513. detail::make_host_and_port_string("example.com", 443, true));
  10514. // IPv4 with non-default HTTP port
  10515. EXPECT_EQ("example.com:8080",
  10516. detail::make_host_and_port_string("example.com", 8080, false));
  10517. // IPv4 with non-default HTTPS port
  10518. EXPECT_EQ("example.com:8443",
  10519. detail::make_host_and_port_string("example.com", 8443, true));
  10520. // IPv6 with default HTTP port (80)
  10521. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  10522. // IPv6 with default HTTPS port (443)
  10523. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  10524. // IPv6 with non-default HTTP port
  10525. EXPECT_EQ("[::1]:8080",
  10526. detail::make_host_and_port_string("::1", 8080, false));
  10527. // IPv6 with non-default HTTPS port
  10528. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  10529. // IPv6 full address with default port
  10530. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  10531. detail::make_host_and_port_string(
  10532. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  10533. // IPv6 full address with non-default port
  10534. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  10535. detail::make_host_and_port_string(
  10536. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  10537. // IPv6 localhost with non-default port
  10538. EXPECT_EQ("[::1]:3000",
  10539. detail::make_host_and_port_string("::1", 3000, false));
  10540. // IPv6 with zone ID (link-local address) with default port
  10541. EXPECT_EQ("[fe80::1%eth0]",
  10542. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  10543. // IPv6 with zone ID (link-local address) with non-default port
  10544. EXPECT_EQ("[fe80::1%eth0]:8080",
  10545. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  10546. // Edge case: Port 443 with is_ssl=false (should add port)
  10547. EXPECT_EQ("example.com:443",
  10548. detail::make_host_and_port_string("example.com", 443, false));
  10549. // Edge case: Port 80 with is_ssl=true (should add port)
  10550. EXPECT_EQ("example.com:80",
  10551. detail::make_host_and_port_string("example.com", 80, true));
  10552. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  10553. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  10554. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  10555. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  10556. // Security fix: Already bracketed IPv6 should not get double brackets
  10557. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  10558. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  10559. EXPECT_EQ("[::1]:8080",
  10560. detail::make_host_and_port_string("[::1]", 8080, false));
  10561. EXPECT_EQ("[2001:db8::1]:8080",
  10562. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  10563. EXPECT_EQ("[fe80::1%eth0]",
  10564. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  10565. EXPECT_EQ("[fe80::1%eth0]:8080",
  10566. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  10567. // Edge case: Empty host (should return as-is)
  10568. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  10569. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  10570. // This is a known limitation but shouldn't crash
  10571. EXPECT_EQ("[host:name]",
  10572. detail::make_host_and_port_string("host:name", 80, false));
  10573. // Port number edge cases (no validation, but should not crash)
  10574. EXPECT_EQ("example.com:0",
  10575. detail::make_host_and_port_string("example.com", 0, false));
  10576. EXPECT_EQ("example.com:-1",
  10577. detail::make_host_and_port_string("example.com", -1, false));
  10578. EXPECT_EQ("example.com:65535",
  10579. detail::make_host_and_port_string("example.com", 65535, false));
  10580. EXPECT_EQ("example.com:65536",
  10581. detail::make_host_and_port_string("example.com", 65536, false));
  10582. }
  10583. #ifdef CPPHTTPLIB_SSL_ENABLED
  10584. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  10585. httplib::SSLClient cli("roblox.com", 443);
  10586. cli.set_follow_location(true);
  10587. auto res = cli.Get("/");
  10588. ASSERT_TRUE(res);
  10589. EXPECT_EQ(StatusCode::OK_200, res->status);
  10590. }
  10591. #endif
  10592. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  10593. Server svr;
  10594. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10595. EXPECT_EQ(res.status, 400);
  10596. });
  10597. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10598. auto se = detail::scope_exit([&] {
  10599. svr.stop();
  10600. thread.join();
  10601. ASSERT_FALSE(svr.is_running());
  10602. });
  10603. svr.wait_until_ready();
  10604. Client cli(HOST, PORT);
  10605. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  10606. }
  10607. TEST(InvalidHeaderCharsTest, is_field_name) {
  10608. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  10609. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  10610. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  10611. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  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("token@123"));
  10615. EXPECT_FALSE(detail::fields::is_field_name(""));
  10616. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  10617. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  10618. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  10619. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  10620. }
  10621. TEST(InvalidHeaderCharsTest, is_field_value) {
  10622. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  10623. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  10624. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  10625. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  10626. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  10627. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  10628. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  10629. EXPECT_TRUE(detail::fields::is_field_value(""));
  10630. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  10631. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  10632. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  10633. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  10634. EXPECT_TRUE(detail::fields::is_field_value("0"));
  10635. }
  10636. TEST(InvalidHeaderCharsTest, OnServer) {
  10637. Server svr;
  10638. svr.Get("/test_name", [&](const Request &req, Response &res) {
  10639. std::string header = "Not Set";
  10640. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10641. res.set_header(header, "value");
  10642. res.set_content("Page Content Page Content", "text/plain");
  10643. });
  10644. svr.Get("/test_value", [&](const Request &req, Response &res) {
  10645. std::string header = "Not Set";
  10646. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10647. res.set_header("X-Test", header);
  10648. res.set_content("Page Content Page Content", "text/plain");
  10649. });
  10650. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10651. auto se = detail::scope_exit([&] {
  10652. svr.stop();
  10653. thread.join();
  10654. ASSERT_FALSE(svr.is_running());
  10655. });
  10656. svr.wait_until_ready();
  10657. Client cli(HOST, PORT);
  10658. {
  10659. auto res = cli.Get(
  10660. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10661. ASSERT_TRUE(res);
  10662. EXPECT_EQ("Page Content Page Content", res->body);
  10663. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10664. }
  10665. {
  10666. auto res = cli.Get(
  10667. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10668. ASSERT_TRUE(res);
  10669. EXPECT_EQ("Page Content Page Content", res->body);
  10670. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10671. }
  10672. }
  10673. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  10674. auto handled = false;
  10675. Server svr;
  10676. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10677. thread t = thread([&] { svr.listen(HOST, PORT); });
  10678. auto se = detail::scope_exit([&] {
  10679. svr.stop();
  10680. t.join();
  10681. ASSERT_FALSE(svr.is_running());
  10682. ASSERT_FALSE(handled);
  10683. });
  10684. svr.wait_until_ready();
  10685. auto req = "POST /test HTTP/1.1\r\n"
  10686. "Content-Length: x\r\n"
  10687. "\r\n";
  10688. std::string response;
  10689. ASSERT_TRUE(send_request(1, req, &response));
  10690. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10691. response.substr(0, response.find("\r\n")));
  10692. }
  10693. #ifndef _WIN32
  10694. TEST(Expect100ContinueTest, ServerClosesConnection) {
  10695. static constexpr char reject[] = "Unauthorized";
  10696. static constexpr char accept[] = "Upload accepted";
  10697. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  10698. Server svr;
  10699. svr.set_expect_100_continue_handler(
  10700. [](const Request & /*req*/, Response &res) {
  10701. res.status = StatusCode::Unauthorized_401;
  10702. res.set_content(reject, "text/plain");
  10703. return res.status;
  10704. });
  10705. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  10706. res.set_content(accept, "text/plain");
  10707. });
  10708. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10709. auto se = detail::scope_exit([&] {
  10710. svr.stop();
  10711. thread.join();
  10712. ASSERT_FALSE(svr.is_running());
  10713. });
  10714. svr.wait_until_ready();
  10715. {
  10716. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  10717. curl_easy_init(), &curl_easy_cleanup};
  10718. ASSERT_NE(curl, nullptr);
  10719. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  10720. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  10721. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  10722. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  10723. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  10724. &curl_slist_free_all};
  10725. ASSERT_NE(list, nullptr);
  10726. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  10727. struct read_data {
  10728. size_t read_size;
  10729. size_t total_size;
  10730. } data = {0, total_size};
  10731. using read_callback_t =
  10732. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10733. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  10734. void *userdata) -> size_t {
  10735. read_data *data = (read_data *)userdata;
  10736. if (!userdata || data->read_size >= data->total_size) { return 0; }
  10737. std::fill_n(ptr, size * nmemb, 'A');
  10738. data->read_size += size * nmemb;
  10739. return size * nmemb;
  10740. };
  10741. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  10742. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  10743. std::vector<char> buffer;
  10744. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  10745. using write_callback_t =
  10746. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10747. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  10748. void *userdata) -> size_t {
  10749. std::vector<char> *buffer = (std::vector<char> *)userdata;
  10750. buffer->reserve(buffer->size() + size * nmemb + 1);
  10751. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  10752. return size * nmemb;
  10753. };
  10754. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  10755. {
  10756. const auto res = curl_easy_perform(curl.get());
  10757. ASSERT_EQ(res, CURLE_OK);
  10758. }
  10759. {
  10760. auto response_code = long{};
  10761. const auto res =
  10762. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  10763. ASSERT_EQ(res, CURLE_OK);
  10764. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  10765. }
  10766. {
  10767. auto dl = curl_off_t{};
  10768. const auto res =
  10769. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  10770. ASSERT_EQ(res, CURLE_OK);
  10771. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  10772. }
  10773. {
  10774. buffer.push_back('\0');
  10775. ASSERT_STRCASEEQ(buffer.data(), reject);
  10776. }
  10777. }
  10778. }
  10779. #endif
  10780. template <typename S, typename C>
  10781. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  10782. svr.Get("/stream", [&](const Request &, Response &res) {
  10783. auto data = new std::string("01234567890123456789");
  10784. res.set_content_provider(
  10785. data->size(), "text/plain",
  10786. [&, data](size_t offset, size_t length, DataSink &sink) {
  10787. const size_t DATA_CHUNK_SIZE = 4;
  10788. const auto &d = *data;
  10789. std::this_thread::sleep_for(std::chrono::seconds(1));
  10790. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  10791. return true;
  10792. },
  10793. [data](bool success) {
  10794. EXPECT_FALSE(success);
  10795. delete data;
  10796. });
  10797. });
  10798. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  10799. auto i = new size_t(0);
  10800. res.set_content_provider(
  10801. "text/plain",
  10802. [i](size_t, DataSink &sink) {
  10803. if (*i < 5) {
  10804. std::this_thread::sleep_for(std::chrono::seconds(1));
  10805. sink.write("abcd", 4);
  10806. (*i)++;
  10807. } else {
  10808. sink.done();
  10809. }
  10810. return true;
  10811. },
  10812. [i](bool success) {
  10813. EXPECT_FALSE(success);
  10814. delete i;
  10815. });
  10816. });
  10817. svr.Get("/chunked", [&](const Request &, Response &res) {
  10818. auto i = new size_t(0);
  10819. res.set_chunked_content_provider(
  10820. "text/plain",
  10821. [i](size_t, DataSink &sink) {
  10822. if (*i < 5) {
  10823. std::this_thread::sleep_for(std::chrono::seconds(1));
  10824. sink.os << "abcd";
  10825. (*i)++;
  10826. } else {
  10827. sink.done();
  10828. }
  10829. return true;
  10830. },
  10831. [i](bool success) {
  10832. EXPECT_FALSE(success);
  10833. delete i;
  10834. });
  10835. });
  10836. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10837. auto se = detail::scope_exit([&] {
  10838. svr.stop();
  10839. listen_thread.join();
  10840. ASSERT_FALSE(svr.is_running());
  10841. });
  10842. svr.wait_until_ready();
  10843. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  10844. {
  10845. auto start = std::chrono::steady_clock::now();
  10846. auto res = cli.Get("/stream");
  10847. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10848. std::chrono::steady_clock::now() - start)
  10849. .count();
  10850. ASSERT_FALSE(res);
  10851. EXPECT_EQ(Error::Read, res.error());
  10852. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10853. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10854. }
  10855. {
  10856. auto start = std::chrono::steady_clock::now();
  10857. auto res = cli.Get("/stream_without_length");
  10858. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10859. std::chrono::steady_clock::now() - start)
  10860. .count();
  10861. ASSERT_FALSE(res);
  10862. EXPECT_EQ(Error::Read, res.error());
  10863. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10864. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10865. }
  10866. {
  10867. auto start = std::chrono::steady_clock::now();
  10868. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  10869. EXPECT_EQ("abcd", string(data, data_length));
  10870. return true;
  10871. });
  10872. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10873. std::chrono::steady_clock::now() - start)
  10874. .count();
  10875. ASSERT_FALSE(res);
  10876. EXPECT_EQ(Error::Read, res.error());
  10877. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10878. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10879. }
  10880. }
  10881. TEST(MaxTimeoutTest, ContentStream) {
  10882. time_t timeout = 2000;
  10883. time_t threshold = 200;
  10884. Server svr;
  10885. Client cli("localhost", PORT);
  10886. max_timeout_test(svr, cli, timeout, threshold);
  10887. }
  10888. #ifdef CPPHTTPLIB_SSL_ENABLED
  10889. TEST(MaxTimeoutTest, ContentStreamSSL) {
  10890. time_t timeout = 2000;
  10891. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  10892. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10893. SSLClient cli("localhost", PORT);
  10894. cli.enable_server_certificate_verification(false);
  10895. max_timeout_test(svr, cli, timeout, threshold);
  10896. }
  10897. #endif
  10898. class EventDispatcher {
  10899. public:
  10900. EventDispatcher() {}
  10901. bool wait_event(DataSink *sink) {
  10902. unique_lock<mutex> lk(m_);
  10903. int id = id_;
  10904. // Wait with timeout to prevent hanging if client disconnects
  10905. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  10906. [&] { return cid_ == id; })) {
  10907. return false; // Timeout occurred
  10908. }
  10909. sink->write(message_.data(), message_.size());
  10910. return true;
  10911. }
  10912. void send_event(const string &message) {
  10913. lock_guard<mutex> lk(m_);
  10914. cid_ = id_++;
  10915. message_ = message;
  10916. cv_.notify_all();
  10917. }
  10918. private:
  10919. mutex m_;
  10920. condition_variable cv_;
  10921. atomic_int id_{0};
  10922. atomic_int cid_{-1};
  10923. string message_;
  10924. };
  10925. TEST(ClientInThreadTest, Issue2068) {
  10926. EventDispatcher ed;
  10927. Server svr;
  10928. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  10929. res.set_chunked_content_provider("text/event-stream",
  10930. [&](size_t /*offset*/, DataSink &sink) {
  10931. return ed.wait_event(&sink);
  10932. });
  10933. });
  10934. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10935. svr.wait_until_ready();
  10936. thread event_thread([&] {
  10937. int id = 0;
  10938. while (svr.is_running()) {
  10939. this_thread::sleep_for(chrono::milliseconds(500));
  10940. std::stringstream ss;
  10941. ss << "data: " << id << "\n\n";
  10942. ed.send_event(ss.str());
  10943. id++;
  10944. }
  10945. });
  10946. auto se = detail::scope_exit([&] {
  10947. svr.stop();
  10948. listen_thread.join();
  10949. event_thread.join();
  10950. ASSERT_FALSE(svr.is_running());
  10951. });
  10952. {
  10953. auto client = detail::make_unique<Client>(HOST, PORT);
  10954. client->set_read_timeout(std::chrono::minutes(10));
  10955. std::atomic<bool> stop{false};
  10956. std::thread t([&] {
  10957. client->Get("/event1",
  10958. [&](const char *, size_t) -> bool { return !stop; });
  10959. });
  10960. std::this_thread::sleep_for(std::chrono::seconds(2));
  10961. stop = true;
  10962. client->stop();
  10963. t.join();
  10964. // Reset client after thread has finished
  10965. client.reset();
  10966. }
  10967. }
  10968. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  10969. auto handled = false;
  10970. Server svr;
  10971. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10972. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10973. auto se = detail::scope_exit([&] {
  10974. svr.stop();
  10975. t.join();
  10976. ASSERT_FALSE(svr.is_running());
  10977. ASSERT_FALSE(handled);
  10978. });
  10979. svr.wait_until_ready();
  10980. // Two Content-Length headers with different values — must be rejected
  10981. auto req = "POST /test HTTP/1.1\r\n"
  10982. "Content-Length: 5\r\n"
  10983. "Content-Length: 10\r\n"
  10984. "\r\n"
  10985. "hello";
  10986. std::string response;
  10987. ASSERT_TRUE(send_request(1, req, &response));
  10988. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10989. response.substr(0, response.find("\r\n")));
  10990. }
  10991. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  10992. auto handled = false;
  10993. Server svr;
  10994. svr.Post("/test", [&](const Request &, Response &res) {
  10995. handled = true;
  10996. res.set_content("ok", "text/plain");
  10997. });
  10998. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10999. auto se = detail::scope_exit([&] {
  11000. svr.stop();
  11001. t.join();
  11002. ASSERT_FALSE(svr.is_running());
  11003. ASSERT_TRUE(handled);
  11004. });
  11005. svr.wait_until_ready();
  11006. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  11007. auto req = "POST /test HTTP/1.1\r\n"
  11008. "Content-Length: 5\r\n"
  11009. "Content-Length: 5\r\n"
  11010. "\r\n"
  11011. "hello";
  11012. std::string response;
  11013. ASSERT_TRUE(send_request(1, req, &response));
  11014. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  11015. }
  11016. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  11017. Server svr;
  11018. svr.Get("/", [](const Request &req, Response &res) {
  11019. EXPECT_EQ(2U, req.trailers.size());
  11020. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  11021. // Denied
  11022. EXPECT_FALSE(req.has_trailer("Content-Length"));
  11023. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  11024. // Accepted
  11025. EXPECT_TRUE(req.has_trailer("X-Hello"));
  11026. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  11027. EXPECT_TRUE(req.has_trailer("X-World"));
  11028. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  11029. res.set_content("ok", "text/plain");
  11030. });
  11031. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11032. auto se = detail::scope_exit([&] {
  11033. svr.stop();
  11034. t.join();
  11035. ASSERT_FALSE(svr.is_running());
  11036. });
  11037. svr.wait_until_ready();
  11038. const std::string req = "GET / HTTP/1.1\r\n"
  11039. "Transfer-Encoding: chunked\r\n"
  11040. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  11041. "\r\n"
  11042. "0\r\n"
  11043. "Content-Length: 10\r\n"
  11044. "Host: internal.local\r\n"
  11045. "Content-Type: malicious/content\r\n"
  11046. "Cookie: any\r\n"
  11047. "Set-Cookie: any\r\n"
  11048. "X-Forwarded-For: attacker.com\r\n"
  11049. "X-Real-Ip: 1.1.1.1\r\n"
  11050. "X-Hello: hello\r\n"
  11051. "X-World: world\r\n"
  11052. "\r\n";
  11053. std::string res;
  11054. ASSERT_TRUE(send_request(1, req, &res));
  11055. }
  11056. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  11057. Server svr;
  11058. std::string observed_remote_addr;
  11059. std::string observed_xff;
  11060. svr.Get("/ip", [&](const Request &req, Response &res) {
  11061. observed_remote_addr = req.remote_addr;
  11062. observed_xff = req.get_header_value("X-Forwarded-For");
  11063. res.set_content("ok", "text/plain");
  11064. });
  11065. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11066. auto se = detail::scope_exit([&] {
  11067. svr.stop();
  11068. t.join();
  11069. ASSERT_FALSE(svr.is_running());
  11070. });
  11071. svr.wait_until_ready();
  11072. Client cli(HOST, PORT);
  11073. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  11074. ASSERT_TRUE(res);
  11075. EXPECT_EQ(StatusCode::OK_200, res->status);
  11076. EXPECT_EQ(observed_xff, "203.0.113.66");
  11077. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11078. observed_remote_addr == "127.0.0.1");
  11079. }
  11080. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  11081. Server svr;
  11082. svr.set_trusted_proxies({"203.0.113.66"});
  11083. std::string observed_remote_addr;
  11084. std::string observed_xff;
  11085. svr.Get("/ip", [&](const Request &req, Response &res) {
  11086. observed_remote_addr = req.remote_addr;
  11087. observed_xff = req.get_header_value("X-Forwarded-For");
  11088. res.set_content("ok", "text/plain");
  11089. });
  11090. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11091. auto se = detail::scope_exit([&] {
  11092. svr.stop();
  11093. t.join();
  11094. ASSERT_FALSE(svr.is_running());
  11095. });
  11096. svr.wait_until_ready();
  11097. Client cli(HOST, PORT);
  11098. auto res = cli.Get("/ip");
  11099. ASSERT_TRUE(res);
  11100. EXPECT_EQ(StatusCode::OK_200, res->status);
  11101. EXPECT_EQ(observed_xff, "");
  11102. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11103. observed_remote_addr == "127.0.0.1");
  11104. }
  11105. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  11106. Server svr;
  11107. svr.set_trusted_proxies({"203.0.113.66"});
  11108. std::string observed_remote_addr;
  11109. std::string observed_xff;
  11110. svr.Get("/ip", [&](const Request &req, Response &res) {
  11111. observed_remote_addr = req.remote_addr;
  11112. observed_xff = req.get_header_value("X-Forwarded-For");
  11113. res.set_content("ok", "text/plain");
  11114. });
  11115. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11116. auto se = detail::scope_exit([&] {
  11117. svr.stop();
  11118. t.join();
  11119. ASSERT_FALSE(svr.is_running());
  11120. });
  11121. svr.wait_until_ready();
  11122. Client cli(HOST, PORT);
  11123. auto res =
  11124. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  11125. ASSERT_TRUE(res);
  11126. EXPECT_EQ(StatusCode::OK_200, res->status);
  11127. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  11128. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11129. }
  11130. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  11131. Server svr;
  11132. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  11133. std::string observed_remote_addr;
  11134. std::string observed_xff;
  11135. svr.Get("/ip", [&](const Request &req, Response &res) {
  11136. observed_remote_addr = req.remote_addr;
  11137. observed_xff = req.get_header_value("X-Forwarded-For");
  11138. res.set_content("ok", "text/plain");
  11139. });
  11140. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11141. auto se = detail::scope_exit([&] {
  11142. svr.stop();
  11143. t.join();
  11144. ASSERT_FALSE(svr.is_running());
  11145. });
  11146. svr.wait_until_ready();
  11147. Client cli(HOST, PORT);
  11148. auto res = cli.Get(
  11149. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11150. ASSERT_TRUE(res);
  11151. EXPECT_EQ(StatusCode::OK_200, res->status);
  11152. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11153. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11154. }
  11155. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  11156. Server svr;
  11157. svr.set_trusted_proxies({"192.0.2.45"});
  11158. std::string observed_remote_addr;
  11159. std::string observed_xff;
  11160. svr.Get("/ip", [&](const Request &req, Response &res) {
  11161. observed_remote_addr = req.remote_addr;
  11162. observed_xff = req.get_header_value("X-Forwarded-For");
  11163. res.set_content("ok", "text/plain");
  11164. });
  11165. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11166. auto se = detail::scope_exit([&] {
  11167. svr.stop();
  11168. t.join();
  11169. ASSERT_FALSE(svr.is_running());
  11170. });
  11171. svr.wait_until_ready();
  11172. Client cli(HOST, PORT);
  11173. auto res =
  11174. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  11175. ASSERT_TRUE(res);
  11176. EXPECT_EQ(StatusCode::OK_200, res->status);
  11177. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  11178. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11179. }
  11180. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  11181. Server svr;
  11182. svr.set_trusted_proxies({"192.0.2.45"});
  11183. std::string observed_remote_addr;
  11184. std::string observed_xff;
  11185. svr.Get("/ip", [&](const Request &req, Response &res) {
  11186. observed_remote_addr = req.remote_addr;
  11187. observed_xff = req.get_header_value("X-Forwarded-For");
  11188. res.set_content("ok", "text/plain");
  11189. });
  11190. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11191. auto se = detail::scope_exit([&] {
  11192. svr.stop();
  11193. t.join();
  11194. ASSERT_FALSE(svr.is_running());
  11195. });
  11196. svr.wait_until_ready();
  11197. Client cli(HOST, PORT);
  11198. auto res = cli.Get(
  11199. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11200. ASSERT_TRUE(res);
  11201. EXPECT_EQ(StatusCode::OK_200, res->status);
  11202. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11203. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11204. }
  11205. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  11206. Server svr;
  11207. svr.set_trusted_proxies({"192.0.2.45"});
  11208. std::string observed_remote_addr;
  11209. std::string observed_xff;
  11210. svr.Get("/ip", [&](const Request &req, Response &res) {
  11211. observed_remote_addr = req.remote_addr;
  11212. observed_xff = req.get_header_value("X-Forwarded-For");
  11213. res.set_content("ok", "text/plain");
  11214. });
  11215. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11216. auto se = detail::scope_exit([&] {
  11217. svr.stop();
  11218. t.join();
  11219. ASSERT_FALSE(svr.is_running());
  11220. });
  11221. svr.wait_until_ready();
  11222. std::string raw_req =
  11223. "GET /ip HTTP/1.1\r\n"
  11224. "Host: localhost\r\n"
  11225. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  11226. "Connection: close\r\n"
  11227. "\r\n";
  11228. std::string out;
  11229. ASSERT_TRUE(send_request(5, raw_req, &out));
  11230. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11231. // Header parser trims surrounding whitespace of the header value
  11232. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  11233. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11234. }
  11235. #ifndef _WIN32
  11236. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  11237. Server svr;
  11238. svr.Post("/post", [&](const Request &req, Response &res) {
  11239. res.set_content(req.body, "text/plain");
  11240. });
  11241. svr.Put("/put", [&](const Request &req, Response &res) {
  11242. res.set_content(req.body, "text/plain");
  11243. });
  11244. svr.Patch("/patch", [&](const Request &req, Response &res) {
  11245. res.set_content(req.body, "text/plain");
  11246. });
  11247. svr.Delete("/delete", [&](const Request &req, Response &res) {
  11248. res.set_content(req.body, "text/plain");
  11249. });
  11250. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11251. auto se = detail::scope_exit([&] {
  11252. svr.stop();
  11253. t.join();
  11254. ASSERT_FALSE(svr.is_running());
  11255. });
  11256. svr.wait_until_ready();
  11257. std::string resp;
  11258. // POST without Content-Length
  11259. ASSERT_TRUE(send_request(5,
  11260. "POST /post HTTP/1.1\r\n"
  11261. "Host: localhost\r\n"
  11262. "Connection: close\r\n"
  11263. "\r\n",
  11264. &resp));
  11265. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11266. // PUT without Content-Length
  11267. resp.clear();
  11268. ASSERT_TRUE(send_request(5,
  11269. "PUT /put HTTP/1.1\r\n"
  11270. "Host: localhost\r\n"
  11271. "Connection: close\r\n"
  11272. "\r\n",
  11273. &resp));
  11274. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11275. // PATCH without Content-Length
  11276. resp.clear();
  11277. ASSERT_TRUE(send_request(5,
  11278. "PATCH /patch HTTP/1.1\r\n"
  11279. "Host: localhost\r\n"
  11280. "Connection: close\r\n"
  11281. "\r\n",
  11282. &resp));
  11283. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11284. // DELETE without Content-Length
  11285. resp.clear();
  11286. ASSERT_TRUE(send_request(5,
  11287. "DELETE /delete HTTP/1.1\r\n"
  11288. "Host: localhost\r\n"
  11289. "Connection: close\r\n"
  11290. "\r\n",
  11291. &resp));
  11292. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11293. }
  11294. #endif
  11295. //==============================================================================
  11296. // open_stream() Tests
  11297. //==============================================================================
  11298. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  11299. std::string result;
  11300. char buf[8192];
  11301. ssize_t n;
  11302. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11303. result.append(buf, static_cast<size_t>(n));
  11304. }
  11305. return result;
  11306. }
  11307. // Mock stream for unit tests
  11308. class MockStream : public Stream {
  11309. public:
  11310. std::string data;
  11311. size_t pos = 0;
  11312. ssize_t error_after = -1; // -1 = no error
  11313. explicit MockStream(const std::string &d, ssize_t err = -1)
  11314. : data(d), error_after(err) {}
  11315. bool is_readable() const override { return true; }
  11316. bool wait_readable() const override { return true; }
  11317. bool wait_writable() const override { return true; }
  11318. ssize_t read(char *ptr, size_t size) override {
  11319. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  11320. if (pos >= data.size()) return 0;
  11321. size_t limit =
  11322. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  11323. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  11324. std::memcpy(ptr, data.data() + pos, to_read);
  11325. pos += to_read;
  11326. return static_cast<ssize_t>(to_read);
  11327. }
  11328. ssize_t write(const char *, size_t) override { return -1; }
  11329. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  11330. ip = "127.0.0.1";
  11331. port = 0;
  11332. }
  11333. void get_local_ip_and_port(std::string &ip, int &port) const override {
  11334. ip = "127.0.0.1";
  11335. port = 0;
  11336. }
  11337. socket_t socket() const override { return INVALID_SOCKET; }
  11338. time_t duration() const override { return 0; }
  11339. };
  11340. TEST(StreamHandleTest, Basic) {
  11341. ClientImpl::StreamHandle handle;
  11342. EXPECT_FALSE(handle.is_valid());
  11343. handle.response = detail::make_unique<Response>();
  11344. handle.error = Error::Connection;
  11345. EXPECT_FALSE(handle.is_valid());
  11346. handle.error = Error::Success;
  11347. EXPECT_TRUE(handle.is_valid());
  11348. }
  11349. TEST(BodyReaderTest, Basic) {
  11350. MockStream stream("Hello, World!");
  11351. detail::BodyReader reader;
  11352. reader.stream = &stream;
  11353. reader.content_length = 13;
  11354. char buf[32];
  11355. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  11356. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  11357. EXPECT_TRUE(reader.eof);
  11358. }
  11359. TEST(BodyReaderTest, NoStream) {
  11360. detail::BodyReader reader;
  11361. char buf[32];
  11362. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11363. EXPECT_EQ(Error::Connection, reader.last_error);
  11364. }
  11365. TEST(BodyReaderTest, Error) {
  11366. MockStream stream("Hello, World!", 5);
  11367. detail::BodyReader reader;
  11368. reader.stream = &stream;
  11369. reader.content_length = 13;
  11370. char buf[32];
  11371. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  11372. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11373. EXPECT_EQ(Error::Read, reader.last_error);
  11374. }
  11375. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  11376. // Mock-based StreamHandle tests relying on private internals are removed.
  11377. class OpenStreamTest : public ::testing::Test {
  11378. protected:
  11379. void SetUp() override {
  11380. svr_.Get("/hello", [](const Request &, Response &res) {
  11381. res.set_content("Hello World!", "text/plain");
  11382. });
  11383. svr_.Get("/large", [](const Request &, Response &res) {
  11384. res.set_content(std::string(10000, 'X'), "text/plain");
  11385. });
  11386. svr_.Get("/chunked", [](const Request &, Response &res) {
  11387. res.set_chunked_content_provider("text/plain",
  11388. [](size_t offset, DataSink &sink) {
  11389. if (offset < 15) {
  11390. sink.write("chunk", 5);
  11391. return true;
  11392. }
  11393. sink.done();
  11394. return true;
  11395. });
  11396. });
  11397. svr_.Get("/compressible", [](const Request &, Response &res) {
  11398. res.set_chunked_content_provider("text/plain", [](size_t offset,
  11399. DataSink &sink) {
  11400. if (offset < 100 * 1024) {
  11401. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  11402. sink.write(chunk.data(), chunk.size());
  11403. return true;
  11404. }
  11405. sink.done();
  11406. return true;
  11407. });
  11408. });
  11409. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  11410. [](const Request & /*req*/, Response &res) {
  11411. auto i = new int(0);
  11412. res.set_header("Trailer", "Content-Length, X-Allowed");
  11413. res.set_chunked_content_provider(
  11414. "text/plain",
  11415. [i](size_t /*offset*/, DataSink &sink) {
  11416. switch (*i) {
  11417. case 0: sink.os << "123"; break;
  11418. case 1: sink.os << "456"; break;
  11419. case 2: sink.os << "789"; break;
  11420. case 3: {
  11421. sink.done_with_trailer(
  11422. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  11423. } break;
  11424. }
  11425. (*i)++;
  11426. return true;
  11427. },
  11428. [i](bool success) {
  11429. EXPECT_TRUE(success);
  11430. delete i;
  11431. });
  11432. });
  11433. // Echo headers endpoint for header-related tests
  11434. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  11435. std::string body;
  11436. for (const auto &h : req.headers) {
  11437. body.append(h.first);
  11438. body.push_back(':');
  11439. body.append(h.second);
  11440. body.push_back('\n');
  11441. }
  11442. res.set_content(body, "text/plain");
  11443. });
  11444. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  11445. std::string body;
  11446. for (const auto &h : req.headers) {
  11447. body.append(h.first);
  11448. body.push_back(':');
  11449. body.append(h.second);
  11450. body.push_back('\n');
  11451. }
  11452. res.set_content(body, "text/plain");
  11453. });
  11454. port_ = svr_.bind_to_any_port("127.0.0.1");
  11455. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11456. svr_.wait_until_ready();
  11457. }
  11458. void TearDown() override {
  11459. svr_.stop();
  11460. if (thread_.joinable()) thread_.join();
  11461. }
  11462. Server svr_;
  11463. std::thread thread_;
  11464. int port_ = 0;
  11465. };
  11466. TEST_F(OpenStreamTest, Basic) {
  11467. Client cli("127.0.0.1", port_);
  11468. auto handle = cli.open_stream("GET", "/hello");
  11469. EXPECT_TRUE(handle.is_valid());
  11470. EXPECT_EQ("Hello World!", read_all(handle));
  11471. }
  11472. TEST_F(OpenStreamTest, SmallBuffer) {
  11473. Client cli("127.0.0.1", port_);
  11474. auto handle = cli.open_stream("GET", "/hello");
  11475. std::string result;
  11476. char buf[4];
  11477. ssize_t n;
  11478. while ((n = handle.read(buf, sizeof(buf))) > 0)
  11479. result.append(buf, static_cast<size_t>(n));
  11480. EXPECT_EQ("Hello World!", result);
  11481. }
  11482. TEST_F(OpenStreamTest, DefaultHeaders) {
  11483. Client cli("127.0.0.1", port_);
  11484. // open_stream GET should include Host, User-Agent and Accept-Encoding
  11485. {
  11486. auto handle = cli.open_stream("GET", "/echo-headers");
  11487. ASSERT_TRUE(handle.is_valid());
  11488. auto body = read_all(handle);
  11489. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  11490. std::string::npos);
  11491. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  11492. std::string::npos);
  11493. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  11494. }
  11495. // open_stream POST with body and no explicit content_type should NOT add
  11496. // text/plain Content-Type (behavior differs from non-streaming path), but
  11497. // should include Content-Length
  11498. {
  11499. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  11500. ASSERT_TRUE(handle.is_valid());
  11501. auto body = read_all(handle);
  11502. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  11503. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  11504. }
  11505. // open_stream POST with explicit Content-Type should preserve it
  11506. {
  11507. auto handle = cli.open_stream("POST", "/echo-headers", {},
  11508. {{"Content-Type", "application/custom"}},
  11509. "{}", "application/custom");
  11510. ASSERT_TRUE(handle.is_valid());
  11511. auto body = read_all(handle);
  11512. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  11513. }
  11514. // User-specified User-Agent must not be overwritten for stream API
  11515. {
  11516. auto handle = cli.open_stream("GET", "/echo-headers", {},
  11517. {{"User-Agent", "MyAgent/1.2"}});
  11518. ASSERT_TRUE(handle.is_valid());
  11519. auto body = read_all(handle);
  11520. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  11521. }
  11522. }
  11523. TEST_F(OpenStreamTest, Large) {
  11524. Client cli("127.0.0.1", port_);
  11525. auto handle = cli.open_stream("GET", "/large");
  11526. EXPECT_EQ(10000u, read_all(handle).size());
  11527. }
  11528. TEST_F(OpenStreamTest, ConnectionError) {
  11529. Client cli("127.0.0.1", 9999);
  11530. auto handle = cli.open_stream("GET", "/hello");
  11531. EXPECT_FALSE(handle.is_valid());
  11532. }
  11533. TEST_F(OpenStreamTest, Chunked) {
  11534. Client cli("127.0.0.1", port_);
  11535. auto handle = cli.open_stream("GET", "/chunked");
  11536. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11537. "Transfer-Encoding") == "chunked");
  11538. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  11539. }
  11540. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  11541. Client cli("127.0.0.1", port_);
  11542. auto handle =
  11543. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  11544. ASSERT_TRUE(handle.is_valid());
  11545. // Consume body to allow trailers to be received/parsed
  11546. auto body = read_all(handle);
  11547. // Explicitly parse trailers (ensure trailers are available for assertion)
  11548. handle.parse_trailers_if_needed();
  11549. EXPECT_EQ(std::string("123456789"), body);
  11550. // The response should include a Trailer header declaring both names
  11551. ASSERT_TRUE(handle.response);
  11552. EXPECT_TRUE(handle.response->has_header("Trailer"));
  11553. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  11554. handle.response->get_header_value("Trailer"));
  11555. // Prohibited trailer must not be present
  11556. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  11557. // Allowed trailer should be present
  11558. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  11559. EXPECT_EQ(std::string("yes"),
  11560. handle.response->get_trailer_value("X-Allowed"));
  11561. // Verify trailers are NOT present as regular headers
  11562. EXPECT_EQ(std::string(""),
  11563. handle.response->get_header_value("Content-Length"));
  11564. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  11565. }
  11566. static std::thread serve_single_response(int port,
  11567. const std::string &response) {
  11568. return std::thread([port, response] {
  11569. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11570. default_socket_options(srv);
  11571. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11572. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11573. sockaddr_in addr{};
  11574. addr.sin_family = AF_INET;
  11575. addr.sin_port = htons(static_cast<uint16_t>(port));
  11576. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11577. int opt = 1;
  11578. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11579. #ifdef _WIN32
  11580. reinterpret_cast<const char *>(&opt),
  11581. #else
  11582. &opt,
  11583. #endif
  11584. sizeof(opt));
  11585. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11586. ::listen(srv, 1);
  11587. sockaddr_in cli_addr{};
  11588. socklen_t cli_len = sizeof(cli_addr);
  11589. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11590. if (cli != INVALID_SOCKET) {
  11591. char buf[4096];
  11592. ::recv(cli, buf, sizeof(buf), 0);
  11593. ::send(cli,
  11594. #ifdef _WIN32
  11595. static_cast<const char *>(response.c_str()),
  11596. static_cast<int>(response.size()),
  11597. #else
  11598. response.c_str(), response.size(),
  11599. #endif
  11600. 0);
  11601. detail::close_socket(cli);
  11602. }
  11603. detail::close_socket(srv);
  11604. });
  11605. }
  11606. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  11607. #ifndef _WIN32
  11608. signal(SIGPIPE, SIG_IGN);
  11609. #endif
  11610. auto server_thread =
  11611. serve_single_response(PORT + 2, "HTTP/1.1 200 OK\r\n"
  11612. "Content-Type: text/plain\r\n"
  11613. "Content-Length: not-a-number\r\n"
  11614. "Connection: close\r\n"
  11615. "\r\n"
  11616. "hello");
  11617. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11618. Client cli("127.0.0.1", PORT + 2);
  11619. auto handle = cli.open_stream("GET", "/");
  11620. EXPECT_FALSE(handle.is_valid());
  11621. server_thread.join();
  11622. }
  11623. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  11624. #ifndef _WIN32
  11625. signal(SIGPIPE, SIG_IGN);
  11626. #endif
  11627. auto server_thread = serve_single_response(
  11628. PORT + 4, "HTTP/1.1 200 OK\r\n"
  11629. "Content-Type: text/plain\r\n"
  11630. "Content-Length: 99999999999999999999999999\r\n"
  11631. "Connection: close\r\n"
  11632. "\r\n"
  11633. "hello");
  11634. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11635. // Before the fix, std::stoull would throw std::out_of_range here and
  11636. // crash the process. After the fix, strtoull silently clamps to
  11637. // ULLONG_MAX so the stream opens without crashing. The important thing
  11638. // is that the process does NOT terminate.
  11639. Client cli("127.0.0.1", PORT + 4);
  11640. auto handle = cli.open_stream("GET", "/");
  11641. EXPECT_TRUE(handle.is_valid());
  11642. server_thread.join();
  11643. }
  11644. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11645. TEST_F(OpenStreamTest, Gzip) {
  11646. Client cli("127.0.0.1", port_);
  11647. auto handle = cli.open_stream("GET", "/compressible", {},
  11648. {{"Accept-Encoding", "gzip"}});
  11649. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  11650. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11651. }
  11652. #endif
  11653. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11654. TEST_F(OpenStreamTest, Brotli) {
  11655. Client cli("127.0.0.1", port_);
  11656. auto handle =
  11657. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  11658. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  11659. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11660. }
  11661. #endif
  11662. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11663. TEST_F(OpenStreamTest, Zstd) {
  11664. Client cli("127.0.0.1", port_);
  11665. auto handle = cli.open_stream("GET", "/compressible", {},
  11666. {{"Accept-Encoding", "zstd"}});
  11667. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  11668. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11669. }
  11670. #endif
  11671. #ifdef CPPHTTPLIB_SSL_ENABLED
  11672. class SSLOpenStreamTest : public ::testing::Test {
  11673. protected:
  11674. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  11675. void SetUp() override {
  11676. svr_.Get("/hello", [](const Request &, Response &res) {
  11677. res.set_content("Hello SSL World!", "text/plain");
  11678. });
  11679. svr_.Get("/chunked", [](const Request &, Response &res) {
  11680. res.set_chunked_content_provider("text/plain",
  11681. [](size_t offset, DataSink &sink) {
  11682. if (offset < 15) {
  11683. sink.write("chunk", 5);
  11684. return true;
  11685. }
  11686. sink.done();
  11687. return true;
  11688. });
  11689. });
  11690. svr_.Post("/echo", [](const Request &req, Response &res) {
  11691. res.set_content(req.body, req.get_header_value("Content-Type"));
  11692. });
  11693. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  11694. std::string body = req.body;
  11695. res.set_chunked_content_provider(
  11696. "text/plain", [body](size_t offset, DataSink &sink) {
  11697. if (offset < body.size()) {
  11698. sink.write(body.data() + offset, body.size() - offset);
  11699. }
  11700. sink.done();
  11701. return true;
  11702. });
  11703. });
  11704. port_ = svr_.bind_to_any_port("127.0.0.1");
  11705. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11706. svr_.wait_until_ready();
  11707. }
  11708. void TearDown() override {
  11709. svr_.stop();
  11710. if (thread_.joinable()) thread_.join();
  11711. }
  11712. SSLServer svr_;
  11713. std::thread thread_;
  11714. int port_ = 0;
  11715. };
  11716. TEST_F(SSLOpenStreamTest, Basic) {
  11717. SSLClient cli("127.0.0.1", port_);
  11718. cli.enable_server_certificate_verification(false);
  11719. auto handle = cli.open_stream("GET", "/hello");
  11720. ASSERT_TRUE(handle.is_valid());
  11721. EXPECT_EQ("Hello SSL World!", read_all(handle));
  11722. }
  11723. TEST_F(SSLOpenStreamTest, Chunked) {
  11724. SSLClient cli("127.0.0.1", port_);
  11725. cli.enable_server_certificate_verification(false);
  11726. auto handle = cli.open_stream("GET", "/chunked");
  11727. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11728. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11729. "Transfer-Encoding") == "chunked");
  11730. auto body = read_all(handle);
  11731. EXPECT_EQ("chunkchunkchunk", body);
  11732. }
  11733. TEST_F(SSLOpenStreamTest, Post) {
  11734. SSLClient cli("127.0.0.1", port_);
  11735. cli.enable_server_certificate_verification(false);
  11736. auto handle =
  11737. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  11738. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11739. EXPECT_EQ(200, handle.response->status);
  11740. auto body = read_all(handle);
  11741. EXPECT_EQ("Hello SSL POST", body);
  11742. }
  11743. TEST_F(SSLOpenStreamTest, PostChunked) {
  11744. SSLClient cli("127.0.0.1", port_);
  11745. cli.enable_server_certificate_verification(false);
  11746. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  11747. "Chunked SSL Data", "text/plain");
  11748. ASSERT_TRUE(handle.is_valid());
  11749. EXPECT_EQ(200, handle.response->status);
  11750. auto body = read_all(handle);
  11751. EXPECT_EQ("Chunked SSL Data", body);
  11752. }
  11753. #endif // CPPHTTPLIB_SSL_ENABLED
  11754. //==============================================================================
  11755. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  11756. // results for various scenarios.
  11757. //==============================================================================
  11758. TEST(ParityTest, GetVsOpenStream) {
  11759. Server svr;
  11760. const std::string path = "/parity";
  11761. const std::string content = "Parity test content: hello world";
  11762. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11763. res.set_content(content, "text/plain");
  11764. });
  11765. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11766. auto se = detail::scope_exit([&] {
  11767. svr.stop();
  11768. t.join();
  11769. ASSERT_FALSE(svr.is_running());
  11770. });
  11771. svr.wait_until_ready();
  11772. Client cli(HOST, PORT);
  11773. // Non-stream path
  11774. auto r1 = cli.Get(path);
  11775. ASSERT_TRUE(r1);
  11776. EXPECT_EQ(StatusCode::OK_200, r1->status);
  11777. // Stream path
  11778. auto h = cli.open_stream("GET", path);
  11779. ASSERT_TRUE(h.is_valid());
  11780. EXPECT_EQ(r1->body, read_all(h));
  11781. }
  11782. // Helper to compress data with provided compressor type T
  11783. template <typename Compressor>
  11784. static std::string compress_payload_for_parity(const std::string &in) {
  11785. std::string out;
  11786. Compressor compressor;
  11787. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  11788. [&](const char *data, size_t n) {
  11789. out.append(data, n);
  11790. return true;
  11791. });
  11792. EXPECT_TRUE(ok);
  11793. return out;
  11794. }
  11795. // Helper function for compression parity tests
  11796. template <typename Compressor>
  11797. static void test_compression_parity(const std::string &original,
  11798. const std::string &path,
  11799. const std::string &encoding) {
  11800. const std::string compressed =
  11801. compress_payload_for_parity<Compressor>(original);
  11802. Server svr;
  11803. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11804. res.set_content(compressed, "application/octet-stream");
  11805. res.set_header("Content-Encoding", encoding);
  11806. });
  11807. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  11808. auto se = detail::scope_exit([&] {
  11809. svr.stop();
  11810. t.join();
  11811. ASSERT_FALSE(svr.is_running());
  11812. });
  11813. svr.wait_until_ready();
  11814. Client cli(HOST, PORT);
  11815. // Non-streaming
  11816. {
  11817. auto res = cli.Get(path);
  11818. ASSERT_TRUE(res);
  11819. EXPECT_EQ(StatusCode::OK_200, res->status);
  11820. EXPECT_EQ(original, res->body);
  11821. }
  11822. // Streaming
  11823. {
  11824. auto h = cli.open_stream("GET", path);
  11825. ASSERT_TRUE(h.is_valid());
  11826. EXPECT_EQ(original, read_all(h));
  11827. }
  11828. }
  11829. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11830. TEST(ParityTest, Gzip) {
  11831. test_compression_parity<detail::gzip_compressor>(
  11832. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  11833. }
  11834. #endif
  11835. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11836. TEST(ParityTest, Brotli) {
  11837. test_compression_parity<detail::brotli_compressor>(
  11838. "Hello, brotli parity test payload", "/parity-br", "br");
  11839. }
  11840. #endif
  11841. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11842. TEST(ParityTest, Zstd) {
  11843. test_compression_parity<detail::zstd_compressor>(
  11844. "Zstandard parity test payload", "/parity-zstd", "zstd");
  11845. }
  11846. #endif
  11847. //==============================================================================
  11848. // New Stream API Tests
  11849. //==============================================================================
  11850. inline std::string read_body(httplib::stream::Result &result) {
  11851. std::string body;
  11852. while (result.next()) {
  11853. body.append(result.data(), result.size());
  11854. }
  11855. return body;
  11856. }
  11857. TEST(ClientConnectionTest, Basic) {
  11858. httplib::ClientConnection conn;
  11859. EXPECT_FALSE(conn.is_open());
  11860. conn.sock = 1;
  11861. EXPECT_TRUE(conn.is_open());
  11862. httplib::ClientConnection conn2(std::move(conn));
  11863. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  11864. conn2.sock = INVALID_SOCKET;
  11865. }
  11866. // Unified test server for all stream::* tests
  11867. class StreamApiTest : public ::testing::Test {
  11868. protected:
  11869. void SetUp() override {
  11870. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11871. res.set_content("Hello World!", "text/plain");
  11872. });
  11873. svr_.Get("/echo-params",
  11874. [](const httplib::Request &req, httplib::Response &res) {
  11875. std::string r;
  11876. for (const auto &p : req.params) {
  11877. if (!r.empty()) r += "&";
  11878. r += p.first + "=" + p.second;
  11879. }
  11880. res.set_content(r, "text/plain");
  11881. });
  11882. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11883. res.set_content(req.body, req.get_header_value("Content-Type"));
  11884. });
  11885. svr_.Post("/echo-headers",
  11886. [](const httplib::Request &req, httplib::Response &res) {
  11887. std::string r;
  11888. for (const auto &h : req.headers)
  11889. r += h.first + ": " + h.second + "\n";
  11890. res.set_content(r, "text/plain");
  11891. });
  11892. svr_.Post("/echo-params",
  11893. [](const httplib::Request &req, httplib::Response &res) {
  11894. std::string r = "params:";
  11895. for (const auto &p : req.params)
  11896. r += p.first + "=" + p.second + ";";
  11897. res.set_content(r + " body:" + req.body, "text/plain");
  11898. });
  11899. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  11900. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  11901. });
  11902. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11903. res.set_content("PUT:" + req.body, "text/plain");
  11904. });
  11905. svr_.Patch("/echo",
  11906. [](const httplib::Request &req, httplib::Response &res) {
  11907. res.set_content("PATCH:" + req.body, "text/plain");
  11908. });
  11909. svr_.Delete(
  11910. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  11911. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  11912. "text/plain");
  11913. });
  11914. svr_.Get("/head-test",
  11915. [](const httplib::Request &, httplib::Response &res) {
  11916. res.set_content("body for HEAD", "text/plain");
  11917. });
  11918. svr_.Options("/options",
  11919. [](const httplib::Request &, httplib::Response &res) {
  11920. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  11921. });
  11922. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  11923. svr_.wait_until_ready();
  11924. }
  11925. void TearDown() override {
  11926. svr_.stop();
  11927. if (thread_.joinable()) thread_.join();
  11928. }
  11929. httplib::Server svr_;
  11930. std::thread thread_;
  11931. };
  11932. // stream::Get tests
  11933. TEST_F(StreamApiTest, GetBasic) {
  11934. httplib::Client cli(HOST, PORT);
  11935. auto result = httplib::stream::Get(cli, "/hello");
  11936. ASSERT_TRUE(result.is_valid());
  11937. EXPECT_EQ(200, result.status());
  11938. EXPECT_EQ("Hello World!", read_body(result));
  11939. }
  11940. TEST_F(StreamApiTest, GetWithParams) {
  11941. httplib::Client cli(HOST, PORT);
  11942. httplib::Params params{{"foo", "bar"}};
  11943. auto result = httplib::stream::Get(cli, "/echo-params", params);
  11944. ASSERT_TRUE(result.is_valid());
  11945. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  11946. }
  11947. TEST_F(StreamApiTest, GetConnectionError) {
  11948. httplib::Client cli(HOST, 9999);
  11949. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  11950. }
  11951. TEST_F(StreamApiTest, Get404) {
  11952. httplib::Client cli(HOST, PORT);
  11953. auto result = httplib::stream::Get(cli, "/nonexistent");
  11954. EXPECT_TRUE(result.is_valid());
  11955. EXPECT_EQ(404, result.status());
  11956. }
  11957. // stream::Post tests
  11958. TEST_F(StreamApiTest, PostBasic) {
  11959. httplib::Client cli(HOST, PORT);
  11960. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  11961. "application/json");
  11962. ASSERT_TRUE(result.is_valid());
  11963. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  11964. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  11965. }
  11966. TEST_F(StreamApiTest, PostWithHeaders) {
  11967. httplib::Client cli(HOST, PORT);
  11968. httplib::Headers headers{{"X-Custom", "value"}};
  11969. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  11970. "text/plain");
  11971. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  11972. }
  11973. TEST_F(StreamApiTest, PostWithParams) {
  11974. httplib::Client cli(HOST, PORT);
  11975. httplib::Params params{{"k", "v"}};
  11976. auto result =
  11977. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  11978. auto body = read_body(result);
  11979. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  11980. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  11981. }
  11982. TEST_F(StreamApiTest, PostLarge) {
  11983. httplib::Client cli(HOST, PORT);
  11984. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  11985. size_t total = 0;
  11986. while (result.next()) {
  11987. total += result.size();
  11988. }
  11989. EXPECT_EQ(100u * 1024u, total);
  11990. }
  11991. // stream::Put/Patch tests
  11992. TEST_F(StreamApiTest, PutAndPatch) {
  11993. httplib::Client cli(HOST, PORT);
  11994. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  11995. EXPECT_EQ("PUT:test", read_body(put));
  11996. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  11997. EXPECT_EQ("PATCH:test", read_body(patch));
  11998. }
  11999. // stream::Delete tests
  12000. TEST_F(StreamApiTest, Delete) {
  12001. httplib::Client cli(HOST, PORT);
  12002. auto del1 = httplib::stream::Delete(cli, "/resource");
  12003. EXPECT_EQ("Deleted", read_body(del1));
  12004. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  12005. EXPECT_EQ("Deleted:data", read_body(del2));
  12006. }
  12007. // stream::Head/Options tests
  12008. TEST_F(StreamApiTest, HeadAndOptions) {
  12009. httplib::Client cli(HOST, PORT);
  12010. auto head = httplib::stream::Head(cli, "/head-test");
  12011. EXPECT_TRUE(head.is_valid());
  12012. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  12013. auto opts = httplib::stream::Options(cli, "/options");
  12014. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  12015. }
  12016. // SSL stream::* tests
  12017. #ifdef CPPHTTPLIB_SSL_ENABLED
  12018. class SSLStreamApiTest : public ::testing::Test {
  12019. protected:
  12020. void SetUp() override {
  12021. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12022. res.set_content("Hello SSL!", "text/plain");
  12023. });
  12024. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12025. res.set_content(req.body, "text/plain");
  12026. });
  12027. port_ = svr_.bind_to_any_port("127.0.0.1");
  12028. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12029. svr_.wait_until_ready();
  12030. }
  12031. void TearDown() override {
  12032. svr_.stop();
  12033. if (thread_.joinable()) thread_.join();
  12034. }
  12035. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  12036. std::thread thread_;
  12037. int port_ = 0;
  12038. };
  12039. TEST_F(SSLStreamApiTest, GetAndPost) {
  12040. httplib::SSLClient cli("127.0.0.1", port_);
  12041. cli.enable_server_certificate_verification(false);
  12042. auto get = httplib::stream::Get(cli, "/hello");
  12043. EXPECT_EQ("Hello SSL!", read_body(get));
  12044. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  12045. EXPECT_EQ("test", read_body(post));
  12046. }
  12047. #endif
  12048. // Tests for Error::Timeout and Error::ConnectionClosed error types
  12049. // These errors are set in SocketStream/SSLSocketStream and propagated through
  12050. // BodyReader
  12051. TEST(ErrorHandlingTest, StreamReadTimeout) {
  12052. // Test that read timeout during streaming is detected
  12053. // Use a large content-length response where server delays mid-stream
  12054. Server svr;
  12055. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12056. // Send a large response with delay in the middle
  12057. res.set_content_provider(
  12058. 1000, // content_length
  12059. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  12060. if (offset < 100) {
  12061. // Send first 100 bytes immediately
  12062. std::string data(100, 'A');
  12063. sink.write(data.c_str(), data.size());
  12064. return true;
  12065. }
  12066. // Then delay longer than client timeout
  12067. std::this_thread::sleep_for(std::chrono::seconds(3));
  12068. std::string data(900, 'B');
  12069. sink.write(data.c_str(), data.size());
  12070. return true;
  12071. });
  12072. });
  12073. auto port = 8091;
  12074. std::thread t([&]() { svr.listen("localhost", port); });
  12075. svr.wait_until_ready();
  12076. Client cli("localhost", port);
  12077. cli.set_read_timeout(1, 0); // 1 second timeout
  12078. auto handle = cli.open_stream("GET", "/slow-stream");
  12079. ASSERT_TRUE(handle.is_valid());
  12080. char buf[256];
  12081. ssize_t total = 0;
  12082. ssize_t n;
  12083. bool got_error = false;
  12084. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12085. total += n;
  12086. }
  12087. if (n < 0) {
  12088. got_error = true;
  12089. // Should be timeout or read error
  12090. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12091. handle.get_read_error() == Error::Read)
  12092. << "Actual error: " << to_string(handle.get_read_error());
  12093. }
  12094. // Either we got an error, or we got less data than expected
  12095. EXPECT_TRUE(got_error || total < 1000)
  12096. << "Expected timeout but got all " << total << " bytes";
  12097. svr.stop();
  12098. t.join();
  12099. }
  12100. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  12101. // Test connection closed detection via BodyReader
  12102. Server svr;
  12103. std::atomic<bool> close_now{false};
  12104. svr.Get("/will-close", [&](const Request &, Response &res) {
  12105. res.set_content_provider(
  12106. 10000, // Large content_length that we won't fully send
  12107. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12108. if (offset < 100) {
  12109. std::string data(100, 'X');
  12110. sink.write(data.c_str(), data.size());
  12111. return true;
  12112. }
  12113. // Wait for signal then abort
  12114. while (!close_now) {
  12115. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12116. }
  12117. return false; // Abort - server will close connection
  12118. });
  12119. });
  12120. auto port = 8092;
  12121. std::thread t([&]() { svr.listen("localhost", port); });
  12122. svr.wait_until_ready();
  12123. Client cli("localhost", port);
  12124. auto handle = cli.open_stream("GET", "/will-close");
  12125. ASSERT_TRUE(handle.is_valid());
  12126. char buf[256];
  12127. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12128. EXPECT_GT(n, 0) << "First read should succeed";
  12129. // Signal server to close
  12130. close_now = true;
  12131. // Keep reading until error or EOF
  12132. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12133. // Keep reading
  12134. }
  12135. // Should get an error since content_length wasn't satisfied
  12136. if (n < 0) {
  12137. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12138. handle.get_read_error() == Error::Read)
  12139. << "Actual error: " << to_string(handle.get_read_error());
  12140. }
  12141. svr.stop();
  12142. t.join();
  12143. }
  12144. #ifdef CPPHTTPLIB_SSL_ENABLED
  12145. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  12146. // Test that read timeout during SSL streaming is detected
  12147. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12148. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12149. res.set_content_provider(
  12150. 1000, "text/plain",
  12151. [](size_t offset, size_t /*length*/, DataSink &sink) {
  12152. if (offset < 100) {
  12153. std::string data(100, 'A');
  12154. sink.write(data.c_str(), data.size());
  12155. return true;
  12156. }
  12157. std::this_thread::sleep_for(std::chrono::seconds(3));
  12158. std::string data(900, 'B');
  12159. sink.write(data.c_str(), data.size());
  12160. return true;
  12161. });
  12162. });
  12163. auto port = 8093;
  12164. std::thread t([&]() { svr.listen("localhost", port); });
  12165. svr.wait_until_ready();
  12166. SSLClient cli("localhost", port);
  12167. cli.enable_server_certificate_verification(false);
  12168. cli.set_read_timeout(1, 0); // 1 second timeout
  12169. auto handle = cli.open_stream("GET", "/slow-stream");
  12170. ASSERT_TRUE(handle.is_valid());
  12171. char buf[256];
  12172. ssize_t total = 0;
  12173. ssize_t n;
  12174. bool got_error = false;
  12175. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12176. total += n;
  12177. }
  12178. if (n < 0) {
  12179. got_error = true;
  12180. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12181. handle.get_read_error() == Error::Read)
  12182. << "Actual error: " << to_string(handle.get_read_error());
  12183. }
  12184. EXPECT_TRUE(got_error || total < 1000)
  12185. << "Expected timeout but got all " << total << " bytes";
  12186. svr.stop();
  12187. t.join();
  12188. }
  12189. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  12190. // Test SSL connection closed detection
  12191. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12192. std::atomic<bool> close_now{false};
  12193. svr.Get("/will-close", [&](const Request &, Response &res) {
  12194. res.set_content_provider(
  12195. 10000, "text/plain",
  12196. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12197. if (offset < 100) {
  12198. std::string data(100, 'X');
  12199. sink.write(data.c_str(), data.size());
  12200. return true;
  12201. }
  12202. while (!close_now) {
  12203. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12204. }
  12205. return false;
  12206. });
  12207. });
  12208. auto port = 8094;
  12209. std::thread t([&]() { svr.listen("localhost", port); });
  12210. svr.wait_until_ready();
  12211. SSLClient cli("localhost", port);
  12212. cli.enable_server_certificate_verification(false);
  12213. auto handle = cli.open_stream("GET", "/will-close");
  12214. ASSERT_TRUE(handle.is_valid());
  12215. char buf[256];
  12216. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12217. EXPECT_GT(n, 0);
  12218. // Signal server to close
  12219. close_now = true;
  12220. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12221. // Keep reading
  12222. }
  12223. if (n < 0) {
  12224. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12225. handle.get_read_error() == Error::Read)
  12226. << "Actual error: " << to_string(handle.get_read_error());
  12227. }
  12228. svr.stop();
  12229. t.join();
  12230. }
  12231. #endif
  12232. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  12233. using namespace httplib;
  12234. // Create a test file
  12235. const char *fname = "etag_testfile.txt";
  12236. const char *content = "etag-content";
  12237. {
  12238. std::ofstream ofs(fname);
  12239. ofs << content;
  12240. ASSERT_TRUE(ofs.good());
  12241. }
  12242. Server svr;
  12243. svr.set_mount_point("/static", ".");
  12244. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12245. svr.wait_until_ready();
  12246. Client cli(HOST, PORT);
  12247. // First request: should get 200 with ETag header
  12248. auto res1 = cli.Get("/static/etag_testfile.txt");
  12249. ASSERT_TRUE(res1);
  12250. ASSERT_EQ(200, res1->status);
  12251. ASSERT_TRUE(res1->has_header("ETag"));
  12252. std::string etag = res1->get_header_value("ETag");
  12253. EXPECT_FALSE(etag.empty());
  12254. // Verify ETag format: W/"hex-hex"
  12255. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  12256. EXPECT_EQ('W', etag[0]);
  12257. EXPECT_EQ('/', etag[1]);
  12258. EXPECT_EQ('"', etag[2]);
  12259. EXPECT_EQ('"', etag.back());
  12260. // Exact match: expect 304 Not Modified
  12261. Headers h2 = {{"If-None-Match", etag}};
  12262. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  12263. ASSERT_TRUE(res2);
  12264. EXPECT_EQ(304, res2->status);
  12265. // Wildcard match: expect 304 Not Modified
  12266. Headers h3 = {{"If-None-Match", "*"}};
  12267. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  12268. ASSERT_TRUE(res3);
  12269. EXPECT_EQ(304, res3->status);
  12270. // Non-matching ETag: expect 200
  12271. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  12272. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  12273. ASSERT_TRUE(res4);
  12274. EXPECT_EQ(200, res4->status);
  12275. // Multiple ETags with one matching: expect 304
  12276. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  12277. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  12278. ASSERT_TRUE(res5);
  12279. EXPECT_EQ(304, res5->status);
  12280. svr.stop();
  12281. t.join();
  12282. std::remove(fname);
  12283. }
  12284. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  12285. using namespace httplib;
  12286. Server svr;
  12287. svr.set_mount_point("/static", ".");
  12288. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12289. svr.wait_until_ready();
  12290. Client cli(HOST, PORT);
  12291. // Send If-None-Match: * to a non-existent file
  12292. Headers h = {{"If-None-Match", "*"}};
  12293. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  12294. ASSERT_TRUE(res);
  12295. EXPECT_EQ(404, res->status);
  12296. svr.stop();
  12297. t.join();
  12298. }
  12299. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  12300. using namespace httplib;
  12301. // Create a test file
  12302. const char *fname = "etag_boundary_testfile.txt";
  12303. const char *content = "boundary-test";
  12304. {
  12305. std::ofstream ofs(fname);
  12306. ofs << content;
  12307. ASSERT_TRUE(ofs.good());
  12308. }
  12309. Server svr;
  12310. svr.set_mount_point("/static", ".");
  12311. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12312. svr.wait_until_ready();
  12313. Client cli(HOST, PORT);
  12314. // Get the actual ETag
  12315. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  12316. ASSERT_TRUE(res1);
  12317. ASSERT_EQ(200, res1->status);
  12318. ASSERT_TRUE(res1->has_header("ETag"));
  12319. std::string etag = res1->get_header_value("ETag");
  12320. // Test 1: Very long ETag value (longer than actual ETag)
  12321. // Should NOT match and return 200 (not trigger out-of-bounds read)
  12322. Headers h1 = {{"If-None-Match", "W/"
  12323. "\"very-long-etag-value-that-is-much-longer-"
  12324. "than-the-actual-etag-value\""}};
  12325. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  12326. ASSERT_TRUE(res2);
  12327. EXPECT_EQ(200, res2->status); // Should not match
  12328. // Test 2: Long string followed by wildcard
  12329. // Should match on "*" and return 304 (without out-of-bounds read on the long
  12330. // string)
  12331. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  12332. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  12333. ASSERT_TRUE(res3);
  12334. EXPECT_EQ(304, res3->status); // Should match on "*"
  12335. // Test 3: Wildcard followed by long string
  12336. // Should match on "*" immediately and return 304
  12337. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  12338. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  12339. ASSERT_TRUE(res4);
  12340. EXPECT_EQ(304, res4->status); // Should match on "*"
  12341. // Test 4: Multiple long non-matching values
  12342. // Should NOT match and return 200 (test that all comparisons are safe)
  12343. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  12344. "W/\"second-long-non-matching-value\", "
  12345. "W/\"third-long-non-matching-value\""}};
  12346. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  12347. ASSERT_TRUE(res5);
  12348. EXPECT_EQ(200, res5->status); // Should not match
  12349. // Test 5: Single character that is not "*" (edge case)
  12350. Headers h5 = {{"If-None-Match", "X"}};
  12351. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  12352. ASSERT_TRUE(res6);
  12353. EXPECT_EQ(200, res6->status); // Should not match
  12354. svr.stop();
  12355. t.join();
  12356. std::remove(fname);
  12357. }
  12358. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  12359. using namespace httplib;
  12360. // Create a test file
  12361. const char *fname = "ims_testfile.txt";
  12362. const char *content = "if-modified-since-test";
  12363. {
  12364. std::ofstream ofs(fname);
  12365. ofs << content;
  12366. ASSERT_TRUE(ofs.good());
  12367. }
  12368. Server svr;
  12369. svr.set_mount_point("/static", ".");
  12370. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12371. svr.wait_until_ready();
  12372. Client cli(HOST, PORT);
  12373. // First request: should get 200 with Last-Modified header
  12374. auto res1 = cli.Get("/static/ims_testfile.txt");
  12375. ASSERT_TRUE(res1);
  12376. ASSERT_EQ(200, res1->status);
  12377. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12378. std::string last_modified = res1->get_header_value("Last-Modified");
  12379. EXPECT_FALSE(last_modified.empty());
  12380. // If-Modified-Since with same time: expect 304
  12381. Headers h2 = {{"If-Modified-Since", last_modified}};
  12382. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  12383. ASSERT_TRUE(res2);
  12384. EXPECT_EQ(304, res2->status);
  12385. // If-Modified-Since with future time: expect 304
  12386. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12387. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  12388. ASSERT_TRUE(res3);
  12389. EXPECT_EQ(304, res3->status);
  12390. // If-Modified-Since with past time: expect 200
  12391. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12392. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  12393. ASSERT_TRUE(res4);
  12394. EXPECT_EQ(200, res4->status);
  12395. // If-None-Match takes precedence over If-Modified-Since
  12396. // (send matching ETag with old If-Modified-Since -> should still be 304)
  12397. ASSERT_TRUE(res1->has_header("ETag"));
  12398. std::string etag = res1->get_header_value("ETag");
  12399. Headers h5 = {{"If-None-Match", etag},
  12400. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12401. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  12402. ASSERT_TRUE(res5);
  12403. EXPECT_EQ(304, res5->status);
  12404. svr.stop();
  12405. t.join();
  12406. std::remove(fname);
  12407. }
  12408. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  12409. using namespace httplib;
  12410. Server svr;
  12411. // Endpoint that returns compressible content
  12412. svr.Get("/compressible", [](const Request &, Response &res) {
  12413. // Return a large enough body to trigger compression
  12414. std::string body(1000, 'a');
  12415. res.set_content(body, "text/plain");
  12416. });
  12417. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12418. svr.wait_until_ready();
  12419. Client cli(HOST, PORT);
  12420. // Request with gzip support: should get Vary header when compressed
  12421. cli.set_compress(true);
  12422. auto res1 = cli.Get("/compressible");
  12423. ASSERT_TRUE(res1);
  12424. EXPECT_EQ(200, res1->status);
  12425. // If Content-Encoding is set, Vary should also be set
  12426. if (res1->has_header("Content-Encoding")) {
  12427. EXPECT_TRUE(res1->has_header("Vary"));
  12428. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  12429. }
  12430. // Request without Accept-Encoding header: should not have compression
  12431. Headers h_no_compress;
  12432. auto res2 = cli.Get("/compressible", h_no_compress);
  12433. ASSERT_TRUE(res2);
  12434. EXPECT_EQ(200, res2->status);
  12435. // Verify Vary header is present when compression is applied
  12436. // (the exact behavior depends on server configuration)
  12437. svr.stop();
  12438. t.join();
  12439. }
  12440. TEST(ETagTest, IfRangeWithETag) {
  12441. using namespace httplib;
  12442. // Create a test file with known content
  12443. const char *fname = "if_range_testfile.txt";
  12444. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  12445. {
  12446. std::ofstream ofs(fname);
  12447. ofs << content;
  12448. ASSERT_TRUE(ofs.good());
  12449. }
  12450. Server svr;
  12451. svr.set_mount_point("/static", ".");
  12452. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12453. svr.wait_until_ready();
  12454. Client cli(HOST, PORT);
  12455. // First request: get ETag
  12456. auto res1 = cli.Get("/static/if_range_testfile.txt");
  12457. ASSERT_TRUE(res1);
  12458. ASSERT_EQ(200, res1->status);
  12459. ASSERT_TRUE(res1->has_header("ETag"));
  12460. std::string etag = res1->get_header_value("ETag");
  12461. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  12462. // Since our server generates weak ETags (W/"..."), If-Range with our
  12463. // ETag should NOT result in partial content - it should return full content.
  12464. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  12465. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  12466. ASSERT_TRUE(res2);
  12467. // Weak ETag in If-Range -> full content (200), not partial (206)
  12468. EXPECT_EQ(200, res2->status);
  12469. EXPECT_EQ(content, res2->body);
  12470. EXPECT_FALSE(res2->has_header("Content-Range"));
  12471. // Range request with non-matching If-Range (ETag): should get 200 (full
  12472. // content)
  12473. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  12474. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  12475. ASSERT_TRUE(res3);
  12476. EXPECT_EQ(200, res3->status);
  12477. EXPECT_EQ(content, res3->body);
  12478. EXPECT_FALSE(res3->has_header("Content-Range"));
  12479. // Range request with strong ETag (hypothetical - our server doesn't generate
  12480. // strong ETags, but if client sends a strong ETag that doesn't match, it
  12481. // should return full content)
  12482. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  12483. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  12484. ASSERT_TRUE(res4);
  12485. EXPECT_EQ(200, res4->status);
  12486. EXPECT_EQ(content, res4->body);
  12487. EXPECT_FALSE(res4->has_header("Content-Range"));
  12488. svr.stop();
  12489. t.join();
  12490. std::remove(fname);
  12491. }
  12492. TEST(ETagTest, IfRangeWithDate) {
  12493. using namespace httplib;
  12494. // Create a test file
  12495. const char *fname = "if_range_date_testfile.txt";
  12496. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  12497. {
  12498. std::ofstream ofs(fname);
  12499. ofs << content;
  12500. ASSERT_TRUE(ofs.good());
  12501. }
  12502. Server svr;
  12503. svr.set_mount_point("/static", ".");
  12504. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12505. svr.wait_until_ready();
  12506. Client cli(HOST, PORT);
  12507. // First request: get Last-Modified
  12508. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  12509. ASSERT_TRUE(res1);
  12510. ASSERT_EQ(200, res1->status);
  12511. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12512. std::string last_modified = res1->get_header_value("Last-Modified");
  12513. // Range request with matching If-Range (date): should get 206
  12514. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  12515. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  12516. ASSERT_TRUE(res2);
  12517. EXPECT_EQ(206, res2->status);
  12518. EXPECT_EQ("FGHIJ", res2->body);
  12519. // Range request with old If-Range date: should get 200 (full content)
  12520. Headers h3 = {{"Range", "bytes=5-9"},
  12521. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12522. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  12523. ASSERT_TRUE(res3);
  12524. EXPECT_EQ(200, res3->status);
  12525. EXPECT_EQ(content, res3->body);
  12526. // Range request with future If-Range date: should get 206
  12527. Headers h4 = {{"Range", "bytes=0-4"},
  12528. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12529. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  12530. ASSERT_TRUE(res4);
  12531. EXPECT_EQ(206, res4->status);
  12532. EXPECT_EQ("ABCDE", res4->body);
  12533. svr.stop();
  12534. t.join();
  12535. std::remove(fname);
  12536. }
  12537. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  12538. using namespace httplib;
  12539. const char *fname = "etag_malformed.txt";
  12540. const char *content = "malformed-etag";
  12541. {
  12542. std::ofstream ofs(fname);
  12543. ofs << content;
  12544. ASSERT_TRUE(ofs.good());
  12545. }
  12546. Server svr;
  12547. svr.set_mount_point("/static", ".");
  12548. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12549. svr.wait_until_ready();
  12550. Client cli(HOST, PORT);
  12551. // baseline: should get 200 and an ETag
  12552. auto res1 = cli.Get("/static/etag_malformed.txt");
  12553. ASSERT_TRUE(res1);
  12554. ASSERT_EQ(200, res1->status);
  12555. ASSERT_TRUE(res1->has_header("ETag"));
  12556. // Malformed ETag value (missing quotes) should be treated as non-matching
  12557. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  12558. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  12559. ASSERT_TRUE(res_bad);
  12560. EXPECT_EQ(200, res_bad->status);
  12561. // Whitespace-only header value should be considered invalid / non-matching
  12562. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  12563. "Host: localhost\r\n"
  12564. "If-None-Match: \r\n"
  12565. "Connection: close\r\n"
  12566. "\r\n";
  12567. std::string out;
  12568. ASSERT_TRUE(send_request(5, raw_req, &out));
  12569. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12570. svr.stop();
  12571. t.join();
  12572. std::remove(fname);
  12573. }
  12574. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  12575. using namespace httplib;
  12576. const char *fname = "ims_invalid_format.txt";
  12577. const char *content = "ims-bad-format";
  12578. {
  12579. std::ofstream ofs(fname);
  12580. ofs << content;
  12581. ASSERT_TRUE(ofs.good());
  12582. }
  12583. Server svr;
  12584. svr.set_mount_point("/static", ".");
  12585. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12586. svr.wait_until_ready();
  12587. Client cli(HOST, PORT);
  12588. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  12589. ASSERT_TRUE(res1);
  12590. ASSERT_EQ(200, res1->status);
  12591. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12592. // If-Modified-Since with invalid format should not result in 304
  12593. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  12594. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  12595. ASSERT_TRUE(res_bad);
  12596. EXPECT_EQ(200, res_bad->status);
  12597. // If-Range with invalid date format should be treated as mismatch -> full
  12598. // content (200)
  12599. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  12600. {"If-Range", "invalid-date"}};
  12601. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  12602. ASSERT_TRUE(res_ifrange);
  12603. EXPECT_EQ(200, res_ifrange->status);
  12604. svr.stop();
  12605. t.join();
  12606. std::remove(fname);
  12607. }
  12608. TEST(ETagTest, IfRangeWithMalformedETag) {
  12609. using namespace httplib;
  12610. const char *fname = "ifrange_malformed.txt";
  12611. const std::string content = "0123456789";
  12612. {
  12613. std::ofstream ofs(fname);
  12614. ofs << content;
  12615. ASSERT_TRUE(ofs.good());
  12616. }
  12617. Server svr;
  12618. svr.set_mount_point("/static", ".");
  12619. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12620. svr.wait_until_ready();
  12621. Client cli(HOST, PORT);
  12622. // First request: get ETag
  12623. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  12624. ASSERT_TRUE(res1);
  12625. ASSERT_EQ(200, res1->status);
  12626. ASSERT_TRUE(res1->has_header("ETag"));
  12627. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  12628. // full content (200)
  12629. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  12630. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  12631. ASSERT_TRUE(res2);
  12632. EXPECT_EQ(200, res2->status);
  12633. EXPECT_EQ(content, res2->body);
  12634. svr.stop();
  12635. t.join();
  12636. std::remove(fname);
  12637. }
  12638. TEST(ETagTest, ExtremeLargeDateValues) {
  12639. using namespace httplib;
  12640. const char *fname = "ims_extreme_date.txt";
  12641. const char *content = "ims-extreme-date";
  12642. {
  12643. std::ofstream ofs(fname);
  12644. ofs << content;
  12645. ASSERT_TRUE(ofs.good());
  12646. }
  12647. Server svr;
  12648. svr.set_mount_point("/static", ".");
  12649. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12650. svr.wait_until_ready();
  12651. Client cli(HOST, PORT);
  12652. auto res1 = cli.Get(std::string("/static/") + fname);
  12653. ASSERT_TRUE(res1);
  12654. ASSERT_EQ(200, res1->status);
  12655. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12656. // Extremely large year that may overflow date parsing routines.
  12657. Headers h_large_date = {
  12658. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12659. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  12660. ASSERT_TRUE(res_bad);
  12661. // Expect server to treat this as invalid/mismatch and return full content
  12662. EXPECT_EQ(200, res_bad->status);
  12663. // If-Range with extremely large date should be treated as mismatch -> full
  12664. // content (200)
  12665. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  12666. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12667. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  12668. ASSERT_TRUE(res_ifrange);
  12669. EXPECT_EQ(200, res_ifrange->status);
  12670. svr.stop();
  12671. t.join();
  12672. std::remove(fname);
  12673. }
  12674. TEST(ETagTest, NegativeFileModificationTime) {
  12675. using namespace httplib;
  12676. const char *fname = "ims_negative_mtime.txt";
  12677. const std::string content = "negative-mtime";
  12678. {
  12679. std::ofstream ofs(fname);
  12680. ofs << content;
  12681. ASSERT_TRUE(ofs.good());
  12682. }
  12683. // Try to set file mtime to a negative value. This may fail on some
  12684. // platforms/filesystems; if it fails, the test will still verify server
  12685. // behaves safely by performing a regular conditional request.
  12686. #if defined(__APPLE__) || defined(__linux__)
  12687. bool set_negative = false;
  12688. do {
  12689. struct timeval times[2];
  12690. // access time: now
  12691. times[0].tv_sec = time(nullptr);
  12692. times[0].tv_usec = 0;
  12693. // modification time: negative (e.g., -1)
  12694. times[1].tv_sec = -1;
  12695. times[1].tv_usec = 0;
  12696. if (utimes(fname, times) == 0) { set_negative = true; }
  12697. } while (0);
  12698. #else
  12699. bool set_negative = false;
  12700. #endif
  12701. Server svr;
  12702. svr.set_mount_point("/static", ".");
  12703. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12704. svr.wait_until_ready();
  12705. Client cli(HOST, PORT);
  12706. auto res1 = cli.Get(std::string("/static/") + fname);
  12707. ASSERT_TRUE(res1);
  12708. ASSERT_EQ(200, res1->status);
  12709. bool has_last_modified = res1->has_header("Last-Modified");
  12710. std::string last_modified;
  12711. if (has_last_modified) {
  12712. last_modified = res1->get_header_value("Last-Modified");
  12713. }
  12714. if (set_negative) {
  12715. // If we successfully set a negative mtime, ensure server returns a
  12716. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  12717. // with an old date and ensure server handles it without crash.
  12718. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  12719. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  12720. ASSERT_TRUE(res2);
  12721. // Behavior may vary; at minimum ensure server responds (200 or 304).
  12722. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  12723. } else {
  12724. // Could not set negative mtime on this platform; fall back to verifying
  12725. // that normal invalid/malformed dates are treated safely (non-304).
  12726. Headers h_bad_date = {
  12727. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12728. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  12729. ASSERT_TRUE(res_bad);
  12730. EXPECT_EQ(200, res_bad->status);
  12731. }
  12732. svr.stop();
  12733. t.join();
  12734. std::remove(fname);
  12735. }
  12736. //==============================================================================
  12737. // SSE Parsing Tests
  12738. //==============================================================================
  12739. class SSEParsingTest : public ::testing::Test {
  12740. protected:
  12741. // Test helper that mimics SSE parsing behavior
  12742. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  12743. int &retry_ms) {
  12744. // Blank line signals end of event
  12745. if (line.empty() || line == "\r") { return true; }
  12746. // Lines starting with ':' are comments (ignored)
  12747. if (!line.empty() && line[0] == ':') { return false; }
  12748. // Find the colon separator
  12749. auto colon_pos = line.find(':');
  12750. if (colon_pos == std::string::npos) {
  12751. // Line with no colon is treated as field name with empty value
  12752. return false;
  12753. }
  12754. std::string field = line.substr(0, colon_pos);
  12755. std::string value;
  12756. // Value starts after colon, skip optional single space
  12757. if (colon_pos + 1 < line.size()) {
  12758. size_t value_start = colon_pos + 1;
  12759. if (line[value_start] == ' ') { value_start++; }
  12760. value = line.substr(value_start);
  12761. // Remove trailing \r if present
  12762. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  12763. }
  12764. // Handle known fields
  12765. if (field == "event") {
  12766. msg.event = value;
  12767. } else if (field == "data") {
  12768. // Multiple data lines are concatenated with newlines
  12769. if (!msg.data.empty()) { msg.data += "\n"; }
  12770. msg.data += value;
  12771. } else if (field == "id") {
  12772. // Empty id is valid (clears the last event ID)
  12773. msg.id = value;
  12774. } else if (field == "retry") {
  12775. // Parse retry interval in milliseconds
  12776. {
  12777. int v = 0;
  12778. auto res =
  12779. detail::from_chars(value.data(), value.data() + value.size(), v);
  12780. if (res.ec == std::errc{}) { retry_ms = v; }
  12781. }
  12782. }
  12783. // Unknown fields are ignored per SSE spec
  12784. return false;
  12785. }
  12786. };
  12787. // Test: Single-line data
  12788. TEST_F(SSEParsingTest, SingleLineData) {
  12789. sse::SSEMessage msg;
  12790. int retry_ms = 3000;
  12791. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  12792. EXPECT_EQ(msg.data, "hello");
  12793. EXPECT_EQ(msg.event, "message");
  12794. // Blank line ends event
  12795. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12796. }
  12797. // Test: Multi-line data
  12798. TEST_F(SSEParsingTest, MultiLineData) {
  12799. sse::SSEMessage msg;
  12800. int retry_ms = 3000;
  12801. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  12802. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  12803. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  12804. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  12805. }
  12806. // Test: Custom event types
  12807. TEST_F(SSEParsingTest, CustomEventType) {
  12808. sse::SSEMessage msg;
  12809. int retry_ms = 3000;
  12810. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  12811. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  12812. EXPECT_EQ(msg.event, "update");
  12813. EXPECT_EQ(msg.data, "payload");
  12814. }
  12815. // Test: Event ID handling
  12816. TEST_F(SSEParsingTest, EventIdHandling) {
  12817. sse::SSEMessage msg;
  12818. int retry_ms = 3000;
  12819. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  12820. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  12821. EXPECT_EQ(msg.id, "12345");
  12822. }
  12823. // Test: Empty event ID (clears last event ID)
  12824. TEST_F(SSEParsingTest, EmptyEventId) {
  12825. sse::SSEMessage msg;
  12826. msg.id = "previous";
  12827. int retry_ms = 3000;
  12828. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  12829. EXPECT_EQ(msg.id, "");
  12830. }
  12831. // Test: Retry field parsing
  12832. TEST_F(SSEParsingTest, RetryFieldParsing) {
  12833. sse::SSEMessage msg;
  12834. int retry_ms = 3000;
  12835. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  12836. EXPECT_EQ(retry_ms, 5000);
  12837. }
  12838. // Test: Invalid retry value
  12839. TEST_F(SSEParsingTest, InvalidRetryValue) {
  12840. sse::SSEMessage msg;
  12841. int retry_ms = 3000;
  12842. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  12843. EXPECT_EQ(retry_ms, 3000); // Unchanged
  12844. }
  12845. // Test: Comments (lines starting with :)
  12846. TEST_F(SSEParsingTest, CommentsIgnored) {
  12847. sse::SSEMessage msg;
  12848. int retry_ms = 3000;
  12849. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  12850. EXPECT_EQ(msg.data, "");
  12851. EXPECT_EQ(msg.event, "message");
  12852. }
  12853. // Test: Colon in value
  12854. TEST_F(SSEParsingTest, ColonInValue) {
  12855. sse::SSEMessage msg;
  12856. int retry_ms = 3000;
  12857. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  12858. EXPECT_EQ(msg.data, "hello:world:test");
  12859. }
  12860. // Test: Line with no colon (field name only)
  12861. TEST_F(SSEParsingTest, FieldNameOnly) {
  12862. sse::SSEMessage msg;
  12863. int retry_ms = 3000;
  12864. // According to SSE spec, this is treated as field name with empty value
  12865. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  12866. // Since we don't recognize "data" without colon, data should be empty
  12867. EXPECT_EQ(msg.data, "");
  12868. }
  12869. // Test: Trailing \r handling
  12870. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  12871. sse::SSEMessage msg;
  12872. int retry_ms = 3000;
  12873. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  12874. EXPECT_EQ(msg.data, "hello");
  12875. }
  12876. // Test: Unknown fields ignored
  12877. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  12878. sse::SSEMessage msg;
  12879. int retry_ms = 3000;
  12880. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  12881. EXPECT_EQ(msg.data, "");
  12882. EXPECT_EQ(msg.event, "message");
  12883. }
  12884. // Test: Space after colon is optional
  12885. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  12886. sse::SSEMessage msg1, msg2;
  12887. int retry_ms = 3000;
  12888. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  12889. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  12890. EXPECT_EQ(msg1.data, "hello");
  12891. EXPECT_EQ(msg2.data, "hello");
  12892. }
  12893. // Test: SSEMessage clear
  12894. TEST_F(SSEParsingTest, MessageClear) {
  12895. sse::SSEMessage msg;
  12896. msg.event = "custom";
  12897. msg.data = "some data";
  12898. msg.id = "123";
  12899. msg.clear();
  12900. EXPECT_EQ(msg.event, "message");
  12901. EXPECT_EQ(msg.data, "");
  12902. EXPECT_EQ(msg.id, "");
  12903. }
  12904. // Test: Complete event parsing
  12905. TEST_F(SSEParsingTest, CompleteEventParsing) {
  12906. sse::SSEMessage msg;
  12907. int retry_ms = 3000;
  12908. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  12909. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  12910. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  12911. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  12912. // Blank line ends event
  12913. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12914. EXPECT_EQ(msg.event, "notification");
  12915. EXPECT_EQ(msg.id, "evt-42");
  12916. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  12917. EXPECT_EQ(retry_ms, 1000);
  12918. }
  12919. //==============================================================================
  12920. // Integration Tests with Server
  12921. //==============================================================================
  12922. class SSEIntegrationTest : public ::testing::Test {
  12923. protected:
  12924. void SetUp() override {
  12925. stop_server_.store(false);
  12926. events_.clear();
  12927. server_ = httplib::detail::make_unique<Server>();
  12928. setup_server();
  12929. start_server();
  12930. }
  12931. void TearDown() override {
  12932. stop_server_.store(true);
  12933. event_cv_.notify_all();
  12934. server_->stop();
  12935. if (server_thread_.joinable()) { server_thread_.join(); }
  12936. }
  12937. void setup_server() {
  12938. // Simple SSE endpoint
  12939. server_->Get("/events", [this](const Request &req, Response &res) {
  12940. auto last_id = req.get_header_value("Last-Event-ID");
  12941. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  12942. res.set_chunked_content_provider(
  12943. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  12944. std::unique_lock<std::mutex> lock(event_mutex_);
  12945. if (event_cv_.wait_for(
  12946. lock, std::chrono::milliseconds(200), [this] {
  12947. return !events_.empty() || stop_server_.load();
  12948. })) {
  12949. if (stop_server_.load()) { return false; }
  12950. if (!events_.empty()) {
  12951. std::string event = events_.front();
  12952. events_.erase(events_.begin());
  12953. sink.write(event.data(), event.size());
  12954. return true;
  12955. }
  12956. }
  12957. return !stop_server_.load();
  12958. });
  12959. });
  12960. // Endpoint that returns error
  12961. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  12962. res.status = 500;
  12963. res.set_content("Internal Server Error", "text/plain");
  12964. });
  12965. // Endpoint for custom event types
  12966. server_->Get("/custom-events", [](const Request &, Response &res) {
  12967. res.set_chunked_content_provider(
  12968. "text/event-stream", [](size_t offset, DataSink &sink) {
  12969. if (offset == 0) {
  12970. std::string event = "event: update\ndata: updated\n\n"
  12971. "event: delete\ndata: deleted\n\n";
  12972. sink.write(event.data(), event.size());
  12973. }
  12974. return false; // End stream after sending
  12975. });
  12976. });
  12977. }
  12978. void start_server() {
  12979. port_ = server_->bind_to_any_port(HOST);
  12980. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  12981. // Wait for server to start
  12982. while (!server_->is_running()) {
  12983. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12984. }
  12985. }
  12986. int get_port() const { return port_; }
  12987. void send_event(const std::string &event) {
  12988. std::lock_guard<std::mutex> lock(event_mutex_);
  12989. events_.push_back(event);
  12990. event_cv_.notify_all();
  12991. }
  12992. std::unique_ptr<Server> server_;
  12993. std::thread server_thread_;
  12994. std::mutex event_mutex_;
  12995. std::condition_variable event_cv_;
  12996. std::vector<std::string> events_;
  12997. std::atomic<bool> stop_server_{false};
  12998. std::string last_received_event_id_;
  12999. int port_ = 0;
  13000. };
  13001. // Test: Successful connection and on_open callback
  13002. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  13003. // Add a simple endpoint that sends one event and closes
  13004. server_->Get("/simple-event", [](const Request &, Response &res) {
  13005. res.set_chunked_content_provider(
  13006. "text/event-stream", [](size_t offset, DataSink &sink) {
  13007. if (offset == 0) {
  13008. std::string event = "data: hello\n\n";
  13009. sink.write(event.data(), event.size());
  13010. }
  13011. return false; // Close stream after sending
  13012. });
  13013. });
  13014. Client client("localhost", get_port());
  13015. sse::SSEClient sse(client, "/simple-event");
  13016. std::atomic<bool> open_called{false};
  13017. std::atomic<bool> message_received{false};
  13018. sse.on_open([&open_called]() { open_called.store(true); });
  13019. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  13020. if (msg.data == "hello") { message_received.store(true); }
  13021. });
  13022. sse.set_reconnect_interval(100);
  13023. sse.set_max_reconnect_attempts(1);
  13024. // Start async
  13025. sse.start_async();
  13026. // Wait for message to be processed
  13027. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13028. sse.stop();
  13029. EXPECT_TRUE(open_called.load());
  13030. EXPECT_TRUE(message_received.load());
  13031. }
  13032. // Test: on_message callback
  13033. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  13034. // Endpoint that sends multiple events then closes
  13035. server_->Get("/multi-event", [](const Request &, Response &res) {
  13036. res.set_chunked_content_provider(
  13037. "text/event-stream", [](size_t offset, DataSink &sink) {
  13038. if (offset == 0) {
  13039. std::string events = "data: message1\n\ndata: message2\n\n";
  13040. sink.write(events.data(), events.size());
  13041. }
  13042. return false;
  13043. });
  13044. });
  13045. Client client("localhost", get_port());
  13046. sse::SSEClient sse(client, "/multi-event");
  13047. std::vector<std::string> received_messages;
  13048. std::mutex messages_mutex;
  13049. sse.on_message([&](const sse::SSEMessage &msg) {
  13050. std::lock_guard<std::mutex> lock(messages_mutex);
  13051. received_messages.push_back(msg.data);
  13052. });
  13053. sse.set_reconnect_interval(100);
  13054. sse.set_max_reconnect_attempts(1);
  13055. sse.start_async();
  13056. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13057. sse.stop();
  13058. std::lock_guard<std::mutex> lock(messages_mutex);
  13059. EXPECT_GE(received_messages.size(), 2u);
  13060. if (received_messages.size() >= 2) {
  13061. EXPECT_EQ(received_messages[0], "message1");
  13062. EXPECT_EQ(received_messages[1], "message2");
  13063. }
  13064. }
  13065. // Test: on_event for specific types
  13066. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  13067. Client client("localhost", get_port());
  13068. sse::SSEClient sse(client, "/custom-events");
  13069. std::atomic<bool> update_received{false};
  13070. std::atomic<bool> delete_received{false};
  13071. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  13072. if (msg.data == "updated") { update_received.store(true); }
  13073. });
  13074. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  13075. if (msg.data == "deleted") { delete_received.store(true); }
  13076. });
  13077. sse.set_max_reconnect_attempts(1);
  13078. sse.start_async();
  13079. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  13080. sse.stop();
  13081. EXPECT_TRUE(update_received.load());
  13082. EXPECT_TRUE(delete_received.load());
  13083. }
  13084. // Test: on_error callback on connection failure
  13085. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  13086. // Connect to a non-existent port
  13087. Client client("localhost", 59999);
  13088. sse::SSEClient sse(client, "/events");
  13089. std::atomic<bool> error_called{false};
  13090. Error received_error = Error::Success;
  13091. sse.on_error([&](Error err) {
  13092. error_called.store(true);
  13093. received_error = err;
  13094. });
  13095. sse.set_reconnect_interval(50);
  13096. sse.set_max_reconnect_attempts(1);
  13097. sse.start_async();
  13098. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13099. sse.stop();
  13100. EXPECT_TRUE(error_called.load());
  13101. EXPECT_NE(received_error, Error::Success);
  13102. }
  13103. // Test: Last-Event-ID header sent on reconnect
  13104. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  13105. // Endpoint that sends event with ID
  13106. server_->Get("/event-with-id", [](const Request &, Response &res) {
  13107. res.set_chunked_content_provider(
  13108. "text/event-stream", [](size_t offset, DataSink &sink) {
  13109. if (offset == 0) {
  13110. std::string event = "id: evt-123\ndata: test\n\n";
  13111. sink.write(event.data(), event.size());
  13112. }
  13113. return false;
  13114. });
  13115. });
  13116. Client client("localhost", get_port());
  13117. sse::SSEClient sse(client, "/event-with-id");
  13118. std::atomic<bool> id_received{false};
  13119. sse.on_message([&](const sse::SSEMessage &msg) {
  13120. if (!msg.id.empty()) { id_received.store(true); }
  13121. });
  13122. sse.set_reconnect_interval(100);
  13123. sse.set_max_reconnect_attempts(1);
  13124. sse.start_async();
  13125. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13126. sse.stop();
  13127. EXPECT_TRUE(id_received.load());
  13128. EXPECT_EQ(sse.last_event_id(), "evt-123");
  13129. }
  13130. // Test: Manual stop
  13131. TEST_F(SSEIntegrationTest, ManualStop) {
  13132. // Endpoint that sends one event and stays open briefly
  13133. std::atomic<bool> handler_running{true};
  13134. server_->Get("/stay-open", [&handler_running](const Request &,
  13135. Response &res) {
  13136. res.set_chunked_content_provider(
  13137. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  13138. if (offset == 0) {
  13139. std::string event = "data: connected\n\n";
  13140. sink.write(event.data(), event.size());
  13141. }
  13142. // Keep connection open while handler_running is true
  13143. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  13144. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13145. }
  13146. return false;
  13147. });
  13148. });
  13149. Client client("localhost", get_port());
  13150. sse::SSEClient sse(client, "/stay-open");
  13151. std::atomic<bool> connected{false};
  13152. sse.on_open([&connected]() { connected.store(true); });
  13153. sse.set_reconnect_interval(100);
  13154. sse.set_max_reconnect_attempts(1);
  13155. sse.start_async();
  13156. // Wait for connection to establish
  13157. for (int i = 0; i < 20 && !connected.load(); ++i) {
  13158. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13159. }
  13160. EXPECT_TRUE(connected.load());
  13161. EXPECT_TRUE(sse.is_connected());
  13162. // Signal handler to stop
  13163. handler_running.store(false);
  13164. // Stop SSE client
  13165. sse.stop();
  13166. EXPECT_FALSE(sse.is_connected());
  13167. }
  13168. // Test: SSEClient with custom headers
  13169. TEST_F(SSEIntegrationTest, CustomHeaders) {
  13170. // Setup a server endpoint that checks for custom header
  13171. std::atomic<bool> header_received{false};
  13172. server_->Get("/header-check", [&](const Request &req, Response &res) {
  13173. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  13174. header_received.store(true);
  13175. }
  13176. res.set_chunked_content_provider("text/event-stream",
  13177. [](size_t, DataSink &) { return false; });
  13178. });
  13179. Client client("localhost", get_port());
  13180. Headers headers = {{"X-Custom-Header", "custom-value"}};
  13181. sse::SSEClient sse(client, "/header-check", headers);
  13182. sse.set_max_reconnect_attempts(1);
  13183. sse.start_async();
  13184. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13185. sse.stop();
  13186. EXPECT_TRUE(header_received.load());
  13187. }
  13188. // Test: Reconnect interval configuration
  13189. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  13190. Client client("localhost", get_port());
  13191. sse::SSEClient sse(client, "/events");
  13192. auto &result = sse.set_reconnect_interval(500);
  13193. // Builder pattern should return reference to self
  13194. EXPECT_EQ(&result, &sse);
  13195. }
  13196. // Test: Max reconnect attempts
  13197. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  13198. // Connect to non-existent port to force reconnects
  13199. Client client("localhost", 59998);
  13200. sse::SSEClient sse(client, "/events");
  13201. std::atomic<int> error_count{0};
  13202. sse.on_error([&](Error) { error_count.fetch_add(1); });
  13203. sse.set_reconnect_interval(50);
  13204. sse.set_max_reconnect_attempts(2);
  13205. auto start = std::chrono::steady_clock::now();
  13206. sse.start(); // Blocking call
  13207. auto end = std::chrono::steady_clock::now();
  13208. // Should have stopped after 2 failed attempts
  13209. EXPECT_GE(error_count.load(), 2);
  13210. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  13211. auto duration =
  13212. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  13213. #ifdef _WIN32
  13214. // Windows is much slower for socket connection failures
  13215. EXPECT_LT(duration.count(), 7000);
  13216. #else
  13217. EXPECT_LT(duration.count(), 1000);
  13218. #endif
  13219. }
  13220. // Test: Multi-line data in integration
  13221. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  13222. // Endpoint with multi-line data
  13223. server_->Get("/multiline-data", [](const Request &, Response &res) {
  13224. res.set_chunked_content_provider(
  13225. "text/event-stream", [](size_t offset, DataSink &sink) {
  13226. if (offset == 0) {
  13227. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  13228. sink.write(event.data(), event.size());
  13229. }
  13230. return false;
  13231. });
  13232. });
  13233. Client client("localhost", get_port());
  13234. sse::SSEClient sse(client, "/multiline-data");
  13235. std::string received_data;
  13236. std::mutex data_mutex;
  13237. sse.on_message([&](const sse::SSEMessage &msg) {
  13238. std::lock_guard<std::mutex> lock(data_mutex);
  13239. received_data = msg.data;
  13240. });
  13241. sse.set_reconnect_interval(100);
  13242. sse.set_max_reconnect_attempts(1);
  13243. sse.start_async();
  13244. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13245. sse.stop();
  13246. std::lock_guard<std::mutex> lock(data_mutex);
  13247. EXPECT_EQ(received_data, "line1\nline2\nline3");
  13248. }
  13249. // Test: Auto-reconnect after server disconnection
  13250. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  13251. std::atomic<int> connection_count{0};
  13252. std::atomic<int> message_count{0};
  13253. // Endpoint that sends one event and closes, forcing reconnect
  13254. server_->Get("/reconnect-test",
  13255. [&connection_count](const Request &, Response &res) {
  13256. connection_count.fetch_add(1);
  13257. res.set_chunked_content_provider(
  13258. "text/event-stream", [](size_t offset, DataSink &sink) {
  13259. if (offset == 0) {
  13260. std::string event = "data: hello\n\n";
  13261. sink.write(event.data(), event.size());
  13262. }
  13263. return false; // Close connection after sending
  13264. });
  13265. });
  13266. Client client("localhost", get_port());
  13267. sse::SSEClient sse(client, "/reconnect-test");
  13268. sse.on_message([&message_count](const sse::SSEMessage &) {
  13269. message_count.fetch_add(1);
  13270. });
  13271. sse.set_reconnect_interval(100);
  13272. sse.set_max_reconnect_attempts(3);
  13273. sse.start_async();
  13274. // Wait long enough for multiple reconnects
  13275. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13276. sse.stop();
  13277. // Should have connected multiple times (initial + reconnects)
  13278. EXPECT_GE(connection_count.load(), 2);
  13279. // Should have received messages from multiple connections
  13280. EXPECT_GE(message_count.load(), 2);
  13281. }
  13282. // Test: Last-Event-ID sent on reconnect
  13283. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  13284. std::atomic<int> connection_count{0};
  13285. std::vector<std::string> received_last_event_ids;
  13286. std::mutex id_mutex;
  13287. // Endpoint that checks Last-Event-ID header and sends event with ID
  13288. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  13289. int conn = connection_count.fetch_add(1);
  13290. // Capture the Last-Event-ID header from each connection
  13291. {
  13292. std::lock_guard<std::mutex> lock(id_mutex);
  13293. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  13294. }
  13295. res.set_chunked_content_provider(
  13296. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  13297. if (offset == 0) {
  13298. std::string event =
  13299. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  13300. sink.write(event.data(), event.size());
  13301. }
  13302. return false;
  13303. });
  13304. });
  13305. Client client("localhost", get_port());
  13306. sse::SSEClient sse(client, "/reconnect-with-id");
  13307. sse.set_reconnect_interval(100);
  13308. sse.set_max_reconnect_attempts(3);
  13309. sse.start_async();
  13310. // Wait for at least 2 connections
  13311. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13312. sse.stop();
  13313. // Verify behavior
  13314. std::lock_guard<std::mutex> lock(id_mutex);
  13315. EXPECT_GE(received_last_event_ids.size(), 2u);
  13316. // First connection should have no Last-Event-ID
  13317. if (!received_last_event_ids.empty()) {
  13318. EXPECT_EQ(received_last_event_ids[0], "");
  13319. }
  13320. // Second connection should have Last-Event-ID from first connection
  13321. if (received_last_event_ids.size() >= 2) {
  13322. EXPECT_EQ(received_last_event_ids[1], "event-0");
  13323. }
  13324. }
  13325. TEST(Issue2318Test, EmptyHostString) {
  13326. {
  13327. httplib::Client cli_empty("", PORT);
  13328. auto res = cli_empty.Get("/");
  13329. ASSERT_FALSE(res);
  13330. EXPECT_EQ(httplib::Error::Connection, res.error());
  13331. }
  13332. {
  13333. httplib::Client cli(" ", PORT);
  13334. auto res = cli.Get("/");
  13335. ASSERT_FALSE(res);
  13336. EXPECT_EQ(httplib::Error::Connection, res.error());
  13337. }
  13338. }
  13339. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13340. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  13341. Server svr;
  13342. // Set a small payload limit (1KB)
  13343. svr.set_payload_max_length(1024);
  13344. svr.Post("/test", [&](const Request &req, Response &res) {
  13345. res.set_content("Body size: " + std::to_string(req.body.size()),
  13346. "text/plain");
  13347. });
  13348. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13349. auto se = detail::scope_exit([&] {
  13350. svr.stop();
  13351. listen_thread.join();
  13352. });
  13353. svr.wait_until_ready();
  13354. // Create data that compresses well but exceeds limit when decompressed
  13355. // 8KB of repeated null bytes compresses to a very small size
  13356. std::string original_data(8 * 1024, '\0');
  13357. // Compress the data using gzip
  13358. std::string compressed_data;
  13359. detail::gzip_compressor compressor;
  13360. compressor.compress(original_data.data(), original_data.size(), true,
  13361. [&](const char *data, size_t size) {
  13362. compressed_data.append(data, size);
  13363. return true;
  13364. });
  13365. // Verify compression worked (compressed should be much smaller)
  13366. ASSERT_LT(compressed_data.size(), original_data.size());
  13367. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  13368. // Send compressed data with Content-Encoding: gzip
  13369. Client cli(HOST, PORT);
  13370. Headers headers = {{"Content-Encoding", "gzip"}};
  13371. auto res =
  13372. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  13373. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  13374. ASSERT_TRUE(res);
  13375. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13376. }
  13377. #endif
  13378. // ============================================================================
  13379. // OpenSSL-Specific Tests
  13380. // ============================================================================
  13381. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13382. X509 *readCertificate(const std::string &strFileName) {
  13383. std::ifstream inStream(strFileName);
  13384. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  13385. std::istreambuf_iterator<char>());
  13386. if (strCertPEM.empty()) return (nullptr);
  13387. BIO *pbCert = BIO_new(BIO_s_mem());
  13388. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  13389. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  13390. BIO_free(pbCert);
  13391. return (pCert);
  13392. }
  13393. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  13394. std::ifstream inStream(strFileName);
  13395. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  13396. std::istreambuf_iterator<char>());
  13397. if (strPrivateKeyPEM.empty()) return (nullptr);
  13398. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  13399. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  13400. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  13401. BIO_free(pbPrivKey);
  13402. return (pPrivateKey);
  13403. }
  13404. TEST(BindServerTest, UpdateCerts) {
  13405. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13406. int port = svr.bind_to_any_port("0.0.0.0");
  13407. ASSERT_TRUE(svr.is_valid());
  13408. ASSERT_TRUE(port > 0);
  13409. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13410. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13411. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13412. ASSERT_TRUE(cert != nullptr);
  13413. ASSERT_TRUE(ca_cert != nullptr);
  13414. ASSERT_TRUE(key != nullptr);
  13415. X509_STORE *cert_store = X509_STORE_new();
  13416. X509_STORE_add_cert(cert_store, ca_cert);
  13417. // svr.update_certs(cert, key, cert_store); // deprecated
  13418. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13419. CLIENT_CA_CERT_FILE);
  13420. ASSERT_TRUE(svr.is_valid());
  13421. svr.stop();
  13422. X509_STORE_free(cert_store);
  13423. X509_free(cert);
  13424. X509_free(ca_cert);
  13425. EVP_PKEY_free(key);
  13426. }
  13427. // Test that SSLServer(X509*, EVP_PKEY*, X509_STORE*) constructor sets
  13428. // client CA list correctly for TLS handshake
  13429. TEST(SSLClientServerTest, X509ConstructorSetsClientCAList) {
  13430. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13431. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13432. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13433. ASSERT_TRUE(cert != nullptr);
  13434. ASSERT_TRUE(ca_cert != nullptr);
  13435. ASSERT_TRUE(key != nullptr);
  13436. X509_STORE *cert_store = X509_STORE_new();
  13437. X509_STORE_add_cert(cert_store, ca_cert);
  13438. // Use X509-based constructor (deprecated but should still work correctly)
  13439. #pragma GCC diagnostic push
  13440. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  13441. SSLServer svr(cert, key, cert_store);
  13442. #pragma GCC diagnostic pop
  13443. ASSERT_TRUE(svr.is_valid());
  13444. // Verify that client CA list is set in SSL_CTX
  13445. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13446. ASSERT_TRUE(ssl_ctx != nullptr);
  13447. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13448. ASSERT_TRUE(ca_list != nullptr);
  13449. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13450. X509_free(cert);
  13451. X509_free(ca_cert);
  13452. EVP_PKEY_free(key);
  13453. }
  13454. // Test that update_certs() updates client CA list correctly
  13455. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  13456. // Start with file-based constructor
  13457. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13458. ASSERT_TRUE(svr.is_valid());
  13459. // Initially no client CA list should be set
  13460. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13461. ASSERT_TRUE(ssl_ctx != nullptr);
  13462. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  13463. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  13464. EXPECT_EQ(0, count_before);
  13465. // Now update with client CA (PEM string)
  13466. std::string cert_pem, key_pem, ca_pem;
  13467. read_file(SERVER_CERT_FILE, cert_pem);
  13468. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13469. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13470. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  13471. ASSERT_TRUE(svr.is_valid());
  13472. // Now client CA list should be set
  13473. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  13474. ASSERT_TRUE(ca_list_after != nullptr);
  13475. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  13476. }
  13477. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  13478. // Test that the file-path SSLServer constructor properly sets the client CA
  13479. // list that is sent to clients during the TLS handshake (CertificateRequest)
  13480. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13481. ASSERT_TRUE(svr.is_valid());
  13482. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13483. ASSERT_TRUE(ssl_ctx != nullptr);
  13484. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13485. ASSERT_TRUE(ca_list != nullptr);
  13486. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13487. }
  13488. #endif
  13489. // ============================================================================
  13490. // MbedTLS-Specific Tests
  13491. // ============================================================================
  13492. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  13493. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  13494. using namespace httplib::tls;
  13495. // Track if callback was invoked
  13496. bool callback_invoked = false;
  13497. // The callback receives void* ctx which is actually MbedTlsContext*
  13498. // We can access the mbedtls_ssl_config via the context
  13499. auto setup_callback = [&callback_invoked](void *ctx) {
  13500. callback_invoked = true;
  13501. // Cast to MbedTlsContext* to access the ssl config
  13502. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  13503. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  13504. // Use static variables to hold certificate data (simplified for test)
  13505. static mbedtls_x509_crt own_cert;
  13506. static mbedtls_pk_context own_key;
  13507. static mbedtls_x509_crt ca_chain;
  13508. static bool initialized = false;
  13509. if (!initialized) {
  13510. mbedtls_x509_crt_init(&own_cert);
  13511. mbedtls_pk_init(&own_key);
  13512. mbedtls_x509_crt_init(&ca_chain);
  13513. // Load server certificate
  13514. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  13515. return false;
  13516. }
  13517. // Load server private key
  13518. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  13519. #if MBEDTLS_VERSION_MAJOR >= 3
  13520. ,
  13521. mbedtls_ctr_drbg_random, nullptr
  13522. #endif
  13523. ) != 0) {
  13524. return false;
  13525. }
  13526. // Load CA chain for client verification
  13527. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  13528. return false;
  13529. }
  13530. initialized = true;
  13531. }
  13532. // Configure the SSL config
  13533. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  13534. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  13535. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  13536. // Set minimum TLS version using mbedTLS native API
  13537. #if MBEDTLS_VERSION_MAJOR >= 3
  13538. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  13539. #else
  13540. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  13541. MBEDTLS_SSL_MINOR_VERSION_3);
  13542. #endif
  13543. return true;
  13544. };
  13545. SSLServer svr(setup_callback);
  13546. ASSERT_TRUE(svr.is_valid());
  13547. ASSERT_TRUE(callback_invoked);
  13548. svr.Get("/test", [&](const Request &req, Response &res) {
  13549. res.set_content("test", "text/plain");
  13550. auto cert = req.peer_cert();
  13551. ASSERT_TRUE(static_cast<bool>(cert));
  13552. auto common_name = cert.subject_cn();
  13553. EXPECT_EQ("Common Name", common_name);
  13554. });
  13555. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13556. auto se = detail::scope_exit([&] {
  13557. svr.stop();
  13558. t.join();
  13559. ASSERT_FALSE(svr.is_running());
  13560. });
  13561. svr.wait_until_ready();
  13562. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13563. cli.enable_server_certificate_verification(false);
  13564. cli.set_connection_timeout(30);
  13565. auto res = cli.Get("/test");
  13566. ASSERT_TRUE(res);
  13567. ASSERT_EQ(StatusCode::OK_200, res->status);
  13568. }
  13569. #endif
  13570. // WebSocket Tests
  13571. TEST(WebSocketTest, RSVBitsMustBeZero) {
  13572. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  13573. // defining the meaning of these bits has been negotiated.
  13574. auto make_frame = [](uint8_t first_byte) {
  13575. std::string frame;
  13576. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  13577. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  13578. frame += "Hello";
  13579. return frame;
  13580. };
  13581. // RSV1 set (0x40)
  13582. {
  13583. detail::BufferStream strm;
  13584. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  13585. ws::Opcode opcode;
  13586. std::string payload;
  13587. bool fin;
  13588. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13589. false, 1024));
  13590. }
  13591. // RSV2 set (0x20)
  13592. {
  13593. detail::BufferStream strm;
  13594. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  13595. ws::Opcode opcode;
  13596. std::string payload;
  13597. bool fin;
  13598. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13599. false, 1024));
  13600. }
  13601. // RSV3 set (0x10)
  13602. {
  13603. detail::BufferStream strm;
  13604. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  13605. ws::Opcode opcode;
  13606. std::string payload;
  13607. bool fin;
  13608. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13609. false, 1024));
  13610. }
  13611. // No RSV bits set - should succeed
  13612. {
  13613. detail::BufferStream strm;
  13614. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  13615. ws::Opcode opcode;
  13616. std::string payload;
  13617. bool fin;
  13618. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13619. false, 1024));
  13620. EXPECT_EQ(ws::Opcode::Text, opcode);
  13621. EXPECT_EQ("Hello", payload);
  13622. EXPECT_TRUE(fin);
  13623. }
  13624. }
  13625. TEST(WebSocketTest, ControlFrameValidation) {
  13626. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  13627. // payload length <= 125.
  13628. // Ping with FIN=0 - must be rejected
  13629. {
  13630. detail::BufferStream strm;
  13631. std::string frame;
  13632. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  13633. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13634. strm.write(frame.data(), frame.size());
  13635. ws::Opcode opcode;
  13636. std::string payload;
  13637. bool fin;
  13638. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13639. false, 1024));
  13640. }
  13641. // Close with FIN=0 - must be rejected
  13642. {
  13643. detail::BufferStream strm;
  13644. std::string frame;
  13645. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  13646. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13647. strm.write(frame.data(), frame.size());
  13648. ws::Opcode opcode;
  13649. std::string payload;
  13650. bool fin;
  13651. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13652. false, 1024));
  13653. }
  13654. // Ping with payload_len=126 (extended length) - must be rejected
  13655. {
  13656. detail::BufferStream strm;
  13657. std::string frame;
  13658. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13659. frame += static_cast<char>(126); // payload_len=126 (>125)
  13660. frame += static_cast<char>(0x00); // extended length high byte
  13661. frame += static_cast<char>(126); // extended length low byte
  13662. frame += std::string(126, 'x');
  13663. strm.write(frame.data(), frame.size());
  13664. ws::Opcode opcode;
  13665. std::string payload;
  13666. bool fin;
  13667. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13668. false, 1024));
  13669. }
  13670. // Ping with FIN=1 and payload_len=125 - should succeed
  13671. {
  13672. detail::BufferStream strm;
  13673. std::string frame;
  13674. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13675. frame += static_cast<char>(125); // payload_len=125
  13676. frame += std::string(125, 'x');
  13677. strm.write(frame.data(), frame.size());
  13678. ws::Opcode opcode;
  13679. std::string payload;
  13680. bool fin;
  13681. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13682. false, 1024));
  13683. EXPECT_EQ(ws::Opcode::Ping, opcode);
  13684. EXPECT_EQ(125u, payload.size());
  13685. EXPECT_TRUE(fin);
  13686. }
  13687. }
  13688. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  13689. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  13690. // length MUST be 0.
  13691. // MSB set - must be rejected
  13692. {
  13693. detail::BufferStream strm;
  13694. std::string frame;
  13695. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13696. frame += static_cast<char>(127); // 64-bit extended length
  13697. frame += static_cast<char>(0x80); // MSB set (invalid)
  13698. frame += std::string(7, '\0'); // remaining 7 bytes of length
  13699. strm.write(frame.data(), frame.size());
  13700. ws::Opcode opcode;
  13701. std::string payload;
  13702. bool fin;
  13703. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13704. false, 1024));
  13705. }
  13706. // MSB clear - should pass length parsing (will be rejected by max_len,
  13707. // but that's a different check; use a small length to verify)
  13708. {
  13709. detail::BufferStream strm;
  13710. std::string frame;
  13711. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13712. frame += static_cast<char>(127); // 64-bit extended length
  13713. frame += std::string(7, '\0'); // high bytes = 0
  13714. frame += static_cast<char>(0x03); // length = 3
  13715. frame += "abc";
  13716. strm.write(frame.data(), frame.size());
  13717. ws::Opcode opcode;
  13718. std::string payload;
  13719. bool fin;
  13720. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13721. false, 1024));
  13722. EXPECT_EQ(ws::Opcode::Text, opcode);
  13723. EXPECT_EQ("abc", payload);
  13724. }
  13725. }
  13726. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  13727. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  13728. // Valid UTF-8
  13729. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  13730. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  13731. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  13732. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  13733. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  13734. // Invalid UTF-8
  13735. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  13736. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  13737. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  13738. EXPECT_FALSE(
  13739. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  13740. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  13741. }
  13742. TEST(WebSocketTest, ConnectAndDisconnect) {
  13743. Server svr;
  13744. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  13745. std::string msg;
  13746. while (ws.read(msg)) {}
  13747. });
  13748. auto port = svr.bind_to_any_port(HOST);
  13749. std::thread t([&]() { svr.listen_after_bind(); });
  13750. svr.wait_until_ready();
  13751. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  13752. ASSERT_TRUE(client.connect());
  13753. EXPECT_TRUE(client.is_open());
  13754. client.close();
  13755. EXPECT_FALSE(client.is_open());
  13756. svr.stop();
  13757. t.join();
  13758. }
  13759. TEST(WebSocketTest, ValidURL) {
  13760. ws::WebSocketClient ws1("ws://localhost:8080/path");
  13761. EXPECT_TRUE(ws1.is_valid());
  13762. ws::WebSocketClient ws2("ws://example.com/path");
  13763. EXPECT_TRUE(ws2.is_valid());
  13764. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  13765. EXPECT_TRUE(ws3.is_valid());
  13766. #ifdef CPPHTTPLIB_SSL_ENABLED
  13767. ws::WebSocketClient wss1("wss://example.com/path");
  13768. EXPECT_TRUE(wss1.is_valid());
  13769. ws::WebSocketClient wss2("wss://example.com:443/path");
  13770. EXPECT_TRUE(wss2.is_valid());
  13771. #endif
  13772. }
  13773. TEST(WebSocketTest, InvalidURL) {
  13774. // No scheme
  13775. ws::WebSocketClient ws1("localhost:8080/path");
  13776. EXPECT_FALSE(ws1.is_valid());
  13777. // No path
  13778. ws::WebSocketClient ws2("ws://localhost:8080");
  13779. EXPECT_FALSE(ws2.is_valid());
  13780. // Empty string
  13781. ws::WebSocketClient ws3("");
  13782. EXPECT_FALSE(ws3.is_valid());
  13783. // Missing host
  13784. ws::WebSocketClient ws4("ws://:8080/path");
  13785. EXPECT_FALSE(ws4.is_valid());
  13786. // Port number overflow — should not crash
  13787. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  13788. EXPECT_FALSE(ws5.is_valid());
  13789. // Port out of range
  13790. ws::WebSocketClient ws6("ws://localhost:99999/path");
  13791. EXPECT_FALSE(ws6.is_valid());
  13792. }
  13793. TEST(WebSocketTest, UnsupportedScheme) {
  13794. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13795. ws::WebSocketClient ws1("http://localhost:8080/path");
  13796. EXPECT_FALSE(ws1.is_valid());
  13797. ws::WebSocketClient ws2("https://localhost:8080/path");
  13798. EXPECT_FALSE(ws2.is_valid());
  13799. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  13800. EXPECT_FALSE(ws3.is_valid());
  13801. #else
  13802. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  13803. std::invalid_argument);
  13804. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  13805. std::invalid_argument);
  13806. #endif
  13807. }
  13808. TEST(WebSocketTest, ConnectWhenInvalid) {
  13809. ws::WebSocketClient ws("not a valid url");
  13810. EXPECT_FALSE(ws.is_valid());
  13811. EXPECT_FALSE(ws.connect());
  13812. }
  13813. TEST(WebSocketTest, DefaultPort) {
  13814. ws::WebSocketClient ws1("ws://example.com/path");
  13815. EXPECT_TRUE(ws1.is_valid());
  13816. // ws:// defaults to port 80 (verified by successful parse)
  13817. #ifdef CPPHTTPLIB_SSL_ENABLED
  13818. ws::WebSocketClient ws2("wss://example.com/path");
  13819. EXPECT_TRUE(ws2.is_valid());
  13820. // wss:// defaults to port 443 (verified by successful parse)
  13821. #endif
  13822. }
  13823. TEST(WebSocketTest, IPv6LiteralAddress) {
  13824. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  13825. EXPECT_TRUE(ws1.is_valid());
  13826. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  13827. EXPECT_TRUE(ws2.is_valid());
  13828. }
  13829. TEST(WebSocketTest, ComplexPath) {
  13830. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  13831. EXPECT_TRUE(ws1.is_valid());
  13832. ws::WebSocketClient ws2("ws://localhost:8080/");
  13833. EXPECT_TRUE(ws2.is_valid());
  13834. }
  13835. class WebSocketIntegrationTest : public ::testing::Test {
  13836. protected:
  13837. void SetUp() override {
  13838. server_ = httplib::detail::make_unique<Server>();
  13839. setup_server();
  13840. start_server();
  13841. }
  13842. void TearDown() override {
  13843. server_->stop();
  13844. if (server_thread_.joinable()) { server_thread_.join(); }
  13845. }
  13846. void setup_server() {
  13847. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  13848. std::string msg;
  13849. ws::ReadResult ret;
  13850. while ((ret = ws.read(msg))) {
  13851. if (ret == ws::Binary) {
  13852. ws.send(msg.data(), msg.size());
  13853. } else {
  13854. ws.send(msg);
  13855. }
  13856. }
  13857. });
  13858. server_->WebSocket("/ws-echo-string",
  13859. [](const Request &, ws::WebSocket &ws) {
  13860. std::string msg;
  13861. while (ws.read(msg)) {
  13862. ws.send("echo: " + msg);
  13863. }
  13864. });
  13865. server_->WebSocket(
  13866. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  13867. // Echo back request metadata
  13868. ws.send("path:" + req.path);
  13869. ws.send("header:" + req.get_header_value("X-Test-Header"));
  13870. std::string msg;
  13871. while (ws.read(msg)) {}
  13872. });
  13873. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  13874. std::string msg;
  13875. ws.read(msg); // wait for a message
  13876. ws.close();
  13877. });
  13878. server_->WebSocket("/ws-close-status",
  13879. [](const Request &, ws::WebSocket &ws) {
  13880. std::string msg;
  13881. ws.read(msg); // wait for a message
  13882. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  13883. });
  13884. server_->WebSocket(
  13885. "/ws-subprotocol",
  13886. [](const Request &, ws::WebSocket &ws) {
  13887. std::string msg;
  13888. while (ws.read(msg)) {
  13889. ws.send(msg);
  13890. }
  13891. },
  13892. [](const std::vector<std::string> &protocols) -> std::string {
  13893. for (const auto &p : protocols) {
  13894. if (p == "graphql-ws") { return p; }
  13895. }
  13896. return "";
  13897. });
  13898. }
  13899. void start_server() {
  13900. port_ = server_->bind_to_any_port(HOST);
  13901. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13902. server_->wait_until_ready();
  13903. }
  13904. std::unique_ptr<Server> server_;
  13905. std::thread server_thread_;
  13906. int port_ = 0;
  13907. };
  13908. TEST_F(WebSocketIntegrationTest, TextEcho) {
  13909. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13910. "/ws-echo");
  13911. ASSERT_TRUE(client.connect());
  13912. ASSERT_TRUE(client.is_open());
  13913. ASSERT_TRUE(client.send("Hello WebSocket"));
  13914. std::string msg;
  13915. EXPECT_EQ(ws::Text, client.read(msg));
  13916. EXPECT_EQ("Hello WebSocket", msg);
  13917. client.close();
  13918. }
  13919. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  13920. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13921. "/ws-echo");
  13922. ASSERT_TRUE(client.connect());
  13923. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  13924. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  13925. std::string msg;
  13926. EXPECT_EQ(ws::Binary, client.read(msg));
  13927. EXPECT_EQ(binary_data, msg);
  13928. client.close();
  13929. }
  13930. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  13931. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13932. "/ws-echo");
  13933. ASSERT_TRUE(client.connect());
  13934. for (int i = 0; i < 10; i++) {
  13935. auto text = "message " + std::to_string(i);
  13936. ASSERT_TRUE(client.send(text));
  13937. std::string msg;
  13938. ASSERT_TRUE(client.read(msg));
  13939. EXPECT_EQ(text, msg);
  13940. }
  13941. client.close();
  13942. }
  13943. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  13944. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13945. "/ws-close");
  13946. ASSERT_TRUE(client.connect());
  13947. // Send a message to trigger the server to close
  13948. ASSERT_TRUE(client.send("trigger close"));
  13949. // The server will close, so read should return false
  13950. std::string msg;
  13951. EXPECT_FALSE(client.read(msg));
  13952. EXPECT_FALSE(client.is_open());
  13953. }
  13954. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  13955. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13956. "/ws-echo");
  13957. ASSERT_TRUE(client.connect());
  13958. // 128KB message
  13959. std::string large_data(128 * 1024, 'X');
  13960. ASSERT_TRUE(client.send(large_data));
  13961. std::string msg;
  13962. ASSERT_TRUE(client.read(msg));
  13963. EXPECT_EQ(large_data, msg);
  13964. client.close();
  13965. }
  13966. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  13967. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13968. "/ws-echo");
  13969. ASSERT_TRUE(client.connect());
  13970. const int num_threads = 4;
  13971. std::vector<std::thread> threads;
  13972. std::atomic<int> send_count{0};
  13973. for (int t = 0; t < num_threads; t++) {
  13974. threads.emplace_back([&client, &send_count, t]() {
  13975. for (int i = 0; i < 5; i++) {
  13976. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  13977. if (client.send(text)) { send_count++; }
  13978. }
  13979. });
  13980. }
  13981. for (auto &th : threads) {
  13982. th.join();
  13983. }
  13984. int received = 0;
  13985. std::string msg;
  13986. while (received < send_count.load()) {
  13987. if (!client.read(msg)) { break; }
  13988. received++;
  13989. }
  13990. EXPECT_EQ(send_count.load(), received);
  13991. client.close();
  13992. }
  13993. TEST_F(WebSocketIntegrationTest, ReadString) {
  13994. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13995. "/ws-echo-string");
  13996. ASSERT_TRUE(client.connect());
  13997. ASSERT_TRUE(client.send("hello"));
  13998. std::string msg;
  13999. ASSERT_TRUE(client.read(msg));
  14000. EXPECT_EQ("echo: hello", msg);
  14001. ASSERT_TRUE(client.send("world"));
  14002. ASSERT_TRUE(client.read(msg));
  14003. EXPECT_EQ("echo: world", msg);
  14004. client.close();
  14005. }
  14006. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  14007. Headers headers = {{"X-Test-Header", "test-value"}};
  14008. ws::WebSocketClient client(
  14009. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  14010. ASSERT_TRUE(client.connect());
  14011. std::string msg;
  14012. ASSERT_TRUE(client.read(msg));
  14013. EXPECT_EQ("path:/ws-request-info", msg);
  14014. ASSERT_TRUE(client.read(msg));
  14015. EXPECT_EQ("header:test-value", msg);
  14016. client.close();
  14017. }
  14018. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  14019. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14020. "/ws-echo");
  14021. client.set_read_timeout(1, 0); // 1 second
  14022. ASSERT_TRUE(client.connect());
  14023. // Don't send anything — server echo handler waits for a message,
  14024. // so read() should time out and return false.
  14025. std::string msg;
  14026. EXPECT_FALSE(client.read(msg));
  14027. }
  14028. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  14029. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14030. "/ws-echo");
  14031. client.set_read_timeout(5, 0);
  14032. ASSERT_TRUE(client.connect());
  14033. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14034. // The server should reject it and close the connection.
  14035. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  14036. client.send(oversized);
  14037. // The server's read() should have failed due to payload limit,
  14038. // so our read() should return false (connection closed).
  14039. std::string msg;
  14040. EXPECT_FALSE(client.read(msg));
  14041. }
  14042. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  14043. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14044. "/ws-echo");
  14045. client.set_read_timeout(10, 0);
  14046. ASSERT_TRUE(client.connect());
  14047. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14048. // This should succeed.
  14049. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  14050. ASSERT_TRUE(client.send(at_limit));
  14051. std::string msg;
  14052. ASSERT_TRUE(client.read(msg));
  14053. EXPECT_EQ(at_limit.size(), msg.size());
  14054. client.close();
  14055. }
  14056. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  14057. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14058. "/nonexistent");
  14059. EXPECT_FALSE(client.connect());
  14060. EXPECT_FALSE(client.is_open());
  14061. }
  14062. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  14063. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14064. "/ws-echo");
  14065. ASSERT_TRUE(client.connect());
  14066. ASSERT_TRUE(client.send(""));
  14067. std::string msg;
  14068. EXPECT_EQ(ws::Text, client.read(msg));
  14069. EXPECT_EQ("", msg);
  14070. client.close();
  14071. }
  14072. TEST_F(WebSocketIntegrationTest, Reconnect) {
  14073. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14074. "/ws-echo");
  14075. // First connection
  14076. ASSERT_TRUE(client.connect());
  14077. ASSERT_TRUE(client.send("first"));
  14078. std::string msg;
  14079. ASSERT_TRUE(client.read(msg));
  14080. EXPECT_EQ("first", msg);
  14081. client.close();
  14082. EXPECT_FALSE(client.is_open());
  14083. // Reconnect using the same client object
  14084. ASSERT_TRUE(client.connect());
  14085. ASSERT_TRUE(client.is_open());
  14086. ASSERT_TRUE(client.send("second"));
  14087. ASSERT_TRUE(client.read(msg));
  14088. EXPECT_EQ("second", msg);
  14089. client.close();
  14090. }
  14091. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  14092. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14093. "/ws-close-status");
  14094. ASSERT_TRUE(client.connect());
  14095. // Trigger the server to close with GoingAway status
  14096. ASSERT_TRUE(client.send("trigger"));
  14097. // read() should return false after receiving the close frame
  14098. std::string msg;
  14099. EXPECT_FALSE(client.read(msg));
  14100. EXPECT_FALSE(client.is_open());
  14101. }
  14102. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  14103. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14104. "/ws-echo");
  14105. ASSERT_TRUE(client.connect());
  14106. client.close(ws::CloseStatus::GoingAway, "client leaving");
  14107. EXPECT_FALSE(client.is_open());
  14108. }
  14109. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  14110. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  14111. ws::WebSocketClient client(
  14112. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14113. ASSERT_TRUE(client.connect());
  14114. // Server should have selected graphql-ws
  14115. EXPECT_EQ("graphql-ws", client.subprotocol());
  14116. client.close();
  14117. }
  14118. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  14119. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  14120. ws::WebSocketClient client(
  14121. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14122. ASSERT_TRUE(client.connect());
  14123. // Server should not have selected any subprotocol
  14124. EXPECT_TRUE(client.subprotocol().empty());
  14125. client.close();
  14126. }
  14127. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  14128. // Connect without requesting any subprotocol
  14129. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14130. "/ws-subprotocol");
  14131. ASSERT_TRUE(client.connect());
  14132. EXPECT_TRUE(client.subprotocol().empty());
  14133. client.close();
  14134. }
  14135. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  14136. Server svr;
  14137. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  14138. if (!req.has_header("Authorization")) {
  14139. res.status = StatusCode::Unauthorized_401;
  14140. res.set_content("Unauthorized", "text/plain");
  14141. return Server::HandlerResponse::Handled;
  14142. }
  14143. return Server::HandlerResponse::Unhandled;
  14144. });
  14145. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14146. std::string msg;
  14147. while (ws.read(msg)) {
  14148. ws.send(msg);
  14149. }
  14150. });
  14151. auto port = svr.bind_to_any_port("localhost");
  14152. std::thread t([&]() { svr.listen_after_bind(); });
  14153. svr.wait_until_ready();
  14154. // Without Authorization header - should be rejected before upgrade
  14155. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  14156. EXPECT_FALSE(client1.connect());
  14157. // With Authorization header - should succeed
  14158. Headers headers = {{"Authorization", "Bearer token123"}};
  14159. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  14160. headers);
  14161. ASSERT_TRUE(client2.connect());
  14162. ASSERT_TRUE(client2.send("hello"));
  14163. std::string msg;
  14164. ASSERT_TRUE(client2.read(msg));
  14165. EXPECT_EQ("hello", msg);
  14166. client2.close();
  14167. svr.stop();
  14168. t.join();
  14169. }
  14170. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14171. class WebSocketSSLIntegrationTest : public ::testing::Test {
  14172. protected:
  14173. void SetUp() override {
  14174. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  14175. SERVER_PRIVATE_KEY_FILE);
  14176. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14177. std::string msg;
  14178. ws::ReadResult ret;
  14179. while ((ret = ws.read(msg))) {
  14180. if (ret == ws::Binary) {
  14181. ws.send(msg.data(), msg.size());
  14182. } else {
  14183. ws.send(msg);
  14184. }
  14185. }
  14186. });
  14187. port_ = server_->bind_to_any_port(HOST);
  14188. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14189. server_->wait_until_ready();
  14190. }
  14191. void TearDown() override {
  14192. server_->stop();
  14193. if (server_thread_.joinable()) { server_thread_.join(); }
  14194. }
  14195. std::unique_ptr<SSLServer> server_;
  14196. std::thread server_thread_;
  14197. int port_ = 0;
  14198. };
  14199. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  14200. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  14201. "/ws-echo");
  14202. client.enable_server_certificate_verification(false);
  14203. ASSERT_TRUE(client.connect());
  14204. ASSERT_TRUE(client.is_open());
  14205. ASSERT_TRUE(client.send("Hello WSS"));
  14206. std::string msg;
  14207. EXPECT_EQ(ws::Text, client.read(msg));
  14208. EXPECT_EQ("Hello WSS", msg);
  14209. client.close();
  14210. }
  14211. #endif
  14212. #if !defined(_WIN32)
  14213. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  14214. auto secret_dir = std::string("./symlink_test_secret");
  14215. auto served_dir = std::string("./symlink_test_served");
  14216. auto secret_file = secret_dir + "/secret.txt";
  14217. auto symlink_path = served_dir + "/escape";
  14218. // Setup: create directories and files
  14219. mkdir(secret_dir.c_str(), 0755);
  14220. mkdir(served_dir.c_str(), 0755);
  14221. {
  14222. std::ofstream ofs(secret_file);
  14223. ofs << "SECRET_DATA";
  14224. }
  14225. // Create symlink using absolute path so it resolves correctly
  14226. char abs_secret[PATH_MAX];
  14227. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  14228. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  14229. auto se = detail::scope_exit([&] {
  14230. unlink(symlink_path.c_str());
  14231. unlink(secret_file.c_str());
  14232. rmdir(served_dir.c_str());
  14233. rmdir(secret_dir.c_str());
  14234. });
  14235. Server svr;
  14236. svr.set_mount_point("/", served_dir);
  14237. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  14238. auto se2 = detail::scope_exit([&] {
  14239. svr.stop();
  14240. listen_thread.join();
  14241. });
  14242. svr.wait_until_ready();
  14243. Client cli("localhost", PORT);
  14244. // Symlink pointing outside base dir should be blocked
  14245. auto res = cli.Get("/escape/secret.txt");
  14246. ASSERT_TRUE(res);
  14247. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  14248. }
  14249. #endif