test.cc 528 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #if __cplusplus >= 202002L
  28. inline std::string u8_to_string(const char8_t *s) {
  29. return std::string(reinterpret_cast<const char *>(s));
  30. }
  31. #define U8(x) u8_to_string(u8##x)
  32. #else
  33. #define U8(x) u8##x
  34. #endif
  35. #define SERVER_CERT_FILE "./cert.pem"
  36. #define SERVER_CERT2_FILE "./cert2.pem"
  37. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  38. #define CA_CERT_FILE "./ca-bundle.crt"
  39. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  40. #define CLIENT_CA_CERT_DIR "."
  41. #define CLIENT_CERT_FILE "./client.cert.pem"
  42. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  43. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  44. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  45. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  46. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  47. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  48. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  49. using namespace std;
  50. using namespace httplib;
  51. const char *HOST = "localhost";
  52. static int get_base_port() {
  53. const char *shard = getenv("GTEST_SHARD_INDEX");
  54. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  55. }
  56. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  57. // New standalone tests MUST use svr.bind_to_any_port() instead.
  58. const int PORT = get_base_port();
  59. const string LONG_QUERY_VALUE = string(25000, '@');
  60. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  61. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  62. const string TOO_LONG_QUERY_URL =
  63. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  64. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  65. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  66. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  67. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  68. return file.name == key;
  69. });
  70. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  71. return *it;
  72. #else
  73. if (it != items.end()) { return *it; }
  74. throw std::runtime_error("invalid multipart form data name error");
  75. #endif
  76. }
  77. static void read_file(const std::string &path, std::string &out) {
  78. std::ifstream fs(path, std::ios_base::binary);
  79. if (!fs) {
  80. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  81. return;
  82. #else
  83. throw std::runtime_error("File not found: " + path);
  84. #endif
  85. }
  86. fs.seekg(0, std::ios_base::end);
  87. auto size = fs.tellg();
  88. fs.seekg(0);
  89. out.resize(static_cast<size_t>(size));
  90. fs.read(&out[0], static_cast<std::streamsize>(size));
  91. }
  92. class UnixSocketTest : public ::testing::Test {
  93. protected:
  94. void TearDown() override { std::remove(pathname_.c_str()); }
  95. void client_GET(const std::string &addr) {
  96. httplib::Client cli{addr};
  97. cli.set_address_family(AF_UNIX);
  98. ASSERT_TRUE(cli.is_valid());
  99. const auto &result = cli.Get(pattern_);
  100. ASSERT_TRUE(result) << "error: " << result.error();
  101. const auto &resp = result.value();
  102. EXPECT_EQ(resp.status, StatusCode::OK_200);
  103. EXPECT_EQ(resp.body, content_);
  104. }
  105. static std::string make_sock_path() {
  106. const char *shard = getenv("GTEST_SHARD_INDEX");
  107. return shard ? std::string("./httplib-server-") + shard + ".sock"
  108. : "./httplib-server.sock";
  109. }
  110. const std::string pathname_{make_sock_path()};
  111. const std::string pattern_{"/hi"};
  112. const std::string content_{"Hello World!"};
  113. };
  114. TEST_F(UnixSocketTest, pathname) {
  115. httplib::Server svr;
  116. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  117. res.set_content(content_, "text/plain");
  118. });
  119. std::thread t{[&] {
  120. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  121. }};
  122. auto se = detail::scope_exit([&] {
  123. svr.stop();
  124. t.join();
  125. ASSERT_FALSE(svr.is_running());
  126. });
  127. svr.wait_until_ready();
  128. ASSERT_TRUE(svr.is_running());
  129. client_GET(pathname_);
  130. }
  131. #if defined(__linux__) || \
  132. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  133. TEST_F(UnixSocketTest, PeerPid) {
  134. httplib::Server svr;
  135. std::string remote_port_val;
  136. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  137. res.set_content(content_, "text/plain");
  138. remote_port_val = std::to_string(req.remote_port);
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  152. }
  153. #endif
  154. #ifdef __linux__
  155. TEST_F(UnixSocketTest, abstract) {
  156. constexpr char svr_path[]{"\x00httplib-server.sock"};
  157. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  158. httplib::Server svr;
  159. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  160. res.set_content(content_, "text/plain");
  161. });
  162. std::thread t{[&] {
  163. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  164. }};
  165. auto se = detail::scope_exit([&] {
  166. svr.stop();
  167. t.join();
  168. ASSERT_FALSE(svr.is_running());
  169. });
  170. svr.wait_until_ready();
  171. ASSERT_TRUE(svr.is_running());
  172. client_GET(abstract_addr);
  173. }
  174. #endif
  175. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  176. httplib::Server svr;
  177. std::string received_host_header;
  178. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  179. // Capture the Host header sent by the client
  180. auto host_iter = req.headers.find("Host");
  181. if (host_iter != req.headers.end()) {
  182. received_host_header = host_iter->second;
  183. }
  184. res.set_content(content_, "text/plain");
  185. });
  186. std::thread t{[&] {
  187. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  188. }};
  189. auto se = detail::scope_exit([&] {
  190. svr.stop();
  191. t.join();
  192. ASSERT_FALSE(svr.is_running());
  193. });
  194. svr.wait_until_ready();
  195. ASSERT_TRUE(svr.is_running());
  196. // Test that Host header is automatically set to "localhost" for Unix socket
  197. // connections
  198. httplib::Client cli{pathname_};
  199. cli.set_address_family(AF_UNIX);
  200. ASSERT_TRUE(cli.is_valid());
  201. const auto &result = cli.Get(pattern_);
  202. ASSERT_TRUE(result) << "error: " << result.error();
  203. const auto &resp = result.value();
  204. EXPECT_EQ(resp.status, StatusCode::OK_200);
  205. EXPECT_EQ(resp.body, content_);
  206. // Verify that Host header was automatically set to "localhost"
  207. EXPECT_EQ(received_host_header, "localhost");
  208. }
  209. #ifndef _WIN32
  210. TEST(SocketStream, wait_writable_UNIX) {
  211. int fds[2];
  212. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  213. const auto asSocketStream = [&](socket_t fd,
  214. std::function<bool(Stream &)> func) {
  215. return detail::process_client_socket(
  216. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  217. };
  218. asSocketStream(fds[0], [&](Stream &s0) {
  219. EXPECT_EQ(s0.socket(), fds[0]);
  220. EXPECT_TRUE(s0.wait_writable());
  221. EXPECT_TRUE(s0.is_peer_alive());
  222. EXPECT_EQ(0, close(fds[1]));
  223. EXPECT_FALSE(s0.is_peer_alive());
  224. return true;
  225. });
  226. EXPECT_EQ(0, close(fds[0]));
  227. }
  228. TEST(SocketStream, wait_writable_INET) {
  229. sockaddr_in addr;
  230. memset(&addr, 0, sizeof(addr));
  231. addr.sin_family = AF_INET;
  232. addr.sin_port = htons(PORT + 1);
  233. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  234. int disconnected_svr_sock = -1;
  235. std::thread svr{[&] {
  236. const int s = socket(AF_INET, SOCK_STREAM, 0);
  237. ASSERT_LE(0, s);
  238. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  239. ASSERT_EQ(0, listen(s, 1));
  240. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  241. ASSERT_EQ(0, close(s));
  242. }};
  243. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  244. std::thread cli{[&] {
  245. const int s = socket(AF_INET, SOCK_STREAM, 0);
  246. ASSERT_LE(0, s);
  247. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  248. ASSERT_EQ(0, close(s));
  249. }};
  250. cli.join();
  251. svr.join();
  252. ASSERT_NE(disconnected_svr_sock, -1);
  253. const auto asSocketStream = [&](socket_t fd,
  254. std::function<bool(Stream &)> func) {
  255. return detail::process_client_socket(
  256. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  257. };
  258. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  259. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  260. // wait_writable() returns true because select_write() only checks if the
  261. // send buffer has space. Peer disconnection is detected later by send().
  262. EXPECT_TRUE(ss.wait_writable());
  263. return true;
  264. });
  265. ASSERT_EQ(0, close(disconnected_svr_sock));
  266. }
  267. #endif // #ifndef _WIN32
  268. TEST(ClientTest, MoveConstructible) {
  269. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  270. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  271. }
  272. TEST(ClientTest, MoveAssignable) {
  273. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  274. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  275. }
  276. #ifdef _WIN32
  277. TEST(StartupTest, WSAStartup) {
  278. WSADATA wsaData;
  279. int ret = WSAStartup(0x0002, &wsaData);
  280. ASSERT_EQ(0, ret);
  281. }
  282. #endif
  283. TEST(DecodePathTest, PercentCharacter) {
  284. EXPECT_EQ(
  285. decode_path_component(
  286. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  287. U8("descrip=Gastos áéíóúñÑ 6"));
  288. }
  289. TEST(DecodePathTest, PercentCharacterNUL) {
  290. string expected;
  291. expected.push_back('x');
  292. expected.push_back('\0');
  293. expected.push_back('x');
  294. EXPECT_EQ(decode_path_component("x%00x"), expected);
  295. }
  296. TEST(DecodePathTest, UnicodeEncoding) {
  297. // %u0041 = 'A' (1-byte UTF-8)
  298. EXPECT_EQ("A", decode_path_component("%u0041"));
  299. // %u00E9 = 'é' (2-byte UTF-8)
  300. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  301. // %u3042 = 'あ' (3-byte UTF-8)
  302. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  303. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  304. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  305. // %uD800 = surrogate (invalid, silently dropped)
  306. EXPECT_EQ("", decode_path_component("%uD800"));
  307. }
  308. TEST(SanitizeFilenameTest, VariousPatterns) {
  309. // Path traversal
  310. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  311. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  312. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  313. // Normal and edge cases
  314. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  315. EXPECT_EQ("filename.txt",
  316. httplib::sanitize_filename("/path/to/filename.txt"));
  317. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  318. EXPECT_EQ("", httplib::sanitize_filename(".."));
  319. EXPECT_EQ("", httplib::sanitize_filename(""));
  320. // Null bytes stripped
  321. EXPECT_EQ("safe.txt",
  322. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  323. // Whitespace-only rejected
  324. EXPECT_EQ("", httplib::sanitize_filename(" "));
  325. }
  326. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  327. string unescapedCharacters = "-_.!~*'()";
  328. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  329. }
  330. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  331. string reservedCharacters = ";,/?:@&=+$";
  332. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  333. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  334. }
  335. TEST(ClientQueryOrder, PreserveOrder) {
  336. // This test reproduces Issue #2259: client may reorder query parameters
  337. // when sending a GET request. The expected behavior is that the client
  338. // preserves the original query string order when the caller supplied it
  339. // as part of the path.
  340. Server svr;
  341. svr.Get("/", [&](const Request &req, Response &res) {
  342. // Echo back the raw target so the test can assert ordering
  343. res.set_content(req.target, "text/plain");
  344. });
  345. std::thread t{[&] { svr.listen(HOST, PORT); }};
  346. auto se = detail::scope_exit([&] {
  347. svr.stop();
  348. t.join();
  349. ASSERT_FALSE(svr.is_running());
  350. });
  351. svr.wait_until_ready();
  352. Client cli(HOST, PORT);
  353. ASSERT_TRUE(cli.is_valid());
  354. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  355. auto res = cli.Get(original);
  356. ASSERT_TRUE(res);
  357. // Expect the echoed target to exactly match the original path (order
  358. // preserved)
  359. EXPECT_EQ(res->body, original);
  360. }
  361. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  362. string chineseCharacters = U8("中国語");
  363. string russianCharacters = U8("дом");
  364. string brazilianCharacters = U8("óculos");
  365. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  366. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  367. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  368. "%D0%B4%D0%BE%D0%BC");
  369. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  370. }
  371. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  372. string unescapedCharacters = "-_.!~*'()";
  373. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  374. }
  375. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  376. string reservedCharacters = ";,/?:@&=+$";
  377. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  378. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  379. }
  380. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  381. string chineseCharacters = U8("中国語");
  382. string russianCharacters = U8("дом");
  383. string brazilianCharacters = U8("óculos");
  384. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  385. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  386. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  387. "%D0%B4%D0%BE%D0%BC");
  388. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  389. }
  390. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  391. // Issue #2082 use case: encoding path component with ampersand
  392. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  393. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  394. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  395. }
  396. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  397. string unescapedCharacters = "-_.!~*'()";
  398. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  399. }
  400. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  401. string reservedCharacters = ";,/?:@&=+$#";
  402. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  403. }
  404. TEST(EncodeUriTest, TestUTF8Characters) {
  405. string chineseCharacters = U8("中国語");
  406. string russianCharacters = U8("дом");
  407. string brazilianCharacters = U8("óculos");
  408. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  409. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  410. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  411. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  412. }
  413. TEST(EncodeUriTest, TestCompleteUri) {
  414. string uri =
  415. "https://example.com/path/to/resource?query=value&param=test#fragment";
  416. EXPECT_EQ(
  417. httplib::encode_uri(uri),
  418. "https://example.com/path/to/resource?query=value&param=test#fragment");
  419. }
  420. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  421. string uri =
  422. "https://example.com/path with spaces/file name.html?q=hello world";
  423. EXPECT_EQ(httplib::encode_uri(uri),
  424. "https://example.com/path%20with%20spaces/"
  425. "file%20name.html?q=hello%20world");
  426. }
  427. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  428. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  429. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  430. }
  431. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  432. string unescapedCharacters = "-_.!~*'()";
  433. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  434. }
  435. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  436. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  437. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  438. string encodedBrazilian = "%C3%B3culos";
  439. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  440. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  441. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  442. }
  443. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  444. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  445. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  446. "Piri Tommy Villiers - on & on");
  447. }
  448. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  449. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  450. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  451. }
  452. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  453. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  454. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  455. }
  456. TEST(DecodeUriTest, TestUTF8Characters) {
  457. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  458. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  459. string encodedBrazilian = "%C3%B3culos";
  460. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  461. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  462. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  463. }
  464. TEST(DecodeUriTest, TestCompleteUri) {
  465. string encodedUri = "https://example.com/path%20with%20spaces/"
  466. "file%20name.html?q=hello%20world";
  467. EXPECT_EQ(
  468. httplib::decode_uri(encodedUri),
  469. "https://example.com/path with spaces/file name.html?q=hello world");
  470. }
  471. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  472. string original =
  473. "https://example.com/path with spaces/file name.html?q=hello world";
  474. string encoded = httplib::encode_uri(original);
  475. string decoded = httplib::decode_uri(encoded);
  476. EXPECT_EQ(decoded, original);
  477. }
  478. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  479. string original = "Piri Tommy Villiers - on & on";
  480. string encoded = httplib::encode_uri_component(original);
  481. string decoded = httplib::decode_uri_component(encoded);
  482. EXPECT_EQ(decoded, original);
  483. }
  484. TEST(TrimTests, TrimStringTests) {
  485. EXPECT_EQ("abc", detail::trim_copy("abc"));
  486. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  487. EXPECT_TRUE(detail::trim_copy("").empty());
  488. }
  489. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  490. // Simple case without quality values
  491. std::vector<std::string> result1;
  492. EXPECT_TRUE(detail::parse_accept_header(
  493. "text/html,application/json,text/plain", result1));
  494. EXPECT_EQ(result1.size(), 3U);
  495. EXPECT_EQ(result1[0], "text/html");
  496. EXPECT_EQ(result1[1], "application/json");
  497. EXPECT_EQ(result1[2], "text/plain");
  498. // With quality values
  499. std::vector<std::string> result2;
  500. EXPECT_TRUE(detail::parse_accept_header(
  501. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  502. EXPECT_EQ(result2.size(), 3U);
  503. EXPECT_EQ(result2[0], "application/json"); // highest q value
  504. EXPECT_EQ(result2[1], "text/html");
  505. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  506. }
  507. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  508. // Mixed with and without quality values
  509. std::vector<std::string> result;
  510. EXPECT_TRUE(detail::parse_accept_header(
  511. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  512. EXPECT_EQ(result.size(), 3U);
  513. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  514. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  515. EXPECT_EQ(result[2], "application/json"); // q=0.5
  516. }
  517. TEST(ParseAcceptHeaderTest, EdgeCases) {
  518. // Empty header
  519. std::vector<std::string> empty_result;
  520. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  521. EXPECT_TRUE(empty_result.empty());
  522. // Single type
  523. std::vector<std::string> single_result;
  524. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  525. EXPECT_EQ(single_result.size(), 1U);
  526. EXPECT_EQ(single_result[0], "application/json");
  527. // Wildcard types
  528. std::vector<std::string> wildcard_result;
  529. EXPECT_TRUE(detail::parse_accept_header(
  530. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  531. EXPECT_EQ(wildcard_result.size(), 3U);
  532. EXPECT_EQ(wildcard_result[0], "application/json");
  533. EXPECT_EQ(wildcard_result[1], "text/*");
  534. EXPECT_EQ(wildcard_result[2], "*/*");
  535. }
  536. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  537. // Common browser Accept header
  538. std::vector<std::string> browser_result;
  539. EXPECT_TRUE(
  540. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  541. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  542. browser_result));
  543. EXPECT_EQ(browser_result.size(), 6U);
  544. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  545. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  546. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  547. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  548. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  549. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  550. // API client header
  551. std::vector<std::string> api_result;
  552. EXPECT_TRUE(detail::parse_accept_header(
  553. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  554. api_result));
  555. EXPECT_EQ(api_result.size(), 3U);
  556. EXPECT_EQ(api_result[0], "application/json");
  557. EXPECT_EQ(api_result[1], "application/xml");
  558. EXPECT_EQ(api_result[2], "text/plain");
  559. }
  560. TEST(ParseAcceptHeaderTest, SpecialCases) {
  561. // Quality value with 3 decimal places
  562. std::vector<std::string> decimal_result;
  563. EXPECT_TRUE(detail::parse_accept_header(
  564. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  565. EXPECT_EQ(decimal_result.size(), 2U);
  566. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  567. EXPECT_EQ(decimal_result[1], "text/html");
  568. // Zero quality (should still be included but with lowest priority)
  569. std::vector<std::string> zero_q_result;
  570. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  571. zero_q_result));
  572. EXPECT_EQ(zero_q_result.size(), 2U);
  573. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  574. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  575. // No spaces around commas
  576. std::vector<std::string> no_space_result;
  577. EXPECT_TRUE(detail::parse_accept_header(
  578. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  579. no_space_result));
  580. EXPECT_EQ(no_space_result.size(), 3U);
  581. EXPECT_EQ(no_space_result[0], "text/html");
  582. EXPECT_EQ(no_space_result[1], "application/json");
  583. EXPECT_EQ(no_space_result[2], "text/plain");
  584. }
  585. TEST(ParseAcceptHeaderTest, InvalidCases) {
  586. std::vector<std::string> result;
  587. // Invalid quality value (> 1.0)
  588. EXPECT_FALSE(
  589. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  590. // Invalid quality value (< 0.0)
  591. EXPECT_FALSE(
  592. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  593. // Invalid quality value (not a number)
  594. EXPECT_FALSE(detail::parse_accept_header(
  595. "text/html;q=invalid,application/json", result));
  596. // Empty quality value
  597. EXPECT_FALSE(
  598. detail::parse_accept_header("text/html;q=,application/json", result));
  599. // Invalid media type format (no slash and not wildcard)
  600. EXPECT_FALSE(
  601. detail::parse_accept_header("invalidtype,application/json", result));
  602. // Empty media type
  603. result.clear();
  604. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  605. // Only commas
  606. result.clear();
  607. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  608. // Valid cases should still work
  609. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  610. EXPECT_EQ(result.size(), 1U);
  611. EXPECT_EQ(result[0], "*/*");
  612. EXPECT_TRUE(detail::parse_accept_header("*", result));
  613. EXPECT_EQ(result.size(), 1U);
  614. EXPECT_EQ(result[0], "*");
  615. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  616. EXPECT_EQ(result.size(), 1U);
  617. EXPECT_EQ(result[0], "text/*");
  618. }
  619. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  620. Server svr;
  621. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  622. EXPECT_EQ(req.accept_content_types.size(), 3U);
  623. EXPECT_EQ(req.accept_content_types[0], "application/json");
  624. EXPECT_EQ(req.accept_content_types[1], "text/html");
  625. EXPECT_EQ(req.accept_content_types[2], "*/*");
  626. res.set_content("ok", "text/plain");
  627. });
  628. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  629. EXPECT_TRUE(false);
  630. res.set_content("bad request", "text/plain");
  631. });
  632. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  633. auto se = detail::scope_exit([&] {
  634. svr.stop();
  635. listen_thread.join();
  636. ASSERT_FALSE(svr.is_running());
  637. });
  638. svr.wait_until_ready();
  639. Client cli("localhost", PORT);
  640. {
  641. auto res =
  642. cli.Get("/accept_ok",
  643. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  644. ASSERT_TRUE(res);
  645. EXPECT_EQ(StatusCode::OK_200, res->status);
  646. }
  647. {
  648. auto res = cli.Get("/accept_bad_request",
  649. {{"Accept", "text/html;q=abc,application/json"}});
  650. ASSERT_TRUE(res);
  651. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  652. }
  653. }
  654. TEST(DivideTest, DivideStringTests) {
  655. auto divide = [](const std::string &str, char d) {
  656. std::string lhs;
  657. std::string rhs;
  658. detail::divide(str, d,
  659. [&](const char *lhs_data, std::size_t lhs_size,
  660. const char *rhs_data, std::size_t rhs_size) {
  661. lhs.assign(lhs_data, lhs_size);
  662. rhs.assign(rhs_data, rhs_size);
  663. });
  664. return std::make_pair(std::move(lhs), std::move(rhs));
  665. };
  666. {
  667. const auto res = divide("", '=');
  668. EXPECT_EQ(res.first, "");
  669. EXPECT_EQ(res.second, "");
  670. }
  671. {
  672. const auto res = divide("=", '=');
  673. EXPECT_EQ(res.first, "");
  674. EXPECT_EQ(res.second, "");
  675. }
  676. {
  677. const auto res = divide(" ", '=');
  678. EXPECT_EQ(res.first, " ");
  679. EXPECT_EQ(res.second, "");
  680. }
  681. {
  682. const auto res = divide("a", '=');
  683. EXPECT_EQ(res.first, "a");
  684. EXPECT_EQ(res.second, "");
  685. }
  686. {
  687. const auto res = divide("a=", '=');
  688. EXPECT_EQ(res.first, "a");
  689. EXPECT_EQ(res.second, "");
  690. }
  691. {
  692. const auto res = divide("=b", '=');
  693. EXPECT_EQ(res.first, "");
  694. EXPECT_EQ(res.second, "b");
  695. }
  696. {
  697. const auto res = divide("a=b", '=');
  698. EXPECT_EQ(res.first, "a");
  699. EXPECT_EQ(res.second, "b");
  700. }
  701. {
  702. const auto res = divide("a=b=", '=');
  703. EXPECT_EQ(res.first, "a");
  704. EXPECT_EQ(res.second, "b=");
  705. }
  706. {
  707. const auto res = divide("a=b=c", '=');
  708. EXPECT_EQ(res.first, "a");
  709. EXPECT_EQ(res.second, "b=c");
  710. }
  711. }
  712. TEST(SplitTest, ParseQueryString) {
  713. string s = "key1=val1&key2=val2&key3=val3";
  714. Params dic;
  715. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  716. [&](const char *b, const char *e) {
  717. string key, val;
  718. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  719. if (key.empty()) {
  720. key.assign(b2, e2);
  721. } else {
  722. val.assign(b2, e2);
  723. }
  724. });
  725. dic.emplace(key, val);
  726. });
  727. EXPECT_EQ("val1", dic.find("key1")->second);
  728. EXPECT_EQ("val2", dic.find("key2")->second);
  729. EXPECT_EQ("val3", dic.find("key3")->second);
  730. }
  731. TEST(SplitTest, ParseInvalidQueryTests) {
  732. {
  733. string s = " ";
  734. Params dict;
  735. detail::parse_query_text(s, dict);
  736. EXPECT_TRUE(dict.empty());
  737. }
  738. {
  739. string s = " = =";
  740. Params dict;
  741. detail::parse_query_text(s, dict);
  742. EXPECT_TRUE(dict.empty());
  743. }
  744. }
  745. TEST(ParseQueryTest, ParseQueryString) {
  746. {
  747. std::string s = "key1=val1&key2=val2&key3=val3";
  748. Params dic;
  749. detail::parse_query_text(s, dic);
  750. EXPECT_EQ("val1", dic.find("key1")->second);
  751. EXPECT_EQ("val2", dic.find("key2")->second);
  752. EXPECT_EQ("val3", dic.find("key3")->second);
  753. }
  754. {
  755. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  756. Params dic;
  757. detail::parse_query_text(s, dic);
  758. EXPECT_EQ("", dic.find("key1")->second);
  759. EXPECT_EQ("val1", dic.find("key2")->second);
  760. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  761. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  762. }
  763. }
  764. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  765. Params dic;
  766. EXPECT_EQ(detail::params_to_query_str(dic), "");
  767. dic.emplace("key1", "val1");
  768. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  769. dic.emplace("key2", "val2");
  770. dic.emplace("key3", "val3");
  771. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  772. }
  773. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  774. string content_type = "multipart/form-data; boundary=something";
  775. string boundary;
  776. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  777. EXPECT_TRUE(ret);
  778. EXPECT_EQ(boundary, "something");
  779. }
  780. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  781. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  782. string boundary;
  783. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  784. EXPECT_TRUE(ret);
  785. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  786. }
  787. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  788. string content_type =
  789. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  790. string boundary;
  791. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  792. EXPECT_TRUE(ret);
  793. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  794. }
  795. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  796. string content_type =
  797. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  798. string boundary;
  799. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  800. EXPECT_TRUE(ret);
  801. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  802. }
  803. TEST(GetHeaderValueTest, DefaultValue) {
  804. Headers headers = {{"Dummy", "Dummy"}};
  805. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  806. EXPECT_STREQ("text/plain", val);
  807. }
  808. TEST(GetHeaderValueTest, DefaultValueInt) {
  809. Headers headers = {{"Dummy", "Dummy"}};
  810. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  811. EXPECT_EQ(100ull, val);
  812. }
  813. TEST(GetHeaderValueTest, RegularValue) {
  814. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  815. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  816. EXPECT_STREQ("text/html", val);
  817. }
  818. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  819. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  820. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  821. EXPECT_STREQ("text/html", val);
  822. }
  823. TEST(GetHeaderValueTest, SetContent) {
  824. Response res;
  825. res.set_content("html", "text/html");
  826. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  827. res.set_content("text", "text/plain");
  828. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  829. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  830. }
  831. TEST(GetHeaderValueTest, RegularValueInt) {
  832. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  833. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  834. EXPECT_EQ(100ull, val);
  835. }
  836. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  837. Headers headers = {{"Content-Length", "x"}};
  838. auto is_invalid_value = false;
  839. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  840. is_invalid_value);
  841. EXPECT_EQ(0ull, val);
  842. EXPECT_TRUE(is_invalid_value);
  843. }
  844. TEST(GetHeaderValueTest, Range) {
  845. {
  846. Headers headers = {make_range_header({{1, -1}})};
  847. auto val = detail::get_header_value(headers, "Range", 0, 0);
  848. EXPECT_STREQ("bytes=1-", val);
  849. }
  850. {
  851. Headers headers = {make_range_header({{-1, 1}})};
  852. auto val = detail::get_header_value(headers, "Range", 0, 0);
  853. EXPECT_STREQ("bytes=-1", val);
  854. }
  855. {
  856. Headers headers = {make_range_header({{1, 10}})};
  857. auto val = detail::get_header_value(headers, "Range", 0, 0);
  858. EXPECT_STREQ("bytes=1-10", val);
  859. }
  860. {
  861. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  862. auto val = detail::get_header_value(headers, "Range", 0, 0);
  863. EXPECT_STREQ("bytes=1-10, 100-", val);
  864. }
  865. {
  866. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  867. auto val = detail::get_header_value(headers, "Range", 0, 0);
  868. EXPECT_STREQ("bytes=1-10, 100-200", val);
  869. }
  870. {
  871. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  872. auto val = detail::get_header_value(headers, "Range", 0, 0);
  873. EXPECT_STREQ("bytes=0-0, -1", val);
  874. }
  875. }
  876. TEST(ParseHeaderValueTest, Range) {
  877. {
  878. Ranges ranges;
  879. auto ret = detail::parse_range_header("bytes=1-", ranges);
  880. EXPECT_TRUE(ret);
  881. EXPECT_EQ(1u, ranges.size());
  882. EXPECT_EQ(1u, ranges[0].first);
  883. EXPECT_EQ(-1, ranges[0].second);
  884. }
  885. {
  886. Ranges ranges;
  887. auto ret = detail::parse_range_header("bytes=-1", ranges);
  888. EXPECT_TRUE(ret);
  889. EXPECT_EQ(1u, ranges.size());
  890. EXPECT_EQ(-1, ranges[0].first);
  891. EXPECT_EQ(1u, ranges[0].second);
  892. }
  893. {
  894. Ranges ranges;
  895. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  896. EXPECT_TRUE(ret);
  897. EXPECT_EQ(1u, ranges.size());
  898. EXPECT_EQ(1u, ranges[0].first);
  899. EXPECT_EQ(10u, ranges[0].second);
  900. }
  901. {
  902. Ranges ranges;
  903. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  904. EXPECT_FALSE(ret);
  905. }
  906. {
  907. Ranges ranges;
  908. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  909. EXPECT_TRUE(ret);
  910. EXPECT_EQ(2u, ranges.size());
  911. EXPECT_EQ(1u, ranges[0].first);
  912. EXPECT_EQ(10u, ranges[0].second);
  913. EXPECT_EQ(100u, ranges[1].first);
  914. EXPECT_EQ(-1, ranges[1].second);
  915. }
  916. {
  917. Ranges ranges;
  918. auto ret =
  919. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  920. EXPECT_TRUE(ret);
  921. EXPECT_EQ(3u, ranges.size());
  922. EXPECT_EQ(1u, ranges[0].first);
  923. EXPECT_EQ(10u, ranges[0].second);
  924. EXPECT_EQ(100u, ranges[1].first);
  925. EXPECT_EQ(200u, ranges[1].second);
  926. EXPECT_EQ(300u, ranges[2].first);
  927. EXPECT_EQ(400u, ranges[2].second);
  928. }
  929. {
  930. Ranges ranges;
  931. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  932. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  933. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  934. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  935. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  936. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  937. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  938. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  939. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  940. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  941. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  942. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  943. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  944. EXPECT_TRUE(ranges.empty());
  945. }
  946. }
  947. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  948. Request req;
  949. req.set_header("Accept-Encoding", "gzip");
  950. Response res;
  951. res.set_header("Content-Type", "text/plain");
  952. auto ret = detail::encoding_type(req, res);
  953. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  954. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  955. #else
  956. EXPECT_TRUE(ret == detail::EncodingType::None);
  957. #endif
  958. }
  959. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  960. Request req;
  961. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  962. Response res;
  963. res.set_header("Content-Type", "text/plain");
  964. auto ret = detail::encoding_type(req, res);
  965. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  966. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  967. #elif CPPHTTPLIB_ZLIB_SUPPORT
  968. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  969. #elif CPPHTTPLIB_ZSTD_SUPPORT
  970. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  971. #else
  972. EXPECT_TRUE(ret == detail::EncodingType::None);
  973. #endif
  974. }
  975. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  976. Request req;
  977. req.set_header("Accept-Encoding",
  978. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  979. Response res;
  980. res.set_header("Content-Type", "text/plain");
  981. auto ret = detail::encoding_type(req, res);
  982. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  983. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  984. #elif CPPHTTPLIB_ZLIB_SUPPORT
  985. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  986. #elif CPPHTTPLIB_ZSTD_SUPPORT
  987. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  988. #else
  989. EXPECT_TRUE(ret == detail::EncodingType::None);
  990. #endif
  991. }
  992. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  993. // All supported encodings rejected with q=0 should return None
  994. Request req;
  995. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  996. Response res;
  997. res.set_header("Content-Type", "text/plain");
  998. auto ret = detail::encoding_type(req, res);
  999. EXPECT_TRUE(ret == detail::EncodingType::None);
  1000. }
  1001. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1002. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1003. Request req;
  1004. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1005. Response res;
  1006. res.set_header("Content-Type", "text/plain");
  1007. auto ret = detail::encoding_type(req, res);
  1008. EXPECT_TRUE(ret == detail::EncodingType::None);
  1009. }
  1010. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1011. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1012. Request req;
  1013. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1014. Response res;
  1015. res.set_header("Content-Type", "text/plain");
  1016. auto ret = detail::encoding_type(req, res);
  1017. EXPECT_TRUE(ret == detail::EncodingType::None);
  1018. }
  1019. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1020. // RFC 7231: Accept-Encoding values are case-insensitive
  1021. Request req;
  1022. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1023. Response res;
  1024. res.set_header("Content-Type", "text/plain");
  1025. auto ret = detail::encoding_type(req, res);
  1026. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1027. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1028. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1029. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1030. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1031. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1032. #else
  1033. EXPECT_TRUE(ret == detail::EncodingType::None);
  1034. #endif
  1035. }
  1036. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1037. // q value should determine priority, not hardcoded order
  1038. Request req;
  1039. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1040. Response res;
  1041. res.set_header("Content-Type", "text/plain");
  1042. auto ret = detail::encoding_type(req, res);
  1043. // gzip has highest q=1.0, so it should be selected even though
  1044. // br and zstd are also supported
  1045. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1046. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1047. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1048. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1049. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1050. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1051. #else
  1052. EXPECT_TRUE(ret == detail::EncodingType::None);
  1053. #endif
  1054. }
  1055. TEST(BufferStreamTest, read) {
  1056. detail::BufferStream strm1;
  1057. Stream &strm = strm1;
  1058. EXPECT_EQ(5, strm.write("hello"));
  1059. char buf[512];
  1060. EXPECT_EQ(2, strm.read(buf, 2));
  1061. EXPECT_EQ('h', buf[0]);
  1062. EXPECT_EQ('e', buf[1]);
  1063. EXPECT_EQ(2, strm.read(buf, 2));
  1064. EXPECT_EQ('l', buf[0]);
  1065. EXPECT_EQ('l', buf[1]);
  1066. EXPECT_EQ(1, strm.read(buf, 1));
  1067. EXPECT_EQ('o', buf[0]);
  1068. EXPECT_EQ(0, strm.read(buf, 1));
  1069. }
  1070. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1071. auto host = "www.httpwatch.com";
  1072. auto ip = hosted_at(host);
  1073. EXPECT_EQ("23.96.13.243", ip);
  1074. std::vector<std::string> addrs;
  1075. hosted_at(host, addrs);
  1076. EXPECT_EQ(1u, addrs.size());
  1077. }
  1078. #if 0 // It depends on each test environment...
  1079. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1080. auto host = "www.youtube.com";
  1081. std::vector<std::string> addrs;
  1082. hosted_at(host, addrs);
  1083. EXPECT_EQ(20u, addrs.size());
  1084. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1085. EXPECT_TRUE(it != addrs.end());
  1086. }
  1087. #endif
  1088. class ChunkedEncodingTest : public ::testing::Test {
  1089. protected:
  1090. ChunkedEncodingTest()
  1091. : cli_(HOST, PORT)
  1092. #ifdef CPPHTTPLIB_SSL_ENABLED
  1093. ,
  1094. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1095. #endif
  1096. {
  1097. cli_.set_connection_timeout(2);
  1098. #ifdef CPPHTTPLIB_SSL_ENABLED
  1099. cli_.enable_server_certificate_verification(false);
  1100. #endif
  1101. }
  1102. virtual void SetUp() {
  1103. read_file("./image.jpg", image_data_);
  1104. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1105. res.set_content("Hello World!", "text/plain");
  1106. });
  1107. svr_.Get(
  1108. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1109. res.set_chunked_content_provider(
  1110. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1111. size_t remaining = image_data_.size() - offset;
  1112. if (remaining == 0) {
  1113. sink.done();
  1114. } else {
  1115. constexpr size_t CHUNK_SIZE = 1024;
  1116. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1117. sink.write(&image_data_[offset], send_size);
  1118. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1119. }
  1120. return true;
  1121. });
  1122. });
  1123. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1124. svr_.wait_until_ready();
  1125. }
  1126. virtual void TearDown() {
  1127. svr_.stop();
  1128. if (!request_threads_.empty()) {
  1129. std::this_thread::sleep_for(std::chrono::seconds(1));
  1130. for (auto &t : request_threads_) {
  1131. t.join();
  1132. }
  1133. }
  1134. t_.join();
  1135. }
  1136. #ifdef CPPHTTPLIB_SSL_ENABLED
  1137. SSLClient cli_;
  1138. SSLServer svr_;
  1139. #else
  1140. Client cli_;
  1141. Server svr_;
  1142. #endif
  1143. thread t_;
  1144. std::vector<thread> request_threads_;
  1145. std::string image_data_;
  1146. };
  1147. TEST_F(ChunkedEncodingTest, NormalGet) {
  1148. auto res = cli_.Get("/chunked");
  1149. ASSERT_TRUE(res);
  1150. std::string out;
  1151. read_file("./image.jpg", out);
  1152. EXPECT_EQ(StatusCode::OK_200, res->status);
  1153. EXPECT_EQ(out, res->body);
  1154. }
  1155. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1156. std::string body;
  1157. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1158. body.append(data, data_length);
  1159. return true;
  1160. });
  1161. ASSERT_TRUE(res);
  1162. std::string out;
  1163. read_file("./image.jpg", out);
  1164. EXPECT_EQ(StatusCode::OK_200, res->status);
  1165. EXPECT_EQ(out, body);
  1166. }
  1167. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1168. std::string body;
  1169. auto res = cli_.Get(
  1170. "/chunked",
  1171. [&](const Response &response) {
  1172. EXPECT_EQ(StatusCode::OK_200, response.status);
  1173. return true;
  1174. },
  1175. [&](const char *data, size_t data_length) {
  1176. body.append(data, data_length);
  1177. return true;
  1178. });
  1179. ASSERT_TRUE(res);
  1180. std::string out;
  1181. read_file("./image.jpg", out);
  1182. EXPECT_EQ(StatusCode::OK_200, res->status);
  1183. EXPECT_EQ(out, body);
  1184. }
  1185. TEST(RangeTest, FromHTTPBin_Online) {
  1186. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1187. auto host = "httpcan.org";
  1188. auto path = std::string{"/range/32"};
  1189. #else
  1190. auto host = "nghttp2.org";
  1191. auto path = std::string{"/httpbin/range/32"};
  1192. #endif
  1193. #ifdef CPPHTTPLIB_SSL_ENABLED
  1194. auto port = 443;
  1195. SSLClient cli(host, port);
  1196. #else
  1197. auto port = 80;
  1198. Client cli(host, port);
  1199. #endif
  1200. cli.set_connection_timeout(5);
  1201. {
  1202. auto res = cli.Get(path);
  1203. ASSERT_TRUE(res);
  1204. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1205. EXPECT_EQ(StatusCode::OK_200, res->status);
  1206. }
  1207. {
  1208. Headers headers = {make_range_header({{1, -1}})};
  1209. auto res = cli.Get(path, headers);
  1210. ASSERT_TRUE(res);
  1211. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1212. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1213. }
  1214. {
  1215. Headers headers = {make_range_header({{1, 10}})};
  1216. auto res = cli.Get(path, headers);
  1217. ASSERT_TRUE(res);
  1218. EXPECT_EQ("bcdefghijk", res->body);
  1219. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1220. }
  1221. {
  1222. Headers headers = {make_range_header({{0, 31}})};
  1223. auto res = cli.Get(path, headers);
  1224. ASSERT_TRUE(res);
  1225. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1226. EXPECT_EQ(StatusCode::OK_200, res->status);
  1227. }
  1228. {
  1229. Headers headers = {make_range_header({{0, -1}})};
  1230. auto res = cli.Get(path, headers);
  1231. ASSERT_TRUE(res);
  1232. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1233. EXPECT_EQ(StatusCode::OK_200, res->status);
  1234. }
  1235. {
  1236. Headers headers = {make_range_header({{0, 32}})};
  1237. auto res = cli.Get(path, headers);
  1238. ASSERT_TRUE(res);
  1239. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1240. }
  1241. }
  1242. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1243. auto host = "unresolvableaddress.local";
  1244. auto path = std::string{"/"};
  1245. #ifdef CPPHTTPLIB_SSL_ENABLED
  1246. auto port = 443;
  1247. SSLClient cli(host, port);
  1248. #else
  1249. auto port = 80;
  1250. Client cli(host, port);
  1251. #endif
  1252. cli.set_connection_timeout(1);
  1253. {
  1254. auto res = cli.Get(path);
  1255. ASSERT_FALSE(res);
  1256. }
  1257. std::this_thread::sleep_for(std::chrono::seconds(8));
  1258. }
  1259. TEST(ConnectionErrorTest, InvalidHost) {
  1260. auto host = "-abcde.com";
  1261. #ifdef CPPHTTPLIB_SSL_ENABLED
  1262. auto port = 443;
  1263. SSLClient cli(host, port);
  1264. #else
  1265. auto port = 80;
  1266. Client cli(host, port);
  1267. #endif
  1268. cli.set_connection_timeout(std::chrono::seconds(2));
  1269. auto res = cli.Get("/");
  1270. ASSERT_TRUE(!res);
  1271. EXPECT_EQ(Error::Connection, res.error());
  1272. }
  1273. TEST(ConnectionErrorTest, InvalidHost2) {
  1274. auto host = "httpcan.org/";
  1275. #ifdef CPPHTTPLIB_SSL_ENABLED
  1276. SSLClient cli(host);
  1277. #else
  1278. Client cli(host);
  1279. #endif
  1280. cli.set_connection_timeout(std::chrono::seconds(2));
  1281. auto res = cli.Get("/");
  1282. ASSERT_TRUE(!res);
  1283. EXPECT_EQ(Error::Connection, res.error());
  1284. }
  1285. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1286. auto host = "httpcan.org/";
  1287. #ifdef CPPHTTPLIB_SSL_ENABLED
  1288. SSLClient cli(host);
  1289. #else
  1290. Client cli(host);
  1291. #endif
  1292. cli.set_connection_timeout(std::chrono::seconds(2));
  1293. auto res = cli.Get("/");
  1294. ASSERT_TRUE(!res);
  1295. stringstream s;
  1296. s << "error code: " << res.error();
  1297. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1298. }
  1299. TEST(ConnectionErrorTest, InvalidPort) {
  1300. auto host = "localhost";
  1301. auto port = 44380;
  1302. #ifdef CPPHTTPLIB_SSL_ENABLED
  1303. SSLClient cli(host, port);
  1304. #else
  1305. Client cli(host, port);
  1306. #endif
  1307. cli.set_connection_timeout(std::chrono::seconds(2));
  1308. auto res = cli.Get("/");
  1309. ASSERT_TRUE(!res);
  1310. EXPECT_TRUE(Error::Connection == res.error() ||
  1311. Error::ConnectionTimeout == res.error());
  1312. }
  1313. TEST(ConnectionErrorTest, Timeout_Online) {
  1314. auto host = "google.com";
  1315. #ifdef CPPHTTPLIB_SSL_ENABLED
  1316. auto port = 44380;
  1317. SSLClient cli(host, port);
  1318. #else
  1319. auto port = 8080;
  1320. Client cli(host, port);
  1321. #endif
  1322. cli.set_connection_timeout(std::chrono::seconds(2));
  1323. // only probe one address type so that the error reason
  1324. // correlates to the timed-out IPv4, not the unsupported
  1325. // IPv6 connection attempt
  1326. cli.set_address_family(AF_INET);
  1327. auto res = cli.Get("/");
  1328. ASSERT_TRUE(!res);
  1329. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1330. }
  1331. TEST(CancelTest, NoCancel_Online) {
  1332. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1333. auto host = "httpcan.org";
  1334. auto path = std::string{"/range/32"};
  1335. #else
  1336. auto host = "nghttp2.org";
  1337. auto path = std::string{"/httpbin/range/32"};
  1338. #endif
  1339. #ifdef CPPHTTPLIB_SSL_ENABLED
  1340. auto port = 443;
  1341. SSLClient cli(host, port);
  1342. #else
  1343. auto port = 80;
  1344. Client cli(host, port);
  1345. #endif
  1346. cli.set_connection_timeout(std::chrono::seconds(5));
  1347. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1348. ASSERT_TRUE(res);
  1349. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1350. EXPECT_EQ(StatusCode::OK_200, res->status);
  1351. }
  1352. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1353. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1354. auto host = "httpcan.org";
  1355. auto path = std::string{"/range/32"};
  1356. #else
  1357. auto host = "nghttp2.org";
  1358. auto path = std::string{"/httpbin/range/32"};
  1359. #endif
  1360. #ifdef CPPHTTPLIB_SSL_ENABLED
  1361. auto port = 443;
  1362. SSLClient cli(host, port);
  1363. #else
  1364. auto port = 80;
  1365. Client cli(host, port);
  1366. #endif
  1367. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1368. cli.set_connection_timeout(std::chrono::seconds(5));
  1369. ASSERT_TRUE(!res);
  1370. EXPECT_EQ(Error::Canceled, res.error());
  1371. }
  1372. TEST(CancelTest, WithCancelLargePayload_Online) {
  1373. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1374. auto host = "httpcan.org";
  1375. auto path = std::string{"/range/65536"};
  1376. #else
  1377. auto host = "nghttp2.org";
  1378. auto path = std::string{"/httpbin/range/65536"};
  1379. #endif
  1380. #ifdef CPPHTTPLIB_SSL_ENABLED
  1381. auto port = 443;
  1382. SSLClient cli(host, port);
  1383. #else
  1384. auto port = 80;
  1385. Client cli(host, port);
  1386. #endif
  1387. cli.set_connection_timeout(std::chrono::seconds(5));
  1388. uint32_t count = 0;
  1389. auto res =
  1390. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1391. ASSERT_TRUE(!res);
  1392. EXPECT_EQ(Error::Canceled, res.error());
  1393. }
  1394. TEST(CancelTest, NoCancelPost) {
  1395. Server svr;
  1396. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1397. res.set_content("Hello World!", "text/plain");
  1398. });
  1399. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1400. auto se = detail::scope_exit([&] {
  1401. svr.stop();
  1402. thread.join();
  1403. ASSERT_FALSE(svr.is_running());
  1404. });
  1405. svr.wait_until_ready();
  1406. Client cli(HOST, PORT);
  1407. cli.set_connection_timeout(std::chrono::seconds(5));
  1408. auto res =
  1409. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1410. "application/json", [](uint64_t, uint64_t) { return true; });
  1411. ASSERT_TRUE(res);
  1412. EXPECT_EQ("Hello World!", res->body);
  1413. EXPECT_EQ(StatusCode::OK_200, res->status);
  1414. }
  1415. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1416. Server svr;
  1417. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1418. res.set_content("Hello World!", "text/plain");
  1419. });
  1420. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1421. auto se = detail::scope_exit([&] {
  1422. svr.stop();
  1423. thread.join();
  1424. ASSERT_FALSE(svr.is_running());
  1425. });
  1426. svr.wait_until_ready();
  1427. Client cli(HOST, PORT);
  1428. cli.set_connection_timeout(std::chrono::seconds(5));
  1429. auto res =
  1430. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1431. "application/json", [](uint64_t, uint64_t) { return false; });
  1432. ASSERT_TRUE(!res);
  1433. EXPECT_EQ(Error::Canceled, res.error());
  1434. }
  1435. TEST(CancelTest, WithCancelLargePayloadPost) {
  1436. Server svr;
  1437. svr.set_payload_max_length(200 * 1024 * 1024);
  1438. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1439. res.set_content(LARGE_DATA, "text/plain");
  1440. });
  1441. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1442. auto se = detail::scope_exit([&] {
  1443. svr.stop();
  1444. thread.join();
  1445. ASSERT_FALSE(svr.is_running());
  1446. });
  1447. svr.wait_until_ready();
  1448. Client cli(HOST, PORT);
  1449. cli.set_payload_max_length(200 * 1024 * 1024);
  1450. cli.set_connection_timeout(std::chrono::seconds(5));
  1451. auto res =
  1452. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1453. "application/json", [](uint64_t, uint64_t) { return false; });
  1454. ASSERT_TRUE(!res);
  1455. EXPECT_EQ(Error::Canceled, res.error());
  1456. }
  1457. TEST(CancelTest, NoCancelPut) {
  1458. Server svr;
  1459. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1460. res.set_content("Hello World!", "text/plain");
  1461. });
  1462. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1463. auto se = detail::scope_exit([&] {
  1464. svr.stop();
  1465. thread.join();
  1466. ASSERT_FALSE(svr.is_running());
  1467. });
  1468. svr.wait_until_ready();
  1469. Client cli(HOST, PORT);
  1470. cli.set_connection_timeout(std::chrono::seconds(5));
  1471. auto res =
  1472. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1473. "application/json", [](uint64_t, uint64_t) { return true; });
  1474. ASSERT_TRUE(res);
  1475. EXPECT_EQ("Hello World!", res->body);
  1476. EXPECT_EQ(StatusCode::OK_200, res->status);
  1477. }
  1478. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1479. Server svr;
  1480. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1481. res.set_content("Hello World!", "text/plain");
  1482. });
  1483. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1484. auto se = detail::scope_exit([&] {
  1485. svr.stop();
  1486. thread.join();
  1487. ASSERT_FALSE(svr.is_running());
  1488. });
  1489. svr.wait_until_ready();
  1490. Client cli(HOST, PORT);
  1491. cli.set_connection_timeout(std::chrono::seconds(5));
  1492. auto res =
  1493. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1494. "application/json", [](uint64_t, uint64_t) { return false; });
  1495. ASSERT_TRUE(!res);
  1496. EXPECT_EQ(Error::Canceled, res.error());
  1497. }
  1498. TEST(CancelTest, WithCancelLargePayloadPut) {
  1499. Server svr;
  1500. svr.set_payload_max_length(200 * 1024 * 1024);
  1501. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1502. res.set_content(LARGE_DATA, "text/plain");
  1503. });
  1504. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1505. auto se = detail::scope_exit([&] {
  1506. svr.stop();
  1507. thread.join();
  1508. ASSERT_FALSE(svr.is_running());
  1509. });
  1510. svr.wait_until_ready();
  1511. Client cli(HOST, PORT);
  1512. cli.set_payload_max_length(200 * 1024 * 1024);
  1513. cli.set_connection_timeout(std::chrono::seconds(5));
  1514. auto res =
  1515. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1516. "application/json", [](uint64_t, uint64_t) { return false; });
  1517. ASSERT_TRUE(!res);
  1518. EXPECT_EQ(Error::Canceled, res.error());
  1519. }
  1520. TEST(CancelTest, NoCancelPatch) {
  1521. Server svr;
  1522. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1523. res.set_content("Hello World!", "text/plain");
  1524. });
  1525. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1526. auto se = detail::scope_exit([&] {
  1527. svr.stop();
  1528. thread.join();
  1529. ASSERT_FALSE(svr.is_running());
  1530. });
  1531. svr.wait_until_ready();
  1532. Client cli(HOST, PORT);
  1533. cli.set_connection_timeout(std::chrono::seconds(5));
  1534. auto res =
  1535. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1536. "application/json", [](uint64_t, uint64_t) { return true; });
  1537. ASSERT_TRUE(res);
  1538. EXPECT_EQ("Hello World!", res->body);
  1539. EXPECT_EQ(StatusCode::OK_200, res->status);
  1540. }
  1541. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1542. Server svr;
  1543. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1544. res.set_content("Hello World!", "text/plain");
  1545. });
  1546. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1547. auto se = detail::scope_exit([&] {
  1548. svr.stop();
  1549. thread.join();
  1550. ASSERT_FALSE(svr.is_running());
  1551. });
  1552. svr.wait_until_ready();
  1553. Client cli(HOST, PORT);
  1554. cli.set_connection_timeout(std::chrono::seconds(5));
  1555. auto res =
  1556. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1557. "application/json", [](uint64_t, uint64_t) { return false; });
  1558. ASSERT_TRUE(!res);
  1559. EXPECT_EQ(Error::Canceled, res.error());
  1560. }
  1561. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1562. Server svr;
  1563. svr.set_payload_max_length(200 * 1024 * 1024);
  1564. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1565. res.set_content(LARGE_DATA, "text/plain");
  1566. });
  1567. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1568. auto se = detail::scope_exit([&] {
  1569. svr.stop();
  1570. thread.join();
  1571. ASSERT_FALSE(svr.is_running());
  1572. });
  1573. svr.wait_until_ready();
  1574. Client cli(HOST, PORT);
  1575. cli.set_payload_max_length(200 * 1024 * 1024);
  1576. cli.set_connection_timeout(std::chrono::seconds(5));
  1577. auto res =
  1578. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1579. "application/json", [](uint64_t, uint64_t) { return false; });
  1580. ASSERT_TRUE(!res);
  1581. EXPECT_EQ(Error::Canceled, res.error());
  1582. }
  1583. TEST(CancelTest, NoCancelDelete) {
  1584. Server svr;
  1585. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1586. res.set_content("Hello World!", "text/plain");
  1587. });
  1588. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1589. auto se = detail::scope_exit([&] {
  1590. svr.stop();
  1591. thread.join();
  1592. ASSERT_FALSE(svr.is_running());
  1593. });
  1594. svr.wait_until_ready();
  1595. Client cli(HOST, PORT);
  1596. cli.set_connection_timeout(std::chrono::seconds(5));
  1597. auto res =
  1598. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1599. "application/json", [](uint64_t, uint64_t) { return true; });
  1600. ASSERT_TRUE(res);
  1601. EXPECT_EQ("Hello World!", res->body);
  1602. EXPECT_EQ(StatusCode::OK_200, res->status);
  1603. }
  1604. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1605. Server svr;
  1606. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1607. res.set_content("Hello World!", "text/plain");
  1608. });
  1609. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1610. auto se = detail::scope_exit([&] {
  1611. svr.stop();
  1612. thread.join();
  1613. ASSERT_FALSE(svr.is_running());
  1614. });
  1615. svr.wait_until_ready();
  1616. Client cli(HOST, PORT);
  1617. cli.set_connection_timeout(std::chrono::seconds(5));
  1618. auto res =
  1619. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1620. "application/json", [](uint64_t, uint64_t) { return false; });
  1621. ASSERT_TRUE(!res);
  1622. EXPECT_EQ(Error::Canceled, res.error());
  1623. }
  1624. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1625. Server svr;
  1626. svr.set_payload_max_length(200 * 1024 * 1024);
  1627. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1628. res.set_content(LARGE_DATA, "text/plain");
  1629. });
  1630. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1631. auto se = detail::scope_exit([&] {
  1632. svr.stop();
  1633. thread.join();
  1634. ASSERT_FALSE(svr.is_running());
  1635. });
  1636. svr.wait_until_ready();
  1637. Client cli(HOST, PORT);
  1638. cli.set_payload_max_length(200 * 1024 * 1024);
  1639. cli.set_connection_timeout(std::chrono::seconds(5));
  1640. auto res =
  1641. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1642. "application/json", [](uint64_t, uint64_t) { return false; });
  1643. ASSERT_TRUE(!res);
  1644. EXPECT_EQ(Error::Canceled, res.error());
  1645. }
  1646. static std::string remove_whitespace(const std::string &input) {
  1647. std::string output;
  1648. output.reserve(input.size());
  1649. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1650. [](unsigned char c) { return !std::isspace(c); });
  1651. return output;
  1652. }
  1653. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1654. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1655. auto host = "httpcan.org";
  1656. auto path = std::string{"/basic-auth/hello/world"};
  1657. #else
  1658. auto host = "nghttp2.org";
  1659. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1660. #endif
  1661. #ifdef CPPHTTPLIB_SSL_ENABLED
  1662. auto port = 443;
  1663. SSLClient cli(host, port);
  1664. #else
  1665. auto port = 80;
  1666. Client cli(host, port);
  1667. #endif
  1668. {
  1669. auto res = cli.Get(path);
  1670. ASSERT_TRUE(res);
  1671. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1672. }
  1673. {
  1674. auto res =
  1675. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1676. ASSERT_TRUE(res);
  1677. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1678. remove_whitespace(res->body));
  1679. EXPECT_EQ(StatusCode::OK_200, res->status);
  1680. }
  1681. {
  1682. cli.set_basic_auth("hello", "world");
  1683. auto res = cli.Get(path);
  1684. ASSERT_TRUE(res);
  1685. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1686. remove_whitespace(res->body));
  1687. EXPECT_EQ(StatusCode::OK_200, res->status);
  1688. }
  1689. {
  1690. cli.set_basic_auth("hello", "bad");
  1691. auto res = cli.Get(path);
  1692. ASSERT_TRUE(res);
  1693. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1694. }
  1695. {
  1696. cli.set_basic_auth("bad", "world");
  1697. auto res = cli.Get(path);
  1698. ASSERT_TRUE(res);
  1699. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1700. }
  1701. }
  1702. #ifdef CPPHTTPLIB_SSL_ENABLED
  1703. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1704. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1705. auto host = "httpcan.org";
  1706. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1707. auto paths = std::vector<std::string>{
  1708. "/digest-auth/auth/hello/world/MD5",
  1709. "/digest-auth/auth/hello/world/SHA-256",
  1710. "/digest-auth/auth/hello/world/SHA-512",
  1711. };
  1712. #else
  1713. auto host = "nghttp2.org";
  1714. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1715. auto paths = std::vector<std::string>{
  1716. "/httpbin/digest-auth/auth/hello/world/MD5",
  1717. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1718. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1719. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1720. };
  1721. #endif
  1722. auto port = 443;
  1723. SSLClient cli(host, port);
  1724. {
  1725. auto res = cli.Get(unauth_path);
  1726. ASSERT_TRUE(res);
  1727. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1728. }
  1729. {
  1730. cli.set_digest_auth("hello", "world");
  1731. for (const auto &path : paths) {
  1732. auto res = cli.Get(path.c_str());
  1733. ASSERT_TRUE(res);
  1734. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1735. std::string algo(path.substr(path.rfind('/') + 1));
  1736. EXPECT_EQ(
  1737. remove_whitespace("{\"algorithm\":\"" + algo +
  1738. "\",\"authenticated\":true,\"user\":\"hello\"}\n"),
  1739. remove_whitespace(res->body));
  1740. #else
  1741. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1742. remove_whitespace(res->body));
  1743. #endif
  1744. EXPECT_EQ(StatusCode::OK_200, res->status);
  1745. }
  1746. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1747. cli.set_digest_auth("hello", "bad");
  1748. for (const auto &path : paths) {
  1749. auto res = cli.Get(path.c_str());
  1750. ASSERT_TRUE(res);
  1751. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1752. }
  1753. #endif
  1754. }
  1755. }
  1756. #endif
  1757. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1758. auto host = "google.com";
  1759. auto another_host = "example.com";
  1760. auto wrong_ip = "0.0.0.0";
  1761. #ifdef CPPHTTPLIB_SSL_ENABLED
  1762. SSLClient cli(host);
  1763. #else
  1764. Client cli(host);
  1765. #endif
  1766. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1767. auto res = cli.Get("/");
  1768. ASSERT_TRUE(res);
  1769. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1770. }
  1771. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1772. auto host = "google.com";
  1773. auto wrong_ip = "0.0.0.0";
  1774. #ifdef CPPHTTPLIB_SSL_ENABLED
  1775. SSLClient cli(host);
  1776. #else
  1777. Client cli(host);
  1778. #endif
  1779. cli.set_hostname_addr_map({{host, wrong_ip}});
  1780. auto res = cli.Get("/");
  1781. ASSERT_TRUE(!res);
  1782. EXPECT_EQ(Error::Connection, res.error());
  1783. }
  1784. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1785. auto host = "nghttp2.org";
  1786. #ifdef CPPHTTPLIB_SSL_ENABLED
  1787. SSLClient cli(host);
  1788. #else
  1789. Client cli(host);
  1790. #endif
  1791. cli.set_follow_location(true);
  1792. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1793. ASSERT_TRUE(res);
  1794. EXPECT_EQ(StatusCode::OK_200, res->status);
  1795. }
  1796. TEST(RedirectTest, Redirect_Online) {
  1797. auto host = "nghttp2.org";
  1798. #ifdef CPPHTTPLIB_SSL_ENABLED
  1799. SSLClient cli(host);
  1800. #else
  1801. Client cli(host);
  1802. #endif
  1803. cli.set_follow_location(true);
  1804. auto res = cli.Get("/httpbin/redirect/3");
  1805. ASSERT_TRUE(res);
  1806. EXPECT_EQ(StatusCode::OK_200, res->status);
  1807. }
  1808. TEST(RelativeRedirectTest, Redirect_Online) {
  1809. auto host = "nghttp2.org";
  1810. #ifdef CPPHTTPLIB_SSL_ENABLED
  1811. SSLClient cli(host);
  1812. #else
  1813. Client cli(host);
  1814. #endif
  1815. cli.set_follow_location(true);
  1816. auto res = cli.Get("/httpbin/relative-redirect/3");
  1817. ASSERT_TRUE(res);
  1818. EXPECT_EQ(StatusCode::OK_200, res->status);
  1819. }
  1820. TEST(TooManyRedirectTest, Redirect_Online) {
  1821. auto host = "nghttp2.org";
  1822. #ifdef CPPHTTPLIB_SSL_ENABLED
  1823. SSLClient cli(host);
  1824. #else
  1825. Client cli(host);
  1826. #endif
  1827. cli.set_follow_location(true);
  1828. auto res = cli.Get("/httpbin/redirect/21");
  1829. ASSERT_TRUE(!res);
  1830. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1831. }
  1832. #ifdef CPPHTTPLIB_SSL_ENABLED
  1833. TEST(YahooRedirectTest, Redirect_Online) {
  1834. Client cli("yahoo.com");
  1835. auto res = cli.Get("/");
  1836. ASSERT_TRUE(res);
  1837. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1838. cli.set_follow_location(true);
  1839. res = cli.Get("/");
  1840. ASSERT_TRUE(res);
  1841. EXPECT_EQ(StatusCode::OK_200, res->status);
  1842. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1843. }
  1844. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1845. #define REDIR_HOST "httpbingo.org"
  1846. #define REDIR_PATH "/redirect-to"
  1847. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1848. SSLClient cli(REDIR_HOST);
  1849. cli.set_follow_location(true);
  1850. auto res =
  1851. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1852. ASSERT_TRUE(res);
  1853. EXPECT_EQ(StatusCode::OK_200, res->status);
  1854. }
  1855. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1856. SSLClient cli(REDIR_HOST);
  1857. cli.set_follow_location(true);
  1858. Params params;
  1859. params.emplace("url", "http://example.com");
  1860. params.emplace("status_code", "302");
  1861. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1862. ASSERT_TRUE(res);
  1863. EXPECT_EQ(StatusCode::OK_200, res->status);
  1864. }
  1865. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1866. SSLClient cli(REDIR_HOST);
  1867. cli.set_follow_location(true);
  1868. Params params;
  1869. params.emplace("url", "http://example.com");
  1870. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1871. ASSERT_TRUE(res);
  1872. EXPECT_EQ(StatusCode::OK_200, res->status);
  1873. }
  1874. TEST(UrlWithSpace, Redirect_Online) {
  1875. SSLClient cli("edge.forgecdn.net");
  1876. cli.set_follow_location(true);
  1877. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1878. ASSERT_TRUE(res);
  1879. EXPECT_EQ(StatusCode::OK_200, res->status);
  1880. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1881. }
  1882. #endif
  1883. #if !defined(_WIN32) && !defined(_WIN64)
  1884. TEST(ReceiveSignals, Signal) {
  1885. auto setupSignalHandlers = []() {
  1886. struct sigaction act;
  1887. sigemptyset(&act.sa_mask);
  1888. act.sa_flags = SA_SIGINFO;
  1889. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1890. switch (sig) {
  1891. case SIGINT:
  1892. default: break;
  1893. }
  1894. };
  1895. ::sigaction(SIGINT, &act, nullptr);
  1896. };
  1897. Server svr;
  1898. int port = 0;
  1899. auto thread = std::thread([&]() {
  1900. setupSignalHandlers();
  1901. port = svr.bind_to_any_port(HOST);
  1902. svr.listen_after_bind();
  1903. });
  1904. auto se = detail::scope_exit([&] {
  1905. svr.stop();
  1906. thread.join();
  1907. ASSERT_FALSE(svr.is_running());
  1908. });
  1909. svr.wait_until_ready();
  1910. ASSERT_TRUE(svr.is_running());
  1911. pthread_kill(thread.native_handle(), SIGINT);
  1912. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1913. ASSERT_TRUE(svr.is_running());
  1914. }
  1915. #endif
  1916. TEST(RedirectToDifferentPort, Redirect) {
  1917. Server svr1;
  1918. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1919. res.set_content("Hello World!", "text/plain");
  1920. });
  1921. int svr1_port = 0;
  1922. auto thread1 = std::thread([&]() {
  1923. svr1_port = svr1.bind_to_any_port(HOST);
  1924. svr1.listen_after_bind();
  1925. });
  1926. Server svr2;
  1927. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1928. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1929. });
  1930. int svr2_port = 0;
  1931. auto thread2 = std::thread([&]() {
  1932. svr2_port = svr2.bind_to_any_port(HOST);
  1933. svr2.listen_after_bind();
  1934. });
  1935. auto se = detail::scope_exit([&] {
  1936. svr2.stop();
  1937. thread2.join();
  1938. svr1.stop();
  1939. thread1.join();
  1940. ASSERT_FALSE(svr2.is_running());
  1941. ASSERT_FALSE(svr1.is_running());
  1942. });
  1943. svr1.wait_until_ready();
  1944. svr2.wait_until_ready();
  1945. Client cli("localhost", svr2_port);
  1946. cli.set_follow_location(true);
  1947. auto res = cli.Get("/2");
  1948. ASSERT_TRUE(res);
  1949. EXPECT_EQ(StatusCode::OK_200, res->status);
  1950. EXPECT_EQ("Hello World!", res->body);
  1951. }
  1952. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  1953. Server svr;
  1954. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  1955. // Port number that overflows int — should not crash
  1956. res.set_redirect("http://localhost:99999999999999999999/target");
  1957. });
  1958. auto port = svr.bind_to_any_port(HOST);
  1959. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  1960. auto se = detail::scope_exit([&] {
  1961. svr.stop();
  1962. thread.join();
  1963. ASSERT_FALSE(svr.is_running());
  1964. });
  1965. svr.wait_until_ready();
  1966. Client cli(HOST, port);
  1967. cli.set_follow_location(true);
  1968. auto res = cli.Get("/redir");
  1969. // Should fail gracefully, not crash (no valid response due to bad port)
  1970. EXPECT_FALSE(res);
  1971. }
  1972. TEST(RedirectFromPageWithContent, Redirect) {
  1973. Server svr;
  1974. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1975. res.set_content("___", "text/plain");
  1976. res.set_redirect("/2");
  1977. });
  1978. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1979. res.set_content("Hello World!", "text/plain");
  1980. });
  1981. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1982. auto se = detail::scope_exit([&] {
  1983. svr.stop();
  1984. th.join();
  1985. ASSERT_FALSE(svr.is_running());
  1986. });
  1987. svr.wait_until_ready();
  1988. {
  1989. Client cli("localhost", PORT);
  1990. cli.set_follow_location(true);
  1991. std::string body;
  1992. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1993. body.append(data, data_length);
  1994. return true;
  1995. });
  1996. ASSERT_TRUE(res);
  1997. EXPECT_EQ(StatusCode::OK_200, res->status);
  1998. EXPECT_EQ("Hello World!", body);
  1999. }
  2000. {
  2001. Client cli("localhost", PORT);
  2002. std::string body;
  2003. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2004. body.append(data, data_length);
  2005. return true;
  2006. });
  2007. ASSERT_TRUE(res);
  2008. EXPECT_EQ(StatusCode::Found_302, res->status);
  2009. EXPECT_EQ("___", body);
  2010. }
  2011. }
  2012. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2013. Server svr;
  2014. auto port_str = std::to_string(PORT);
  2015. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2016. auto expected_host = "[::1]:" + port_str;
  2017. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2018. res.set_content("___", "text/plain");
  2019. // res.set_redirect("/2");
  2020. res.set_redirect(redirect_url);
  2021. });
  2022. svr.Get("/2", [&](const Request &req, Response &res) {
  2023. auto host_header = req.headers.find("Host");
  2024. ASSERT_TRUE(host_header != req.headers.end());
  2025. EXPECT_EQ(expected_host, host_header->second);
  2026. res.set_content("Hello World!", "text/plain");
  2027. });
  2028. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2029. auto se = detail::scope_exit([&] {
  2030. svr.stop();
  2031. th.join();
  2032. ASSERT_FALSE(svr.is_running());
  2033. });
  2034. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2035. // actually starts anything, so the condition !svr.is_running() will
  2036. // always remain true, and the loop never stops.
  2037. // This basically counts how many milliseconds have passed since the
  2038. // call to svr.listen(), and if after 5 seconds nothing started yet
  2039. // aborts the test.
  2040. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2041. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2042. ASSERT_LT(milliseconds, 5000U);
  2043. }
  2044. {
  2045. Client cli("::1", PORT);
  2046. cli.set_follow_location(true);
  2047. std::string body;
  2048. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2049. body.append(data, data_length);
  2050. return true;
  2051. });
  2052. ASSERT_TRUE(res);
  2053. EXPECT_EQ(StatusCode::OK_200, res->status);
  2054. EXPECT_EQ("Hello World!", body);
  2055. }
  2056. {
  2057. Client cli("::1", PORT);
  2058. std::string body;
  2059. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2060. body.append(data, data_length);
  2061. return true;
  2062. });
  2063. ASSERT_TRUE(res);
  2064. EXPECT_EQ(StatusCode::Found_302, res->status);
  2065. EXPECT_EQ("___", body);
  2066. }
  2067. }
  2068. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2069. Server svr;
  2070. svr.Get("/foo", [](const Request &req, Response &res) {
  2071. auto a = req.params.find("a");
  2072. if (a != req.params.end()) {
  2073. res.set_content((*a).second, "text/plain");
  2074. res.status = StatusCode::OK_200;
  2075. } else {
  2076. res.status = StatusCode::BadRequest_400;
  2077. }
  2078. });
  2079. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2080. auto se = detail::scope_exit([&] {
  2081. svr.stop();
  2082. thread.join();
  2083. ASSERT_FALSE(svr.is_running());
  2084. });
  2085. svr.wait_until_ready();
  2086. {
  2087. Client cli(HOST, PORT);
  2088. cli.set_path_encode(false);
  2089. auto res = cli.Get("/foo?a=explicitly+encoded");
  2090. ASSERT_TRUE(res);
  2091. EXPECT_EQ(StatusCode::OK_200, res->status);
  2092. // This expects it back with a space, as the `+` won't have been
  2093. // url-encoded, and server-side the params get decoded turning `+`
  2094. // into spaces.
  2095. EXPECT_EQ("explicitly encoded", res->body);
  2096. }
  2097. }
  2098. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2099. Server svr;
  2100. svr.Get("/", [](const Request &req, Response &) {
  2101. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2102. });
  2103. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2104. auto se = detail::scope_exit([&] {
  2105. svr.stop();
  2106. thread.join();
  2107. ASSERT_FALSE(svr.is_running());
  2108. });
  2109. svr.wait_until_ready();
  2110. {
  2111. Client cli(HOST, PORT);
  2112. cli.set_path_encode(false);
  2113. auto res = cli.Get("/?something=%0A");
  2114. ASSERT_TRUE(res);
  2115. EXPECT_EQ(StatusCode::OK_200, res->status);
  2116. }
  2117. }
  2118. TEST(BindServerTest, BindDualStack) {
  2119. Server svr;
  2120. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2121. res.set_content("Hello World!", "text/plain");
  2122. });
  2123. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2124. auto se = detail::scope_exit([&] {
  2125. svr.stop();
  2126. thread.join();
  2127. ASSERT_FALSE(svr.is_running());
  2128. });
  2129. svr.wait_until_ready();
  2130. {
  2131. Client cli("127.0.0.1", PORT);
  2132. auto res = cli.Get("/1");
  2133. ASSERT_TRUE(res);
  2134. EXPECT_EQ(StatusCode::OK_200, res->status);
  2135. EXPECT_EQ("Hello World!", res->body);
  2136. }
  2137. {
  2138. Client cli("::1", PORT);
  2139. auto res = cli.Get("/1");
  2140. ASSERT_TRUE(res);
  2141. EXPECT_EQ(StatusCode::OK_200, res->status);
  2142. EXPECT_EQ("Hello World!", res->body);
  2143. }
  2144. }
  2145. TEST(BindServerTest, BindAndListenSeparately) {
  2146. Server svr;
  2147. int port = svr.bind_to_any_port("0.0.0.0");
  2148. ASSERT_TRUE(svr.is_valid());
  2149. ASSERT_TRUE(port > 0);
  2150. svr.stop();
  2151. }
  2152. #ifdef CPPHTTPLIB_SSL_ENABLED
  2153. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2154. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2155. CLIENT_CA_CERT_DIR);
  2156. int port = svr.bind_to_any_port("0.0.0.0");
  2157. ASSERT_TRUE(svr.is_valid());
  2158. ASSERT_TRUE(port > 0);
  2159. svr.stop();
  2160. }
  2161. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2162. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2163. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2164. int port = svr.bind_to_any_port("0.0.0.0");
  2165. ASSERT_TRUE(svr.is_valid());
  2166. ASSERT_TRUE(port > 0);
  2167. svr.stop();
  2168. }
  2169. TEST(BindServerTest, UpdateCertsPem) {
  2170. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2171. int port = svr.bind_to_any_port("0.0.0.0");
  2172. ASSERT_TRUE(svr.is_valid());
  2173. ASSERT_TRUE(port > 0);
  2174. // Read PEM files
  2175. std::string cert_pem, key_pem, ca_pem;
  2176. read_file(SERVER_CERT_FILE, cert_pem);
  2177. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2178. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2179. // Update server certificates using PEM API
  2180. ASSERT_TRUE(
  2181. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2182. ASSERT_TRUE(svr.is_valid());
  2183. svr.stop();
  2184. }
  2185. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2186. // Start server with client CA (enables client auth)
  2187. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2188. ASSERT_TRUE(svr.is_valid());
  2189. bool handler_called = false;
  2190. svr.Get("/test", [&](const Request &req, Response &res) {
  2191. handler_called = true;
  2192. // Verify client certificate is present
  2193. auto cert = req.peer_cert();
  2194. EXPECT_TRUE(static_cast<bool>(cert));
  2195. res.set_content("ok", "text/plain");
  2196. });
  2197. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2198. auto se = detail::scope_exit([&] {
  2199. svr.stop();
  2200. t.join();
  2201. ASSERT_FALSE(svr.is_running());
  2202. });
  2203. svr.wait_until_ready();
  2204. // Read PEM files
  2205. std::string cert_pem, key_pem, ca_pem;
  2206. read_file(SERVER_CERT_FILE, cert_pem);
  2207. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2208. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2209. // Update server certificates and client CA using PEM API while server running
  2210. ASSERT_TRUE(
  2211. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2212. // Connect with client certificate
  2213. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2214. cli.enable_server_certificate_verification(false);
  2215. cli.set_connection_timeout(30);
  2216. auto res = cli.Get("/test");
  2217. ASSERT_TRUE(res);
  2218. ASSERT_EQ(StatusCode::OK_200, res->status);
  2219. ASSERT_TRUE(handler_called);
  2220. EXPECT_EQ("ok", res->body);
  2221. }
  2222. #endif
  2223. TEST(ErrorHandlerTest, ContentLength) {
  2224. Server svr;
  2225. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2226. res.status = StatusCode::OK_200;
  2227. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2228. "text/html"); // <= Content-Length still 13
  2229. });
  2230. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2231. res.set_content("Hello World!\n", "text/plain");
  2232. res.status = 524;
  2233. });
  2234. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2235. auto se = detail::scope_exit([&] {
  2236. svr.stop();
  2237. thread.join();
  2238. ASSERT_FALSE(svr.is_running());
  2239. });
  2240. svr.wait_until_ready();
  2241. {
  2242. Client cli(HOST, PORT);
  2243. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2244. ASSERT_TRUE(res);
  2245. EXPECT_EQ(StatusCode::OK_200, res->status);
  2246. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2247. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2248. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2249. }
  2250. }
  2251. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2252. TEST(ExceptionTest, WithoutExceptionHandler) {
  2253. Server svr;
  2254. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2255. throw std::runtime_error("exception...");
  2256. });
  2257. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2258. throw std::runtime_error("exception\r\n...");
  2259. });
  2260. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2261. auto se = detail::scope_exit([&] {
  2262. svr.stop();
  2263. listen_thread.join();
  2264. ASSERT_FALSE(svr.is_running());
  2265. });
  2266. svr.wait_until_ready();
  2267. Client cli("localhost", PORT);
  2268. {
  2269. auto res = cli.Get("/exception");
  2270. ASSERT_TRUE(res);
  2271. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2272. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2273. }
  2274. {
  2275. auto res = cli.Get("/unknown");
  2276. ASSERT_TRUE(res);
  2277. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2278. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2279. }
  2280. }
  2281. TEST(ExceptionTest, WithExceptionHandler) {
  2282. Server svr;
  2283. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2284. std::exception_ptr ep) {
  2285. EXPECT_FALSE(ep == nullptr);
  2286. try {
  2287. std::rethrow_exception(ep);
  2288. } catch (std::exception &e) {
  2289. EXPECT_EQ("abc", std::string(e.what()));
  2290. } catch (...) {}
  2291. res.status = StatusCode::InternalServerError_500;
  2292. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2293. "text/html"); // <= Content-Length still 13 at this point
  2294. });
  2295. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2296. res.set_content("Hello World!\n", "text/plain");
  2297. throw std::runtime_error("abc");
  2298. });
  2299. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2300. auto se = detail::scope_exit([&] {
  2301. svr.stop();
  2302. thread.join();
  2303. ASSERT_FALSE(svr.is_running());
  2304. });
  2305. svr.wait_until_ready();
  2306. for (size_t i = 0; i < 10; i++) {
  2307. Client cli(HOST, PORT);
  2308. for (size_t j = 0; j < 100; j++) {
  2309. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2310. ASSERT_TRUE(res);
  2311. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2312. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2313. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2314. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2315. }
  2316. cli.set_keep_alive(true);
  2317. for (size_t j = 0; j < 100; j++) {
  2318. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2319. ASSERT_TRUE(res);
  2320. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2321. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2322. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2323. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2324. }
  2325. }
  2326. }
  2327. TEST(ExceptionTest, AndErrorHandler) {
  2328. Server svr;
  2329. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2330. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2331. });
  2332. svr.set_exception_handler(
  2333. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2334. EXPECT_FALSE(ep == nullptr);
  2335. try {
  2336. std::rethrow_exception(ep);
  2337. } catch (std::exception &e) {
  2338. res.set_content(e.what(), "text/html");
  2339. } catch (...) {}
  2340. res.status = StatusCode::InternalServerError_500;
  2341. });
  2342. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2343. throw std::runtime_error("EXCEPTION");
  2344. });
  2345. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2346. res.set_content("ERROR", "text/html");
  2347. res.status = StatusCode::InternalServerError_500;
  2348. });
  2349. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2350. auto se = detail::scope_exit([&] {
  2351. svr.stop();
  2352. thread.join();
  2353. ASSERT_FALSE(svr.is_running());
  2354. });
  2355. svr.wait_until_ready();
  2356. Client cli(HOST, PORT);
  2357. {
  2358. auto res = cli.Get("/exception");
  2359. ASSERT_TRUE(res);
  2360. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2361. EXPECT_EQ("EXCEPTION", res->body);
  2362. }
  2363. {
  2364. auto res = cli.Get("/error");
  2365. ASSERT_TRUE(res);
  2366. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2367. EXPECT_EQ("ERROR", res->body);
  2368. }
  2369. {
  2370. auto res = cli.Get("/invalid");
  2371. ASSERT_TRUE(res);
  2372. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2373. EXPECT_EQ("NOT_FOUND", res->body);
  2374. }
  2375. }
  2376. #endif
  2377. TEST(NoContentTest, ContentLength) {
  2378. Server svr;
  2379. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2380. res.status = StatusCode::NoContent_204;
  2381. });
  2382. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2383. auto se = detail::scope_exit([&] {
  2384. svr.stop();
  2385. thread.join();
  2386. ASSERT_FALSE(svr.is_running());
  2387. });
  2388. svr.wait_until_ready();
  2389. {
  2390. Client cli(HOST, PORT);
  2391. auto res = cli.Get("/hi");
  2392. ASSERT_TRUE(res);
  2393. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2394. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2395. }
  2396. }
  2397. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2398. #ifdef CPPHTTPLIB_SSL_ENABLED
  2399. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2400. ASSERT_TRUE(svr.is_valid());
  2401. #else
  2402. Server svr;
  2403. #endif
  2404. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2405. if (req.path == "/routing_handler") {
  2406. res.set_header("PRE_ROUTING", "on");
  2407. res.set_content("Routing Handler", "text/plain");
  2408. return httplib::Server::HandlerResponse::Handled;
  2409. }
  2410. return httplib::Server::HandlerResponse::Unhandled;
  2411. });
  2412. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2413. res.set_content("Error", "text/html");
  2414. });
  2415. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2416. if (req.path == "/routing_handler") {
  2417. res.set_header("POST_ROUTING", "on");
  2418. }
  2419. });
  2420. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2421. res.set_content("Hello World!\n", "text/plain");
  2422. });
  2423. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2424. auto se = detail::scope_exit([&] {
  2425. svr.stop();
  2426. thread.join();
  2427. ASSERT_FALSE(svr.is_running());
  2428. });
  2429. svr.wait_until_ready();
  2430. {
  2431. #ifdef CPPHTTPLIB_SSL_ENABLED
  2432. SSLClient cli(HOST, PORT);
  2433. cli.enable_server_certificate_verification(false);
  2434. #else
  2435. Client cli(HOST, PORT);
  2436. #endif
  2437. auto res = cli.Get("/routing_handler");
  2438. ASSERT_TRUE(res);
  2439. EXPECT_EQ(StatusCode::OK_200, res->status);
  2440. EXPECT_EQ("Routing Handler", res->body);
  2441. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2442. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2443. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2444. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2445. }
  2446. {
  2447. #ifdef CPPHTTPLIB_SSL_ENABLED
  2448. SSLClient cli(HOST, PORT);
  2449. cli.enable_server_certificate_verification(false);
  2450. #else
  2451. Client cli(HOST, PORT);
  2452. #endif
  2453. auto res = cli.Get("/hi");
  2454. ASSERT_TRUE(res);
  2455. EXPECT_EQ(StatusCode::OK_200, res->status);
  2456. EXPECT_EQ("Hello World!\n", res->body);
  2457. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2458. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2459. }
  2460. {
  2461. #ifdef CPPHTTPLIB_SSL_ENABLED
  2462. SSLClient cli(HOST, PORT);
  2463. cli.enable_server_certificate_verification(false);
  2464. #else
  2465. Client cli(HOST, PORT);
  2466. #endif
  2467. auto res = cli.Get("/aaa");
  2468. ASSERT_TRUE(res);
  2469. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2470. EXPECT_EQ("Error", res->body);
  2471. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2472. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2473. }
  2474. }
  2475. TEST(RequestHandlerTest, PreRequestHandler) {
  2476. auto route_path = "/user/:user";
  2477. Server svr;
  2478. svr.Get("/hi", [](const Request &, Response &res) {
  2479. res.set_content("hi", "text/plain");
  2480. });
  2481. svr.Get(route_path, [](const Request &req, Response &res) {
  2482. res.set_content(req.path_params.at("user"), "text/plain");
  2483. });
  2484. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2485. if (req.matched_route == route_path) {
  2486. auto user = req.path_params.at("user");
  2487. if (user != "john") {
  2488. res.status = StatusCode::Forbidden_403;
  2489. res.set_content("error", "text/html");
  2490. return Server::HandlerResponse::Handled;
  2491. }
  2492. }
  2493. return Server::HandlerResponse::Unhandled;
  2494. });
  2495. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2496. auto se = detail::scope_exit([&] {
  2497. svr.stop();
  2498. thread.join();
  2499. ASSERT_FALSE(svr.is_running());
  2500. });
  2501. svr.wait_until_ready();
  2502. Client cli(HOST, PORT);
  2503. {
  2504. auto res = cli.Get("/hi");
  2505. ASSERT_TRUE(res);
  2506. EXPECT_EQ(StatusCode::OK_200, res->status);
  2507. EXPECT_EQ("hi", res->body);
  2508. }
  2509. {
  2510. auto res = cli.Get("/user/john");
  2511. ASSERT_TRUE(res);
  2512. EXPECT_EQ(StatusCode::OK_200, res->status);
  2513. EXPECT_EQ("john", res->body);
  2514. }
  2515. {
  2516. auto res = cli.Get("/user/invalid-user");
  2517. ASSERT_TRUE(res);
  2518. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2519. EXPECT_EQ("error", res->body);
  2520. }
  2521. }
  2522. TEST(AnyTest, BasicOperations) {
  2523. // Default construction
  2524. httplib::any a;
  2525. EXPECT_FALSE(a.has_value());
  2526. // Value construction and any_cast (pointer form, noexcept)
  2527. httplib::any b(42);
  2528. EXPECT_TRUE(b.has_value());
  2529. auto *p = httplib::any_cast<int>(&b);
  2530. ASSERT_NE(nullptr, p);
  2531. EXPECT_EQ(42, *p);
  2532. // Type mismatch → nullptr
  2533. auto *q = httplib::any_cast<std::string>(&b);
  2534. EXPECT_EQ(nullptr, q);
  2535. // any_cast (value form) succeeds
  2536. EXPECT_EQ(42, httplib::any_cast<int>(b));
  2537. // any_cast (value form) throws on type mismatch
  2538. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2539. EXPECT_THROW(httplib::any_cast<std::string>(b), httplib::bad_any_cast);
  2540. #endif
  2541. // Copy
  2542. httplib::any c = b;
  2543. EXPECT_EQ(42, httplib::any_cast<int>(c));
  2544. // Move
  2545. httplib::any d = std::move(c);
  2546. EXPECT_EQ(42, httplib::any_cast<int>(d));
  2547. // Assignment with different type
  2548. b = std::string("hello");
  2549. EXPECT_EQ("hello", httplib::any_cast<std::string>(b));
  2550. // Reset
  2551. b.reset();
  2552. EXPECT_FALSE(b.has_value());
  2553. }
  2554. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2555. struct AuthCtx {
  2556. std::string user_id;
  2557. };
  2558. Server svr;
  2559. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2560. res.user_data["auth"] = AuthCtx{"alice"};
  2561. return Server::HandlerResponse::Unhandled;
  2562. });
  2563. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2564. auto *ctx = httplib::any_cast<AuthCtx>(&res.user_data["auth"]);
  2565. ASSERT_NE(nullptr, ctx);
  2566. res.set_content("Hello " + ctx->user_id, "text/plain");
  2567. });
  2568. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2569. auto se = detail::scope_exit([&] {
  2570. svr.stop();
  2571. thread.join();
  2572. ASSERT_FALSE(svr.is_running());
  2573. });
  2574. svr.wait_until_ready();
  2575. Client cli(HOST, PORT);
  2576. auto res = cli.Get("/me");
  2577. ASSERT_TRUE(res);
  2578. EXPECT_EQ(StatusCode::OK_200, res->status);
  2579. EXPECT_EQ("Hello alice", res->body);
  2580. }
  2581. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2582. struct RoleCtx {
  2583. std::string role;
  2584. };
  2585. Server svr;
  2586. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2587. res.user_data["role"] = RoleCtx{"admin"};
  2588. return Server::HandlerResponse::Unhandled;
  2589. });
  2590. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2591. auto *ctx = httplib::any_cast<RoleCtx>(&res.user_data["role"]);
  2592. ASSERT_NE(nullptr, ctx);
  2593. res.set_content(ctx->role, "text/plain");
  2594. });
  2595. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2596. auto se = detail::scope_exit([&] {
  2597. svr.stop();
  2598. thread.join();
  2599. ASSERT_FALSE(svr.is_running());
  2600. });
  2601. svr.wait_until_ready();
  2602. Client cli(HOST, PORT);
  2603. auto res = cli.Get("/role");
  2604. ASSERT_TRUE(res);
  2605. EXPECT_EQ(StatusCode::OK_200, res->status);
  2606. EXPECT_EQ("admin", res->body);
  2607. }
  2608. TEST(InvalidFormatTest, StatusCode) {
  2609. Server svr;
  2610. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2611. res.set_content("Hello World!\n", "text/plain");
  2612. res.status = 9999; // Status should be a three-digit code...
  2613. });
  2614. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2615. auto se = detail::scope_exit([&] {
  2616. svr.stop();
  2617. thread.join();
  2618. ASSERT_FALSE(svr.is_running());
  2619. });
  2620. svr.wait_until_ready();
  2621. {
  2622. Client cli(HOST, PORT);
  2623. auto res = cli.Get("/hi");
  2624. ASSERT_FALSE(res);
  2625. }
  2626. }
  2627. TEST(URLFragmentTest, WithFragment) {
  2628. Server svr;
  2629. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2630. EXPECT_TRUE(req.target == "/hi");
  2631. });
  2632. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2633. auto se = detail::scope_exit([&] {
  2634. svr.stop();
  2635. thread.join();
  2636. ASSERT_FALSE(svr.is_running());
  2637. });
  2638. svr.wait_until_ready();
  2639. {
  2640. Client cli(HOST, PORT);
  2641. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2642. EXPECT_TRUE(res);
  2643. EXPECT_EQ(StatusCode::OK_200, res->status);
  2644. res = cli.Get("/hi%23key1=val1=key2=val2");
  2645. EXPECT_TRUE(res);
  2646. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2647. }
  2648. }
  2649. TEST(HeaderWriter, SetHeaderWriter) {
  2650. Server svr;
  2651. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2652. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2653. return detail::write_headers(strm, hdrs);
  2654. });
  2655. svr.Get("/hi", [](const Request &req, Response &res) {
  2656. auto it = req.headers.find("CustomClientHeader");
  2657. EXPECT_TRUE(it != req.headers.end());
  2658. EXPECT_EQ(it->second, "CustomClientValue");
  2659. res.set_content("Hello World!\n", "text/plain");
  2660. });
  2661. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2662. auto se = detail::scope_exit([&] {
  2663. svr.stop();
  2664. thread.join();
  2665. ASSERT_FALSE(svr.is_running());
  2666. });
  2667. svr.wait_until_ready();
  2668. {
  2669. Client cli(HOST, PORT);
  2670. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2671. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2672. return detail::write_headers(strm, hdrs);
  2673. });
  2674. auto res = cli.Get("/hi");
  2675. EXPECT_TRUE(res);
  2676. EXPECT_EQ(StatusCode::OK_200, res->status);
  2677. auto it = res->headers.find("CustomServerHeader");
  2678. EXPECT_TRUE(it != res->headers.end());
  2679. EXPECT_EQ(it->second, "CustomServerValue");
  2680. }
  2681. }
  2682. class ServerTest : public ::testing::Test {
  2683. protected:
  2684. ServerTest()
  2685. : cli_(HOST, PORT)
  2686. #ifdef CPPHTTPLIB_SSL_ENABLED
  2687. ,
  2688. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2689. #endif
  2690. {
  2691. #ifdef CPPHTTPLIB_SSL_ENABLED
  2692. cli_.enable_server_certificate_verification(false);
  2693. #endif
  2694. // Allow LARGE_DATA (100MB) responses
  2695. cli_.set_payload_max_length(200 * 1024 * 1024);
  2696. }
  2697. virtual void SetUp() {
  2698. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2699. svr_.set_payload_max_length(200 * 1024 * 1024);
  2700. svr_.set_mount_point("/", "./www");
  2701. svr_.set_mount_point("/mount", "./www2");
  2702. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2703. svr_.Get("/hi",
  2704. [&](const Request & /*req*/, Response &res) {
  2705. res.set_content("Hello World!", "text/plain");
  2706. })
  2707. .Get("/file_content",
  2708. [&](const Request & /*req*/, Response &res) {
  2709. res.set_file_content("./www/dir/test.html");
  2710. })
  2711. .Get("/file_content_with_content_type",
  2712. [&](const Request & /*req*/, Response &res) {
  2713. res.set_file_content("./www/file", "text/plain");
  2714. })
  2715. .Get("/invalid_file_content",
  2716. [&](const Request & /*req*/, Response &res) {
  2717. res.set_file_content("./www/dir/invalid_file_path");
  2718. })
  2719. .Get("/http_response_splitting",
  2720. [&](const Request & /*req*/, Response &res) {
  2721. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2722. EXPECT_EQ(0U, res.headers.size());
  2723. EXPECT_FALSE(res.has_header("a"));
  2724. res.set_header("a", "1\nSet-Cookie: a=1");
  2725. EXPECT_EQ(0U, res.headers.size());
  2726. EXPECT_FALSE(res.has_header("a"));
  2727. res.set_header("a", "1\rSet-Cookie: a=1");
  2728. EXPECT_EQ(0U, res.headers.size());
  2729. EXPECT_FALSE(res.has_header("a"));
  2730. res.set_header("a\r\nb", "0");
  2731. EXPECT_EQ(0U, res.headers.size());
  2732. EXPECT_FALSE(res.has_header("a"));
  2733. res.set_header("a\rb", "0");
  2734. EXPECT_EQ(0U, res.headers.size());
  2735. EXPECT_FALSE(res.has_header("a"));
  2736. res.set_header("a\nb", "0");
  2737. EXPECT_EQ(0U, res.headers.size());
  2738. EXPECT_FALSE(res.has_header("a"));
  2739. res.set_redirect("1\r\nSet-Cookie: a=1");
  2740. EXPECT_EQ(0U, res.headers.size());
  2741. EXPECT_FALSE(res.has_header("Location"));
  2742. })
  2743. .Get("/slow",
  2744. [&](const Request & /*req*/, Response &res) {
  2745. std::this_thread::sleep_for(std::chrono::seconds(2));
  2746. res.set_content("slow", "text/plain");
  2747. })
  2748. #if 0
  2749. .Post("/slowpost",
  2750. [&](const Request & /*req*/, Response &res) {
  2751. std::this_thread::sleep_for(std::chrono::seconds(2));
  2752. res.set_content("slow", "text/plain");
  2753. })
  2754. #endif
  2755. .Get("/remote_addr",
  2756. [&](const Request &req, Response &res) {
  2757. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2758. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2759. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2760. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2761. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2762. #endif
  2763. res.set_content(req.remote_addr, "text/plain");
  2764. })
  2765. .Get("/local_addr",
  2766. [&](const Request &req, Response &res) {
  2767. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2768. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2769. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2770. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2771. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2772. #endif
  2773. auto local_addr = req.local_addr;
  2774. auto local_port = std::to_string(req.local_port);
  2775. res.set_content(local_addr.append(":").append(local_port),
  2776. "text/plain");
  2777. })
  2778. .Get("/endwith%",
  2779. [&](const Request & /*req*/, Response &res) {
  2780. res.set_content("Hello World!", "text/plain");
  2781. })
  2782. .Get("/a\\+\\+b",
  2783. [&](const Request &req, Response &res) {
  2784. ASSERT_TRUE(req.has_param("a +b"));
  2785. auto val = req.get_param_value("a +b");
  2786. res.set_content(val, "text/plain");
  2787. })
  2788. .Get("/", [&](const Request & /*req*/,
  2789. Response &res) { res.set_redirect("/hi"); })
  2790. .Post("/1",
  2791. [](const Request & /*req*/, Response &res) {
  2792. res.set_redirect("/2", StatusCode::SeeOther_303);
  2793. })
  2794. .Get("/2",
  2795. [](const Request & /*req*/, Response &res) {
  2796. res.set_content("redirected.", "text/plain");
  2797. res.status = StatusCode::OK_200;
  2798. })
  2799. .Post("/person",
  2800. [&](const Request &req, Response &res) {
  2801. if (req.has_param("name") && req.has_param("note")) {
  2802. persons_[req.get_param_value("name")] =
  2803. req.get_param_value("note");
  2804. } else {
  2805. res.status = StatusCode::BadRequest_400;
  2806. }
  2807. })
  2808. .Put("/person",
  2809. [&](const Request &req, Response &res) {
  2810. if (req.has_param("name") && req.has_param("note")) {
  2811. persons_[req.get_param_value("name")] =
  2812. req.get_param_value("note");
  2813. } else {
  2814. res.status = StatusCode::BadRequest_400;
  2815. }
  2816. })
  2817. .Get("/person/(.*)",
  2818. [&](const Request &req, Response &res) {
  2819. string name = req.matches[1];
  2820. if (persons_.find(name) != persons_.end()) {
  2821. auto note = persons_[name];
  2822. res.set_content(note, "text/plain");
  2823. } else {
  2824. res.status = StatusCode::NotFound_404;
  2825. }
  2826. })
  2827. .Delete("/person",
  2828. [&](const Request &req, Response &res) {
  2829. if (req.has_param("name")) {
  2830. string name = req.get_param_value("name");
  2831. if (persons_.find(name) != persons_.end()) {
  2832. persons_.erase(name);
  2833. res.set_content("DELETED", "text/plain");
  2834. } else {
  2835. res.status = StatusCode::NotFound_404;
  2836. }
  2837. } else {
  2838. res.status = StatusCode::BadRequest_400;
  2839. }
  2840. })
  2841. .Post("/x-www-form-urlencoded-json",
  2842. [&](const Request &req, Response &res) {
  2843. auto json = req.get_param_value("json");
  2844. ASSERT_EQ(JSON_DATA, json);
  2845. res.set_content(json, "appliation/json");
  2846. res.status = StatusCode::OK_200;
  2847. })
  2848. .Get("/streamed-chunked",
  2849. [&](const Request & /*req*/, Response &res) {
  2850. res.set_chunked_content_provider(
  2851. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2852. sink.os << "123";
  2853. sink.os << "456";
  2854. sink.os << "789";
  2855. sink.done();
  2856. return true;
  2857. });
  2858. })
  2859. .Get("/streamed-chunked-with-prohibited-trailer",
  2860. [&](const Request & /*req*/, Response &res) {
  2861. auto i = new int(0);
  2862. // Declare both a prohibited trailer (Content-Length) and an
  2863. // allowed one
  2864. res.set_header("Trailer", "Content-Length, X-Allowed");
  2865. res.set_chunked_content_provider(
  2866. "text/plain",
  2867. [i](size_t /*offset*/, DataSink &sink) {
  2868. switch (*i) {
  2869. case 0: sink.os << "123"; break;
  2870. case 1: sink.os << "456"; break;
  2871. case 2: sink.os << "789"; break;
  2872. case 3: {
  2873. sink.done_with_trailer(
  2874. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2875. } break;
  2876. }
  2877. (*i)++;
  2878. return true;
  2879. },
  2880. [i](bool success) {
  2881. EXPECT_TRUE(success);
  2882. delete i;
  2883. });
  2884. })
  2885. .Get("/streamed-chunked2",
  2886. [&](const Request & /*req*/, Response &res) {
  2887. auto i = new int(0);
  2888. res.set_chunked_content_provider(
  2889. "text/plain",
  2890. [i](size_t /*offset*/, DataSink &sink) {
  2891. switch (*i) {
  2892. case 0: sink.os << "123"; break;
  2893. case 1: sink.os << "456"; break;
  2894. case 2: sink.os << "789"; break;
  2895. case 3: sink.done(); break;
  2896. }
  2897. (*i)++;
  2898. return true;
  2899. },
  2900. [i](bool success) {
  2901. EXPECT_TRUE(success);
  2902. delete i;
  2903. });
  2904. })
  2905. .Get("/streamed-chunked-with-trailer",
  2906. [&](const Request & /*req*/, Response &res) {
  2907. auto i = new int(0);
  2908. res.set_header("Trailer", "Dummy1, Dummy2");
  2909. res.set_chunked_content_provider(
  2910. "text/plain",
  2911. [i](size_t /*offset*/, DataSink &sink) {
  2912. switch (*i) {
  2913. case 0: sink.os << "123"; break;
  2914. case 1: sink.os << "456"; break;
  2915. case 2: sink.os << "789"; break;
  2916. case 3: {
  2917. sink.done_with_trailer(
  2918. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2919. } break;
  2920. }
  2921. (*i)++;
  2922. return true;
  2923. },
  2924. [i](bool success) {
  2925. EXPECT_TRUE(success);
  2926. delete i;
  2927. });
  2928. })
  2929. .Get("/streamed",
  2930. [&](const Request & /*req*/, Response &res) {
  2931. res.set_content_provider(
  2932. 6, "text/plain",
  2933. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2934. sink.os << (offset < 3 ? "a" : "b");
  2935. return true;
  2936. });
  2937. })
  2938. .Get("/streamed-with-range",
  2939. [&](const Request &req, Response &res) {
  2940. auto data = new std::string("abcdefg");
  2941. res.set_content_provider(
  2942. data->size(), "text/plain",
  2943. [data](size_t offset, size_t length, DataSink &sink) {
  2944. size_t DATA_CHUNK_SIZE = 4;
  2945. const auto &d = *data;
  2946. auto out_len =
  2947. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2948. auto ret =
  2949. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2950. EXPECT_TRUE(ret);
  2951. return true;
  2952. },
  2953. [data, &req](bool success) {
  2954. EXPECT_EQ(success, !req.has_param("error"));
  2955. delete data;
  2956. });
  2957. })
  2958. .Get("/streamed-cancel",
  2959. [&](const Request & /*req*/, Response &res) {
  2960. res.set_content_provider(
  2961. size_t(-1), "text/plain",
  2962. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2963. sink.os << "data_chunk";
  2964. return true;
  2965. });
  2966. })
  2967. .Get("/regex-with-delimiter",
  2968. [&](const Request &req, Response & /*res*/) {
  2969. ASSERT_TRUE(req.has_param("key"));
  2970. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2971. })
  2972. .Get("/with-range",
  2973. [&](const Request & /*req*/, Response &res) {
  2974. res.set_content("abcdefg", "text/plain");
  2975. })
  2976. .Get("/test-start-time",
  2977. [&](const Request &req, Response & /*res*/) {
  2978. EXPECT_NE(req.start_time_,
  2979. std::chrono::steady_clock::time_point::min());
  2980. })
  2981. .Get("/with-range-customized-response",
  2982. [&](const Request & /*req*/, Response &res) {
  2983. res.status = StatusCode::BadRequest_400;
  2984. res.set_content(JSON_DATA, "application/json");
  2985. })
  2986. .Post("/chunked",
  2987. [&](const Request &req, Response & /*res*/) {
  2988. EXPECT_EQ(req.body, "dechunked post body");
  2989. })
  2990. .Post("/large-chunked",
  2991. [&](const Request &req, Response & /*res*/) {
  2992. std::string expected(6 * 30 * 1024u, 'a');
  2993. EXPECT_EQ(req.body, expected);
  2994. })
  2995. .Post("/multipart",
  2996. [&](const Request &req, Response & /*res*/) {
  2997. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2998. req.form.get_field_count("text2") +
  2999. req.form.get_field_count("file3") +
  3000. req.form.get_field_count("file4"));
  3001. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3002. req.form.get_file_count("file2"));
  3003. ASSERT_TRUE(!req.form.has_file("???"));
  3004. ASSERT_TRUE(!req.form.has_field("???"));
  3005. ASSERT_TRUE(req.body.empty());
  3006. {
  3007. const auto &text = req.form.get_field("text1");
  3008. EXPECT_EQ("text default", text);
  3009. }
  3010. {
  3011. const auto &text = req.form.get_field("text2");
  3012. EXPECT_EQ("aωb", text);
  3013. }
  3014. {
  3015. const auto &file = req.form.get_file("file1");
  3016. EXPECT_EQ("hello.txt", file.filename);
  3017. EXPECT_EQ("text/plain", file.content_type);
  3018. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3019. }
  3020. {
  3021. const auto &file = req.form.get_file("file2");
  3022. EXPECT_EQ("world.json", file.filename);
  3023. EXPECT_EQ("application/json", file.content_type);
  3024. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3025. }
  3026. {
  3027. const auto &text = req.form.get_field("file3");
  3028. EXPECT_EQ(0u, text.size());
  3029. }
  3030. {
  3031. const auto &text = req.form.get_field("file4");
  3032. EXPECT_EQ(0u, text.size());
  3033. }
  3034. })
  3035. .Post("/multipart/multi_file_values",
  3036. [&](const Request &req, Response & /*res*/) {
  3037. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3038. req.form.get_field_count("multi_text1"));
  3039. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3040. ASSERT_TRUE(!req.form.has_file("???"));
  3041. ASSERT_TRUE(!req.form.has_field("???"));
  3042. ASSERT_TRUE(req.body.empty());
  3043. {
  3044. const auto &text = req.form.get_field("text");
  3045. EXPECT_EQ("default text", text);
  3046. }
  3047. {
  3048. const auto &text1_values = req.form.get_fields("multi_text1");
  3049. EXPECT_EQ(2u, text1_values.size());
  3050. EXPECT_EQ("aaaaa", text1_values[0]);
  3051. EXPECT_EQ("bbbbb", text1_values[1]);
  3052. }
  3053. {
  3054. const auto &file1_values = req.form.get_files("multi_file1");
  3055. EXPECT_EQ(2u, file1_values.size());
  3056. auto file1 = file1_values[0];
  3057. EXPECT_EQ(file1.filename, "hello.txt");
  3058. EXPECT_EQ(file1.content_type, "text/plain");
  3059. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3060. auto file2 = file1_values[1];
  3061. EXPECT_EQ(file2.filename, "world.json");
  3062. EXPECT_EQ(file2.content_type, "application/json");
  3063. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3064. }
  3065. })
  3066. .Post("/empty",
  3067. [&](const Request &req, Response &res) {
  3068. EXPECT_EQ(req.body, "");
  3069. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3070. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3071. res.set_content("empty", "text/plain");
  3072. })
  3073. .Post("/empty-no-content-type",
  3074. [&](const Request &req, Response &res) {
  3075. EXPECT_EQ(req.body, "");
  3076. EXPECT_FALSE(req.has_header("Content-Type"));
  3077. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3078. res.set_content("empty-no-content-type", "text/plain");
  3079. })
  3080. .Post("/path-only",
  3081. [&](const Request &req, Response &res) {
  3082. EXPECT_EQ(req.body, "");
  3083. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3084. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3085. res.set_content("path-only", "text/plain");
  3086. })
  3087. .Post("/path-headers-only",
  3088. [&](const Request &req, Response &res) {
  3089. EXPECT_EQ(req.body, "");
  3090. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3091. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3092. EXPECT_EQ("world", req.get_header_value("hello"));
  3093. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3094. res.set_content("path-headers-only", "text/plain");
  3095. })
  3096. .Post("/post-large",
  3097. [&](const Request &req, Response &res) {
  3098. EXPECT_EQ(req.body, LARGE_DATA);
  3099. res.set_content(req.body, "text/plain");
  3100. })
  3101. .Post("/post-loopback",
  3102. [&](const Request &, Response &res,
  3103. ContentReader const &content_reader) {
  3104. std::string body;
  3105. content_reader([&](const char *data, size_t data_length) {
  3106. body.append(data, data_length);
  3107. return true;
  3108. });
  3109. res.set_content(body, "text/plain");
  3110. })
  3111. .Put("/put-loopback",
  3112. [&](const Request &, Response &res,
  3113. ContentReader const &content_reader) {
  3114. std::string body;
  3115. content_reader([&](const char *data, size_t data_length) {
  3116. body.append(data, data_length);
  3117. return true;
  3118. });
  3119. res.set_content(body, "text/plain");
  3120. })
  3121. .Patch("/patch-loopback",
  3122. [&](const Request &, Response &res,
  3123. ContentReader const &content_reader) {
  3124. std::string body;
  3125. content_reader([&](const char *data, size_t data_length) {
  3126. body.append(data, data_length);
  3127. return true;
  3128. });
  3129. res.set_content(body, "text/plain");
  3130. })
  3131. .Put("/empty-no-content-type",
  3132. [&](const Request &req, Response &res) {
  3133. EXPECT_EQ(req.body, "");
  3134. EXPECT_FALSE(req.has_header("Content-Type"));
  3135. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3136. res.set_content("empty-no-content-type", "text/plain");
  3137. })
  3138. .Put("/put",
  3139. [&](const Request &req, Response &res) {
  3140. EXPECT_EQ(req.body, "PUT");
  3141. res.set_content(req.body, "text/plain");
  3142. })
  3143. .Put("/put-large",
  3144. [&](const Request &req, Response &res) {
  3145. EXPECT_EQ(req.body, LARGE_DATA);
  3146. res.set_content(req.body, "text/plain");
  3147. })
  3148. .Patch("/patch",
  3149. [&](const Request &req, Response &res) {
  3150. EXPECT_EQ(req.body, "PATCH");
  3151. res.set_content(req.body, "text/plain");
  3152. })
  3153. .Delete("/delete",
  3154. [&](const Request & /*req*/, Response &res) {
  3155. res.set_content("DELETE", "text/plain");
  3156. })
  3157. .Delete("/delete-body",
  3158. [&](const Request &req, Response &res) {
  3159. EXPECT_EQ(req.body, "content");
  3160. res.set_content(req.body, "text/plain");
  3161. })
  3162. .Options(R"(\*)",
  3163. [&](const Request & /*req*/, Response &res) {
  3164. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3165. })
  3166. .Get("/request-target",
  3167. [&](const Request &req, Response & /*res*/) {
  3168. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3169. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3170. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3171. })
  3172. .Get("/long-query-value",
  3173. [&](const Request &req, Response & /*res*/) {
  3174. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3175. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3176. })
  3177. .Get("/too-long-query-value",
  3178. [&](const Request &req, Response & /*res*/) {
  3179. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3180. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3181. })
  3182. .Get("/array-param",
  3183. [&](const Request &req, Response & /*res*/) {
  3184. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3185. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3186. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3187. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3188. })
  3189. .Post("/validate-no-multiple-headers",
  3190. [&](const Request &req, Response & /*res*/) {
  3191. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3192. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3193. })
  3194. .Post("/content_receiver",
  3195. [&](const Request &req, Response &res,
  3196. const ContentReader &content_reader) {
  3197. if (req.is_multipart_form_data()) {
  3198. std::vector<FormData> items;
  3199. content_reader(
  3200. [&](const FormData &file) {
  3201. items.push_back(file);
  3202. return true;
  3203. },
  3204. [&](const char *data, size_t data_length) {
  3205. items.back().content.append(data, data_length);
  3206. return true;
  3207. });
  3208. EXPECT_EQ(5u, items.size());
  3209. {
  3210. const auto &file = get_file_value(items, "text1");
  3211. EXPECT_TRUE(file.filename.empty());
  3212. EXPECT_EQ("text default", file.content);
  3213. }
  3214. {
  3215. const auto &file = get_file_value(items, "text2");
  3216. EXPECT_TRUE(file.filename.empty());
  3217. EXPECT_EQ("aωb", file.content);
  3218. }
  3219. {
  3220. const auto &file = get_file_value(items, "file1");
  3221. EXPECT_EQ("hello.txt", file.filename);
  3222. EXPECT_EQ("text/plain", file.content_type);
  3223. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3224. }
  3225. {
  3226. const auto &file = get_file_value(items, "file2");
  3227. EXPECT_EQ("world.json", file.filename);
  3228. EXPECT_EQ("application/json", file.content_type);
  3229. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3230. }
  3231. {
  3232. const auto &file = get_file_value(items, "file3");
  3233. EXPECT_TRUE(file.filename.empty());
  3234. EXPECT_EQ("application/octet-stream", file.content_type);
  3235. EXPECT_EQ(0u, file.content.size());
  3236. }
  3237. } else {
  3238. std::string body;
  3239. content_reader([&](const char *data, size_t data_length) {
  3240. EXPECT_EQ(7U, data_length);
  3241. body.append(data, data_length);
  3242. return true;
  3243. });
  3244. EXPECT_EQ(body, "content");
  3245. res.set_content(body, "text/plain");
  3246. }
  3247. })
  3248. .Put("/content_receiver",
  3249. [&](const Request & /*req*/, Response &res,
  3250. const ContentReader &content_reader) {
  3251. std::string body;
  3252. content_reader([&](const char *data, size_t data_length) {
  3253. body.append(data, data_length);
  3254. return true;
  3255. });
  3256. EXPECT_EQ(body, "content");
  3257. res.set_content(body, "text/plain");
  3258. })
  3259. .Patch("/content_receiver",
  3260. [&](const Request & /*req*/, Response &res,
  3261. const ContentReader &content_reader) {
  3262. std::string body;
  3263. content_reader([&](const char *data, size_t data_length) {
  3264. body.append(data, data_length);
  3265. return true;
  3266. });
  3267. EXPECT_EQ(body, "content");
  3268. res.set_content(body, "text/plain");
  3269. })
  3270. .Post("/query-string-and-body",
  3271. [&](const Request &req, Response & /*res*/) {
  3272. ASSERT_TRUE(req.has_param("key"));
  3273. EXPECT_EQ(req.get_param_value("key"), "value");
  3274. EXPECT_EQ(req.body, "content");
  3275. })
  3276. .Get("/last-request",
  3277. [&](const Request &req, Response & /*res*/) {
  3278. EXPECT_EQ("close", req.get_header_value("Connection"));
  3279. })
  3280. .Get(R"(/redirect/(\d+))",
  3281. [&](const Request &req, Response &res) {
  3282. auto num = std::stoi(req.matches[1]) + 1;
  3283. std::string url = "/redirect/" + std::to_string(num);
  3284. res.set_redirect(url);
  3285. })
  3286. .Post("/binary",
  3287. [&](const Request &req, Response &res) {
  3288. EXPECT_EQ(4U, req.body.size());
  3289. EXPECT_EQ("application/octet-stream",
  3290. req.get_header_value("Content-Type"));
  3291. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3292. res.set_content(req.body, "application/octet-stream");
  3293. })
  3294. .Put("/binary",
  3295. [&](const Request &req, Response &res) {
  3296. EXPECT_EQ(4U, req.body.size());
  3297. EXPECT_EQ("application/octet-stream",
  3298. req.get_header_value("Content-Type"));
  3299. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3300. res.set_content(req.body, "application/octet-stream");
  3301. })
  3302. .Patch("/binary",
  3303. [&](const Request &req, Response &res) {
  3304. EXPECT_EQ(4U, req.body.size());
  3305. EXPECT_EQ("application/octet-stream",
  3306. req.get_header_value("Content-Type"));
  3307. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3308. res.set_content(req.body, "application/octet-stream");
  3309. })
  3310. .Delete("/binary",
  3311. [&](const Request &req, Response &res) {
  3312. EXPECT_EQ(4U, req.body.size());
  3313. EXPECT_EQ("application/octet-stream",
  3314. req.get_header_value("Content-Type"));
  3315. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3316. res.set_content(req.body, "application/octet-stream");
  3317. })
  3318. .Get("/issue1772",
  3319. [&](const Request & /*req*/, Response &res) {
  3320. res.status = 401;
  3321. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3322. })
  3323. .Delete("/issue609",
  3324. [](const httplib::Request &, httplib::Response &res,
  3325. const httplib::ContentReader &) {
  3326. res.set_content("ok", "text/plain");
  3327. })
  3328. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3329. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3330. .Get("/compress",
  3331. [&](const Request & /*req*/, Response &res) {
  3332. res.set_content(
  3333. "12345678901234567890123456789012345678901234567890123456789"
  3334. "01234567890123456789012345678901234567890",
  3335. "text/plain");
  3336. })
  3337. .Get("/compress-with-charset",
  3338. [&](const Request & /*req*/, Response &res) {
  3339. res.set_content(
  3340. "12345678901234567890123456789012345678901234567890123456789"
  3341. "01234567890123456789012345678901234567890",
  3342. "application/json; charset=utf-8");
  3343. })
  3344. .Get("/nocompress",
  3345. [&](const Request & /*req*/, Response &res) {
  3346. res.set_content(
  3347. "12345678901234567890123456789012345678901234567890123456789"
  3348. "01234567890123456789012345678901234567890",
  3349. "application/octet-stream");
  3350. })
  3351. .Post("/compress-multipart",
  3352. [&](const Request &req, Response & /*res*/) {
  3353. EXPECT_EQ(2u, req.form.fields.size());
  3354. ASSERT_TRUE(!req.form.has_field("???"));
  3355. {
  3356. const auto &text = req.form.get_field("key1");
  3357. EXPECT_EQ("test", text);
  3358. }
  3359. {
  3360. const auto &text = req.form.get_field("key2");
  3361. EXPECT_EQ("--abcdefg123", text);
  3362. }
  3363. })
  3364. #endif
  3365. ;
  3366. persons_["john"] = "programmer";
  3367. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3368. svr_.wait_until_ready();
  3369. }
  3370. virtual void TearDown() {
  3371. svr_.stop();
  3372. if (!request_threads_.empty()) {
  3373. std::this_thread::sleep_for(std::chrono::seconds(1));
  3374. for (auto &t : request_threads_) {
  3375. t.join();
  3376. }
  3377. }
  3378. t_.join();
  3379. }
  3380. map<string, string> persons_;
  3381. #ifdef CPPHTTPLIB_SSL_ENABLED
  3382. SSLClient cli_;
  3383. SSLServer svr_;
  3384. #else
  3385. Client cli_;
  3386. Server svr_;
  3387. #endif
  3388. thread t_;
  3389. std::vector<thread> request_threads_;
  3390. };
  3391. TEST_F(ServerTest, GetMethod200) {
  3392. auto res = cli_.Get("/hi");
  3393. ASSERT_TRUE(res);
  3394. EXPECT_EQ("HTTP/1.1", res->version);
  3395. EXPECT_EQ(StatusCode::OK_200, res->status);
  3396. EXPECT_EQ("OK", res->reason);
  3397. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3398. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3399. EXPECT_EQ("Hello World!", res->body);
  3400. }
  3401. TEST_F(ServerTest, GetEmptyFile) {
  3402. auto res = cli_.Get("/empty_file");
  3403. ASSERT_TRUE(res);
  3404. EXPECT_EQ(StatusCode::OK_200, res->status);
  3405. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3406. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3407. EXPECT_EQ("", res->body);
  3408. }
  3409. TEST_F(ServerTest, GetFileContent) {
  3410. auto res = cli_.Get("/file_content");
  3411. ASSERT_TRUE(res);
  3412. EXPECT_EQ(StatusCode::OK_200, res->status);
  3413. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3414. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3415. EXPECT_EQ("test.html", res->body);
  3416. }
  3417. TEST_F(ServerTest, GetFileContentWithRange) {
  3418. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3419. ASSERT_TRUE(res);
  3420. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3421. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3422. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3423. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3424. EXPECT_EQ("est", res->body);
  3425. }
  3426. TEST_F(ServerTest, GetFileContentWithContentType) {
  3427. auto res = cli_.Get("/file_content_with_content_type");
  3428. ASSERT_TRUE(res);
  3429. EXPECT_EQ(StatusCode::OK_200, res->status);
  3430. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3431. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3432. EXPECT_EQ("file\n", res->body);
  3433. }
  3434. TEST_F(ServerTest, GetInvalidFileContent) {
  3435. auto res = cli_.Get("/invalid_file_content");
  3436. ASSERT_TRUE(res);
  3437. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3438. }
  3439. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3440. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3441. ASSERT_TRUE(res);
  3442. EXPECT_EQ("HTTP/1.1", res->version);
  3443. EXPECT_EQ(StatusCode::OK_200, res->status);
  3444. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3445. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3446. EXPECT_EQ("Hello World!", res->body);
  3447. }
  3448. TEST_F(ServerTest, GetMethod302) {
  3449. auto res = cli_.Get("/");
  3450. ASSERT_TRUE(res);
  3451. EXPECT_EQ(StatusCode::Found_302, res->status);
  3452. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3453. }
  3454. TEST_F(ServerTest, GetMethod302Redirect) {
  3455. cli_.set_follow_location(true);
  3456. auto res = cli_.Get("/");
  3457. ASSERT_TRUE(res);
  3458. EXPECT_EQ(StatusCode::OK_200, res->status);
  3459. EXPECT_EQ("Hello World!", res->body);
  3460. EXPECT_EQ("/hi", res->location);
  3461. }
  3462. TEST_F(ServerTest, GetMethod404) {
  3463. auto res = cli_.Get("/invalid");
  3464. ASSERT_TRUE(res);
  3465. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3466. }
  3467. TEST_F(ServerTest, HeadMethod200) {
  3468. auto res = cli_.Head("/hi");
  3469. ASSERT_TRUE(res);
  3470. EXPECT_EQ(StatusCode::OK_200, res->status);
  3471. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3472. EXPECT_TRUE(res->body.empty());
  3473. }
  3474. TEST_F(ServerTest, HeadMethod200Static) {
  3475. auto res = cli_.Head("/mount/dir/index.html");
  3476. ASSERT_TRUE(res);
  3477. EXPECT_EQ(StatusCode::OK_200, res->status);
  3478. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3479. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3480. EXPECT_TRUE(res->body.empty());
  3481. }
  3482. TEST_F(ServerTest, HeadMethod404) {
  3483. auto res = cli_.Head("/invalid");
  3484. ASSERT_TRUE(res);
  3485. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3486. EXPECT_TRUE(res->body.empty());
  3487. }
  3488. TEST_F(ServerTest, GetMethodPersonJohn) {
  3489. auto res = cli_.Get("/person/john");
  3490. ASSERT_TRUE(res);
  3491. EXPECT_EQ(StatusCode::OK_200, res->status);
  3492. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3493. EXPECT_EQ("programmer", res->body);
  3494. }
  3495. TEST_F(ServerTest, PostMethod1) {
  3496. auto res = cli_.Get("/person/john1");
  3497. ASSERT_TRUE(res);
  3498. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3499. res = cli_.Post("/person", "name=john1&note=coder",
  3500. "application/x-www-form-urlencoded");
  3501. ASSERT_TRUE(res);
  3502. ASSERT_EQ(StatusCode::OK_200, res->status);
  3503. res = cli_.Get("/person/john1");
  3504. ASSERT_TRUE(res);
  3505. ASSERT_EQ(StatusCode::OK_200, res->status);
  3506. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3507. ASSERT_EQ("coder", res->body);
  3508. }
  3509. TEST_F(ServerTest, PostMethod2) {
  3510. auto res = cli_.Get("/person/john2");
  3511. ASSERT_TRUE(res);
  3512. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3513. Params params;
  3514. params.emplace("name", "john2");
  3515. params.emplace("note", "coder");
  3516. res = cli_.Post("/person", params);
  3517. ASSERT_TRUE(res);
  3518. ASSERT_EQ(StatusCode::OK_200, res->status);
  3519. res = cli_.Get("/person/john2");
  3520. ASSERT_TRUE(res);
  3521. ASSERT_EQ(StatusCode::OK_200, res->status);
  3522. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3523. ASSERT_EQ("coder", res->body);
  3524. }
  3525. TEST_F(ServerTest, PutMethod3) {
  3526. auto res = cli_.Get("/person/john3");
  3527. ASSERT_TRUE(res);
  3528. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3529. Params params;
  3530. params.emplace("name", "john3");
  3531. params.emplace("note", "coder");
  3532. res = cli_.Put("/person", params);
  3533. ASSERT_TRUE(res);
  3534. ASSERT_EQ(StatusCode::OK_200, res->status);
  3535. res = cli_.Get("/person/john3");
  3536. ASSERT_TRUE(res);
  3537. ASSERT_EQ(StatusCode::OK_200, res->status);
  3538. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3539. ASSERT_EQ("coder", res->body);
  3540. }
  3541. TEST_F(ServerTest, DeleteMethod1) {
  3542. auto res = cli_.Get("/person/john4");
  3543. ASSERT_TRUE(res);
  3544. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3545. Params params;
  3546. params.emplace("name", "john4");
  3547. params.emplace("note", "coder");
  3548. res = cli_.Post("/person", params);
  3549. ASSERT_TRUE(res);
  3550. ASSERT_EQ(StatusCode::OK_200, res->status);
  3551. res = cli_.Get("/person/john4");
  3552. ASSERT_TRUE(res);
  3553. ASSERT_EQ(StatusCode::OK_200, res->status);
  3554. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3555. ASSERT_EQ("coder", res->body);
  3556. Params delete_params;
  3557. delete_params.emplace("name", "john4");
  3558. res = cli_.Delete("/person", delete_params);
  3559. ASSERT_TRUE(res);
  3560. ASSERT_EQ(StatusCode::OK_200, res->status);
  3561. ASSERT_EQ("DELETED", res->body);
  3562. res = cli_.Get("/person/john4");
  3563. ASSERT_TRUE(res);
  3564. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3565. }
  3566. TEST_F(ServerTest, DeleteMethod2) {
  3567. auto res = cli_.Get("/person/john5");
  3568. ASSERT_TRUE(res);
  3569. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3570. Params params;
  3571. params.emplace("name", "john5");
  3572. params.emplace("note", "developer");
  3573. res = cli_.Post("/person", params);
  3574. ASSERT_TRUE(res);
  3575. ASSERT_EQ(StatusCode::OK_200, res->status);
  3576. res = cli_.Get("/person/john5");
  3577. ASSERT_TRUE(res);
  3578. ASSERT_EQ(StatusCode::OK_200, res->status);
  3579. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3580. ASSERT_EQ("developer", res->body);
  3581. Params delete_params;
  3582. delete_params.emplace("name", "john5");
  3583. Headers headers;
  3584. headers.emplace("Custom-Header", "test-value");
  3585. res = cli_.Delete("/person", headers, delete_params);
  3586. ASSERT_TRUE(res);
  3587. ASSERT_EQ(StatusCode::OK_200, res->status);
  3588. ASSERT_EQ("DELETED", res->body);
  3589. res = cli_.Get("/person/john5");
  3590. ASSERT_TRUE(res);
  3591. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3592. }
  3593. TEST_F(ServerTest, DeleteMethod3) {
  3594. auto res = cli_.Get("/person/john6");
  3595. ASSERT_TRUE(res);
  3596. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3597. Params params;
  3598. params.emplace("name", "john6");
  3599. params.emplace("note", "tester");
  3600. res = cli_.Post("/person", params);
  3601. ASSERT_TRUE(res);
  3602. ASSERT_EQ(StatusCode::OK_200, res->status);
  3603. res = cli_.Get("/person/john6");
  3604. ASSERT_TRUE(res);
  3605. ASSERT_EQ(StatusCode::OK_200, res->status);
  3606. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3607. ASSERT_EQ("tester", res->body);
  3608. Params delete_params;
  3609. delete_params.emplace("name", "john6");
  3610. Headers headers;
  3611. headers.emplace("Custom-Header", "test-value");
  3612. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3613. ASSERT_TRUE(res);
  3614. ASSERT_EQ(StatusCode::OK_200, res->status);
  3615. ASSERT_EQ("DELETED", res->body);
  3616. res = cli_.Get("/person/john6");
  3617. ASSERT_TRUE(res);
  3618. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3619. }
  3620. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3621. Params params;
  3622. params.emplace("json", JSON_DATA);
  3623. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3624. ASSERT_TRUE(res);
  3625. ASSERT_EQ(StatusCode::OK_200, res->status);
  3626. ASSERT_EQ(JSON_DATA, res->body);
  3627. }
  3628. TEST_F(ServerTest, PostEmptyContent) {
  3629. auto res = cli_.Post("/empty", "", "text/plain");
  3630. ASSERT_TRUE(res);
  3631. ASSERT_EQ(StatusCode::OK_200, res->status);
  3632. ASSERT_EQ("empty", res->body);
  3633. }
  3634. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3635. auto res = cli_.Post("/empty-no-content-type");
  3636. ASSERT_TRUE(res);
  3637. ASSERT_EQ(StatusCode::OK_200, res->status);
  3638. ASSERT_EQ("empty-no-content-type", res->body);
  3639. }
  3640. TEST_F(ServerTest, PostPathOnly) {
  3641. auto res = cli_.Post("/path-only");
  3642. ASSERT_TRUE(res);
  3643. ASSERT_EQ(StatusCode::OK_200, res->status);
  3644. ASSERT_EQ("path-only", res->body);
  3645. }
  3646. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3647. auto res = cli_.Post("/path-headers-only",
  3648. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3649. ASSERT_TRUE(res);
  3650. ASSERT_EQ(StatusCode::OK_200, res->status);
  3651. ASSERT_EQ("path-headers-only", res->body);
  3652. }
  3653. TEST_F(ServerTest, PostLarge) {
  3654. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3655. ASSERT_TRUE(res);
  3656. ASSERT_EQ(StatusCode::OK_200, res->status);
  3657. EXPECT_EQ(LARGE_DATA, res->body);
  3658. }
  3659. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3660. auto res = cli_.Put("/empty-no-content-type");
  3661. ASSERT_TRUE(res);
  3662. ASSERT_EQ(StatusCode::OK_200, res->status);
  3663. ASSERT_EQ("empty-no-content-type", res->body);
  3664. }
  3665. TEST_F(ServerTest, GetMethodDir) {
  3666. auto res = cli_.Get("/dir/");
  3667. ASSERT_TRUE(res);
  3668. EXPECT_EQ(StatusCode::OK_200, res->status);
  3669. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3670. auto body = R"(<html>
  3671. <head>
  3672. </head>
  3673. <body>
  3674. <a href="/dir/test.html">Test</a>
  3675. <a href="/hi">hi</a>
  3676. </body>
  3677. </html>
  3678. )";
  3679. EXPECT_EQ(body, res->body);
  3680. }
  3681. TEST_F(ServerTest, GetMethodDirTest) {
  3682. auto res = cli_.Get("/dir/test.html");
  3683. ASSERT_TRUE(res);
  3684. EXPECT_EQ(StatusCode::OK_200, res->status);
  3685. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3686. EXPECT_EQ("test.html", res->body);
  3687. }
  3688. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3689. auto res = cli_.Get("/dir/../dir/test.html");
  3690. ASSERT_TRUE(res);
  3691. EXPECT_EQ(StatusCode::OK_200, res->status);
  3692. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3693. EXPECT_EQ("test.html", res->body);
  3694. }
  3695. TEST_F(ServerTest, GetMethodInvalidPath) {
  3696. auto res = cli_.Get("/dir/../test.html");
  3697. ASSERT_TRUE(res);
  3698. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3699. }
  3700. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3701. auto res = cli_.Get("/../www/dir/test.html");
  3702. ASSERT_TRUE(res);
  3703. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3704. }
  3705. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3706. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3707. ASSERT_TRUE(res);
  3708. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3709. }
  3710. TEST_F(ServerTest, GetMethodDirMountTest) {
  3711. auto res = cli_.Get("/mount/dir/test.html");
  3712. ASSERT_TRUE(res);
  3713. EXPECT_EQ(StatusCode::OK_200, res->status);
  3714. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3715. EXPECT_EQ("test.html", res->body);
  3716. }
  3717. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3718. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3719. ASSERT_TRUE(res);
  3720. EXPECT_EQ(StatusCode::OK_200, res->status);
  3721. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3722. EXPECT_EQ("test.html", res->body);
  3723. }
  3724. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3725. auto res = cli_.Get("/mount/dir/../test.html");
  3726. ASSERT_TRUE(res);
  3727. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3728. }
  3729. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3730. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3731. ASSERT_TRUE(res);
  3732. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3733. }
  3734. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3735. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3736. ASSERT_TRUE(res);
  3737. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3738. }
  3739. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3740. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3741. ASSERT_TRUE(res);
  3742. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3743. }
  3744. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3745. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3746. ASSERT_TRUE(res);
  3747. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3748. }
  3749. TEST_F(ServerTest, PostMethod303) {
  3750. auto res = cli_.Post("/1", "body", "text/plain");
  3751. ASSERT_TRUE(res);
  3752. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3753. EXPECT_EQ("/2", res->get_header_value("Location"));
  3754. }
  3755. TEST_F(ServerTest, PostMethod303Redirect) {
  3756. cli_.set_follow_location(true);
  3757. auto res = cli_.Post("/1", "body", "text/plain");
  3758. ASSERT_TRUE(res);
  3759. EXPECT_EQ(StatusCode::OK_200, res->status);
  3760. EXPECT_EQ("redirected.", res->body);
  3761. EXPECT_EQ("/2", res->location);
  3762. }
  3763. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3764. auto res = cli_.Get("/dir/test.abcde");
  3765. ASSERT_TRUE(res);
  3766. EXPECT_EQ(StatusCode::OK_200, res->status);
  3767. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3768. EXPECT_EQ("abcde", res->body);
  3769. }
  3770. TEST_F(ServerTest, StaticFileRange) {
  3771. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3772. ASSERT_TRUE(res);
  3773. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3774. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3775. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3776. EXPECT_EQ(true, res->has_header("Content-Range"));
  3777. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3778. EXPECT_EQ(std::string("cd"), res->body);
  3779. }
  3780. TEST_F(ServerTest, StaticFileRanges) {
  3781. auto res =
  3782. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3783. ASSERT_TRUE(res);
  3784. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3785. EXPECT_TRUE(
  3786. res->get_header_value("Content-Type")
  3787. .find(
  3788. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3789. 0);
  3790. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3791. }
  3792. TEST_F(ServerTest, StaticFileRangeHead) {
  3793. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3794. ASSERT_TRUE(res);
  3795. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3796. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3797. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3798. EXPECT_EQ(true, res->has_header("Content-Range"));
  3799. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3800. }
  3801. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3802. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3803. ASSERT_TRUE(res);
  3804. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3805. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3806. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3807. EXPECT_EQ(true, res->has_header("Content-Range"));
  3808. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3809. res->get_header_value("Content-Range"));
  3810. EXPECT_EQ("LAST\n", res->body);
  3811. }
  3812. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3813. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3814. ASSERT_TRUE(res);
  3815. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3816. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3817. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3818. EXPECT_EQ(true, res->has_header("Content-Range"));
  3819. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3820. }
  3821. TEST_F(ServerTest, StaticFileBigFile) {
  3822. auto res = cli_.Get("/dir/1MB.txt");
  3823. ASSERT_TRUE(res);
  3824. EXPECT_EQ(StatusCode::OK_200, res->status);
  3825. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3826. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3827. }
  3828. TEST_F(ServerTest, InvalidBaseDirMount) {
  3829. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3830. }
  3831. TEST_F(ServerTest, Binary) {
  3832. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3833. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3834. "application/octet-stream");
  3835. ASSERT_TRUE(res);
  3836. ASSERT_EQ(StatusCode::OK_200, res->status);
  3837. ASSERT_EQ(4U, res->body.size());
  3838. res = cli_.Put("/binary", binary.data(), binary.size(),
  3839. "application/octet-stream");
  3840. ASSERT_TRUE(res);
  3841. ASSERT_EQ(StatusCode::OK_200, res->status);
  3842. ASSERT_EQ(4U, res->body.size());
  3843. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3844. "application/octet-stream");
  3845. ASSERT_TRUE(res);
  3846. ASSERT_EQ(StatusCode::OK_200, res->status);
  3847. ASSERT_EQ(4U, res->body.size());
  3848. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3849. "application/octet-stream");
  3850. ASSERT_TRUE(res);
  3851. ASSERT_EQ(StatusCode::OK_200, res->status);
  3852. ASSERT_EQ(4U, res->body.size());
  3853. }
  3854. TEST_F(ServerTest, BinaryString) {
  3855. auto binary = std::string("\x00\x01\x02\x03", 4);
  3856. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3857. ASSERT_TRUE(res);
  3858. ASSERT_EQ(StatusCode::OK_200, res->status);
  3859. ASSERT_EQ(4U, res->body.size());
  3860. res = cli_.Put("/binary", binary, "application/octet-stream");
  3861. ASSERT_TRUE(res);
  3862. ASSERT_EQ(StatusCode::OK_200, res->status);
  3863. ASSERT_EQ(4U, res->body.size());
  3864. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3865. ASSERT_TRUE(res);
  3866. ASSERT_EQ(StatusCode::OK_200, res->status);
  3867. ASSERT_EQ(4U, res->body.size());
  3868. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3869. ASSERT_TRUE(res);
  3870. ASSERT_EQ(StatusCode::OK_200, res->status);
  3871. ASSERT_EQ(4U, res->body.size());
  3872. }
  3873. TEST_F(ServerTest, EmptyRequest) {
  3874. auto res = cli_.Get("");
  3875. ASSERT_TRUE(!res);
  3876. EXPECT_EQ(Error::Connection, res.error());
  3877. }
  3878. TEST_F(ServerTest, LongRequest) {
  3879. std::string request;
  3880. for (size_t i = 0; i < 545; i++) {
  3881. request += "/TooLongRequest";
  3882. }
  3883. request += "OK";
  3884. auto res = cli_.Get(request.c_str());
  3885. ASSERT_TRUE(res);
  3886. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3887. }
  3888. TEST_F(ServerTest, TooLongRequest) {
  3889. std::string request;
  3890. for (size_t i = 0; i < 546; i++) {
  3891. request += "/TooLongRequest";
  3892. }
  3893. request += "_NG";
  3894. auto start = std::chrono::high_resolution_clock::now();
  3895. cli_.set_keep_alive(true);
  3896. auto res = cli_.Get(request.c_str());
  3897. auto end = std::chrono::high_resolution_clock::now();
  3898. auto elapsed =
  3899. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3900. .count();
  3901. ASSERT_TRUE(res);
  3902. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3903. EXPECT_LE(elapsed, 1000);
  3904. EXPECT_EQ("close", res->get_header_value("Connection"));
  3905. EXPECT_FALSE(cli_.is_socket_open());
  3906. }
  3907. TEST_F(ServerTest, AlmostTooLongRequest) {
  3908. // test for #2046 - URI length check shouldn't include other content on req
  3909. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3910. // leading /, space, HTTP/1.1)
  3911. std::string request =
  3912. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3913. auto res = cli_.Get(request.c_str());
  3914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3915. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3916. }
  3917. TEST_F(ServerTest, LongHeader) {
  3918. Request req;
  3919. req.method = "GET";
  3920. req.path = "/hi";
  3921. std::string host_and_port;
  3922. host_and_port += HOST;
  3923. host_and_port += ":";
  3924. host_and_port += std::to_string(PORT);
  3925. req.headers.emplace("Host", host_and_port.c_str());
  3926. req.headers.emplace("Accept", "*/*");
  3927. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3928. req.headers.emplace(
  3929. "Header-Name",
  3930. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3931. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3932. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3933. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3934. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3935. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3936. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3937. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3938. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3939. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3940. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3941. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3942. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3943. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3944. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3945. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3946. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3947. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3948. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3949. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3950. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3951. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3952. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3953. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3954. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3955. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3956. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3957. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3958. "@@@@@@@@@@@@@@@@");
  3959. auto res = std::make_shared<Response>();
  3960. auto error = Error::Success;
  3961. auto ret = cli_.send(req, *res, error);
  3962. ASSERT_TRUE(ret);
  3963. EXPECT_EQ(StatusCode::OK_200, res->status);
  3964. }
  3965. TEST_F(ServerTest, LongQueryValue) {
  3966. auto start = std::chrono::high_resolution_clock::now();
  3967. cli_.set_keep_alive(true);
  3968. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3969. auto end = std::chrono::high_resolution_clock::now();
  3970. auto elapsed =
  3971. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3972. .count();
  3973. ASSERT_TRUE(res);
  3974. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3975. EXPECT_LE(elapsed, 1000);
  3976. EXPECT_EQ("close", res->get_header_value("Connection"));
  3977. EXPECT_FALSE(cli_.is_socket_open());
  3978. }
  3979. TEST_F(ServerTest, TooLongQueryValue) {
  3980. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3981. ASSERT_FALSE(res);
  3982. EXPECT_EQ(Error::Read, res.error());
  3983. }
  3984. TEST_F(ServerTest, TooLongHeader) {
  3985. Request req;
  3986. req.method = "GET";
  3987. req.path = "/hi";
  3988. std::string host_and_port;
  3989. host_and_port += HOST;
  3990. host_and_port += ":";
  3991. host_and_port += std::to_string(PORT);
  3992. req.headers.emplace("Host", host_and_port.c_str());
  3993. req.headers.emplace("Accept", "*/*");
  3994. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3995. req.headers.emplace(
  3996. "Header-Name",
  3997. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3998. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3999. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4000. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4001. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4002. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4003. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4004. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4005. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4006. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4007. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4008. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4009. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4010. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4011. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4012. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4013. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4014. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4015. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4016. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4017. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4018. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4019. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4020. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4021. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4022. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4023. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4024. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4025. "@@@@@@@@@@@@@@@@@");
  4026. auto res = std::make_shared<Response>();
  4027. auto error = Error::Success;
  4028. auto ret = cli_.send(req, *res, error);
  4029. ASSERT_TRUE(ret);
  4030. EXPECT_EQ(StatusCode::OK_200, res->status);
  4031. }
  4032. TEST_F(ServerTest, HeaderCountAtLimit) {
  4033. // Test with headers just under the 100 limit
  4034. httplib::Headers headers;
  4035. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4036. // This should keep us just under the 100 header limit
  4037. for (int i = 0; i < 95; i++) {
  4038. std::string name = "X-Test-Header-" + std::to_string(i);
  4039. std::string value = "value" + std::to_string(i);
  4040. headers.emplace(name, value);
  4041. }
  4042. // This should work fine as we're under the limit
  4043. auto res = cli_.Get("/hi", headers);
  4044. EXPECT_TRUE(res);
  4045. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4046. }
  4047. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4048. // Test with many headers to exceed the 100 limit
  4049. httplib::Headers headers;
  4050. // Add 150 headers to definitely exceed the 100 limit
  4051. for (int i = 0; i < 150; i++) {
  4052. std::string name = "X-Test-Header-" + std::to_string(i);
  4053. std::string value = "value" + std::to_string(i);
  4054. headers.emplace(name, value);
  4055. }
  4056. // This should fail due to exceeding header count limit
  4057. cli_.set_keep_alive(true);
  4058. auto res = cli_.Get("/hi", headers);
  4059. // The server should respond with 400 Bad Request
  4060. ASSERT_TRUE(res);
  4061. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4062. EXPECT_EQ("close", res->get_header_value("Connection"));
  4063. EXPECT_FALSE(cli_.is_socket_open());
  4064. }
  4065. TEST_F(ServerTest, PercentEncoding) {
  4066. auto res = cli_.Get("/e%6edwith%");
  4067. ASSERT_TRUE(res);
  4068. EXPECT_EQ(StatusCode::OK_200, res->status);
  4069. }
  4070. TEST_F(ServerTest, PercentEncodingUnicode) {
  4071. auto res = cli_.Get("/e%u006edwith%");
  4072. ASSERT_TRUE(res);
  4073. EXPECT_EQ(StatusCode::OK_200, res->status);
  4074. }
  4075. TEST_F(ServerTest, InvalidPercentEncoding) {
  4076. auto res = cli_.Get("/%endwith%");
  4077. ASSERT_TRUE(res);
  4078. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4079. }
  4080. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4081. auto res = cli_.Get("/%uendwith%");
  4082. ASSERT_TRUE(res);
  4083. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4084. }
  4085. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4086. auto res = cli_.Get("/hello?aaa=bbb%");
  4087. ASSERT_TRUE(res);
  4088. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4089. }
  4090. TEST_F(ServerTest, PlusSignEncoding) {
  4091. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4092. ASSERT_TRUE(res);
  4093. EXPECT_EQ(StatusCode::OK_200, res->status);
  4094. EXPECT_EQ("a +b", res->body);
  4095. }
  4096. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4097. // This test simulates a potential DoS attack using many headers
  4098. // to verify our security fix prevents memory exhaustion
  4099. httplib::Headers attack_headers;
  4100. // Attempt to add many headers like an attacker would (200 headers to far
  4101. // exceed limit)
  4102. for (int i = 0; i < 200; i++) {
  4103. std::string name = "X-Attack-Header-" + std::to_string(i);
  4104. std::string value = "attack_payload_" + std::to_string(i);
  4105. attack_headers.emplace(name, value);
  4106. }
  4107. // Try to POST with excessive headers
  4108. cli_.set_keep_alive(true);
  4109. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4110. // Should either fail or return 400 Bad Request due to security limit
  4111. if (res) {
  4112. // If we get a response, it should be 400 Bad Request
  4113. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4114. EXPECT_EQ("close", res->get_header_value("Connection"));
  4115. }
  4116. EXPECT_FALSE(cli_.is_socket_open());
  4117. }
  4118. TEST_F(ServerTest, MultipartFormData) {
  4119. UploadFormDataItems items = {
  4120. {"text1", "text default", "", ""},
  4121. {"text2", "aωb", "", ""},
  4122. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4123. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4124. {"file3", "", "", "application/octet-stream"},
  4125. {"file4", "", "", " application/json tmp-string "}};
  4126. auto res = cli_.Post("/multipart", items);
  4127. ASSERT_TRUE(res);
  4128. EXPECT_EQ(StatusCode::OK_200, res->status);
  4129. }
  4130. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4131. UploadFormDataItems items = {
  4132. {"text", "default text", "", ""},
  4133. {"multi_text1", "aaaaa", "", ""},
  4134. {"multi_text1", "bbbbb", "", ""},
  4135. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4136. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4137. "application/json"},
  4138. };
  4139. auto res = cli_.Post("/multipart/multi_file_values", items);
  4140. ASSERT_TRUE(res);
  4141. EXPECT_EQ(StatusCode::OK_200, res->status);
  4142. }
  4143. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4144. auto res = cli_.Get("/hi");
  4145. ASSERT_TRUE(res);
  4146. EXPECT_EQ(StatusCode::OK_200, res->status);
  4147. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4148. EXPECT_EQ("Hello World!", res->body);
  4149. }
  4150. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4151. Request req;
  4152. req.method = "POST";
  4153. req.path = "/chunked";
  4154. std::string host_and_port;
  4155. host_and_port += HOST;
  4156. host_and_port += ":";
  4157. host_and_port += std::to_string(PORT);
  4158. req.headers.emplace("Host", host_and_port.c_str());
  4159. req.headers.emplace("Accept", "*/*");
  4160. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4161. req.headers.emplace("Content-Type", "text/plain");
  4162. req.headers.emplace("Content-Length", "0");
  4163. req.headers.emplace(
  4164. "Transfer-Encoding",
  4165. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4166. // Client does not chunk, so make a chunked body manually.
  4167. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4168. auto res = std::make_shared<Response>();
  4169. auto error = Error::Success;
  4170. auto ret = cli_.send(req, *res, error);
  4171. ASSERT_TRUE(ret);
  4172. EXPECT_EQ(StatusCode::OK_200, res->status);
  4173. }
  4174. TEST_F(ServerTest, GetStreamed2) {
  4175. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4176. ASSERT_TRUE(res);
  4177. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4178. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4179. EXPECT_EQ(true, res->has_header("Content-Range"));
  4180. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4181. EXPECT_EQ(std::string("ab"), res->body);
  4182. }
  4183. TEST_F(ServerTest, GetStreamed) {
  4184. auto res = cli_.Get("/streamed");
  4185. ASSERT_TRUE(res);
  4186. EXPECT_EQ(StatusCode::OK_200, res->status);
  4187. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4188. EXPECT_EQ(std::string("aaabbb"), res->body);
  4189. }
  4190. TEST_F(ServerTest, GetStreamedWithRange1) {
  4191. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4192. ASSERT_TRUE(res);
  4193. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4194. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4195. EXPECT_EQ(true, res->has_header("Content-Range"));
  4196. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4197. EXPECT_EQ(std::string("def"), res->body);
  4198. }
  4199. TEST_F(ServerTest, GetStreamedWithRange2) {
  4200. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4201. ASSERT_TRUE(res);
  4202. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4203. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4204. EXPECT_EQ(true, res->has_header("Content-Range"));
  4205. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4206. EXPECT_EQ(std::string("bcdefg"), res->body);
  4207. }
  4208. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4209. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4210. ASSERT_TRUE(res);
  4211. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4212. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4213. EXPECT_EQ(true, res->has_header("Content-Range"));
  4214. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4215. EXPECT_EQ(std::string("efg"), res->body);
  4216. }
  4217. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4218. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4219. ASSERT_TRUE(res);
  4220. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4221. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4222. EXPECT_EQ(false, res->has_header("Content-Range"));
  4223. EXPECT_EQ(0U, res->body.size());
  4224. }
  4225. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4226. auto res = cli_.Get("/streamed-with-range",
  4227. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4228. "92233720368547758079223372036854775807"}});
  4229. ASSERT_TRUE(res);
  4230. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4231. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4232. EXPECT_EQ(false, res->has_header("Content-Range"));
  4233. EXPECT_EQ(0U, res->body.size());
  4234. }
  4235. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4236. auto res = cli_.Get(
  4237. "/with-range",
  4238. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4239. {"Accept-Encoding", ""}});
  4240. ASSERT_TRUE(res);
  4241. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4242. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4243. EXPECT_EQ(true, res->has_header("Content-Range"));
  4244. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4245. EXPECT_EQ(std::string("abcdefg"), res->body);
  4246. }
  4247. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4248. auto res = cli_.Get("/with-range", {
  4249. {"Range", "bytes=0-"},
  4250. {"Accept-Encoding", ""},
  4251. });
  4252. ASSERT_TRUE(res);
  4253. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4254. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4255. EXPECT_EQ(true, res->has_header("Content-Range"));
  4256. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4257. EXPECT_EQ(std::string("abcdefg"), res->body);
  4258. }
  4259. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4260. auto res =
  4261. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4262. ASSERT_TRUE(res);
  4263. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4264. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4265. EXPECT_EQ(false, res->has_header("Content-Range"));
  4266. EXPECT_EQ(267U, res->body.size());
  4267. // Check that both range contents are present
  4268. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4269. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4270. // Check that Content-Range headers are present for both ranges
  4271. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4272. std::string::npos);
  4273. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4274. std::string::npos);
  4275. }
  4276. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4277. Ranges ranges;
  4278. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4279. ranges.emplace_back(0, -1);
  4280. }
  4281. auto res =
  4282. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4283. ASSERT_TRUE(res);
  4284. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4285. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4286. EXPECT_EQ(false, res->has_header("Content-Range"));
  4287. EXPECT_EQ(0U, res->body.size());
  4288. }
  4289. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4290. auto res =
  4291. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4292. ASSERT_TRUE(res);
  4293. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4294. EXPECT_EQ(5U, res->body.size());
  4295. // Check that overlapping ranges are coalesced into a single range
  4296. EXPECT_EQ("bcdef", res->body);
  4297. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4298. // Should be single range, not multipart
  4299. EXPECT_TRUE(res->has_header("Content-Range"));
  4300. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4301. }
  4302. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4303. auto res =
  4304. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4305. ASSERT_TRUE(res);
  4306. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4307. EXPECT_EQ(268U, res->body.size());
  4308. // Check that both range contents are present
  4309. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4310. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4311. // Check that Content-Range headers are present for both ranges
  4312. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4313. std::string::npos);
  4314. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4315. std::string::npos);
  4316. }
  4317. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4318. auto res =
  4319. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4320. ASSERT_TRUE(res);
  4321. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4322. EXPECT_EQ(269U, res->body.size());
  4323. // Check that both duplicate range contents are present
  4324. size_t first_abc = res->body.find("abc\r\n");
  4325. EXPECT_TRUE(first_abc != std::string::npos);
  4326. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4327. EXPECT_TRUE(second_abc != std::string::npos);
  4328. // Check that Content-Range headers are present for both ranges
  4329. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4330. EXPECT_TRUE(first_range != std::string::npos);
  4331. size_t second_range =
  4332. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4333. EXPECT_TRUE(second_range != std::string::npos);
  4334. }
  4335. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4336. auto res = cli_.Get("/streamed-with-range?error",
  4337. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4338. ASSERT_TRUE(res);
  4339. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4340. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4341. EXPECT_EQ(false, res->has_header("Content-Range"));
  4342. EXPECT_EQ(0U, res->body.size());
  4343. }
  4344. TEST_F(ServerTest, GetStreamedEndless) {
  4345. uint64_t offset = 0;
  4346. auto res = cli_.Get("/streamed-cancel",
  4347. [&](const char * /*data*/, uint64_t data_length) {
  4348. if (offset < 100) {
  4349. offset += data_length;
  4350. return true;
  4351. }
  4352. return false;
  4353. });
  4354. ASSERT_TRUE(!res);
  4355. EXPECT_EQ(Error::Canceled, res.error());
  4356. }
  4357. TEST_F(ServerTest, ClientStop) {
  4358. std::atomic_size_t count{4};
  4359. std::vector<std::thread> threads;
  4360. for (auto i = count.load(); i != 0; --i) {
  4361. threads.emplace_back([&]() {
  4362. auto res = cli_.Get("/streamed-cancel",
  4363. [&](const char *, uint64_t) { return true; });
  4364. --count;
  4365. ASSERT_TRUE(!res);
  4366. EXPECT_TRUE(res.error() == Error::Canceled ||
  4367. res.error() == Error::Read || res.error() == Error::Write);
  4368. });
  4369. }
  4370. std::this_thread::sleep_for(std::chrono::seconds(2));
  4371. while (count != 0) {
  4372. cli_.stop();
  4373. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4374. }
  4375. for (auto &t : threads) {
  4376. t.join();
  4377. }
  4378. }
  4379. TEST_F(ServerTest, GetWithRange1) {
  4380. auto res = cli_.Get("/with-range", {
  4381. make_range_header({{3, 5}}),
  4382. {"Accept-Encoding", ""},
  4383. });
  4384. ASSERT_TRUE(res);
  4385. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4386. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4387. EXPECT_EQ(true, res->has_header("Content-Range"));
  4388. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4389. EXPECT_EQ(std::string("def"), res->body);
  4390. }
  4391. TEST_F(ServerTest, GetWithRange2) {
  4392. auto res = cli_.Get("/with-range", {
  4393. make_range_header({{1, -1}}),
  4394. {"Accept-Encoding", ""},
  4395. });
  4396. ASSERT_TRUE(res);
  4397. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4398. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4399. EXPECT_EQ(true, res->has_header("Content-Range"));
  4400. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4401. EXPECT_EQ(std::string("bcdefg"), res->body);
  4402. }
  4403. TEST_F(ServerTest, GetWithRange3) {
  4404. auto res = cli_.Get("/with-range", {
  4405. make_range_header({{0, 0}}),
  4406. {"Accept-Encoding", ""},
  4407. });
  4408. ASSERT_TRUE(res);
  4409. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4410. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4411. EXPECT_EQ(true, res->has_header("Content-Range"));
  4412. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4413. EXPECT_EQ(std::string("a"), res->body);
  4414. }
  4415. TEST_F(ServerTest, GetWithRange4) {
  4416. auto res = cli_.Get("/with-range", {
  4417. make_range_header({{-1, 2}}),
  4418. {"Accept-Encoding", ""},
  4419. });
  4420. ASSERT_TRUE(res);
  4421. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4422. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4423. EXPECT_EQ(true, res->has_header("Content-Range"));
  4424. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4425. EXPECT_EQ(std::string("fg"), res->body);
  4426. }
  4427. TEST_F(ServerTest, GetWithRange5) {
  4428. auto res = cli_.Get("/with-range", {
  4429. make_range_header({{0, 5}}),
  4430. {"Accept-Encoding", ""},
  4431. });
  4432. ASSERT_TRUE(res);
  4433. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4434. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4435. EXPECT_EQ(true, res->has_header("Content-Range"));
  4436. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4437. EXPECT_EQ(std::string("abcdef"), res->body);
  4438. }
  4439. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4440. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4441. ASSERT_TRUE(res);
  4442. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4443. }
  4444. TEST_F(ServerTest, GetWithRangeMultipart) {
  4445. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4446. ASSERT_TRUE(res);
  4447. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4448. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4449. EXPECT_EQ(false, res->has_header("Content-Range"));
  4450. EXPECT_EQ(267U, res->body.size());
  4451. }
  4452. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4453. auto res =
  4454. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4455. ASSERT_TRUE(res);
  4456. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4457. }
  4458. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4459. auto res = cli_.Get("/with-range-customized-response",
  4460. {{make_range_header({{1, 2}})}});
  4461. ASSERT_TRUE(res);
  4462. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4463. EXPECT_EQ(true, res->has_header("Content-Length"));
  4464. EXPECT_EQ(false, res->has_header("Content-Range"));
  4465. EXPECT_EQ(JSON_DATA, res->body);
  4466. }
  4467. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4468. auto res = cli_.Get("/with-range-customized-response",
  4469. {{make_range_header({{1, 2}, {4, 5}})}});
  4470. ASSERT_TRUE(res);
  4471. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4472. EXPECT_EQ(true, res->has_header("Content-Length"));
  4473. EXPECT_EQ(false, res->has_header("Content-Range"));
  4474. EXPECT_EQ(JSON_DATA, res->body);
  4475. }
  4476. TEST_F(ServerTest, Issue1772) {
  4477. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4478. ASSERT_TRUE(res);
  4479. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4480. }
  4481. TEST_F(ServerTest, Issue609) {
  4482. auto res = cli_.Delete("/issue609");
  4483. ASSERT_TRUE(res);
  4484. EXPECT_EQ(StatusCode::OK_200, res->status);
  4485. EXPECT_EQ(std::string("ok"), res->body);
  4486. }
  4487. TEST_F(ServerTest, GetStreamedChunked) {
  4488. auto res = cli_.Get("/streamed-chunked");
  4489. ASSERT_TRUE(res);
  4490. EXPECT_EQ(StatusCode::OK_200, res->status);
  4491. EXPECT_EQ(std::string("123456789"), res->body);
  4492. }
  4493. TEST_F(ServerTest, GetStreamedChunked2) {
  4494. auto res = cli_.Get("/streamed-chunked2");
  4495. ASSERT_TRUE(res);
  4496. EXPECT_EQ(StatusCode::OK_200, res->status);
  4497. EXPECT_EQ(std::string("123456789"), res->body);
  4498. }
  4499. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4500. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4501. ASSERT_TRUE(res);
  4502. EXPECT_EQ(StatusCode::OK_200, res->status);
  4503. EXPECT_EQ(std::string("123456789"), res->body);
  4504. EXPECT_TRUE(res->has_header("Trailer"));
  4505. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4506. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4507. // Trailers are now stored separately from headers (security fix)
  4508. EXPECT_EQ(2U, res->trailers.size());
  4509. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4510. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4511. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4512. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4513. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4514. // Verify trailers are NOT in headers (security verification)
  4515. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4516. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4517. }
  4518. TEST_F(ServerTest, LargeChunkedPost) {
  4519. Request req;
  4520. req.method = "POST";
  4521. req.path = "/large-chunked";
  4522. std::string host_and_port;
  4523. host_and_port += HOST;
  4524. host_and_port += ":";
  4525. host_and_port += std::to_string(PORT);
  4526. req.headers.emplace("Host", host_and_port.c_str());
  4527. req.headers.emplace("Accept", "*/*");
  4528. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4529. req.headers.emplace("Content-Type", "text/plain");
  4530. req.headers.emplace("Content-Length", "0");
  4531. req.headers.emplace("Transfer-Encoding", "chunked");
  4532. std::string long_string(30 * 1024u, 'a');
  4533. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4534. // Attempt to make a large enough post to exceed OS buffers, to test that
  4535. // the server handles short reads if the full chunk data isn't available.
  4536. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4537. auto res = std::make_shared<Response>();
  4538. auto error = Error::Success;
  4539. auto ret = cli_.send(req, *res, error);
  4540. ASSERT_TRUE(ret);
  4541. EXPECT_EQ(StatusCode::OK_200, res->status);
  4542. }
  4543. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4544. auto res = cli_.Get("/remote_addr");
  4545. ASSERT_TRUE(res);
  4546. EXPECT_EQ(StatusCode::OK_200, res->status);
  4547. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4548. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4549. }
  4550. TEST_F(ServerTest, GetMethodLocalAddr) {
  4551. auto res = cli_.Get("/local_addr");
  4552. ASSERT_TRUE(res);
  4553. EXPECT_EQ(StatusCode::OK_200, res->status);
  4554. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4555. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4556. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4557. }
  4558. TEST_F(ServerTest, HTTPResponseSplitting) {
  4559. auto res = cli_.Get("/http_response_splitting");
  4560. ASSERT_TRUE(res);
  4561. EXPECT_EQ(StatusCode::OK_200, res->status);
  4562. }
  4563. TEST_F(ServerTest, SlowRequest) {
  4564. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4565. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4566. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4567. }
  4568. #if 0
  4569. TEST_F(ServerTest, SlowPost) {
  4570. char buffer[64 * 1024];
  4571. memset(buffer, 0x42, sizeof(buffer));
  4572. auto res = cli_.Post(
  4573. "/slowpost", 64 * 1024 * 1024,
  4574. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4575. auto ret = sink.write(buffer, sizeof(buffer));
  4576. EXPECT_TRUE(ret);
  4577. return true;
  4578. },
  4579. "text/plain");
  4580. ASSERT_TRUE(res);
  4581. EXPECT_EQ(StatusCode::OK_200, res->status);
  4582. }
  4583. TEST_F(ServerTest, SlowPostFail) {
  4584. char buffer[64 * 1024];
  4585. memset(buffer, 0x42, sizeof(buffer));
  4586. cli_.set_write_timeout(std::chrono::seconds(0));
  4587. auto res = cli_.Post(
  4588. "/slowpost", 64 * 1024 * 1024,
  4589. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4590. sink.write(buffer, sizeof(buffer));
  4591. return true;
  4592. },
  4593. "text/plain");
  4594. ASSERT_TRUE(!res);
  4595. EXPECT_EQ(Error::Write, res.error());
  4596. }
  4597. #endif
  4598. TEST_F(ServerTest, Put) {
  4599. auto res = cli_.Put("/put", "PUT", "text/plain");
  4600. ASSERT_TRUE(res);
  4601. EXPECT_EQ(StatusCode::OK_200, res->status);
  4602. EXPECT_EQ("PUT", res->body);
  4603. }
  4604. TEST_F(ServerTest, PutWithContentProvider) {
  4605. auto res = cli_.Put(
  4606. "/put", 3,
  4607. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4608. sink.os << "PUT";
  4609. return true;
  4610. },
  4611. "text/plain");
  4612. ASSERT_TRUE(res);
  4613. EXPECT_EQ(StatusCode::OK_200, res->status);
  4614. EXPECT_EQ("PUT", res->body);
  4615. }
  4616. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4617. auto res = cli_.Post(
  4618. "/post", 42,
  4619. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4620. return false;
  4621. },
  4622. "text/plain");
  4623. ASSERT_TRUE(!res);
  4624. EXPECT_EQ(Error::Canceled, res.error());
  4625. }
  4626. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4627. auto res = cli_.Put(
  4628. "/put",
  4629. [](size_t /*offset*/, DataSink &sink) {
  4630. sink.os << "PUT";
  4631. sink.done();
  4632. return true;
  4633. },
  4634. "text/plain");
  4635. ASSERT_TRUE(res);
  4636. EXPECT_EQ(StatusCode::OK_200, res->status);
  4637. EXPECT_EQ("PUT", res->body);
  4638. }
  4639. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4640. auto res = cli_.Post(
  4641. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4642. "text/plain");
  4643. ASSERT_TRUE(!res);
  4644. EXPECT_EQ(Error::Canceled, res.error());
  4645. }
  4646. TEST_F(ServerTest, PostLoopBack) {
  4647. std::string body;
  4648. auto res = cli_.Post(
  4649. "/post-loopback", 9,
  4650. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4651. EXPECT_EQ(9u, length);
  4652. sink.write("123", 3);
  4653. sink.write("456", 3);
  4654. sink.write("789", 3);
  4655. return true;
  4656. },
  4657. "text/plain",
  4658. [&body](const char *data, size_t data_length) {
  4659. body.append(data, data_length);
  4660. return true;
  4661. });
  4662. ASSERT_TRUE(res);
  4663. EXPECT_EQ(StatusCode::OK_200, res->status);
  4664. EXPECT_EQ("123456789", body);
  4665. }
  4666. TEST_F(ServerTest, PutLoopBack) {
  4667. std::string body;
  4668. auto res = cli_.Put(
  4669. "/put-loopback", 9,
  4670. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4671. EXPECT_EQ(9u, length);
  4672. sink.write("123", 3);
  4673. sink.write("456", 3);
  4674. sink.write("789", 3);
  4675. return true;
  4676. },
  4677. "text/plain",
  4678. [&body](const char *data, size_t data_length) {
  4679. body.append(data, data_length);
  4680. return true;
  4681. });
  4682. ASSERT_TRUE(res);
  4683. EXPECT_EQ(StatusCode::OK_200, res->status);
  4684. EXPECT_EQ("123456789", body);
  4685. }
  4686. TEST_F(ServerTest, PatchLoopBack) {
  4687. std::string body;
  4688. auto res = cli_.Patch(
  4689. "/patch-loopback", 9,
  4690. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4691. EXPECT_EQ(9u, length);
  4692. sink.write("123", 3);
  4693. sink.write("456", 3);
  4694. sink.write("789", 3);
  4695. return true;
  4696. },
  4697. "text/plain",
  4698. [&body](const char *data, size_t data_length) {
  4699. body.append(data, data_length);
  4700. return true;
  4701. });
  4702. ASSERT_TRUE(res);
  4703. EXPECT_EQ(StatusCode::OK_200, res->status);
  4704. EXPECT_EQ("123456789", body);
  4705. }
  4706. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4707. std::string body;
  4708. auto res = cli_.Post(
  4709. "/post-loopback",
  4710. [](size_t /*offset*/, DataSink &sink) {
  4711. sink.write("123", 3);
  4712. sink.write("456", 3);
  4713. sink.write("789", 3);
  4714. sink.done();
  4715. return true;
  4716. },
  4717. "text/plain",
  4718. [&body](const char *data, size_t data_length) {
  4719. body.append(data, data_length);
  4720. return true;
  4721. });
  4722. ASSERT_TRUE(res);
  4723. EXPECT_EQ(StatusCode::OK_200, res->status);
  4724. EXPECT_EQ("123456789", body);
  4725. }
  4726. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4727. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4728. cli_.set_compress(true);
  4729. auto res = cli_.Put(
  4730. "/put", 3,
  4731. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4732. sink.os << "PUT";
  4733. return true;
  4734. },
  4735. "text/plain");
  4736. ASSERT_TRUE(res);
  4737. EXPECT_EQ(StatusCode::OK_200, res->status);
  4738. EXPECT_EQ("PUT", res->body);
  4739. }
  4740. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4741. cli_.set_compress(true);
  4742. auto res = cli_.Post(
  4743. "/post", 42,
  4744. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4745. return false;
  4746. },
  4747. "text/plain");
  4748. ASSERT_TRUE(!res);
  4749. EXPECT_EQ(Error::Canceled, res.error());
  4750. }
  4751. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4752. cli_.set_compress(true);
  4753. auto res = cli_.Put(
  4754. "/put",
  4755. [](size_t /*offset*/, DataSink &sink) {
  4756. sink.os << "PUT";
  4757. sink.done();
  4758. return true;
  4759. },
  4760. "text/plain");
  4761. ASSERT_TRUE(res);
  4762. EXPECT_EQ(StatusCode::OK_200, res->status);
  4763. EXPECT_EQ("PUT", res->body);
  4764. }
  4765. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4766. cli_.set_compress(true);
  4767. auto res = cli_.Post(
  4768. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4769. "text/plain");
  4770. ASSERT_TRUE(!res);
  4771. EXPECT_EQ(Error::Canceled, res.error());
  4772. }
  4773. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4774. cli_.set_compress(true);
  4775. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4776. ASSERT_TRUE(res);
  4777. EXPECT_EQ(StatusCode::OK_200, res->status);
  4778. EXPECT_EQ(LARGE_DATA, res->body);
  4779. }
  4780. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4781. #ifdef CPPHTTPLIB_SSL_ENABLED
  4782. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4783. Client cli(s.c_str());
  4784. cli.enable_server_certificate_verification(false);
  4785. #else
  4786. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4787. Client cli(s.c_str());
  4788. #endif
  4789. cli.set_compress(true);
  4790. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4791. ASSERT_TRUE(res);
  4792. EXPECT_EQ(StatusCode::OK_200, res->status);
  4793. EXPECT_EQ(LARGE_DATA, res->body);
  4794. // The compressed size should be less than a 10th of the original. May vary
  4795. // depending on the zlib library.
  4796. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4797. static_cast<uint64_t>(10 * 1024 * 1024));
  4798. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4799. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  4800. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  4801. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4802. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4803. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  4804. #endif
  4805. }
  4806. TEST_F(ServerTest, PutContentWithDeflate) {
  4807. cli_.set_compress(false);
  4808. Headers headers;
  4809. headers.emplace("Content-Encoding", "deflate");
  4810. // PUT in deflate format:
  4811. auto res = cli_.Put("/put", headers,
  4812. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4813. ASSERT_TRUE(res);
  4814. EXPECT_EQ(StatusCode::OK_200, res->status);
  4815. EXPECT_EQ("PUT", res->body);
  4816. }
  4817. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4818. Headers headers;
  4819. headers.emplace("Accept-Encoding", "gzip, deflate");
  4820. auto res = cli_.Get("/streamed-chunked", headers);
  4821. ASSERT_TRUE(res);
  4822. EXPECT_EQ(StatusCode::OK_200, res->status);
  4823. EXPECT_EQ(std::string("123456789"), res->body);
  4824. }
  4825. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4826. Headers headers;
  4827. headers.emplace("Accept-Encoding", "gzip, deflate");
  4828. auto res = cli_.Get("/streamed-chunked2", headers);
  4829. ASSERT_TRUE(res);
  4830. EXPECT_EQ(StatusCode::OK_200, res->status);
  4831. EXPECT_EQ(std::string("123456789"), res->body);
  4832. }
  4833. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4834. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4835. ASSERT_TRUE(res);
  4836. EXPECT_EQ(StatusCode::OK_200, res->status);
  4837. }
  4838. TEST(GzipDecompressor, ChunkedDecompression) {
  4839. std::string data;
  4840. for (size_t i = 0; i < 32 * 1024; ++i) {
  4841. data.push_back(static_cast<char>('a' + i % 26));
  4842. }
  4843. std::string compressed_data;
  4844. {
  4845. httplib::detail::gzip_compressor compressor;
  4846. bool result = compressor.compress(
  4847. data.data(), data.size(),
  4848. /*last=*/true,
  4849. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4850. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4851. compressed_data_size);
  4852. return true;
  4853. });
  4854. ASSERT_TRUE(result);
  4855. }
  4856. std::string decompressed_data;
  4857. {
  4858. httplib::detail::gzip_decompressor decompressor;
  4859. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4860. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4861. size_t chunk_size = 130;
  4862. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4863. chunk_begin += chunk_size) {
  4864. size_t current_chunk_size =
  4865. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4866. bool result = decompressor.decompress(
  4867. compressed_data.data() + chunk_begin, current_chunk_size,
  4868. [&](const char *decompressed_data_chunk,
  4869. size_t decompressed_data_chunk_size) {
  4870. decompressed_data.insert(decompressed_data.size(),
  4871. decompressed_data_chunk,
  4872. decompressed_data_chunk_size);
  4873. return true;
  4874. });
  4875. ASSERT_TRUE(result);
  4876. }
  4877. }
  4878. ASSERT_EQ(data, decompressed_data);
  4879. }
  4880. TEST(GzipDecompressor, DeflateDecompression) {
  4881. std::string original_text = "Raw deflate without gzip";
  4882. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4883. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4884. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4885. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4886. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4887. std::string decompressed_data;
  4888. {
  4889. httplib::detail::gzip_decompressor decompressor;
  4890. bool result = decompressor.decompress(
  4891. compressed_data.data(), compressed_data.size(),
  4892. [&](const char *decompressed_data_chunk,
  4893. size_t decompressed_data_chunk_size) {
  4894. decompressed_data.insert(decompressed_data.size(),
  4895. decompressed_data_chunk,
  4896. decompressed_data_chunk_size);
  4897. return true;
  4898. });
  4899. ASSERT_TRUE(result);
  4900. }
  4901. ASSERT_EQ(original_text, decompressed_data);
  4902. }
  4903. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4904. std::string original_text = "Raw deflate without gzip";
  4905. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4906. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4907. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4908. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4909. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4910. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4911. std::string decompressed_data;
  4912. {
  4913. httplib::detail::gzip_decompressor decompressor;
  4914. bool result = decompressor.decompress(
  4915. compressed_data.data(), compressed_data.size(),
  4916. [&](const char *decompressed_data_chunk,
  4917. size_t decompressed_data_chunk_size) {
  4918. decompressed_data.insert(decompressed_data.size(),
  4919. decompressed_data_chunk,
  4920. decompressed_data_chunk_size);
  4921. return true;
  4922. });
  4923. ASSERT_TRUE(result);
  4924. }
  4925. ASSERT_EQ(original_text, decompressed_data);
  4926. }
  4927. #endif
  4928. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4929. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4930. Headers headers;
  4931. headers.emplace("Accept-Encoding", "br");
  4932. auto res = cli_.Get("/streamed-chunked", headers);
  4933. ASSERT_TRUE(res);
  4934. EXPECT_EQ(StatusCode::OK_200, res->status);
  4935. EXPECT_EQ(std::string("123456789"), res->body);
  4936. }
  4937. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4938. Headers headers;
  4939. headers.emplace("Accept-Encoding", "br");
  4940. auto res = cli_.Get("/streamed-chunked2", headers);
  4941. ASSERT_TRUE(res);
  4942. EXPECT_EQ(StatusCode::OK_200, res->status);
  4943. EXPECT_EQ(std::string("123456789"), res->body);
  4944. }
  4945. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  4946. cli_.set_compress(true);
  4947. auto res = cli_.Put(
  4948. "/put", 3,
  4949. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4950. sink.os << "PUT";
  4951. return true;
  4952. },
  4953. "text/plain");
  4954. ASSERT_TRUE(res);
  4955. EXPECT_EQ(StatusCode::OK_200, res->status);
  4956. EXPECT_EQ("PUT", res->body);
  4957. }
  4958. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  4959. cli_.set_compress(true);
  4960. auto res = cli_.Put(
  4961. "/put",
  4962. [](size_t /*offset*/, DataSink &sink) {
  4963. sink.os << "PUT";
  4964. sink.done();
  4965. return true;
  4966. },
  4967. "text/plain");
  4968. ASSERT_TRUE(res);
  4969. EXPECT_EQ(StatusCode::OK_200, res->status);
  4970. EXPECT_EQ("PUT", res->body);
  4971. }
  4972. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  4973. cli_.set_compress(true);
  4974. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4975. ASSERT_TRUE(res);
  4976. EXPECT_EQ(StatusCode::OK_200, res->status);
  4977. EXPECT_EQ(LARGE_DATA, res->body);
  4978. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  4979. }
  4980. #endif
  4981. TEST_F(ServerTest, Patch) {
  4982. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4983. ASSERT_TRUE(res);
  4984. EXPECT_EQ(StatusCode::OK_200, res->status);
  4985. EXPECT_EQ("PATCH", res->body);
  4986. }
  4987. TEST_F(ServerTest, Delete) {
  4988. auto res = cli_.Delete("/delete");
  4989. ASSERT_TRUE(res);
  4990. EXPECT_EQ(StatusCode::OK_200, res->status);
  4991. EXPECT_EQ("DELETE", res->body);
  4992. }
  4993. TEST_F(ServerTest, DeleteContentReceiver) {
  4994. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4995. ASSERT_TRUE(res);
  4996. EXPECT_EQ(StatusCode::OK_200, res->status);
  4997. EXPECT_EQ("content", res->body);
  4998. }
  4999. TEST_F(ServerTest, Options) {
  5000. auto res = cli_.Options("*");
  5001. ASSERT_TRUE(res);
  5002. EXPECT_EQ(StatusCode::OK_200, res->status);
  5003. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5004. EXPECT_TRUE(res->body.empty());
  5005. }
  5006. TEST_F(ServerTest, URL) {
  5007. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5008. ASSERT_TRUE(res);
  5009. EXPECT_EQ(StatusCode::OK_200, res->status);
  5010. }
  5011. TEST_F(ServerTest, ArrayParam) {
  5012. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5013. ASSERT_TRUE(res);
  5014. EXPECT_EQ(StatusCode::OK_200, res->status);
  5015. }
  5016. TEST_F(ServerTest, NoMultipleHeaders) {
  5017. Headers headers = {{"Content-Length", "5"}};
  5018. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5019. "text/plain");
  5020. ASSERT_TRUE(res);
  5021. EXPECT_EQ(StatusCode::OK_200, res->status);
  5022. }
  5023. TEST_F(ServerTest, PostContentReceiver) {
  5024. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5025. ASSERT_TRUE(res);
  5026. ASSERT_EQ(StatusCode::OK_200, res->status);
  5027. ASSERT_EQ("content", res->body);
  5028. }
  5029. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5030. UploadFormDataItems items = {
  5031. {"text1", "text default", "", ""},
  5032. {"text2", "aωb", "", ""},
  5033. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5034. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5035. {"file3", "", "", "application/octet-stream"},
  5036. };
  5037. auto res = cli_.Post("/content_receiver", items);
  5038. ASSERT_TRUE(res);
  5039. EXPECT_EQ(StatusCode::OK_200, res->status);
  5040. }
  5041. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5042. UploadFormDataItems items = {
  5043. {"text1", "text default", "", ""},
  5044. {"text2", "aωb", "", ""},
  5045. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5046. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5047. {"file3", "", "", "application/octet-stream"},
  5048. };
  5049. auto boundary = std::string("+++++");
  5050. std::string body;
  5051. for (const auto &item : items) {
  5052. body += "--" + boundary + "\r\n";
  5053. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5054. if (!item.filename.empty()) {
  5055. body += "; filename=\"" + item.filename + "\"";
  5056. }
  5057. body += "\r\n";
  5058. if (!item.content_type.empty()) {
  5059. body += "Content-Type: " + item.content_type + "\r\n";
  5060. }
  5061. body += "\r\n";
  5062. body += item.content + "\r\n";
  5063. }
  5064. body += "--" + boundary + "--\r\n";
  5065. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5066. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5067. ASSERT_TRUE(res);
  5068. EXPECT_EQ(StatusCode::OK_200, res->status);
  5069. }
  5070. TEST_F(ServerTest, PostContentReceiverGzip) {
  5071. cli_.set_compress(true);
  5072. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5073. ASSERT_TRUE(res);
  5074. ASSERT_EQ(StatusCode::OK_200, res->status);
  5075. ASSERT_EQ("content", res->body);
  5076. }
  5077. TEST_F(ServerTest, PutContentReceiver) {
  5078. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5079. ASSERT_TRUE(res);
  5080. ASSERT_EQ(StatusCode::OK_200, res->status);
  5081. ASSERT_EQ("content", res->body);
  5082. }
  5083. TEST_F(ServerTest, PatchContentReceiver) {
  5084. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5085. ASSERT_TRUE(res);
  5086. ASSERT_EQ(StatusCode::OK_200, res->status);
  5087. ASSERT_EQ("content", res->body);
  5088. }
  5089. template <typename ClientType>
  5090. void TestWithHeadersAndContentReceiver(
  5091. ClientType &cli,
  5092. std::function<Result(ClientType &, const std::string &, const Headers &,
  5093. const std::string &, const std::string &,
  5094. ContentReceiver, DownloadProgress)>
  5095. request_func) {
  5096. Headers headers;
  5097. headers.emplace("X-Custom-Header", "test-value");
  5098. std::string received_body;
  5099. auto res = request_func(
  5100. cli, "/content_receiver", headers, "content", "application/json",
  5101. [&](const char *data, size_t data_length) {
  5102. received_body.append(data, data_length);
  5103. return true;
  5104. },
  5105. nullptr);
  5106. ASSERT_TRUE(res);
  5107. EXPECT_EQ(StatusCode::OK_200, res->status);
  5108. EXPECT_EQ("content", received_body);
  5109. }
  5110. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5111. #ifdef CPPHTTPLIB_SSL_ENABLED
  5112. using ClientT = SSLClient;
  5113. #else
  5114. using ClientT = Client;
  5115. #endif
  5116. TestWithHeadersAndContentReceiver<ClientT>(
  5117. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5118. const std::string &body, const std::string &content_type,
  5119. ContentReceiver receiver, DownloadProgress progress) {
  5120. return cli.Post(path, headers, body, content_type, receiver, progress);
  5121. });
  5122. }
  5123. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5124. #ifdef CPPHTTPLIB_SSL_ENABLED
  5125. using ClientT = SSLClient;
  5126. #else
  5127. using ClientT = Client;
  5128. #endif
  5129. TestWithHeadersAndContentReceiver<ClientT>(
  5130. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5131. const std::string &body, const std::string &content_type,
  5132. ContentReceiver receiver, DownloadProgress progress) {
  5133. return cli.Put(path, headers, body, content_type, receiver, progress);
  5134. });
  5135. }
  5136. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5137. #ifdef CPPHTTPLIB_SSL_ENABLED
  5138. using ClientT = SSLClient;
  5139. #else
  5140. using ClientT = Client;
  5141. #endif
  5142. TestWithHeadersAndContentReceiver<ClientT>(
  5143. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5144. const std::string &body, const std::string &content_type,
  5145. ContentReceiver receiver, DownloadProgress progress) {
  5146. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5147. });
  5148. }
  5149. template <typename ClientType>
  5150. void TestWithHeadersAndContentReceiverWithProgress(
  5151. ClientType &cli,
  5152. std::function<Result(ClientType &, const std::string &, const Headers &,
  5153. const std::string &, const std::string &,
  5154. ContentReceiver, DownloadProgress)>
  5155. request_func) {
  5156. Headers headers;
  5157. headers.emplace("X-Test-Header", "progress-test");
  5158. std::string received_body;
  5159. auto progress_called = false;
  5160. auto res = request_func(
  5161. cli, "/content_receiver", headers, "content", "text/plain",
  5162. [&](const char *data, size_t data_length) {
  5163. received_body.append(data, data_length);
  5164. return true;
  5165. },
  5166. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5167. progress_called = true;
  5168. return true;
  5169. });
  5170. ASSERT_TRUE(res);
  5171. EXPECT_EQ(StatusCode::OK_200, res->status);
  5172. EXPECT_EQ("content", received_body);
  5173. EXPECT_TRUE(progress_called);
  5174. }
  5175. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5176. #ifdef CPPHTTPLIB_SSL_ENABLED
  5177. using ClientT = SSLClient;
  5178. #else
  5179. using ClientT = Client;
  5180. #endif
  5181. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5182. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5183. const std::string &body, const std::string &content_type,
  5184. ContentReceiver receiver, DownloadProgress progress) {
  5185. return cli.Post(path, headers, body, content_type, receiver, progress);
  5186. });
  5187. }
  5188. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5189. #ifdef CPPHTTPLIB_SSL_ENABLED
  5190. using ClientT = SSLClient;
  5191. #else
  5192. using ClientT = Client;
  5193. #endif
  5194. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5195. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5196. const std::string &body, const std::string &content_type,
  5197. ContentReceiver receiver, DownloadProgress progress) {
  5198. return cli.Put(path, headers, body, content_type, receiver, progress);
  5199. });
  5200. }
  5201. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5202. #ifdef CPPHTTPLIB_SSL_ENABLED
  5203. using ClientT = SSLClient;
  5204. #else
  5205. using ClientT = Client;
  5206. #endif
  5207. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5208. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5209. const std::string &body, const std::string &content_type,
  5210. ContentReceiver receiver, DownloadProgress progress) {
  5211. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5212. });
  5213. }
  5214. template <typename ClientType>
  5215. void TestWithHeadersAndContentReceiverError(
  5216. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5217. const Headers &, const std::string &,
  5218. const std::string &, ContentReceiver)>
  5219. request_func) {
  5220. Headers headers;
  5221. headers.emplace("X-Error-Test", "true");
  5222. std::string received_body;
  5223. auto receiver_failed = false;
  5224. auto res =
  5225. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5226. [&](const char *data, size_t data_length) {
  5227. received_body.append(data, data_length);
  5228. receiver_failed = true;
  5229. return false;
  5230. });
  5231. ASSERT_FALSE(res);
  5232. EXPECT_TRUE(receiver_failed);
  5233. }
  5234. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5235. #ifdef CPPHTTPLIB_SSL_ENABLED
  5236. using ClientT = SSLClient;
  5237. #else
  5238. using ClientT = Client;
  5239. #endif
  5240. TestWithHeadersAndContentReceiverError<ClientT>(
  5241. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5242. const std::string &body, const std::string &content_type,
  5243. ContentReceiver receiver) {
  5244. return cli.Post(path, headers, body, content_type, receiver);
  5245. });
  5246. }
  5247. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5248. #ifdef CPPHTTPLIB_SSL_ENABLED
  5249. using ClientT = SSLClient;
  5250. #else
  5251. using ClientT = Client;
  5252. #endif
  5253. TestWithHeadersAndContentReceiverError<ClientT>(
  5254. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5255. const std::string &body, const std::string &content_type,
  5256. ContentReceiver receiver) {
  5257. return cli.Put(path, headers, body, content_type, receiver);
  5258. });
  5259. }
  5260. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5261. #ifdef CPPHTTPLIB_SSL_ENABLED
  5262. using ClientT = SSLClient;
  5263. #else
  5264. using ClientT = Client;
  5265. #endif
  5266. TestWithHeadersAndContentReceiverError<ClientT>(
  5267. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5268. const std::string &body, const std::string &content_type,
  5269. ContentReceiver receiver) {
  5270. return cli.Patch(path, headers, body, content_type, receiver);
  5271. });
  5272. }
  5273. TEST_F(ServerTest, PostQueryStringAndBody) {
  5274. auto res =
  5275. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5276. ASSERT_TRUE(res);
  5277. ASSERT_EQ(StatusCode::OK_200, res->status);
  5278. }
  5279. TEST_F(ServerTest, HTTP2Magic) {
  5280. Request req;
  5281. req.method = "PRI";
  5282. req.path = "*";
  5283. req.body = "SM";
  5284. auto res = std::make_shared<Response>();
  5285. auto error = Error::Success;
  5286. auto ret = cli_.send(req, *res, error);
  5287. ASSERT_TRUE(ret);
  5288. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5289. }
  5290. TEST_F(ServerTest, KeepAlive) {
  5291. auto res = cli_.Get("/hi");
  5292. ASSERT_TRUE(res);
  5293. EXPECT_EQ(StatusCode::OK_200, res->status);
  5294. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5295. EXPECT_EQ("Hello World!", res->body);
  5296. res = cli_.Get("/hi");
  5297. ASSERT_TRUE(res);
  5298. EXPECT_EQ(StatusCode::OK_200, res->status);
  5299. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5300. EXPECT_EQ("Hello World!", res->body);
  5301. res = cli_.Get("/hi");
  5302. ASSERT_TRUE(res);
  5303. EXPECT_EQ(StatusCode::OK_200, res->status);
  5304. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5305. EXPECT_EQ("Hello World!", res->body);
  5306. res = cli_.Get("/not-exist");
  5307. ASSERT_TRUE(res);
  5308. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5309. res = cli_.Post("/empty", "", "text/plain");
  5310. ASSERT_TRUE(res);
  5311. EXPECT_EQ(StatusCode::OK_200, res->status);
  5312. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5313. EXPECT_EQ("empty", res->body);
  5314. EXPECT_EQ("close", res->get_header_value("Connection"));
  5315. res = cli_.Post(
  5316. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5317. "text/plain");
  5318. ASSERT_TRUE(res);
  5319. EXPECT_EQ(StatusCode::OK_200, res->status);
  5320. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5321. EXPECT_EQ("empty", res->body);
  5322. cli_.set_keep_alive(false);
  5323. res = cli_.Get("/last-request");
  5324. ASSERT_TRUE(res);
  5325. EXPECT_EQ(StatusCode::OK_200, res->status);
  5326. EXPECT_EQ("close", res->get_header_value("Connection"));
  5327. }
  5328. TEST_F(ServerTest, TooManyRedirect) {
  5329. cli_.set_follow_location(true);
  5330. auto res = cli_.Get("/redirect/0");
  5331. ASSERT_TRUE(!res);
  5332. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5333. }
  5334. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5335. Request req;
  5336. req.method = "FOOBAR";
  5337. req.path = "/hi";
  5338. cli_.set_keep_alive(true);
  5339. auto res = cli_.send(req);
  5340. ASSERT_TRUE(res);
  5341. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5342. EXPECT_EQ("close", res->get_header_value("Connection"));
  5343. EXPECT_FALSE(cli_.is_socket_open());
  5344. }
  5345. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5346. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5347. TEST_F(ServerTest, Gzip) {
  5348. Headers headers;
  5349. headers.emplace("Accept-Encoding", "gzip, deflate");
  5350. auto res = cli_.Get("/compress", headers);
  5351. ASSERT_TRUE(res);
  5352. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5353. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5354. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5355. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5356. "7890123456789012345678901234567890",
  5357. res->body);
  5358. EXPECT_EQ(StatusCode::OK_200, res->status);
  5359. }
  5360. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5361. Headers headers;
  5362. headers.emplace("Accept-Encoding", "gzip, deflate");
  5363. auto res = cli_.Get("/compress-with-charset", headers);
  5364. ASSERT_TRUE(res);
  5365. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5366. EXPECT_EQ("application/json; charset=utf-8",
  5367. res->get_header_value("Content-Type"));
  5368. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5369. "7890123456789012345678901234567890",
  5370. res->body);
  5371. EXPECT_EQ(StatusCode::OK_200, res->status);
  5372. }
  5373. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5374. Headers headers;
  5375. headers.emplace("Accept-Encoding", "");
  5376. auto res = cli_.Get("/compress", headers);
  5377. ASSERT_TRUE(res);
  5378. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5379. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5380. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5381. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5382. "7890123456789012345678901234567890",
  5383. res->body);
  5384. EXPECT_EQ(StatusCode::OK_200, res->status);
  5385. }
  5386. TEST_F(ServerTest, GzipWithContentReceiver) {
  5387. Headers headers;
  5388. headers.emplace("Accept-Encoding", "gzip, deflate");
  5389. std::string body;
  5390. auto res = cli_.Get("/compress", headers,
  5391. [&](const char *data, uint64_t data_length) {
  5392. EXPECT_EQ(100U, data_length);
  5393. body.append(data, data_length);
  5394. return true;
  5395. });
  5396. ASSERT_TRUE(res);
  5397. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5398. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5399. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5400. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5401. "7890123456789012345678901234567890",
  5402. body);
  5403. EXPECT_EQ(StatusCode::OK_200, res->status);
  5404. }
  5405. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5406. Headers headers;
  5407. headers.emplace("Accept-Encoding", "gzip, deflate");
  5408. cli_.set_decompress(false);
  5409. auto res = cli_.Get("/compress", headers);
  5410. ASSERT_TRUE(res);
  5411. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5412. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5413. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5414. EXPECT_EQ(33U, res->body.size());
  5415. EXPECT_EQ(StatusCode::OK_200, res->status);
  5416. }
  5417. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5418. Headers headers;
  5419. headers.emplace("Accept-Encoding", "");
  5420. std::string body;
  5421. auto res = cli_.Get("/compress", headers,
  5422. [&](const char *data, uint64_t data_length) {
  5423. EXPECT_EQ(100U, data_length);
  5424. body.append(data, data_length);
  5425. return true;
  5426. });
  5427. ASSERT_TRUE(res);
  5428. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5429. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5430. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5431. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5432. "7890123456789012345678901234567890",
  5433. body);
  5434. EXPECT_EQ(StatusCode::OK_200, res->status);
  5435. }
  5436. TEST_F(ServerTest, NoGzip) {
  5437. Headers headers;
  5438. headers.emplace("Accept-Encoding", "gzip, deflate");
  5439. auto res = cli_.Get("/nocompress", headers);
  5440. ASSERT_TRUE(res);
  5441. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5442. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5443. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5444. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5445. "7890123456789012345678901234567890",
  5446. res->body);
  5447. EXPECT_EQ(StatusCode::OK_200, res->status);
  5448. }
  5449. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5450. Headers headers;
  5451. headers.emplace("Accept-Encoding", "gzip, deflate");
  5452. std::string body;
  5453. auto res = cli_.Get("/nocompress", headers,
  5454. [&](const char *data, uint64_t data_length) {
  5455. EXPECT_EQ(100U, data_length);
  5456. body.append(data, data_length);
  5457. return true;
  5458. });
  5459. ASSERT_TRUE(res);
  5460. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5461. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5462. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5463. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5464. "7890123456789012345678901234567890",
  5465. body);
  5466. EXPECT_EQ(StatusCode::OK_200, res->status);
  5467. }
  5468. TEST_F(ServerTest, MultipartFormDataGzip) {
  5469. UploadFormDataItems items = {
  5470. {"key1", "test", "", ""},
  5471. {"key2", "--abcdefg123", "", ""},
  5472. };
  5473. cli_.set_compress(true);
  5474. auto res = cli_.Post("/compress-multipart", items);
  5475. ASSERT_TRUE(res);
  5476. EXPECT_EQ(StatusCode::OK_200, res->status);
  5477. }
  5478. #endif
  5479. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5480. TEST_F(ServerTest, Brotli) {
  5481. Headers headers;
  5482. headers.emplace("Accept-Encoding", "br");
  5483. auto res = cli_.Get("/compress", headers);
  5484. ASSERT_TRUE(res);
  5485. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5486. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5487. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5488. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5489. "7890123456789012345678901234567890",
  5490. res->body);
  5491. EXPECT_EQ(StatusCode::OK_200, res->status);
  5492. }
  5493. #endif
  5494. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5495. TEST_F(ServerTest, Zstd) {
  5496. Headers headers;
  5497. headers.emplace("Accept-Encoding", "zstd");
  5498. auto res = cli_.Get("/compress", headers);
  5499. ASSERT_TRUE(res);
  5500. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5501. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5502. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5503. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5504. "7890123456789012345678901234567890",
  5505. res->body);
  5506. EXPECT_EQ(StatusCode::OK_200, res->status);
  5507. }
  5508. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5509. Headers headers;
  5510. headers.emplace("Accept-Encoding", "");
  5511. auto res = cli_.Get("/compress", headers);
  5512. ASSERT_TRUE(res);
  5513. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5514. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5515. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5516. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5517. "7890123456789012345678901234567890",
  5518. res->body);
  5519. EXPECT_EQ(StatusCode::OK_200, res->status);
  5520. }
  5521. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5522. Headers headers;
  5523. headers.emplace("Accept-Encoding", "zstd");
  5524. std::string body;
  5525. auto res = cli_.Get("/compress", headers,
  5526. [&](const char *data, uint64_t data_length) {
  5527. EXPECT_EQ(100U, data_length);
  5528. body.append(data, data_length);
  5529. return true;
  5530. });
  5531. ASSERT_TRUE(res);
  5532. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5533. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5534. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5535. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5536. "7890123456789012345678901234567890",
  5537. body);
  5538. EXPECT_EQ(StatusCode::OK_200, res->status);
  5539. }
  5540. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5541. Headers headers;
  5542. headers.emplace("Accept-Encoding", "zstd");
  5543. cli_.set_decompress(false);
  5544. auto res = cli_.Get("/compress", headers);
  5545. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5546. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5547. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5548. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5549. ASSERT_TRUE(res);
  5550. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5551. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5552. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5553. EXPECT_EQ(StatusCode::OK_200, res->status);
  5554. ASSERT_EQ(26U, res->body.size());
  5555. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5556. 0);
  5557. }
  5558. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5559. Headers headers;
  5560. headers.emplace("Accept-Encoding", "");
  5561. std::string body;
  5562. auto res = cli_.Get("/compress", headers,
  5563. [&](const char *data, uint64_t data_length) {
  5564. EXPECT_EQ(100U, data_length);
  5565. body.append(data, data_length);
  5566. return true;
  5567. });
  5568. ASSERT_TRUE(res);
  5569. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5570. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5571. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5572. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5573. "7890123456789012345678901234567890",
  5574. body);
  5575. EXPECT_EQ(StatusCode::OK_200, res->status);
  5576. }
  5577. TEST_F(ServerTest, NoZstd) {
  5578. Headers headers;
  5579. headers.emplace("Accept-Encoding", "zstd");
  5580. auto res = cli_.Get("/nocompress", headers);
  5581. ASSERT_TRUE(res);
  5582. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5583. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5584. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5585. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5586. "7890123456789012345678901234567890",
  5587. res->body);
  5588. EXPECT_EQ(StatusCode::OK_200, res->status);
  5589. }
  5590. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5591. Headers headers;
  5592. headers.emplace("Accept-Encoding", "zstd");
  5593. std::string body;
  5594. auto res = cli_.Get("/nocompress", headers,
  5595. [&](const char *data, uint64_t data_length) {
  5596. EXPECT_EQ(100U, data_length);
  5597. body.append(data, data_length);
  5598. return true;
  5599. });
  5600. ASSERT_TRUE(res);
  5601. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5602. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5603. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5604. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5605. "7890123456789012345678901234567890",
  5606. body);
  5607. EXPECT_EQ(StatusCode::OK_200, res->status);
  5608. }
  5609. // TODO: How to enable zstd ??
  5610. TEST_F(ServerTest, MultipartFormDataZstd) {
  5611. UploadFormDataItems items = {
  5612. {"key1", "test", "", ""},
  5613. {"key2", "--abcdefg123", "", ""},
  5614. };
  5615. Headers headers;
  5616. headers.emplace("Accept-Encoding", "zstd");
  5617. cli_.set_compress(true);
  5618. auto res = cli_.Post("/compress-multipart", headers, items);
  5619. ASSERT_TRUE(res);
  5620. EXPECT_EQ(StatusCode::OK_200, res->status);
  5621. }
  5622. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5623. Headers headers;
  5624. headers.emplace("Accept-Encoding", "zstd");
  5625. cli_.set_compress(true);
  5626. auto res = cli_.Put(
  5627. "/put", headers, 3,
  5628. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5629. sink.os << "PUT";
  5630. return true;
  5631. },
  5632. "text/plain");
  5633. ASSERT_TRUE(res);
  5634. EXPECT_EQ(StatusCode::OK_200, res->status);
  5635. EXPECT_EQ("PUT", res->body);
  5636. }
  5637. // Pre-compression logging tests
  5638. TEST_F(ServerTest, PreCompressionLogging) {
  5639. // Test data for compression (matches the actual /compress endpoint content)
  5640. const std::string test_content =
  5641. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5642. "3456789012345678901234567890";
  5643. // Variables to capture logging data
  5644. std::string pre_compression_body;
  5645. std::string pre_compression_content_type;
  5646. std::string pre_compression_content_encoding;
  5647. std::string post_compression_body;
  5648. std::string post_compression_content_type;
  5649. std::string post_compression_content_encoding;
  5650. // Set up pre-compression logger
  5651. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5652. const Response &res) {
  5653. pre_compression_body = res.body;
  5654. pre_compression_content_type = res.get_header_value("Content-Type");
  5655. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5656. });
  5657. // Set up post-compression logger
  5658. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5659. post_compression_body = res.body;
  5660. post_compression_content_type = res.get_header_value("Content-Type");
  5661. post_compression_content_encoding =
  5662. res.get_header_value("Content-Encoding");
  5663. });
  5664. // Test with gzip compression
  5665. Headers headers;
  5666. headers.emplace("Accept-Encoding", "gzip");
  5667. auto res = cli_.Get("/compress", headers);
  5668. // Verify response was compressed
  5669. ASSERT_TRUE(res);
  5670. EXPECT_EQ(StatusCode::OK_200, res->status);
  5671. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5672. // Verify pre-compression logger captured uncompressed content
  5673. EXPECT_EQ(test_content, pre_compression_body);
  5674. EXPECT_EQ("text/plain", pre_compression_content_type);
  5675. EXPECT_TRUE(pre_compression_content_encoding
  5676. .empty()); // No encoding header before compression
  5677. // Verify post-compression logger captured compressed content
  5678. EXPECT_NE(test_content,
  5679. post_compression_body); // Should be different after compression
  5680. EXPECT_EQ("text/plain", post_compression_content_type);
  5681. EXPECT_EQ("gzip", post_compression_content_encoding);
  5682. // Verify compressed content is smaller
  5683. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5684. }
  5685. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5686. const std::string test_content =
  5687. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5688. "3456789012345678901234567890";
  5689. std::string pre_compression_body;
  5690. std::string post_compression_body;
  5691. svr_.set_pre_compression_logger(
  5692. [&](const Request & /*req*/, const Response &res) {
  5693. pre_compression_body = res.body;
  5694. });
  5695. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5696. post_compression_body = res.body;
  5697. });
  5698. Headers headers;
  5699. headers.emplace("Accept-Encoding", "br");
  5700. auto res = cli_.Get("/compress", headers);
  5701. ASSERT_TRUE(res);
  5702. EXPECT_EQ(StatusCode::OK_200, res->status);
  5703. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5704. // Verify pre-compression content is uncompressed
  5705. EXPECT_EQ(test_content, pre_compression_body);
  5706. // Verify post-compression content is compressed
  5707. EXPECT_NE(test_content, post_compression_body);
  5708. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5709. }
  5710. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5711. const std::string test_content =
  5712. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5713. "3456789012345678901234567890";
  5714. std::string pre_compression_body;
  5715. std::string post_compression_body;
  5716. svr_.set_pre_compression_logger(
  5717. [&](const Request & /*req*/, const Response &res) {
  5718. pre_compression_body = res.body;
  5719. });
  5720. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5721. post_compression_body = res.body;
  5722. });
  5723. // Request without compression (use /nocompress endpoint)
  5724. Headers headers;
  5725. auto res = cli_.Get("/nocompress", headers);
  5726. ASSERT_TRUE(res);
  5727. EXPECT_EQ(StatusCode::OK_200, res->status);
  5728. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5729. // Pre-compression logger should not be called when no compression is applied
  5730. EXPECT_TRUE(
  5731. pre_compression_body.empty()); // Pre-compression logger not called
  5732. EXPECT_EQ(
  5733. test_content,
  5734. post_compression_body); // Post-compression logger captures final content
  5735. }
  5736. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5737. const std::string test_content =
  5738. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5739. "3456789012345678901234567890";
  5740. std::string pre_compression_body;
  5741. bool pre_logger_called = false;
  5742. // Set only pre-compression logger
  5743. svr_.set_pre_compression_logger(
  5744. [&](const Request & /*req*/, const Response &res) {
  5745. pre_compression_body = res.body;
  5746. pre_logger_called = true;
  5747. });
  5748. Headers headers;
  5749. headers.emplace("Accept-Encoding", "gzip");
  5750. auto res = cli_.Get("/compress", headers);
  5751. ASSERT_TRUE(res);
  5752. EXPECT_EQ(StatusCode::OK_200, res->status);
  5753. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5754. // Verify pre-compression logger was called
  5755. EXPECT_TRUE(pre_logger_called);
  5756. EXPECT_EQ(test_content, pre_compression_body);
  5757. }
  5758. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5759. {
  5760. // Test with Expect: 100-continue header - success case
  5761. // Server returns 100 Continue, client sends body, server returns 200 OK
  5762. Request req;
  5763. req.method = "POST";
  5764. req.path = "/post-large";
  5765. req.set_header("Expect", "100-continue");
  5766. req.body = LARGE_DATA;
  5767. Response res;
  5768. auto error = Error::Success;
  5769. cli_.set_keep_alive(true);
  5770. auto ret = cli_.send(req, res, error);
  5771. EXPECT_TRUE(ret);
  5772. EXPECT_EQ(StatusCode::OK_200, res.status);
  5773. EXPECT_EQ(LARGE_DATA, res.body);
  5774. }
  5775. {
  5776. // Test with Expect: 100-continue header - error case
  5777. // Client should not send the body when server returns an error
  5778. Request req;
  5779. req.method = "POST";
  5780. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5781. req.set_header("Expect", "100-continue");
  5782. req.body = LARGE_DATA;
  5783. Response res;
  5784. auto error = Error::Success;
  5785. auto start = std::chrono::high_resolution_clock::now();
  5786. cli_.set_keep_alive(true);
  5787. auto ret = cli_.send(req, res, error);
  5788. auto end = std::chrono::high_resolution_clock::now();
  5789. auto elapsed =
  5790. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5791. .count();
  5792. // With Expect: 100-continue, request completes successfully but with error
  5793. EXPECT_TRUE(ret);
  5794. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5795. EXPECT_EQ("close", res.get_header_value("Connection"));
  5796. EXPECT_FALSE(cli_.is_socket_open());
  5797. EXPECT_LE(elapsed, 200);
  5798. }
  5799. {
  5800. // Send an extra GET request to ensure error recovery without hanging
  5801. Request req;
  5802. req.method = "GET";
  5803. req.path = "/hi";
  5804. auto start = std::chrono::high_resolution_clock::now();
  5805. auto res = cli_.send(req);
  5806. auto end = std::chrono::high_resolution_clock::now();
  5807. auto elapsed =
  5808. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5809. .count();
  5810. ASSERT_TRUE(res);
  5811. EXPECT_EQ(StatusCode::OK_200, res->status);
  5812. EXPECT_EQ("Hello World!", res->body);
  5813. EXPECT_LE(elapsed, 500);
  5814. }
  5815. }
  5816. TEST(ZstdDecompressor, ChunkedDecompression) {
  5817. std::string data;
  5818. for (size_t i = 0; i < 32 * 1024; ++i) {
  5819. data.push_back(static_cast<char>('a' + i % 26));
  5820. }
  5821. std::string compressed_data;
  5822. {
  5823. httplib::detail::zstd_compressor compressor;
  5824. bool result = compressor.compress(
  5825. data.data(), data.size(),
  5826. /*last=*/true,
  5827. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5828. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5829. compressed_data_size);
  5830. return true;
  5831. });
  5832. ASSERT_TRUE(result);
  5833. }
  5834. std::string decompressed_data;
  5835. {
  5836. httplib::detail::zstd_decompressor decompressor;
  5837. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5838. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5839. size_t chunk_size = 130;
  5840. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5841. chunk_begin += chunk_size) {
  5842. size_t current_chunk_size =
  5843. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5844. bool result = decompressor.decompress(
  5845. compressed_data.data() + chunk_begin, current_chunk_size,
  5846. [&](const char *decompressed_data_chunk,
  5847. size_t decompressed_data_chunk_size) {
  5848. decompressed_data.insert(decompressed_data.size(),
  5849. decompressed_data_chunk,
  5850. decompressed_data_chunk_size);
  5851. return true;
  5852. });
  5853. ASSERT_TRUE(result);
  5854. }
  5855. }
  5856. ASSERT_EQ(data, decompressed_data);
  5857. }
  5858. TEST(ZstdDecompressor, Decompress) {
  5859. std::string original_text = "Compressed with ZSTD";
  5860. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5861. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5862. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5863. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5864. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5865. std::string decompressed_data;
  5866. {
  5867. httplib::detail::zstd_decompressor decompressor;
  5868. bool result = decompressor.decompress(
  5869. compressed_data.data(), compressed_data.size(),
  5870. [&](const char *decompressed_data_chunk,
  5871. size_t decompressed_data_chunk_size) {
  5872. decompressed_data.insert(decompressed_data.size(),
  5873. decompressed_data_chunk,
  5874. decompressed_data_chunk_size);
  5875. return true;
  5876. });
  5877. ASSERT_TRUE(result);
  5878. }
  5879. ASSERT_EQ(original_text, decompressed_data);
  5880. }
  5881. #endif
  5882. // Sends a raw request to a server listening at HOST:PORT.
  5883. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5884. std::string *resp = nullptr) {
  5885. auto error = Error::Success;
  5886. auto client_sock = detail::create_client_socket(
  5887. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5888. /*connection_timeout_sec=*/5, 0,
  5889. /*read_timeout_sec=*/5, 0,
  5890. /*write_timeout_sec=*/5, 0, std::string(), error);
  5891. if (client_sock == INVALID_SOCKET) { return false; }
  5892. auto ret = detail::process_client_socket(
  5893. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5894. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5895. if (req.size() !=
  5896. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5897. return false;
  5898. }
  5899. char buf[512];
  5900. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5901. while (line_reader.getline()) {
  5902. if (resp) { *resp += line_reader.ptr(); }
  5903. }
  5904. return true;
  5905. });
  5906. detail::close_socket(client_sock);
  5907. return ret;
  5908. }
  5909. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5910. Server svr;
  5911. std::string header_value;
  5912. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5913. header_value = req.get_header_value("foo");
  5914. res.set_content("ok", "text/plain");
  5915. });
  5916. thread t = thread([&] { svr.listen(HOST, PORT); });
  5917. auto se = detail::scope_exit([&] {
  5918. svr.stop();
  5919. t.join();
  5920. ASSERT_FALSE(svr.is_running());
  5921. });
  5922. svr.wait_until_ready();
  5923. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5924. // like characters are not treated the same - use vertical tab and escape.
  5925. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5926. "foo: \t \v bar \x1B\t \r\n"
  5927. "Connection: close\r\n"
  5928. "\r\n";
  5929. std::string res;
  5930. ASSERT_TRUE(send_request(5, req, &res));
  5931. EXPECT_EQ(header_value, "");
  5932. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5933. }
  5934. // Sends a raw request and verifies that there isn't a crash or exception.
  5935. static void test_raw_request(const std::string &req,
  5936. std::string *out = nullptr) {
  5937. Server svr;
  5938. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5939. res.set_content("ok", "text/plain");
  5940. });
  5941. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5942. res.set_content("ok", "text/plain");
  5943. });
  5944. svr.Get("/header_field_value_check",
  5945. [&](const Request & /*req*/, Response &res) {
  5946. res.set_content("ok", "text/plain");
  5947. });
  5948. // Server read timeout must be longer than the client read timeout for the
  5949. // bug to reproduce, probably to force the server to process a request
  5950. // without a trailing blank line.
  5951. const time_t client_read_timeout_sec = 1;
  5952. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5953. bool listen_thread_ok = false;
  5954. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5955. auto se = detail::scope_exit([&] {
  5956. svr.stop();
  5957. t.join();
  5958. ASSERT_FALSE(svr.is_running());
  5959. EXPECT_TRUE(listen_thread_ok);
  5960. });
  5961. svr.wait_until_ready();
  5962. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5963. }
  5964. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5965. // A certain header line causes an exception if the header property is parsed
  5966. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5967. test_raw_request(
  5968. "GET /hi HTTP/1.1\r\n"
  5969. " : "
  5970. " "
  5971. " ");
  5972. }
  5973. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5974. // A certain header line causes an exception if the header property *name* is
  5975. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5976. // greedy matcher and requires backtracking when there are a lot of ":"
  5977. // characters.
  5978. // This occurs with libc++ but not libstdc++.
  5979. test_raw_request(
  5980. "GET /hi HTTP/1.1\r\n"
  5981. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5982. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5983. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5984. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5985. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5986. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5987. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5988. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5989. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5990. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5991. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5992. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5993. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5994. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5995. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5996. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5997. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5998. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5999. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6000. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6001. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6002. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6003. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6004. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6005. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6006. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6007. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6008. "&&&%%%");
  6009. }
  6010. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6011. // Make sure this doesn't crash the server.
  6012. // In a previous version of the header line regex, the "\r" rendered the line
  6013. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6014. // a new position where the leading white space ended and the field value
  6015. // began.
  6016. // The crash occurs with libc++ but not libstdc++.
  6017. test_raw_request("GET /hi HTTP/1.1\r\n"
  6018. "a:" +
  6019. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6020. "\r\n"
  6021. "\r\n");
  6022. }
  6023. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6024. std::string out;
  6025. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6026. "Content-Type: text/plain\r\n"
  6027. "Transfer-Encoding: chunked\r\n"
  6028. "\r\n"
  6029. "nothex\r\n",
  6030. &out);
  6031. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6032. }
  6033. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6034. std::string out;
  6035. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6036. "Content-Type: text/plain\r\n"
  6037. "Transfer-Encoding: chunked\r\n"
  6038. "\r\n"
  6039. "3\r\n"
  6040. "xyz\r\n"
  6041. "NaN\r\n",
  6042. &out);
  6043. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6044. }
  6045. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6046. std::string out;
  6047. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6048. "Content-Type: text/plain\r\n"
  6049. "Transfer-Encoding: chunked\r\n"
  6050. "\r\n"
  6051. // Length is too large for 64 bits.
  6052. "1ffffffffffffffff\r\n"
  6053. "xyz\r\n",
  6054. &out);
  6055. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6056. }
  6057. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6058. test_raw_request("GET /hi HTTP/1.1\r\n"
  6059. "Content-Type: text/plain\r\n\r");
  6060. }
  6061. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6062. std::string out;
  6063. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6064. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6065. }
  6066. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6067. Server svr;
  6068. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6069. EXPECT_TRUE(!req.remote_addr.empty());
  6070. });
  6071. thread t = thread([&] { svr.listen(HOST, PORT); });
  6072. auto se = detail::scope_exit([&] {
  6073. svr.stop();
  6074. t.join();
  6075. ASSERT_FALSE(svr.is_running());
  6076. });
  6077. svr.wait_until_ready();
  6078. // Send an invalid request line to trigger Bad Request
  6079. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6080. std::string out;
  6081. ASSERT_TRUE(send_request(5, bad_req, &out));
  6082. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6083. }
  6084. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6085. std::string out;
  6086. std::string request(
  6087. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6088. test_raw_request(request, &out);
  6089. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6090. }
  6091. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6092. std::string out;
  6093. std::string request(
  6094. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6095. test_raw_request(request, &out);
  6096. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6097. }
  6098. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6099. std::string out;
  6100. std::string request(
  6101. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6102. test_raw_request(request, &out);
  6103. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6104. }
  6105. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6106. std::string out;
  6107. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6108. "Test: \r\n\r\n",
  6109. &out);
  6110. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6111. }
  6112. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6113. Server svr;
  6114. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6115. res.set_header("Cache-Control", "no-cache");
  6116. res.set_chunked_content_provider(
  6117. "text/event-stream", [](size_t offset, DataSink &sink) {
  6118. std::string s = "data:";
  6119. s += std::to_string(offset);
  6120. s += "\n\n";
  6121. auto ret = sink.write(s.data(), s.size());
  6122. EXPECT_TRUE(ret);
  6123. std::this_thread::sleep_for(std::chrono::seconds(1));
  6124. return true;
  6125. });
  6126. });
  6127. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6128. svr.wait_until_ready();
  6129. Client client(HOST, PORT);
  6130. const Headers headers = {{"Accept", "text/event-stream"}};
  6131. auto get_thread = std::thread([&client, &headers]() {
  6132. auto res = client.Get(
  6133. "/events", headers,
  6134. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6135. });
  6136. auto se = detail::scope_exit([&] {
  6137. svr.stop();
  6138. get_thread.join();
  6139. listen_thread.join();
  6140. ASSERT_FALSE(svr.is_running());
  6141. });
  6142. // Give GET time to get a few messages.
  6143. std::this_thread::sleep_for(std::chrono::seconds(2));
  6144. }
  6145. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6146. httplib::Server svr;
  6147. svr.Post("/hi",
  6148. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6149. res.status = StatusCode::OK_200;
  6150. });
  6151. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6152. svr.wait_until_ready();
  6153. Client cli(HOST, PORT);
  6154. auto res = cli.Post("/hi", "data", "text/plain");
  6155. ASSERT_TRUE(res);
  6156. EXPECT_EQ(StatusCode::OK_200, res->status);
  6157. svr.stop();
  6158. thread.join();
  6159. ASSERT_FALSE(svr.is_running());
  6160. res = cli.Post("/hi", "data", "text/plain");
  6161. ASSERT_FALSE(res);
  6162. }
  6163. TEST(ServerStopTest, ListenFailure) {
  6164. Server svr;
  6165. auto t = thread([&]() {
  6166. auto ret = svr.listen("????", PORT);
  6167. EXPECT_FALSE(ret);
  6168. });
  6169. svr.wait_until_ready();
  6170. svr.stop();
  6171. t.join();
  6172. }
  6173. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6174. TEST(ServerStopTest, Decommision) {
  6175. Server svr;
  6176. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6177. for (int i = 0; i < 4; i++) {
  6178. auto is_even = !(i % 2);
  6179. std::thread t{[&] {
  6180. try {
  6181. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6182. if (is_even) {
  6183. throw std::runtime_error("Some thing that happens to go wrong.");
  6184. }
  6185. svr.listen(HOST, PORT);
  6186. } catch (...) { svr.decommission(); }
  6187. }};
  6188. svr.wait_until_ready();
  6189. // Server is up
  6190. {
  6191. Client cli(HOST, PORT);
  6192. auto res = cli.Get("/hi");
  6193. if (is_even) {
  6194. EXPECT_FALSE(res);
  6195. } else {
  6196. EXPECT_TRUE(res);
  6197. EXPECT_EQ("hi...", res->body);
  6198. }
  6199. }
  6200. svr.stop();
  6201. t.join();
  6202. // Server is down...
  6203. {
  6204. Client cli(HOST, PORT);
  6205. auto res = cli.Get("/hi");
  6206. EXPECT_FALSE(res);
  6207. }
  6208. }
  6209. }
  6210. #endif
  6211. // Helper function for string body upload progress tests
  6212. template <typename SetupHandler, typename ClientCall>
  6213. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6214. ClientCall &&client_call,
  6215. const string &body) {
  6216. Server svr;
  6217. setup_handler(svr);
  6218. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6219. auto se = detail::scope_exit([&] {
  6220. svr.stop();
  6221. t.join();
  6222. });
  6223. svr.wait_until_ready();
  6224. Client cli(HOST, PORT);
  6225. vector<uint64_t> progress_values;
  6226. bool progress_called = false;
  6227. auto res =
  6228. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6229. progress_values.push_back(current);
  6230. progress_called = true;
  6231. return true;
  6232. });
  6233. ASSERT_TRUE(res);
  6234. EXPECT_EQ(200, res->status);
  6235. EXPECT_TRUE(progress_called);
  6236. }
  6237. TEST(UploadProgressTest, PostStringBodyBasic) {
  6238. TestStringBodyUploadProgress(
  6239. [](Server &svr) {
  6240. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6241. res.set_content("received", "text/plain");
  6242. });
  6243. },
  6244. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6245. return cli.Post("/test", body, "text/plain", progress_callback);
  6246. },
  6247. "test data for upload progress");
  6248. }
  6249. TEST(UploadProgressTest, PutStringBodyBasic) {
  6250. TestStringBodyUploadProgress(
  6251. [](Server &svr) {
  6252. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6253. res.set_content("put received", "text/plain");
  6254. });
  6255. },
  6256. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6257. return cli.Put("/test", body, "text/plain", progress_callback);
  6258. },
  6259. "put test data for upload progress");
  6260. }
  6261. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6262. TestStringBodyUploadProgress(
  6263. [](Server &svr) {
  6264. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6265. res.set_content("patch received", "text/plain");
  6266. });
  6267. },
  6268. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6269. return cli.Patch("/test", body, "text/plain", progress_callback);
  6270. },
  6271. "patch test data for upload progress");
  6272. }
  6273. // Helper function for content provider upload progress tests
  6274. template <typename SetupHandler, typename ClientCall>
  6275. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6276. ClientCall &&client_call) {
  6277. Server svr;
  6278. setup_handler(svr);
  6279. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6280. auto se = detail::scope_exit([&] {
  6281. svr.stop();
  6282. t.join();
  6283. });
  6284. svr.wait_until_ready();
  6285. Client cli(HOST, PORT);
  6286. vector<uint64_t> progress_values;
  6287. auto res =
  6288. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6289. progress_values.push_back(current);
  6290. return true;
  6291. });
  6292. ASSERT_TRUE(res);
  6293. EXPECT_EQ(200, res->status);
  6294. EXPECT_FALSE(progress_values.empty());
  6295. }
  6296. TEST(UploadProgressTest, PostContentProviderProgress) {
  6297. TestContentProviderUploadProgress(
  6298. [](Server &svr) {
  6299. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6300. res.set_content("provider received", "text/plain");
  6301. });
  6302. },
  6303. [](Client &cli, UploadProgress progress_callback) {
  6304. return cli.Post(
  6305. "/test", 10,
  6306. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6307. sink.os << "test data";
  6308. return true;
  6309. },
  6310. "text/plain", progress_callback);
  6311. });
  6312. }
  6313. // Helper function for multipart upload progress tests
  6314. template <typename SetupHandler, typename ClientCall>
  6315. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6316. ClientCall &&client_call,
  6317. const string &endpoint) {
  6318. Server svr;
  6319. setup_handler(svr);
  6320. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6321. auto se = detail::scope_exit([&] {
  6322. svr.stop();
  6323. t.join();
  6324. });
  6325. svr.wait_until_ready();
  6326. Client cli(HOST, PORT);
  6327. vector<uint64_t> progress_values;
  6328. UploadFormDataItems items = {
  6329. {"field1", "value1", "", ""},
  6330. {"field2", "longer value for progress tracking test", "", ""},
  6331. {"file1", "file content data for upload progress", "test.txt",
  6332. "text/plain"}};
  6333. auto res = client_call(cli, endpoint, items,
  6334. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6335. progress_values.push_back(current);
  6336. return true;
  6337. });
  6338. ASSERT_TRUE(res);
  6339. EXPECT_EQ(200, res->status);
  6340. EXPECT_FALSE(progress_values.empty());
  6341. }
  6342. TEST(UploadProgressTest, PostMultipartProgress) {
  6343. TestMultipartUploadProgress(
  6344. [](Server &svr) {
  6345. svr.Post("/multipart", [](const Request &req, Response &res) {
  6346. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6347. res.set_content("multipart received", "text/plain");
  6348. });
  6349. },
  6350. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6351. UploadProgress progress_callback) {
  6352. return cli.Post(endpoint, items, progress_callback);
  6353. },
  6354. "/multipart");
  6355. }
  6356. // Helper function for basic download progress tests
  6357. template <typename SetupHandler, typename ClientCall>
  6358. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6359. ClientCall &&client_call, const string &endpoint,
  6360. size_t expected_content_size) {
  6361. Server svr;
  6362. setup_handler(svr);
  6363. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6364. auto se = detail::scope_exit([&] {
  6365. svr.stop();
  6366. t.join();
  6367. });
  6368. svr.wait_until_ready();
  6369. Client cli(HOST, PORT);
  6370. vector<uint64_t> progress_values;
  6371. auto res = client_call(cli, endpoint,
  6372. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6373. progress_values.push_back(current);
  6374. return true;
  6375. });
  6376. ASSERT_TRUE(res);
  6377. EXPECT_EQ(200, res->status);
  6378. EXPECT_FALSE(progress_values.empty());
  6379. EXPECT_EQ(expected_content_size, res->body.size());
  6380. }
  6381. TEST(DownloadProgressTest, GetBasic) {
  6382. TestBasicDownloadProgress(
  6383. [](Server &svr) {
  6384. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6385. string content(1000, 'D');
  6386. res.set_content(content, "text/plain");
  6387. });
  6388. },
  6389. [](Client &cli, const string &endpoint,
  6390. DownloadProgress progress_callback) {
  6391. return cli.Get(endpoint, progress_callback);
  6392. },
  6393. "/download", 1000u);
  6394. }
  6395. // Helper function for content receiver download progress tests
  6396. template <typename SetupHandler, typename ClientCall>
  6397. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6398. ClientCall &&client_call,
  6399. const string &endpoint,
  6400. size_t expected_content_size) {
  6401. Server svr;
  6402. setup_handler(svr);
  6403. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6404. auto se = detail::scope_exit([&] {
  6405. svr.stop();
  6406. t.join();
  6407. });
  6408. svr.wait_until_ready();
  6409. Client cli(HOST, PORT);
  6410. vector<uint64_t> progress_values;
  6411. string received_body;
  6412. auto res = client_call(
  6413. cli, endpoint,
  6414. [&](const char *data, size_t data_length) -> bool {
  6415. received_body.append(data, data_length);
  6416. return true;
  6417. },
  6418. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6419. progress_values.push_back(current);
  6420. return true;
  6421. });
  6422. ASSERT_TRUE(res);
  6423. EXPECT_EQ(200, res->status);
  6424. EXPECT_FALSE(progress_values.empty());
  6425. EXPECT_EQ(expected_content_size, received_body.size());
  6426. EXPECT_TRUE(res->body.empty());
  6427. }
  6428. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6429. TestContentReceiverDownloadProgress(
  6430. [](Server &svr) {
  6431. svr.Get("/download-receiver",
  6432. [](const Request & /*req*/, Response &res) {
  6433. string content(2000, 'R');
  6434. res.set_content(content, "text/plain");
  6435. });
  6436. },
  6437. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6438. DownloadProgress progress_callback) {
  6439. return cli.Get(endpoint, content_receiver, progress_callback);
  6440. },
  6441. "/download-receiver", 2000u);
  6442. }
  6443. TEST(StreamingTest, NoContentLengthStreaming) {
  6444. Server svr;
  6445. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6446. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6447. if (offset < 6) {
  6448. sink.os << (offset < 3 ? "a" : "b");
  6449. } else {
  6450. sink.done();
  6451. }
  6452. return true;
  6453. });
  6454. });
  6455. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6456. auto listen_se = detail::scope_exit([&] {
  6457. svr.stop();
  6458. listen_thread.join();
  6459. ASSERT_FALSE(svr.is_running());
  6460. });
  6461. svr.wait_until_ready();
  6462. Client client(HOST, PORT);
  6463. auto get_thread = std::thread([&client]() {
  6464. std::string s;
  6465. auto res =
  6466. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6467. s += std::string(data, len);
  6468. return true;
  6469. });
  6470. ASSERT_TRUE(res);
  6471. EXPECT_EQ(StatusCode::OK_200, res->status);
  6472. EXPECT_EQ("aaabbb", s);
  6473. });
  6474. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6475. // Give GET time to get a few messages.
  6476. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6477. }
  6478. TEST(MountTest, Unmount) {
  6479. Server svr;
  6480. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6481. auto se = detail::scope_exit([&] {
  6482. svr.stop();
  6483. listen_thread.join();
  6484. ASSERT_FALSE(svr.is_running());
  6485. });
  6486. svr.wait_until_ready();
  6487. Client cli("localhost", PORT);
  6488. svr.set_mount_point("/mount2", "./www2");
  6489. auto res = cli.Get("/");
  6490. ASSERT_TRUE(res);
  6491. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6492. res = cli.Get("/mount2/dir/test.html");
  6493. ASSERT_TRUE(res);
  6494. EXPECT_EQ(StatusCode::OK_200, res->status);
  6495. svr.set_mount_point("/", "./www");
  6496. res = cli.Get("/dir/");
  6497. ASSERT_TRUE(res);
  6498. EXPECT_EQ(StatusCode::OK_200, res->status);
  6499. svr.remove_mount_point("/");
  6500. res = cli.Get("/dir/");
  6501. ASSERT_TRUE(res);
  6502. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6503. svr.remove_mount_point("/mount2");
  6504. res = cli.Get("/mount2/dir/test.html");
  6505. ASSERT_TRUE(res);
  6506. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6507. }
  6508. TEST(MountTest, Redicect) {
  6509. Server svr;
  6510. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6511. auto se = detail::scope_exit([&] {
  6512. svr.stop();
  6513. listen_thread.join();
  6514. ASSERT_FALSE(svr.is_running());
  6515. });
  6516. svr.set_mount_point("/", "./www");
  6517. svr.wait_until_ready();
  6518. Client cli("localhost", PORT);
  6519. auto res = cli.Get("/dir/");
  6520. ASSERT_TRUE(res);
  6521. EXPECT_EQ(StatusCode::OK_200, res->status);
  6522. res = cli.Get("/dir");
  6523. ASSERT_TRUE(res);
  6524. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6525. res = cli.Get("/file");
  6526. ASSERT_TRUE(res);
  6527. EXPECT_EQ(StatusCode::OK_200, res->status);
  6528. res = cli.Get("/file/");
  6529. ASSERT_TRUE(res);
  6530. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6531. cli.set_follow_location(true);
  6532. res = cli.Get("/dir");
  6533. ASSERT_TRUE(res);
  6534. EXPECT_EQ(StatusCode::OK_200, res->status);
  6535. }
  6536. TEST(MountTest, MultibytesPathName) {
  6537. Server svr;
  6538. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6539. auto se = detail::scope_exit([&] {
  6540. svr.stop();
  6541. listen_thread.join();
  6542. ASSERT_FALSE(svr.is_running());
  6543. });
  6544. svr.set_mount_point("/", "./www");
  6545. svr.wait_until_ready();
  6546. Client cli("localhost", PORT);
  6547. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6548. ASSERT_TRUE(res);
  6549. EXPECT_EQ(StatusCode::OK_200, res->status);
  6550. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6551. }
  6552. TEST(KeepAliveTest, ReadTimeout) {
  6553. Server svr;
  6554. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6555. std::this_thread::sleep_for(std::chrono::seconds(2));
  6556. res.set_content("a", "text/plain");
  6557. });
  6558. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6559. res.set_content("b", "text/plain");
  6560. });
  6561. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6562. auto se = detail::scope_exit([&] {
  6563. svr.stop();
  6564. listen_thread.join();
  6565. ASSERT_FALSE(svr.is_running());
  6566. });
  6567. svr.wait_until_ready();
  6568. Client cli("localhost", PORT);
  6569. cli.set_keep_alive(true);
  6570. cli.set_read_timeout(std::chrono::seconds(1));
  6571. auto resa = cli.Get("/a");
  6572. ASSERT_FALSE(resa);
  6573. EXPECT_EQ(Error::Read, resa.error());
  6574. auto resb = cli.Get("/b");
  6575. ASSERT_TRUE(resb);
  6576. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6577. EXPECT_EQ("b", resb->body);
  6578. }
  6579. TEST(KeepAliveTest, MaxCount) {
  6580. size_t keep_alive_max_count = 3;
  6581. Server svr;
  6582. svr.set_keep_alive_max_count(keep_alive_max_count);
  6583. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6584. res.set_content("Hello World!", "text/plain");
  6585. });
  6586. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6587. auto se = detail::scope_exit([&] {
  6588. svr.stop();
  6589. listen_thread.join();
  6590. ASSERT_FALSE(svr.is_running());
  6591. });
  6592. svr.wait_until_ready();
  6593. Client cli(HOST, PORT);
  6594. cli.set_keep_alive(true);
  6595. for (size_t i = 0; i < 5; i++) {
  6596. auto result = cli.Get("/hi");
  6597. ASSERT_TRUE(result);
  6598. EXPECT_EQ(StatusCode::OK_200, result->status);
  6599. if (i == keep_alive_max_count - 1) {
  6600. EXPECT_EQ("close", result->get_header_value("Connection"));
  6601. } else {
  6602. EXPECT_FALSE(result->has_header("Connection"));
  6603. }
  6604. }
  6605. }
  6606. TEST(KeepAliveTest, Issue1041) {
  6607. Server svr;
  6608. svr.set_keep_alive_timeout(3);
  6609. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6610. res.set_content("Hello World!", "text/plain");
  6611. });
  6612. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6613. auto se = detail::scope_exit([&] {
  6614. svr.stop();
  6615. listen_thread.join();
  6616. ASSERT_FALSE(svr.is_running());
  6617. });
  6618. svr.wait_until_ready();
  6619. Client cli(HOST, PORT);
  6620. cli.set_keep_alive(true);
  6621. auto result = cli.Get("/hi");
  6622. ASSERT_TRUE(result);
  6623. EXPECT_EQ(StatusCode::OK_200, result->status);
  6624. std::this_thread::sleep_for(std::chrono::seconds(5));
  6625. result = cli.Get("/hi");
  6626. ASSERT_TRUE(result);
  6627. EXPECT_EQ(StatusCode::OK_200, result->status);
  6628. }
  6629. TEST(KeepAliveTest, Issue1959) {
  6630. Server svr;
  6631. svr.set_keep_alive_timeout(5);
  6632. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6633. res.set_content("a", "text/plain");
  6634. });
  6635. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6636. auto se = detail::scope_exit([&] {
  6637. if (!svr.is_running()) return;
  6638. svr.stop();
  6639. listen_thread.join();
  6640. ASSERT_FALSE(svr.is_running());
  6641. });
  6642. svr.wait_until_ready();
  6643. Client cli("localhost", PORT);
  6644. cli.set_keep_alive(true);
  6645. using namespace std::chrono;
  6646. auto start = steady_clock::now();
  6647. cli.Get("/a");
  6648. svr.stop();
  6649. listen_thread.join();
  6650. auto end = steady_clock::now();
  6651. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6652. EXPECT_LT(elapsed, 5000);
  6653. }
  6654. #ifdef CPPHTTPLIB_SSL_ENABLED
  6655. TEST(KeepAliveTest, SSLClientReconnection) {
  6656. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6657. ASSERT_TRUE(svr.is_valid());
  6658. svr.set_keep_alive_timeout(1);
  6659. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6660. res.set_content("Hello World!", "text/plain");
  6661. });
  6662. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6663. auto se = detail::scope_exit([&] {
  6664. svr.stop();
  6665. listen_thread.join();
  6666. ASSERT_FALSE(svr.is_running());
  6667. });
  6668. svr.wait_until_ready();
  6669. SSLClient cli(HOST, PORT);
  6670. cli.enable_server_certificate_verification(false);
  6671. cli.set_keep_alive(true);
  6672. auto result = cli.Get("/hi");
  6673. ASSERT_TRUE(result);
  6674. EXPECT_EQ(StatusCode::OK_200, result->status);
  6675. result = cli.Get("/hi");
  6676. ASSERT_TRUE(result);
  6677. EXPECT_EQ(StatusCode::OK_200, result->status);
  6678. std::this_thread::sleep_for(std::chrono::seconds(2));
  6679. // Recoonect
  6680. result = cli.Get("/hi");
  6681. ASSERT_TRUE(result);
  6682. EXPECT_EQ(StatusCode::OK_200, result->status);
  6683. result = cli.Get("/hi");
  6684. ASSERT_TRUE(result);
  6685. EXPECT_EQ(StatusCode::OK_200, result->status);
  6686. }
  6687. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6688. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6689. ASSERT_TRUE(svr.is_valid());
  6690. svr.set_keep_alive_timeout(1);
  6691. std::string content = "reconnect";
  6692. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6693. res.set_content("Hello World!", "text/plain");
  6694. });
  6695. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6696. auto se = detail::scope_exit([&] {
  6697. svr.stop();
  6698. listen_thread.join();
  6699. ASSERT_FALSE(svr.is_running());
  6700. });
  6701. svr.wait_until_ready();
  6702. SSLClient cli(HOST, PORT);
  6703. cli.enable_server_certificate_verification(false);
  6704. cli.set_keep_alive(true);
  6705. auto result = cli.Post(
  6706. "/hi", content.size(),
  6707. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6708. sink.write(content.c_str(), content.size());
  6709. return true;
  6710. },
  6711. "text/plain");
  6712. ASSERT_TRUE(result);
  6713. EXPECT_EQ(200, result->status);
  6714. std::this_thread::sleep_for(std::chrono::seconds(2));
  6715. // Recoonect
  6716. result = cli.Post(
  6717. "/hi", content.size(),
  6718. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6719. sink.write(content.c_str(), content.size());
  6720. return true;
  6721. },
  6722. "text/plain");
  6723. ASSERT_TRUE(result);
  6724. EXPECT_EQ(200, result->status);
  6725. result = cli.Post(
  6726. "/hi", content.size(),
  6727. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6728. sink.write(content.c_str(), content.size());
  6729. return true;
  6730. },
  6731. "text/plain");
  6732. ASSERT_TRUE(result);
  6733. EXPECT_EQ(200, result->status);
  6734. }
  6735. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6736. using namespace httplib::tls;
  6737. {
  6738. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6739. ASSERT_TRUE(svr.is_valid());
  6740. svr.Get("/sni", [&](const Request &req, Response &res) {
  6741. std::string expected = req.sni();
  6742. EXPECT_EQ(expected, req.get_param_value("expected"));
  6743. res.set_content("ok", "text/plain");
  6744. });
  6745. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6746. auto se = detail::scope_exit([&] {
  6747. svr.stop();
  6748. listen_thread.join();
  6749. ASSERT_FALSE(svr.is_running());
  6750. });
  6751. svr.wait_until_ready();
  6752. {
  6753. SSLClient cli("localhost", PORT);
  6754. cli.enable_server_certificate_verification(false);
  6755. auto res = cli.Get("/sni?expected=localhost");
  6756. ASSERT_TRUE(res);
  6757. }
  6758. {
  6759. SSLClient cli("::1", PORT);
  6760. cli.enable_server_certificate_verification(false);
  6761. auto res = cli.Get("/sni?expected=");
  6762. // NOTE: This may fail if the server is listening on IPv4 only
  6763. // (e.g., when localhost resolves to 127.0.0.1 only)
  6764. if (res) {
  6765. EXPECT_EQ(StatusCode::OK_200, res->status);
  6766. } else {
  6767. EXPECT_EQ(Error::Connection, res.error());
  6768. }
  6769. }
  6770. }
  6771. }
  6772. #endif
  6773. TEST(ClientProblemDetectionTest, ContentProvider) {
  6774. Server svr;
  6775. size_t content_length = 1024 * 1024;
  6776. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6777. res.set_content_provider(
  6778. content_length, "text/plain",
  6779. [&](size_t offset, size_t length, DataSink &sink) {
  6780. auto out_len = std::min(length, static_cast<size_t>(1024));
  6781. std::string out(out_len, '@');
  6782. sink.write(out.data(), out_len);
  6783. return offset < 4096;
  6784. },
  6785. [](bool success) { ASSERT_FALSE(success); });
  6786. });
  6787. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6788. res.set_content_provider(
  6789. 0, "text/plain",
  6790. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6791. EXPECT_TRUE(false);
  6792. return true;
  6793. },
  6794. [](bool success) { ASSERT_FALSE(success); });
  6795. });
  6796. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6797. auto se = detail::scope_exit([&] {
  6798. svr.stop();
  6799. listen_thread.join();
  6800. ASSERT_FALSE(svr.is_running());
  6801. });
  6802. svr.wait_until_ready();
  6803. Client cli("localhost", PORT);
  6804. {
  6805. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6806. size_t /*data_length*/) { return false; });
  6807. ASSERT_FALSE(res);
  6808. }
  6809. {
  6810. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6811. size_t /*data_length*/) { return false; });
  6812. ASSERT_TRUE(res);
  6813. }
  6814. }
  6815. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6816. Server svr;
  6817. svr.set_error_handler([](Request const &, Response &res) -> void {
  6818. res.set_chunked_content_provider(
  6819. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6820. sink.os << "hello";
  6821. sink.os << "world";
  6822. sink.done();
  6823. return true;
  6824. });
  6825. });
  6826. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6827. auto se = detail::scope_exit([&] {
  6828. svr.stop();
  6829. listen_thread.join();
  6830. ASSERT_FALSE(svr.is_running());
  6831. });
  6832. svr.wait_until_ready();
  6833. Client cli("localhost", PORT);
  6834. auto res = cli.Get("/");
  6835. ASSERT_TRUE(res);
  6836. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6837. EXPECT_EQ("helloworld", res->body);
  6838. }
  6839. TEST(LongPollingTest, ClientCloseDetection) {
  6840. Server svr;
  6841. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6842. res.set_chunked_content_provider(
  6843. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6844. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6845. sink.os << "hello";
  6846. auto count = 10;
  6847. while (count > 0 && sink.is_writable()) {
  6848. this_thread::sleep_for(chrono::milliseconds(10));
  6849. count--;
  6850. }
  6851. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6852. return true;
  6853. });
  6854. });
  6855. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6856. auto se = detail::scope_exit([&] {
  6857. svr.stop();
  6858. listen_thread.join();
  6859. ASSERT_FALSE(svr.is_running());
  6860. });
  6861. svr.wait_until_ready();
  6862. Client cli("localhost", PORT);
  6863. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6864. EXPECT_EQ("hello", string(data, data_length));
  6865. return false; // close the socket immediately.
  6866. });
  6867. ASSERT_FALSE(res);
  6868. }
  6869. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  6870. Server svr;
  6871. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6872. res.set_chunked_content_provider(
  6873. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6874. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6875. sink.os << "hello";
  6876. EXPECT_TRUE(sink.os.good());
  6877. // Wait for the client to close the connection
  6878. auto count = 10;
  6879. while (count > 0 && sink.is_writable()) {
  6880. this_thread::sleep_for(chrono::milliseconds(10));
  6881. count--;
  6882. }
  6883. // After client disconnect, write repeatedly until the socket
  6884. // write actually fails (small writes may be absorbed by the
  6885. // kernel buffer)
  6886. std::string chunk(1024, 'x');
  6887. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  6888. sink.os << chunk;
  6889. }
  6890. EXPECT_TRUE(sink.os.fail());
  6891. return true;
  6892. });
  6893. });
  6894. auto port = svr.bind_to_any_port("localhost");
  6895. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  6896. auto se = detail::scope_exit([&] {
  6897. svr.stop();
  6898. listen_thread.join();
  6899. ASSERT_FALSE(svr.is_running());
  6900. });
  6901. svr.wait_until_ready();
  6902. Client cli("localhost", port);
  6903. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6904. EXPECT_EQ("hello", string(data, data_length));
  6905. return false; // close the socket immediately.
  6906. });
  6907. ASSERT_FALSE(res);
  6908. }
  6909. TEST(GetWithParametersTest, GetWithParameters) {
  6910. Server svr;
  6911. svr.Get("/", [&](const Request &req, Response &) {
  6912. EXPECT_EQ("world", req.get_param_value("hello"));
  6913. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6914. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6915. });
  6916. svr.Get("/params", [&](const Request &req, Response &) {
  6917. EXPECT_EQ("world", req.get_param_value("hello"));
  6918. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6919. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6920. });
  6921. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6922. EXPECT_EQ("resource-id", req.matches[1]);
  6923. EXPECT_EQ("foo", req.get_param_value("param1"));
  6924. EXPECT_EQ("bar", req.get_param_value("param2"));
  6925. });
  6926. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6927. EXPECT_EQ("user-id", req.path_params.at("id"));
  6928. EXPECT_EQ("foo", req.get_param_value("param1"));
  6929. EXPECT_EQ("bar", req.get_param_value("param2"));
  6930. });
  6931. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6932. auto se = detail::scope_exit([&] {
  6933. svr.stop();
  6934. listen_thread.join();
  6935. ASSERT_FALSE(svr.is_running());
  6936. });
  6937. svr.wait_until_ready();
  6938. {
  6939. Client cli(HOST, PORT);
  6940. Params params;
  6941. params.emplace("hello", "world");
  6942. params.emplace("hello2", "world2");
  6943. params.emplace("hello3", "world3");
  6944. auto res = cli.Get("/", params, Headers{});
  6945. ASSERT_TRUE(res);
  6946. EXPECT_EQ(StatusCode::OK_200, res->status);
  6947. }
  6948. {
  6949. Client cli(HOST, PORT);
  6950. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6951. ASSERT_TRUE(res);
  6952. EXPECT_EQ(StatusCode::OK_200, res->status);
  6953. }
  6954. {
  6955. Client cli(HOST, PORT);
  6956. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6957. ASSERT_TRUE(res);
  6958. EXPECT_EQ(StatusCode::OK_200, res->status);
  6959. }
  6960. {
  6961. Client cli(HOST, PORT);
  6962. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6963. ASSERT_TRUE(res);
  6964. EXPECT_EQ(StatusCode::OK_200, res->status);
  6965. }
  6966. }
  6967. TEST(GetWithParametersTest, GetWithParameters2) {
  6968. Server svr;
  6969. svr.Get("/", [&](const Request &req, Response &res) {
  6970. auto text = req.get_param_value("hello");
  6971. res.set_content(text, "text/plain");
  6972. });
  6973. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6974. auto se = detail::scope_exit([&] {
  6975. svr.stop();
  6976. listen_thread.join();
  6977. ASSERT_FALSE(svr.is_running());
  6978. });
  6979. svr.wait_until_ready();
  6980. Client cli("localhost", PORT);
  6981. Params params;
  6982. params.emplace("hello", "world");
  6983. std::string body;
  6984. auto res = cli.Get("/", params, Headers{},
  6985. [&](const char *data, size_t data_length) {
  6986. body.append(data, data_length);
  6987. return true;
  6988. });
  6989. ASSERT_TRUE(res);
  6990. EXPECT_EQ(StatusCode::OK_200, res->status);
  6991. EXPECT_EQ("world", body);
  6992. }
  6993. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6994. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6995. auto host = "httpcan.org";
  6996. auto path = std::string{"/range/32"};
  6997. #else
  6998. auto host = "nghttp2.org";
  6999. auto path = std::string{"/httpbin/range/32"};
  7000. #endif
  7001. #ifdef CPPHTTPLIB_SSL_ENABLED
  7002. SSLClient cli(host);
  7003. #else
  7004. Client cli(host);
  7005. #endif
  7006. cli.set_default_headers({make_range_header({{1, 10}})});
  7007. cli.set_connection_timeout(5);
  7008. {
  7009. auto res = cli.Get(path);
  7010. ASSERT_TRUE(res);
  7011. EXPECT_EQ("bcdefghijk", res->body);
  7012. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7013. }
  7014. {
  7015. auto res = cli.Get(path);
  7016. ASSERT_TRUE(res);
  7017. EXPECT_EQ("bcdefghijk", res->body);
  7018. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7019. }
  7020. }
  7021. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7022. Server svr;
  7023. svr.set_default_headers({{"Hello", "World"}});
  7024. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7025. res.set_content("ok", "text/plain");
  7026. });
  7027. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7028. auto se = detail::scope_exit([&] {
  7029. svr.stop();
  7030. listen_thread.join();
  7031. ASSERT_FALSE(svr.is_running());
  7032. });
  7033. svr.wait_until_ready();
  7034. Client cli("localhost", PORT);
  7035. auto res = cli.Get("/");
  7036. ASSERT_TRUE(res);
  7037. EXPECT_EQ(StatusCode::OK_200, res->status);
  7038. EXPECT_EQ("ok", res->body);
  7039. EXPECT_EQ("World", res->get_header_value("Hello"));
  7040. }
  7041. #ifdef CPPHTTPLIB_SSL_ENABLED
  7042. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7043. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7044. ASSERT_TRUE(svr.is_valid());
  7045. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7046. std::this_thread::sleep_for(std::chrono::seconds(2));
  7047. res.set_content("a", "text/plain");
  7048. });
  7049. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7050. res.set_content("b", "text/plain");
  7051. });
  7052. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7053. auto se = detail::scope_exit([&] {
  7054. svr.stop();
  7055. listen_thread.join();
  7056. ASSERT_FALSE(svr.is_running());
  7057. });
  7058. svr.wait_until_ready();
  7059. SSLClient cli("localhost", PORT);
  7060. cli.enable_server_certificate_verification(false);
  7061. cli.set_keep_alive(true);
  7062. cli.set_read_timeout(std::chrono::seconds(1));
  7063. auto resa = cli.Get("/a");
  7064. ASSERT_TRUE(!resa);
  7065. EXPECT_EQ(Error::Read, resa.error());
  7066. auto resb = cli.Get("/b");
  7067. ASSERT_TRUE(resb);
  7068. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7069. EXPECT_EQ("b", resb->body);
  7070. }
  7071. #endif
  7072. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7073. protected:
  7074. ServerTestWithAI_PASSIVE()
  7075. : cli_(HOST, PORT)
  7076. #ifdef CPPHTTPLIB_SSL_ENABLED
  7077. ,
  7078. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7079. #endif
  7080. {
  7081. #ifdef CPPHTTPLIB_SSL_ENABLED
  7082. cli_.enable_server_certificate_verification(false);
  7083. #endif
  7084. }
  7085. virtual void SetUp() {
  7086. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7087. res.set_content("Hello World!", "text/plain");
  7088. });
  7089. t_ = thread(
  7090. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7091. svr_.wait_until_ready();
  7092. }
  7093. virtual void TearDown() {
  7094. svr_.stop();
  7095. t_.join();
  7096. }
  7097. #ifdef CPPHTTPLIB_SSL_ENABLED
  7098. SSLClient cli_;
  7099. SSLServer svr_;
  7100. #else
  7101. Client cli_;
  7102. Server svr_;
  7103. #endif
  7104. thread t_;
  7105. };
  7106. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7107. auto res = cli_.Get("/hi");
  7108. ASSERT_TRUE(res);
  7109. EXPECT_EQ(StatusCode::OK_200, res->status);
  7110. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7111. EXPECT_EQ("Hello World!", res->body);
  7112. }
  7113. class ServerUpDownTest : public ::testing::Test {
  7114. protected:
  7115. ServerUpDownTest() : cli_(HOST, PORT) {}
  7116. virtual void SetUp() {
  7117. t_ = thread([&]() {
  7118. svr_.bind_to_any_port(HOST);
  7119. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7120. ASSERT_TRUE(svr_.listen_after_bind());
  7121. });
  7122. svr_.wait_until_ready();
  7123. }
  7124. virtual void TearDown() {
  7125. svr_.stop();
  7126. t_.join();
  7127. }
  7128. Client cli_;
  7129. Server svr_;
  7130. thread t_;
  7131. };
  7132. TEST_F(ServerUpDownTest, QuickStartStop) {
  7133. // Should not crash, especially when run with
  7134. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7135. }
  7136. class PayloadMaxLengthTest : public ::testing::Test {
  7137. protected:
  7138. PayloadMaxLengthTest()
  7139. : cli_(HOST, PORT)
  7140. #ifdef CPPHTTPLIB_SSL_ENABLED
  7141. ,
  7142. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7143. #endif
  7144. {
  7145. #ifdef CPPHTTPLIB_SSL_ENABLED
  7146. cli_.enable_server_certificate_verification(false);
  7147. #endif
  7148. }
  7149. virtual void SetUp() {
  7150. svr_.set_payload_max_length(8);
  7151. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7152. res.set_content("test", "text/plain");
  7153. });
  7154. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7155. svr_.wait_until_ready();
  7156. }
  7157. virtual void TearDown() {
  7158. svr_.stop();
  7159. t_.join();
  7160. }
  7161. #ifdef CPPHTTPLIB_SSL_ENABLED
  7162. SSLClient cli_;
  7163. SSLServer svr_;
  7164. #else
  7165. Client cli_;
  7166. Server svr_;
  7167. #endif
  7168. thread t_;
  7169. };
  7170. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7171. auto res = cli_.Post("/test", "123456789", "text/plain");
  7172. ASSERT_TRUE(res);
  7173. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7174. res = cli_.Post("/test", "12345678", "text/plain");
  7175. ASSERT_TRUE(res);
  7176. EXPECT_EQ(StatusCode::OK_200, res->status);
  7177. }
  7178. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7179. // Test chunked encoding with payload exceeding the 8-byte limit
  7180. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7181. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7182. ASSERT_TRUE(res);
  7183. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7184. }
  7185. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7186. // Test chunked encoding with payload within the 8-byte limit
  7187. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7188. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7189. ASSERT_TRUE(res);
  7190. EXPECT_EQ(StatusCode::OK_200, res->status);
  7191. }
  7192. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7193. // Test using send_request to send chunked data exceeding payload limit
  7194. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7195. "Host: " +
  7196. std::string(HOST) + ":" + std::to_string(PORT) +
  7197. "\r\n"
  7198. "Transfer-Encoding: chunked\r\n"
  7199. "Connection: close\r\n"
  7200. "\r\n"
  7201. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7202. "0123456789\r\n"
  7203. "0\r\n" // End chunk
  7204. "\r\n";
  7205. std::string response;
  7206. bool result = send_request(1, chunked_request, &response);
  7207. if (!result) {
  7208. // If send_request fails, it might be because the server closed the
  7209. // connection due to payload limit enforcement, which is acceptable
  7210. SUCCEED()
  7211. << "Server rejected oversized chunked request (connection closed)";
  7212. } else {
  7213. // If we got a response, check if it's an error response or connection was
  7214. // closed early Short response length indicates connection was closed due to
  7215. // payload limit
  7216. if (response.length() <= 10) {
  7217. SUCCEED() << "Server closed connection for oversized chunked request";
  7218. } else {
  7219. // Check for error status codes
  7220. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7221. response.find("Payload Too Large") != std::string::npos ||
  7222. response.find("400") != std::string::npos);
  7223. }
  7224. }
  7225. }
  7226. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7227. // Test request without Content-Length header exceeding payload limit
  7228. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7229. "Host: " +
  7230. std::string(HOST) + ":" +
  7231. std::to_string(PORT) +
  7232. "\r\n"
  7233. "Connection: close\r\n"
  7234. "\r\n";
  7235. // Add payload exceeding the 8-byte limit
  7236. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7237. request_without_content_length += large_payload;
  7238. std::string response;
  7239. bool result = send_request(1, request_without_content_length, &response);
  7240. if (!result) {
  7241. // If send_request fails, server likely closed connection due to payload
  7242. // limit
  7243. SUCCEED() << "Server rejected oversized request without Content-Length "
  7244. "(connection closed)";
  7245. } else {
  7246. // Check if server responded with error or closed connection early
  7247. if (response.length() <= 10) {
  7248. SUCCEED() << "Server closed connection for oversized request without "
  7249. "Content-Length";
  7250. } else {
  7251. // Check for error status codes
  7252. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7253. response.find("Payload Too Large") != std::string::npos ||
  7254. response.find("400") != std::string::npos);
  7255. }
  7256. }
  7257. }
  7258. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7259. // Test request without Content-Length header within payload limit
  7260. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7261. "Host: " +
  7262. std::string(HOST) + ":" +
  7263. std::to_string(PORT) +
  7264. "\r\n"
  7265. "Connection: close\r\n"
  7266. "\r\n";
  7267. // Add payload within the 8-byte limit
  7268. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7269. request_without_content_length += small_payload;
  7270. std::string response;
  7271. bool result = send_request(1, request_without_content_length, &response);
  7272. // For requests without Content-Length, the server may have different behavior
  7273. // The key is that it should not reject due to payload limit for small
  7274. // payloads
  7275. if (result) {
  7276. // Check for any HTTP response (success or error, but not connection closed)
  7277. if (response.length() > 10) {
  7278. SUCCEED()
  7279. << "Server processed request without Content-Length within limit";
  7280. } else {
  7281. // Short response might indicate connection closed, which is acceptable
  7282. SUCCEED() << "Server closed connection for request without "
  7283. "Content-Length (acceptable behavior)";
  7284. }
  7285. } else {
  7286. // Connection failure might be due to protocol requirements
  7287. SUCCEED() << "Connection issue with request without Content-Length "
  7288. "(environment-specific)";
  7289. }
  7290. }
  7291. class LargePayloadMaxLengthTest : public ::testing::Test {
  7292. protected:
  7293. LargePayloadMaxLengthTest()
  7294. : cli_(HOST, PORT)
  7295. #ifdef CPPHTTPLIB_SSL_ENABLED
  7296. ,
  7297. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7298. #endif
  7299. {
  7300. #ifdef CPPHTTPLIB_SSL_ENABLED
  7301. cli_.enable_server_certificate_verification(false);
  7302. #endif
  7303. }
  7304. virtual void SetUp() {
  7305. // Set 10MB payload limit
  7306. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7307. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7308. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7309. res.set_content("Large payload test", "text/plain");
  7310. });
  7311. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7312. svr_.wait_until_ready();
  7313. }
  7314. virtual void TearDown() {
  7315. svr_.stop();
  7316. t_.join();
  7317. }
  7318. #ifdef CPPHTTPLIB_SSL_ENABLED
  7319. SSLClient cli_;
  7320. SSLServer svr_;
  7321. #else
  7322. Client cli_;
  7323. Server svr_;
  7324. #endif
  7325. thread t_;
  7326. };
  7327. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7328. // Test chunked encoding with payload within 10MB limit
  7329. std::string medium_payload(5 * 1024 * 1024,
  7330. 'A'); // 5MB payload, within 10MB limit
  7331. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7332. ASSERT_TRUE(res);
  7333. EXPECT_EQ(StatusCode::OK_200, res->status);
  7334. }
  7335. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7336. // Test chunked encoding with payload exceeding 10MB limit
  7337. std::string large_payload(12 * 1024 * 1024,
  7338. 'B'); // 12MB payload, exceeds 10MB limit
  7339. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7340. // Server may either return 413 or close the connection
  7341. if (res) {
  7342. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7343. } else {
  7344. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7345. }
  7346. }
  7347. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7348. // Test request without Content-Length header within 10MB limit
  7349. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7350. "Host: " +
  7351. std::string(HOST) + ":" +
  7352. std::to_string(PORT) +
  7353. "\r\n"
  7354. "Connection: close\r\n"
  7355. "\r\n";
  7356. // Add 1MB payload (within 10MB limit)
  7357. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7358. request_without_content_length += medium_payload;
  7359. std::string response;
  7360. bool result = send_request(5, request_without_content_length, &response);
  7361. if (result) {
  7362. // Should get a proper HTTP response for payloads within limit
  7363. if (response.length() > 10) {
  7364. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7365. "10MB limit";
  7366. } else {
  7367. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7368. "Content-Length)";
  7369. }
  7370. } else {
  7371. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7372. }
  7373. }
  7374. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7375. // Test request without Content-Length header exceeding 10MB limit
  7376. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7377. "Host: " +
  7378. std::string(HOST) + ":" +
  7379. std::to_string(PORT) +
  7380. "\r\n"
  7381. "Connection: close\r\n"
  7382. "\r\n";
  7383. // Add 12MB payload (exceeds 10MB limit)
  7384. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7385. request_without_content_length += large_payload;
  7386. std::string response;
  7387. bool result = send_request(10, request_without_content_length, &response);
  7388. if (!result) {
  7389. // Server should close connection due to payload limit
  7390. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7391. "(connection closed)";
  7392. } else {
  7393. // Check for error response
  7394. if (response.length() <= 10) {
  7395. SUCCEED()
  7396. << "Server closed connection for 12MB request exceeding 10MB limit";
  7397. } else {
  7398. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7399. response.find("Payload Too Large") != std::string::npos ||
  7400. response.find("400") != std::string::npos);
  7401. }
  7402. }
  7403. }
  7404. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7405. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7406. // path.
  7407. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7408. Server svr;
  7409. const size_t LIMIT = 64 * 1024; // 64KB
  7410. svr.set_payload_max_length(LIMIT);
  7411. size_t total = 0;
  7412. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7413. const ContentReader &content_reader) {
  7414. content_reader([&](const char * /*data*/, size_t len) {
  7415. total += len;
  7416. return true;
  7417. });
  7418. res.status = 200;
  7419. res.set_content("stream_ok", "text/plain");
  7420. });
  7421. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7422. auto se = detail::scope_exit([&] {
  7423. svr.stop();
  7424. thread.join();
  7425. ASSERT_FALSE(svr.is_running());
  7426. });
  7427. svr.wait_until_ready();
  7428. // Prepare 256KB raw data and gzip-compress it
  7429. std::string raw(256 * 1024, 'A');
  7430. std::string gz;
  7431. {
  7432. z_stream zs{};
  7433. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7434. Z_DEFAULT_STRATEGY);
  7435. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7436. zs.avail_in = static_cast<uInt>(raw.size());
  7437. char outbuf[4096];
  7438. int ret;
  7439. do {
  7440. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7441. zs.avail_out = sizeof(outbuf);
  7442. ret = deflate(&zs, Z_FINISH);
  7443. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7444. } while (ret != Z_STREAM_END);
  7445. deflateEnd(&zs);
  7446. }
  7447. Client cli(HOST, PORT);
  7448. cli.set_connection_timeout(std::chrono::seconds(5));
  7449. Headers headers = {{"Content-Encoding", "gzip"}};
  7450. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7451. "application/octet-stream");
  7452. ASSERT_TRUE(res);
  7453. // Server must reject oversized decompressed payloads with 413.
  7454. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7455. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7456. EXPECT_LE(total, LIMIT);
  7457. }
  7458. #endif
  7459. // Regression test for DoS vulnerability: a malicious server sending a response
  7460. // without Content-Length header must not cause unbounded memory consumption on
  7461. // the client side. The client should stop reading after a reasonable limit,
  7462. // similar to the server-side set_payload_max_length protection.
  7463. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7464. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7465. #ifndef _WIN32
  7466. signal(SIGPIPE, SIG_IGN);
  7467. #endif
  7468. auto server_thread = std::thread([] {
  7469. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7470. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7471. default_socket_options(srv);
  7472. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7473. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7474. sockaddr_in addr{};
  7475. addr.sin_family = AF_INET;
  7476. addr.sin_port = htons(PORT + 2);
  7477. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7478. int opt = 1;
  7479. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7480. #ifdef _WIN32
  7481. reinterpret_cast<const char *>(&opt),
  7482. #else
  7483. &opt,
  7484. #endif
  7485. sizeof(opt));
  7486. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7487. ::listen(srv, 1);
  7488. sockaddr_in cli_addr{};
  7489. socklen_t cli_len = sizeof(cli_addr);
  7490. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7491. if (cli != INVALID_SOCKET) {
  7492. char buf[4096];
  7493. ::recv(cli, buf, sizeof(buf), 0);
  7494. // Malicious response: no Content-Length, no chunked encoding
  7495. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7496. "Connection: close\r\n"
  7497. "\r\n";
  7498. ::send(cli,
  7499. #ifdef _WIN32
  7500. static_cast<const char *>(response_header.c_str()),
  7501. static_cast<int>(response_header.size()),
  7502. #else
  7503. response_header.c_str(), response_header.size(),
  7504. #endif
  7505. 0);
  7506. // Send 10MB of data
  7507. std::string chunk(64 * 1024, 'A');
  7508. size_t total_sent = 0;
  7509. while (total_sent < MALICIOUS_DATA_SIZE) {
  7510. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7511. auto sent = ::send(cli,
  7512. #ifdef _WIN32
  7513. static_cast<const char *>(chunk.c_str()),
  7514. static_cast<int>(to_send),
  7515. #else
  7516. chunk.c_str(), to_send,
  7517. #endif
  7518. 0);
  7519. if (sent <= 0) break;
  7520. total_sent += static_cast<size_t>(sent);
  7521. }
  7522. detail::close_socket(cli);
  7523. }
  7524. detail::close_socket(srv);
  7525. });
  7526. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7527. size_t total_read = 0;
  7528. {
  7529. Client cli("127.0.0.1", PORT + 2);
  7530. cli.set_read_timeout(5, 0);
  7531. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7532. auto stream = cli.open_stream("GET", "/malicious");
  7533. ASSERT_TRUE(stream.is_valid());
  7534. char buffer[64 * 1024];
  7535. ssize_t n;
  7536. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7537. total_read += static_cast<size_t>(n);
  7538. }
  7539. } // StreamHandle and Client destroyed here, closing the socket
  7540. server_thread.join();
  7541. // With set_payload_max_length, the client must stop reading before consuming
  7542. // all 10MB. The read loop should be cut off at or near the configured limit.
  7543. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7544. << "Client read " << total_read << " bytes, exceeding the configured "
  7545. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7546. }
  7547. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7548. // the entire response body without truncation.
  7549. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7550. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7551. #ifndef _WIN32
  7552. signal(SIGPIPE, SIG_IGN);
  7553. #endif
  7554. auto server_thread = std::thread([] {
  7555. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7556. default_socket_options(srv);
  7557. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7558. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7559. sockaddr_in addr{};
  7560. addr.sin_family = AF_INET;
  7561. addr.sin_port = htons(PORT + 2);
  7562. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7563. int opt = 1;
  7564. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7565. #ifdef _WIN32
  7566. reinterpret_cast<const char *>(&opt),
  7567. #else
  7568. &opt,
  7569. #endif
  7570. sizeof(opt));
  7571. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7572. ::listen(srv, 1);
  7573. sockaddr_in cli_addr{};
  7574. socklen_t cli_len = sizeof(cli_addr);
  7575. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7576. if (cli != INVALID_SOCKET) {
  7577. char buf[4096];
  7578. ::recv(cli, buf, sizeof(buf), 0);
  7579. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7580. "Connection: close\r\n"
  7581. "\r\n";
  7582. ::send(cli,
  7583. #ifdef _WIN32
  7584. static_cast<const char *>(response_header.c_str()),
  7585. static_cast<int>(response_header.size()),
  7586. #else
  7587. response_header.c_str(), response_header.size(),
  7588. #endif
  7589. 0);
  7590. std::string chunk(64 * 1024, 'A');
  7591. size_t total_sent = 0;
  7592. while (total_sent < DATA_SIZE) {
  7593. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7594. auto sent = ::send(cli,
  7595. #ifdef _WIN32
  7596. static_cast<const char *>(chunk.c_str()),
  7597. static_cast<int>(to_send),
  7598. #else
  7599. chunk.c_str(), to_send,
  7600. #endif
  7601. 0);
  7602. if (sent <= 0) break;
  7603. total_sent += static_cast<size_t>(sent);
  7604. }
  7605. #ifdef _WIN32
  7606. ::shutdown(cli, SD_SEND);
  7607. #else
  7608. ::shutdown(cli, SHUT_WR);
  7609. #endif
  7610. // Drain until the client closes its end, ensuring all data is delivered
  7611. char drain[1024];
  7612. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7613. detail::close_socket(cli);
  7614. }
  7615. detail::close_socket(srv);
  7616. });
  7617. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7618. size_t total_read = 0;
  7619. {
  7620. Client cli("127.0.0.1", PORT + 2);
  7621. cli.set_read_timeout(5, 0);
  7622. cli.set_payload_max_length(0); // 0 means no limit
  7623. auto stream = cli.open_stream("GET", "/data");
  7624. ASSERT_TRUE(stream.is_valid());
  7625. char buffer[64 * 1024];
  7626. ssize_t n;
  7627. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7628. total_read += static_cast<size_t>(n);
  7629. }
  7630. }
  7631. server_thread.join();
  7632. EXPECT_EQ(total_read, DATA_SIZE)
  7633. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7634. << " bytes without truncation, but only read " << total_read << " bytes.";
  7635. }
  7636. // Verify that content_receiver bypasses the default payload_max_length,
  7637. // allowing streaming downloads larger than 100MB without requiring an explicit
  7638. // set_payload_max_length call.
  7639. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  7640. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7641. #ifndef _WIN32
  7642. signal(SIGPIPE, SIG_IGN);
  7643. #endif
  7644. auto server_thread = std::thread([] {
  7645. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7646. default_socket_options(srv);
  7647. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7648. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7649. sockaddr_in addr{};
  7650. addr.sin_family = AF_INET;
  7651. addr.sin_port = htons(PORT + 2);
  7652. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7653. int opt = 1;
  7654. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7655. #ifdef _WIN32
  7656. reinterpret_cast<const char *>(&opt),
  7657. #else
  7658. &opt,
  7659. #endif
  7660. sizeof(opt));
  7661. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7662. ::listen(srv, 1);
  7663. sockaddr_in cli_addr{};
  7664. socklen_t cli_len = sizeof(cli_addr);
  7665. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7666. if (cli != INVALID_SOCKET) {
  7667. char buf[4096];
  7668. ::recv(cli, buf, sizeof(buf), 0);
  7669. // Response with Content-Length larger than default 100MB limit
  7670. auto content_length = std::to_string(DATA_SIZE);
  7671. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7672. "Content-Length: " +
  7673. content_length +
  7674. "\r\n"
  7675. "Connection: close\r\n"
  7676. "\r\n";
  7677. ::send(cli,
  7678. #ifdef _WIN32
  7679. static_cast<const char *>(response_header.c_str()),
  7680. static_cast<int>(response_header.size()),
  7681. #else
  7682. response_header.c_str(), response_header.size(),
  7683. #endif
  7684. 0);
  7685. std::string chunk(64 * 1024, 'A');
  7686. size_t total_sent = 0;
  7687. while (total_sent < DATA_SIZE) {
  7688. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7689. auto sent = ::send(cli,
  7690. #ifdef _WIN32
  7691. static_cast<const char *>(chunk.c_str()),
  7692. static_cast<int>(to_send),
  7693. #else
  7694. chunk.c_str(), to_send,
  7695. #endif
  7696. 0);
  7697. if (sent <= 0) break;
  7698. total_sent += static_cast<size_t>(sent);
  7699. }
  7700. detail::close_socket(cli);
  7701. }
  7702. detail::close_socket(srv);
  7703. });
  7704. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7705. size_t total_received = 0;
  7706. {
  7707. Client cli("127.0.0.1", PORT + 2);
  7708. cli.set_read_timeout(10, 0);
  7709. // Do NOT call set_payload_max_length — use the default 100MB limit
  7710. auto res =
  7711. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7712. total_received += data_length;
  7713. return true;
  7714. });
  7715. ASSERT_TRUE(res);
  7716. EXPECT_EQ(StatusCode::OK_200, res->status);
  7717. }
  7718. server_thread.join();
  7719. EXPECT_EQ(total_received, DATA_SIZE)
  7720. << "With content_receiver, the client should read all " << DATA_SIZE
  7721. << " bytes despite the default 100MB payload_max_length, but only read "
  7722. << total_received << " bytes.";
  7723. }
  7724. // Verify that an explicit set_payload_max_length smaller than the response is
  7725. // enforced even when a content_receiver is used.
  7726. TEST(ClientVulnerabilityTest,
  7727. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  7728. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7729. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  7730. #ifndef _WIN32
  7731. signal(SIGPIPE, SIG_IGN);
  7732. #endif
  7733. auto server_thread = std::thread([] {
  7734. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7735. default_socket_options(srv);
  7736. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7737. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7738. sockaddr_in addr{};
  7739. addr.sin_family = AF_INET;
  7740. addr.sin_port = htons(PORT + 2);
  7741. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7742. int opt = 1;
  7743. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7744. #ifdef _WIN32
  7745. reinterpret_cast<const char *>(&opt),
  7746. #else
  7747. &opt,
  7748. #endif
  7749. sizeof(opt));
  7750. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7751. ::listen(srv, 1);
  7752. sockaddr_in cli_addr{};
  7753. socklen_t cli_len = sizeof(cli_addr);
  7754. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7755. if (cli != INVALID_SOCKET) {
  7756. char buf[4096];
  7757. ::recv(cli, buf, sizeof(buf), 0);
  7758. auto content_length = std::to_string(DATA_SIZE);
  7759. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7760. "Content-Length: " +
  7761. content_length +
  7762. "\r\n"
  7763. "Connection: close\r\n"
  7764. "\r\n";
  7765. ::send(cli,
  7766. #ifdef _WIN32
  7767. static_cast<const char *>(response_header.c_str()),
  7768. static_cast<int>(response_header.size()),
  7769. #else
  7770. response_header.c_str(), response_header.size(),
  7771. #endif
  7772. 0);
  7773. std::string chunk(64 * 1024, 'A');
  7774. size_t total_sent = 0;
  7775. while (total_sent < DATA_SIZE) {
  7776. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7777. auto sent = ::send(cli,
  7778. #ifdef _WIN32
  7779. static_cast<const char *>(chunk.c_str()),
  7780. static_cast<int>(to_send),
  7781. #else
  7782. chunk.c_str(), to_send,
  7783. #endif
  7784. 0);
  7785. if (sent <= 0) break;
  7786. total_sent += static_cast<size_t>(sent);
  7787. }
  7788. detail::close_socket(cli);
  7789. }
  7790. detail::close_socket(srv);
  7791. });
  7792. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7793. size_t total_received = 0;
  7794. {
  7795. Client cli("127.0.0.1", PORT + 2);
  7796. cli.set_read_timeout(10, 0);
  7797. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  7798. auto res =
  7799. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7800. total_received += data_length;
  7801. return true;
  7802. });
  7803. // Should fail because 200MB exceeds the explicit 150MB limit
  7804. EXPECT_FALSE(res);
  7805. }
  7806. server_thread.join();
  7807. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  7808. << "Client with content_receiver should respect the explicit "
  7809. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  7810. << total_received << " bytes.";
  7811. }
  7812. // Verify that an explicit set_payload_max_length larger than the response
  7813. // allows the content_receiver to read all data successfully.
  7814. TEST(ClientVulnerabilityTest,
  7815. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  7816. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7817. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  7818. #ifndef _WIN32
  7819. signal(SIGPIPE, SIG_IGN);
  7820. #endif
  7821. auto server_thread = std::thread([] {
  7822. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7823. default_socket_options(srv);
  7824. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7825. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7826. sockaddr_in addr{};
  7827. addr.sin_family = AF_INET;
  7828. addr.sin_port = htons(PORT + 2);
  7829. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7830. int opt = 1;
  7831. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7832. #ifdef _WIN32
  7833. reinterpret_cast<const char *>(&opt),
  7834. #else
  7835. &opt,
  7836. #endif
  7837. sizeof(opt));
  7838. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7839. ::listen(srv, 1);
  7840. sockaddr_in cli_addr{};
  7841. socklen_t cli_len = sizeof(cli_addr);
  7842. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7843. if (cli != INVALID_SOCKET) {
  7844. char buf[4096];
  7845. ::recv(cli, buf, sizeof(buf), 0);
  7846. auto content_length = std::to_string(DATA_SIZE);
  7847. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7848. "Content-Length: " +
  7849. content_length +
  7850. "\r\n"
  7851. "Connection: close\r\n"
  7852. "\r\n";
  7853. ::send(cli,
  7854. #ifdef _WIN32
  7855. static_cast<const char *>(response_header.c_str()),
  7856. static_cast<int>(response_header.size()),
  7857. #else
  7858. response_header.c_str(), response_header.size(),
  7859. #endif
  7860. 0);
  7861. std::string chunk(64 * 1024, 'A');
  7862. size_t total_sent = 0;
  7863. while (total_sent < DATA_SIZE) {
  7864. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7865. auto sent = ::send(cli,
  7866. #ifdef _WIN32
  7867. static_cast<const char *>(chunk.c_str()),
  7868. static_cast<int>(to_send),
  7869. #else
  7870. chunk.c_str(), to_send,
  7871. #endif
  7872. 0);
  7873. if (sent <= 0) break;
  7874. total_sent += static_cast<size_t>(sent);
  7875. }
  7876. #ifdef _WIN32
  7877. ::shutdown(cli, SD_SEND);
  7878. #else
  7879. ::shutdown(cli, SHUT_WR);
  7880. #endif
  7881. char drain[1024];
  7882. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7883. detail::close_socket(cli);
  7884. }
  7885. detail::close_socket(srv);
  7886. });
  7887. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7888. size_t total_received = 0;
  7889. {
  7890. Client cli("127.0.0.1", PORT + 2);
  7891. cli.set_read_timeout(10, 0);
  7892. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  7893. auto res =
  7894. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7895. total_received += data_length;
  7896. return true;
  7897. });
  7898. ASSERT_TRUE(res);
  7899. EXPECT_EQ(StatusCode::OK_200, res->status);
  7900. }
  7901. server_thread.join();
  7902. EXPECT_EQ(total_received, DATA_SIZE)
  7903. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  7904. << " bytes (larger than " << DATA_SIZE
  7905. << " bytes response), content_receiver should read all data, but only "
  7906. "read "
  7907. << total_received << " bytes.";
  7908. }
  7909. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  7910. // Regression test for "zip bomb" attack on the client side: a malicious server
  7911. // sends a small gzip-compressed response that decompresses to a huge payload.
  7912. // The client must enforce payload_max_length on the decompressed size.
  7913. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  7914. constexpr size_t DECOMPRESSED_SIZE =
  7915. 10 * 1024 * 1024; // 10MB after decompression
  7916. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7917. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  7918. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  7919. std::string compressed;
  7920. {
  7921. httplib::detail::gzip_compressor compressor;
  7922. bool ok =
  7923. compressor.compress(uncompressed.data(), uncompressed.size(),
  7924. /*last=*/true, [&](const char *buf, size_t len) {
  7925. compressed.append(buf, len);
  7926. return true;
  7927. });
  7928. ASSERT_TRUE(ok);
  7929. }
  7930. // Sanity: compressed data should be much smaller than the decompressed size
  7931. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  7932. #ifndef _WIN32
  7933. signal(SIGPIPE, SIG_IGN);
  7934. #endif
  7935. // Set up the listening socket in the main thread so the server is guaranteed
  7936. // to be ready before the client connects (eliminates race condition).
  7937. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7938. default_socket_options(srv);
  7939. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7940. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7941. sockaddr_in addr{};
  7942. addr.sin_family = AF_INET;
  7943. addr.sin_port = htons(PORT + 3);
  7944. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7945. int opt = 1;
  7946. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7947. #ifdef _WIN32
  7948. reinterpret_cast<const char *>(&opt),
  7949. #else
  7950. &opt,
  7951. #endif
  7952. sizeof(opt));
  7953. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  7954. ASSERT_EQ(0, ::listen(srv, 1));
  7955. auto server_thread = std::thread([&compressed, srv] {
  7956. sockaddr_in cli_addr{};
  7957. socklen_t cli_len = sizeof(cli_addr);
  7958. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7959. if (cli != INVALID_SOCKET) {
  7960. // Read the full HTTP request (until \r\n\r\n)
  7961. char buf[4096];
  7962. size_t total = 0;
  7963. while (total < sizeof(buf)) {
  7964. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  7965. if (n <= 0) break;
  7966. total += static_cast<size_t>(n);
  7967. // Check for end of headers
  7968. if (total >= 4) {
  7969. std::string req(buf, total);
  7970. if (req.find("\r\n\r\n") != std::string::npos) break;
  7971. }
  7972. }
  7973. // Malicious response: gzip-compressed body, no Content-Length
  7974. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7975. "Content-Encoding: gzip\r\n"
  7976. "Connection: close\r\n"
  7977. "\r\n";
  7978. ::send(cli,
  7979. #ifdef _WIN32
  7980. static_cast<const char *>(response_header.c_str()),
  7981. static_cast<int>(response_header.size()),
  7982. #else
  7983. response_header.c_str(), response_header.size(),
  7984. #endif
  7985. 0);
  7986. // Send the compressed payload (small on the wire, huge when decompressed)
  7987. size_t total_sent = 0;
  7988. while (total_sent < compressed.size()) {
  7989. auto to_send = std::min(compressed.size() - total_sent,
  7990. static_cast<size_t>(64 * 1024));
  7991. auto sent =
  7992. ::send(cli,
  7993. #ifdef _WIN32
  7994. static_cast<const char *>(compressed.c_str() + total_sent),
  7995. static_cast<int>(to_send),
  7996. #else
  7997. compressed.c_str() + total_sent, to_send,
  7998. #endif
  7999. 0);
  8000. if (sent <= 0) break;
  8001. total_sent += static_cast<size_t>(sent);
  8002. }
  8003. detail::close_socket(cli);
  8004. }
  8005. });
  8006. auto se = detail::scope_exit([&] {
  8007. detail::close_socket(srv);
  8008. server_thread.join();
  8009. });
  8010. size_t total_decompressed = 0;
  8011. {
  8012. Client cli("127.0.0.1", PORT + 3);
  8013. cli.set_read_timeout(5, 0);
  8014. cli.set_decompress(true);
  8015. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8016. auto stream = cli.open_stream("GET", "/zipbomb");
  8017. ASSERT_TRUE(stream.is_valid());
  8018. char buffer[64 * 1024];
  8019. ssize_t n;
  8020. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8021. total_decompressed += static_cast<size_t>(n);
  8022. }
  8023. }
  8024. // The decompressed size must be capped by payload_max_length. Without
  8025. // protection, the client would decompress the full 10MB from a tiny
  8026. // compressed payload, enabling a zip bomb DoS attack.
  8027. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8028. << "Client decompressed " << total_decompressed
  8029. << " bytes from a gzip response. The decompressed size should be "
  8030. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8031. }
  8032. #endif
  8033. TEST(HostAndPortPropertiesTest, NoSSL) {
  8034. httplib::Client cli("www.google.com", 1234);
  8035. ASSERT_EQ("www.google.com", cli.host());
  8036. ASSERT_EQ(1234, cli.port());
  8037. }
  8038. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8039. httplib::Client cli("www.google.com:1234");
  8040. ASSERT_EQ("www.google.com", cli.host());
  8041. ASSERT_EQ(1234, cli.port());
  8042. }
  8043. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8044. // Port number that overflows int — should not crash, client becomes invalid
  8045. httplib::Client cli("http://www.google.com:99999999999999999999");
  8046. ASSERT_FALSE(cli.is_valid());
  8047. }
  8048. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8049. // Port 99999 exceeds valid range (1-65535) — should not crash
  8050. httplib::Client cli("http://www.google.com:99999");
  8051. ASSERT_FALSE(cli.is_valid());
  8052. }
  8053. #ifdef CPPHTTPLIB_SSL_ENABLED
  8054. TEST(HostAndPortPropertiesTest, SSL) {
  8055. httplib::SSLClient cli("www.google.com");
  8056. ASSERT_EQ("www.google.com", cli.host());
  8057. ASSERT_EQ(443, cli.port());
  8058. }
  8059. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8060. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8061. std::string cert;
  8062. read_file(CA_CERT_FILE, cert);
  8063. httplib::SSLClient httplib_client("www.google.com");
  8064. // Load CA store first time
  8065. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8066. // Load CA store second time (update)
  8067. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8068. // Verify client is still valid and can make connections
  8069. httplib_client.enable_server_certificate_verification(true);
  8070. auto res = httplib_client.Get("/");
  8071. ASSERT_TRUE(res);
  8072. // Google may return 200 or 301 depending on various factors
  8073. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8074. res->status == StatusCode::MovedPermanently_301);
  8075. }
  8076. TEST(SSLClientTest, ServerNameIndication_Online) {
  8077. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  8078. auto host = "httpcan.org";
  8079. auto path = std::string{"/get"};
  8080. #else
  8081. auto host = "nghttp2.org";
  8082. auto path = std::string{"/httpbin/get"};
  8083. #endif
  8084. SSLClient cli(host, 443);
  8085. auto res = cli.Get(path);
  8086. ASSERT_TRUE(res);
  8087. ASSERT_EQ(StatusCode::OK_200, res->status);
  8088. }
  8089. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8090. // Use a site that will cause SSL verification failure due to self-signed cert
  8091. SSLClient cli("self-signed.badssl.com", 443);
  8092. cli.enable_server_certificate_verification(true);
  8093. auto res = cli.Get("/");
  8094. ASSERT_TRUE(!res);
  8095. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8096. // Verify backend error is captured for SSLServerVerification
  8097. // This occurs when certificate verification fails
  8098. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8099. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8100. EXPECT_NE(0UL, res.ssl_backend_error());
  8101. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8102. // For OpenSSL, ssl_error is 0 for verification errors
  8103. EXPECT_EQ(0, res.ssl_error());
  8104. #if !defined(_WIN32) || \
  8105. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8106. // On non-Windows or when Windows Schannel is disabled, the error comes
  8107. // from OpenSSL's verification
  8108. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8109. res.ssl_backend_error());
  8110. #endif
  8111. #endif
  8112. }
  8113. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8114. // Use a site where hostname doesn't match the certificate
  8115. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8116. SSLClient cli("wrong.host.badssl.com", 443);
  8117. cli.enable_server_certificate_verification(true);
  8118. cli.enable_server_hostname_verification(true);
  8119. auto res = cli.Get("/");
  8120. ASSERT_TRUE(!res);
  8121. // The error type depends on when hostname verification occurs:
  8122. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8123. // - Mbed TLS: SSLServerVerification (during handshake)
  8124. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8125. res.error() == Error::SSLServerVerification);
  8126. // Verify backend error is captured for hostname verification failure
  8127. EXPECT_NE(0UL, res.ssl_backend_error());
  8128. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8129. // For OpenSSL, ssl_error is 0 for verification errors
  8130. EXPECT_EQ(0, res.ssl_error());
  8131. #if !defined(_WIN32) || \
  8132. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8133. // On non-Windows or when Windows Schannel is disabled, the error comes
  8134. // from OpenSSL's hostname verification
  8135. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8136. res.ssl_backend_error());
  8137. #endif
  8138. #endif
  8139. }
  8140. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8141. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8142. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8143. SSLClient cli("www.google.com", 443);
  8144. cli.enable_server_certificate_verification(true);
  8145. auto res = cli.Get("/");
  8146. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8147. }
  8148. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8149. SSLClient cli("www.google.com", 443);
  8150. cli.enable_server_certificate_verification(true);
  8151. cli.enable_windows_certificate_verification(false);
  8152. auto res = cli.Get("/");
  8153. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8154. }
  8155. #endif
  8156. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8157. Client cli("https://google.com");
  8158. auto res = cli.Get("/");
  8159. ASSERT_TRUE(res);
  8160. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8161. }
  8162. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8163. SSLClient cli("google.com");
  8164. cli.set_ca_cert_path(CA_CERT_FILE);
  8165. auto res = cli.Get("/");
  8166. ASSERT_TRUE(res);
  8167. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8168. }
  8169. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8170. SSLClient cli("google.com");
  8171. cli.enable_server_certificate_verification(true);
  8172. cli.set_ca_cert_path("hello");
  8173. auto res = cli.Get("/");
  8174. ASSERT_TRUE(!res);
  8175. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8176. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8177. // should be set
  8178. EXPECT_EQ(0, res.ssl_error());
  8179. // Verify backend error is captured for SSLLoadingCerts
  8180. // This error occurs when loading CA certificates fails
  8181. EXPECT_NE(0UL, res.ssl_backend_error());
  8182. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8183. // OpenSSL specific error codes:
  8184. // > openssl errstr 0x80000002
  8185. // error:80000002:system library::No such file or directory
  8186. // > openssl errstr 0xA000126
  8187. // error:0A000126:SSL routines::unexpected eof while reading
  8188. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8189. res.ssl_backend_error() == 0xA000126);
  8190. #endif
  8191. }
  8192. TEST(SSLClientTest, ServerCertificateVerification4) {
  8193. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8194. ASSERT_TRUE(svr.is_valid());
  8195. svr.Get("/test", [&](const Request &, Response &res) {
  8196. res.set_content("test", "text/plain");
  8197. svr.stop();
  8198. ASSERT_TRUE(true);
  8199. });
  8200. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8201. auto se = detail::scope_exit([&] {
  8202. t.join();
  8203. ASSERT_FALSE(svr.is_running());
  8204. });
  8205. svr.wait_until_ready();
  8206. SSLClient cli("127.0.0.1", PORT);
  8207. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8208. cli.enable_server_certificate_verification(true);
  8209. cli.set_connection_timeout(30);
  8210. auto res = cli.Get("/test");
  8211. ASSERT_TRUE(res);
  8212. ASSERT_EQ(StatusCode::OK_200, res->status);
  8213. }
  8214. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8215. std::string cert;
  8216. read_file(CA_CERT_FILE, cert);
  8217. SSLClient cli("google.com");
  8218. cli.load_ca_cert_store(cert.data(), cert.size());
  8219. const auto res = cli.Get("/");
  8220. ASSERT_TRUE(res);
  8221. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8222. }
  8223. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8224. // clang-format off
  8225. static constexpr char cert[] =
  8226. "GlobalSign Root CA\n"
  8227. "==================\n"
  8228. "-----BEGIN CERTIFICATE-----\n"
  8229. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8230. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8231. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8232. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8233. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8234. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8235. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8236. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8237. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8238. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8239. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8240. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8241. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8242. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8243. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8244. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8245. "-----END CERTIFICATE-----\n";
  8246. // clang-format on
  8247. SSLClient cli("google.com");
  8248. cli.load_ca_cert_store(cert, sizeof(cert));
  8249. const auto res = cli.Get("/");
  8250. ASSERT_TRUE(res);
  8251. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8252. }
  8253. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8254. SSLClient cli("www.youtube.com");
  8255. cli.set_ca_cert_path(CA_CERT_FILE);
  8256. cli.enable_server_certificate_verification(true);
  8257. cli.set_follow_location(true);
  8258. auto res = cli.Get("/");
  8259. ASSERT_TRUE(res);
  8260. ASSERT_EQ(StatusCode::OK_200, res->status);
  8261. }
  8262. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8263. SSLClient cli("wWw.YouTube.Com");
  8264. cli.set_ca_cert_path(CA_CERT_FILE);
  8265. cli.enable_server_certificate_verification(true);
  8266. cli.enable_server_hostname_verification(true);
  8267. cli.set_follow_location(true);
  8268. auto res = cli.Get("/");
  8269. ASSERT_TRUE(res);
  8270. ASSERT_EQ(StatusCode::OK_200, res->status);
  8271. }
  8272. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8273. SSLClient cli("gOoGlE.COm");
  8274. cli.enable_server_certificate_verification(true);
  8275. cli.enable_server_hostname_verification(true);
  8276. cli.set_follow_location(true);
  8277. auto res = cli.Get("/");
  8278. ASSERT_TRUE(res);
  8279. ASSERT_EQ(StatusCode::OK_200, res->status);
  8280. }
  8281. TEST(SSLClientTest, Issue2004_Online) {
  8282. Client client("https://google.com");
  8283. client.set_follow_location(true);
  8284. auto res = client.Get("/");
  8285. ASSERT_TRUE(res);
  8286. ASSERT_EQ(StatusCode::OK_200, res->status);
  8287. auto body = res->body;
  8288. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8289. }
  8290. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8291. // Create SSLClient with invalid cert/key to make is_valid() return false
  8292. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8293. "nonexistent_key.pem");
  8294. // is_valid() should be false due to cert loading failure
  8295. ASSERT_FALSE(cli.is_valid());
  8296. auto res = cli.Get("/");
  8297. ASSERT_FALSE(res);
  8298. EXPECT_EQ(Error::SSLConnection, res.error());
  8299. }
  8300. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8301. // Test for Issue #2251: SSL error not properly reported when client cert
  8302. // and key paths are swapped or mismatched
  8303. // This simulates the scenario where user accidentally swaps the cert and key
  8304. // files
  8305. // Using client cert file as private key and vice versa (completely wrong)
  8306. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8307. // Should fail validation due to cert/key mismatch
  8308. ASSERT_FALSE(cli.is_valid());
  8309. // Attempt to make a request should fail with proper error
  8310. auto res = cli.Get("/");
  8311. ASSERT_FALSE(res);
  8312. EXPECT_EQ(Error::SSLConnection, res.error());
  8313. // SSL error should be recorded in the Result object (this is the key fix for
  8314. // Issue #2251)
  8315. auto backend_error = res.ssl_backend_error();
  8316. EXPECT_NE(0u, backend_error);
  8317. }
  8318. // Tests cert/key mismatch detection at the TLS context level
  8319. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8320. // Test that using mismatched cert/key causes connection failure.
  8321. // We verify this at the SSLClient level rather than through internal
  8322. // TLS API functions.
  8323. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8324. cli.enable_server_certificate_verification(false);
  8325. cli.set_connection_timeout(2);
  8326. // The mismatch should cause a connection or handshake error
  8327. auto res = cli.Get("/test");
  8328. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8329. // Either way, the request should fail
  8330. EXPECT_FALSE(res);
  8331. }
  8332. #endif
  8333. #if 0
  8334. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8335. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8336. ASSERT_TRUE(cli != nullptr);
  8337. cli->set_address_family(AF_INET6);
  8338. cli->set_interface("en0");
  8339. auto res = cli->Get("/get");
  8340. ASSERT_TRUE(res);
  8341. ASSERT_EQ(StatusCode::OK_200, res->status);
  8342. }
  8343. #endif
  8344. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8345. #ifdef CPPHTTPLIB_SSL_ENABLED
  8346. void ClientCertPresent(
  8347. const std::string &client_cert_file,
  8348. const std::string &client_private_key_file,
  8349. const std::string &client_encrypted_private_key_pass = std::string()) {
  8350. using namespace httplib::tls;
  8351. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8352. CLIENT_CA_CERT_DIR);
  8353. ASSERT_TRUE(svr.is_valid());
  8354. svr.Get("/test", [&](const Request &req, Response &res) {
  8355. res.set_content("test", "text/plain");
  8356. auto cert = req.peer_cert();
  8357. ASSERT_TRUE(static_cast<bool>(cert));
  8358. std::string common_name = cert.subject_cn();
  8359. EXPECT_EQ("Common Name", common_name);
  8360. });
  8361. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8362. auto se = detail::scope_exit([&] {
  8363. svr.stop();
  8364. t.join();
  8365. ASSERT_FALSE(svr.is_running());
  8366. });
  8367. svr.wait_until_ready();
  8368. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8369. client_encrypted_private_key_pass);
  8370. cli.enable_server_certificate_verification(false);
  8371. cli.set_connection_timeout(30);
  8372. auto res = cli.Get("/test");
  8373. ASSERT_TRUE(res);
  8374. ASSERT_EQ(StatusCode::OK_200, res->status);
  8375. }
  8376. TEST(SSLClientServerTest, ClientCertPresent) {
  8377. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8378. }
  8379. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8380. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8381. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8382. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8383. }
  8384. // PEM memory-based constructor tests (works with all TLS backends)
  8385. void PemMemoryClientCertPresent(
  8386. const std::string &client_cert_file,
  8387. const std::string &client_private_key_file,
  8388. const std::string &client_encrypted_private_key_pass = std::string()) {
  8389. // Read PEM files into memory
  8390. std::string server_cert_pem, server_key_pem;
  8391. std::string client_ca_pem;
  8392. std::string client_cert_pem, client_key_pem;
  8393. read_file(SERVER_CERT_FILE, server_cert_pem);
  8394. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8395. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8396. read_file(client_cert_file, client_cert_pem);
  8397. read_file(client_private_key_file, client_key_pem);
  8398. // Create server with PEM memory
  8399. SSLServer::PemMemory server_pem = {
  8400. server_cert_pem.c_str(),
  8401. server_cert_pem.size(),
  8402. server_key_pem.c_str(),
  8403. server_key_pem.size(),
  8404. client_ca_pem.c_str(),
  8405. client_ca_pem.size(),
  8406. nullptr // no password for server key
  8407. };
  8408. SSLServer svr(server_pem);
  8409. ASSERT_TRUE(svr.is_valid());
  8410. svr.Get("/test", [&](const Request &, Response &res) {
  8411. res.set_content("test", "text/plain");
  8412. });
  8413. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8414. auto se = detail::scope_exit([&] {
  8415. svr.stop();
  8416. t.join();
  8417. ASSERT_FALSE(svr.is_running());
  8418. });
  8419. svr.wait_until_ready();
  8420. // Create client with PEM memory
  8421. const char *password = client_encrypted_private_key_pass.empty()
  8422. ? nullptr
  8423. : client_encrypted_private_key_pass.c_str();
  8424. SSLClient::PemMemory client_pem = {
  8425. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8426. client_key_pem.size(), password};
  8427. SSLClient cli(HOST, PORT, client_pem);
  8428. cli.enable_server_certificate_verification(false);
  8429. cli.set_connection_timeout(30);
  8430. auto res = cli.Get("/test");
  8431. ASSERT_TRUE(res);
  8432. ASSERT_EQ(StatusCode::OK_200, res->status);
  8433. }
  8434. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8435. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8436. }
  8437. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8438. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8439. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8440. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8441. }
  8442. TEST(SSLClientServerTest, ClientCertMissing) {
  8443. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8444. CLIENT_CA_CERT_DIR);
  8445. ASSERT_TRUE(svr.is_valid());
  8446. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8447. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8448. auto se = detail::scope_exit([&] {
  8449. svr.stop();
  8450. t.join();
  8451. ASSERT_FALSE(svr.is_running());
  8452. });
  8453. svr.wait_until_ready();
  8454. SSLClient cli(HOST, PORT);
  8455. cli.set_connection_timeout(30);
  8456. auto res = cli.Get("/test");
  8457. ASSERT_TRUE(!res);
  8458. // When client cert is missing and server requires it, connection fails
  8459. // Error type depends on backend implementation
  8460. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8461. res.error() == Error::SSLConnection);
  8462. // Verify backend error is captured
  8463. // Note: This test may have different error codes depending on the exact
  8464. // verification failure
  8465. EXPECT_NE(0UL, res.ssl_backend_error());
  8466. }
  8467. TEST(SSLClientServerTest, TrustDirOptional) {
  8468. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8469. ASSERT_TRUE(svr.is_valid());
  8470. svr.Get("/test", [&](const Request &, Response &res) {
  8471. res.set_content("test", "text/plain");
  8472. });
  8473. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8474. auto se = detail::scope_exit([&] {
  8475. svr.stop();
  8476. t.join();
  8477. ASSERT_FALSE(svr.is_running());
  8478. });
  8479. svr.wait_until_ready();
  8480. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8481. cli.enable_server_certificate_verification(false);
  8482. cli.set_connection_timeout(30);
  8483. auto res = cli.Get("/test");
  8484. ASSERT_TRUE(res);
  8485. ASSERT_EQ(StatusCode::OK_200, res->status);
  8486. }
  8487. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8488. class NoListenSSLServer : public SSLServer {
  8489. public:
  8490. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8491. const char *client_ca_cert_file_path,
  8492. const char *client_ca_cert_dir_path = nullptr)
  8493. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8494. client_ca_cert_dir_path),
  8495. stop_(false) {}
  8496. std::atomic_bool stop_;
  8497. private:
  8498. bool process_and_close_socket(socket_t /*sock*/) override {
  8499. // Don't create SSL context
  8500. while (!stop_.load()) {
  8501. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8502. }
  8503. return true;
  8504. }
  8505. };
  8506. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8507. CLIENT_CA_CERT_FILE);
  8508. ASSERT_TRUE(svr.is_valid());
  8509. svr.Get("/test", [&](const Request &, Response &res) {
  8510. res.set_content("test", "text/plain");
  8511. });
  8512. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8513. auto se = detail::scope_exit([&] {
  8514. svr.stop_ = true;
  8515. svr.stop();
  8516. t.join();
  8517. ASSERT_FALSE(svr.is_running());
  8518. });
  8519. svr.wait_until_ready();
  8520. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8521. cli.enable_server_certificate_verification(false);
  8522. cli.set_connection_timeout(1);
  8523. auto res = cli.Get("/test");
  8524. ASSERT_TRUE(!res);
  8525. EXPECT_EQ(Error::SSLConnection, res.error());
  8526. // Timeout results in WantRead error code (maps to backend-specific value)
  8527. EXPECT_NE(0, res.ssl_error());
  8528. }
  8529. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8530. // Test SSLServer with client certificate verification using the standard
  8531. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8532. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8533. CLIENT_CA_CERT_DIR);
  8534. ASSERT_TRUE(svr.is_valid());
  8535. svr.Get("/test", [&](const Request &req, Response &res) {
  8536. res.set_content("test", "text/plain");
  8537. auto cert = req.peer_cert();
  8538. ASSERT_TRUE(static_cast<bool>(cert));
  8539. auto common_name = cert.subject_cn();
  8540. EXPECT_EQ("Common Name", common_name);
  8541. });
  8542. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8543. auto se = detail::scope_exit([&] {
  8544. svr.stop();
  8545. t.join();
  8546. ASSERT_FALSE(svr.is_running());
  8547. });
  8548. svr.wait_until_ready();
  8549. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8550. cli.enable_server_certificate_verification(false);
  8551. cli.set_connection_timeout(30);
  8552. auto res = cli.Get("/test");
  8553. ASSERT_TRUE(res);
  8554. ASSERT_EQ(StatusCode::OK_200, res->status);
  8555. }
  8556. // Test verify_hostname for both OpenSSL and MbedTLS backends
  8557. // Verifies that wildcard matching and exact matching work consistently
  8558. TEST(SSLClientServerTest, TlsVerifyHostname) {
  8559. using namespace httplib::tls;
  8560. // We need a running server to test against
  8561. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8562. ASSERT_TRUE(svr.is_valid());
  8563. svr.Get("/test", [](const Request &, Response &res) {
  8564. res.set_content("ok", "text/plain");
  8565. });
  8566. thread t([&]() { svr.listen(HOST, PORT); });
  8567. auto se = detail::scope_exit([&] {
  8568. svr.stop();
  8569. t.join();
  8570. });
  8571. svr.wait_until_ready();
  8572. bool verify_callback_called = false;
  8573. bool verify_result_wrong = false;
  8574. SSLClient cli(HOST, PORT);
  8575. cli.enable_server_certificate_verification(true);
  8576. cli.set_ca_cert_path(CA_CERT_FILE);
  8577. cli.set_connection_timeout(5);
  8578. // Note: Test certificate has CN="Common Name", not "localhost"
  8579. bool verify_result_cn = false;
  8580. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8581. verify_callback_called = true;
  8582. if (!ctx.cert) return false;
  8583. // Test 1: "Common Name" should match (our test server cert CN)
  8584. verify_result_cn = ctx.check_hostname("Common Name");
  8585. // Test 2: wrong hostname should not match
  8586. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  8587. return true; // Accept for the purpose of this test
  8588. });
  8589. auto res = cli.Get("/test");
  8590. // The request may succeed or fail depending on cert configuration
  8591. // but the callback should have been called
  8592. ASSERT_TRUE(verify_callback_called)
  8593. << "Verify callback should have been called";
  8594. // CN="Common Name" should match our test certificate
  8595. EXPECT_TRUE(verify_result_cn)
  8596. << "verify_hostname should match 'Common Name' (certificate CN)";
  8597. // Wrong hostname should not match
  8598. EXPECT_FALSE(verify_result_wrong)
  8599. << "verify_hostname should not match 'wronghost.example.com'";
  8600. }
  8601. #endif
  8602. // mbedTLS-specific callback constructor test
  8603. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8604. #ifdef CPPHTTPLIB_SSL_ENABLED
  8605. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8606. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8607. ASSERT_TRUE(svr.is_valid());
  8608. // Set up a handler to verify client certificate is present
  8609. bool client_cert_verified = false;
  8610. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8611. // Verify that client certificate was provided
  8612. client_cert_verified = true;
  8613. res.set_content("success", "text/plain");
  8614. });
  8615. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8616. auto se = detail::scope_exit([&] {
  8617. svr.stop();
  8618. t.join();
  8619. ASSERT_FALSE(svr.is_running());
  8620. });
  8621. svr.wait_until_ready();
  8622. // Client with certificate
  8623. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8624. cli.enable_server_certificate_verification(false);
  8625. cli.set_connection_timeout(30);
  8626. auto res = cli.Get("/test");
  8627. ASSERT_TRUE(res);
  8628. ASSERT_EQ(StatusCode::OK_200, res->status);
  8629. ASSERT_TRUE(client_cert_verified);
  8630. EXPECT_EQ("success", res->body);
  8631. }
  8632. #endif
  8633. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  8634. // backends
  8635. #ifdef CPPHTTPLIB_SSL_ENABLED
  8636. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  8637. using namespace httplib::tls;
  8638. // Test that when client CA cert file is provided,
  8639. // the server properly requests and validates client certificates
  8640. // Create a server with client authentication
  8641. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8642. ASSERT_TRUE(svr.is_valid());
  8643. bool handler_called = false;
  8644. svr.Get("/test", [&](const Request &req, Response &res) {
  8645. handler_called = true;
  8646. // Verify that a client certificate was provided
  8647. auto cert = req.peer_cert();
  8648. ASSERT_TRUE(static_cast<bool>(cert));
  8649. // Get the issuer name
  8650. std::string issuer_str = cert.issuer_name();
  8651. ASSERT_FALSE(issuer_str.empty());
  8652. // The client certificate should be issued by our test CA
  8653. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  8654. res.set_content("authenticated", "text/plain");
  8655. });
  8656. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8657. auto se = detail::scope_exit([&] {
  8658. svr.stop();
  8659. t.join();
  8660. ASSERT_FALSE(svr.is_running());
  8661. });
  8662. svr.wait_until_ready();
  8663. // Connect with a client certificate issued by the CA
  8664. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8665. cli.enable_server_certificate_verification(false);
  8666. cli.set_connection_timeout(30);
  8667. auto res = cli.Get("/test");
  8668. ASSERT_TRUE(res);
  8669. ASSERT_EQ(StatusCode::OK_200, res->status);
  8670. ASSERT_TRUE(handler_called);
  8671. EXPECT_EQ("authenticated", res->body);
  8672. }
  8673. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  8674. using namespace httplib::tls;
  8675. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8676. ASSERT_TRUE(svr.is_valid());
  8677. svr.Get("/test", [](const Request &, Response &res) {
  8678. res.set_content("ok", "text/plain");
  8679. });
  8680. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8681. auto se = detail::scope_exit([&] {
  8682. svr.stop();
  8683. t.join();
  8684. });
  8685. svr.wait_until_ready();
  8686. SSLClient cli(HOST, PORT);
  8687. cli.enable_server_certificate_verification(false);
  8688. cli.set_connection_timeout(30);
  8689. bool cert_checked = false;
  8690. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8691. if (ctx.cert) {
  8692. auto sans = ctx.sans();
  8693. // Test certificate may or may not have SANs - just verify the API
  8694. // works If SANs exist, verify the types are valid
  8695. for (const auto &san : sans) {
  8696. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  8697. san.type == SanType::EMAIL || san.type == SanType::URI ||
  8698. san.type == SanType::OTHER);
  8699. EXPECT_FALSE(san.value.empty());
  8700. }
  8701. cert_checked = true;
  8702. }
  8703. return true;
  8704. });
  8705. auto res = cli.Get("/test");
  8706. ASSERT_TRUE(res);
  8707. EXPECT_TRUE(cert_checked);
  8708. }
  8709. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  8710. using namespace httplib::tls;
  8711. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8712. ASSERT_TRUE(svr.is_valid());
  8713. svr.Get("/test", [](const Request &, Response &res) {
  8714. res.set_content("ok", "text/plain");
  8715. });
  8716. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8717. auto se = detail::scope_exit([&] {
  8718. svr.stop();
  8719. t.join();
  8720. });
  8721. svr.wait_until_ready();
  8722. SSLClient cli(HOST, PORT);
  8723. cli.enable_server_certificate_verification(false);
  8724. cli.set_connection_timeout(30);
  8725. bool validity_checked = false;
  8726. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8727. if (ctx.cert) {
  8728. time_t not_before = 0, not_after = 0;
  8729. bool result = ctx.validity(not_before, not_after);
  8730. EXPECT_TRUE(result);
  8731. // Verify that not_before < now < not_after for a valid cert
  8732. time_t now = time(nullptr);
  8733. EXPECT_LT(not_before, now);
  8734. EXPECT_GT(not_after, now);
  8735. validity_checked = true;
  8736. }
  8737. return true;
  8738. });
  8739. auto res = cli.Get("/test");
  8740. ASSERT_TRUE(res);
  8741. EXPECT_TRUE(validity_checked);
  8742. }
  8743. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  8744. using namespace httplib::tls;
  8745. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8746. ASSERT_TRUE(svr.is_valid());
  8747. svr.Get("/test", [](const Request &, Response &res) {
  8748. res.set_content("ok", "text/plain");
  8749. });
  8750. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8751. auto se = detail::scope_exit([&] {
  8752. svr.stop();
  8753. t.join();
  8754. });
  8755. svr.wait_until_ready();
  8756. SSLClient cli(HOST, PORT);
  8757. cli.enable_server_certificate_verification(false);
  8758. cli.set_connection_timeout(30);
  8759. bool serial_checked = false;
  8760. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8761. if (ctx.cert) {
  8762. std::string serial = ctx.serial();
  8763. EXPECT_FALSE(serial.empty());
  8764. // Serial should be a hex string
  8765. for (char c : serial) {
  8766. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  8767. (c >= 'a' && c <= 'f'));
  8768. }
  8769. serial_checked = true;
  8770. }
  8771. return true;
  8772. });
  8773. auto res = cli.Get("/test");
  8774. ASSERT_TRUE(res);
  8775. EXPECT_TRUE(serial_checked);
  8776. }
  8777. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  8778. // Test 1: Valid CA file - no error should be recorded
  8779. {
  8780. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8781. CLIENT_CA_CERT_FILE);
  8782. ASSERT_TRUE(svr.is_valid());
  8783. // With valid setup, last_ssl_error should be 0
  8784. EXPECT_EQ(0, svr.ssl_last_error());
  8785. }
  8786. // Test 2: Invalid CA file content
  8787. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  8788. {
  8789. // Create a temporary file with completely invalid content
  8790. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  8791. {
  8792. std::ofstream ofs(temp_invalid_ca);
  8793. ofs << "This is not a certificate file at all\n";
  8794. ofs << "Just plain text content\n";
  8795. }
  8796. // Create server with invalid CA file
  8797. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  8798. // Clean up temporary file
  8799. std::remove(temp_invalid_ca);
  8800. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  8801. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  8802. // Note: SSL_CTX_load_verify_locations typically fails first,
  8803. // but our error handling code path is still exercised
  8804. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  8805. }
  8806. }
  8807. TEST(VerifyCallbackTest, VerifyContextFields) {
  8808. using namespace httplib::tls;
  8809. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8810. ASSERT_TRUE(svr.is_valid());
  8811. svr.Get("/test", [](const Request &, Response &res) {
  8812. res.set_content("ok", "text/plain");
  8813. });
  8814. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8815. auto se = detail::scope_exit([&] {
  8816. svr.stop();
  8817. t.join();
  8818. });
  8819. svr.wait_until_ready();
  8820. SSLClient cli(HOST, PORT);
  8821. cli.enable_server_certificate_verification(false);
  8822. cli.set_connection_timeout(30);
  8823. int callback_count = 0;
  8824. bool saw_leaf_cert = false;
  8825. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8826. if (ctx.cert) {
  8827. callback_count++;
  8828. // We should see at least one certificate (the leaf)
  8829. std::string cn = ctx.subject_cn();
  8830. if (!cn.empty()) { saw_leaf_cert = true; }
  8831. // Verify context fields are populated
  8832. EXPECT_NE(ctx.session, nullptr);
  8833. EXPECT_GE(ctx.depth, 0);
  8834. }
  8835. return true;
  8836. });
  8837. auto res = cli.Get("/test");
  8838. ASSERT_TRUE(res);
  8839. EXPECT_GT(callback_count, 0);
  8840. EXPECT_TRUE(saw_leaf_cert);
  8841. }
  8842. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  8843. using httplib::tls::TlsError;
  8844. // Test that verify_error_to_string returns empty for success
  8845. std::string success_str = TlsError::verify_error_to_string(0);
  8846. EXPECT_TRUE(success_str.empty());
  8847. // Test that verify_error_to_string returns non-empty for error codes
  8848. // Using a common error code (certificate expired)
  8849. std::string error_str =
  8850. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  8851. EXPECT_FALSE(error_str.empty());
  8852. }
  8853. TEST(SessionVerifierTest, CertificateAccepted) {
  8854. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8855. ASSERT_TRUE(svr.is_valid());
  8856. svr.Get("/test", [](const Request &, Response &res) {
  8857. res.set_content("ok", "text/plain");
  8858. });
  8859. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8860. auto se = detail::scope_exit([&] {
  8861. svr.stop();
  8862. t.join();
  8863. });
  8864. svr.wait_until_ready();
  8865. SSLClient cli(HOST, PORT);
  8866. cli.enable_server_certificate_verification(false);
  8867. cli.set_connection_timeout(30);
  8868. bool callback_called = false;
  8869. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8870. EXPECT_NE(session, nullptr);
  8871. callback_called = true;
  8872. return SSLVerifierResponse::CertificateAccepted;
  8873. });
  8874. auto res = cli.Get("/test");
  8875. ASSERT_TRUE(res);
  8876. EXPECT_EQ(200, res->status);
  8877. EXPECT_TRUE(callback_called);
  8878. }
  8879. TEST(SessionVerifierTest, CertificateRejected) {
  8880. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8881. ASSERT_TRUE(svr.is_valid());
  8882. svr.Get("/test", [](const Request &, Response &res) {
  8883. res.set_content("ok", "text/plain");
  8884. });
  8885. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8886. auto se = detail::scope_exit([&] {
  8887. svr.stop();
  8888. t.join();
  8889. });
  8890. svr.wait_until_ready();
  8891. SSLClient cli(HOST, PORT);
  8892. cli.enable_server_certificate_verification(false);
  8893. cli.set_connection_timeout(30);
  8894. bool callback_called = false;
  8895. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8896. EXPECT_NE(session, nullptr);
  8897. callback_called = true;
  8898. return SSLVerifierResponse::CertificateRejected;
  8899. });
  8900. auto res = cli.Get("/test");
  8901. EXPECT_FALSE(res);
  8902. EXPECT_TRUE(callback_called);
  8903. }
  8904. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  8905. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8906. ASSERT_TRUE(svr.is_valid());
  8907. svr.Get("/test", [](const Request &, Response &res) {
  8908. res.set_content("ok", "text/plain");
  8909. });
  8910. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8911. auto se = detail::scope_exit([&] {
  8912. svr.stop();
  8913. t.join();
  8914. });
  8915. svr.wait_until_ready();
  8916. // NoDecisionMade with verification disabled should succeed (no default check)
  8917. SSLClient cli(HOST, PORT);
  8918. cli.enable_server_certificate_verification(false);
  8919. cli.set_connection_timeout(30);
  8920. bool callback_called = false;
  8921. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8922. EXPECT_NE(session, nullptr);
  8923. callback_called = true;
  8924. return SSLVerifierResponse::NoDecisionMade;
  8925. });
  8926. auto res = cli.Get("/test");
  8927. ASSERT_TRUE(res);
  8928. EXPECT_EQ(200, res->status);
  8929. EXPECT_TRUE(callback_called);
  8930. }
  8931. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  8932. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8933. ASSERT_TRUE(svr.is_valid());
  8934. svr.Get("/test", [](const Request &, Response &res) {
  8935. res.set_content("ok", "text/plain");
  8936. });
  8937. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8938. auto se = detail::scope_exit([&] {
  8939. svr.stop();
  8940. t.join();
  8941. });
  8942. svr.wait_until_ready();
  8943. // NoDecisionMade with verification enabled should fail (self-signed cert).
  8944. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  8945. // so we only check that the request fails, not whether the callback was
  8946. // called.
  8947. SSLClient cli(HOST, PORT);
  8948. cli.enable_server_certificate_verification(true);
  8949. cli.set_connection_timeout(30);
  8950. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8951. EXPECT_NE(session, nullptr);
  8952. return SSLVerifierResponse::NoDecisionMade;
  8953. });
  8954. auto res = cli.Get("/test");
  8955. EXPECT_FALSE(res);
  8956. }
  8957. TEST(SSLClientServerTest, ClientCAListFromPem) {
  8958. // Test SSL server using PemMemory constructor with client CA certificates
  8959. // Read PEM files
  8960. std::string server_cert_pem, server_key_pem, client_ca_pem;
  8961. read_file(SERVER_CERT_FILE, server_cert_pem);
  8962. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8963. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8964. // Create SSLServer with PemMemory constructor including client CA
  8965. SSLServer::PemMemory server_pem = {
  8966. server_cert_pem.c_str(),
  8967. server_cert_pem.size(),
  8968. server_key_pem.c_str(),
  8969. server_key_pem.size(),
  8970. client_ca_pem.c_str(),
  8971. client_ca_pem.size(),
  8972. nullptr // no password for server key
  8973. };
  8974. SSLServer svr(server_pem);
  8975. ASSERT_TRUE(svr.is_valid());
  8976. // No SSL error should be recorded for valid setup
  8977. EXPECT_EQ(0, svr.ssl_last_error());
  8978. // Set up server endpoints
  8979. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  8980. res.set_content("ok", "text/plain");
  8981. });
  8982. // Start server in a thread
  8983. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  8984. svr.wait_until_ready();
  8985. // Connect with client certificate (using constructor with paths)
  8986. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8987. cli.enable_server_certificate_verification(false);
  8988. auto res = cli.Get("/test-pem-ca");
  8989. ASSERT_TRUE(res);
  8990. EXPECT_EQ(200, res->status);
  8991. EXPECT_EQ("ok", res->body);
  8992. svr.stop();
  8993. server_thread.join();
  8994. }
  8995. #endif
  8996. #ifdef _WIN32
  8997. TEST(CleanupTest, WSACleanup) {
  8998. int ret = WSACleanup();
  8999. ASSERT_EQ(0, ret);
  9000. }
  9001. #endif
  9002. #ifndef CPPHTTPLIB_SSL_ENABLED
  9003. TEST(NoSSLSupport, SimpleInterface) {
  9004. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  9005. }
  9006. #endif
  9007. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9008. TEST(InvalidScheme, SimpleInterface) {
  9009. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  9010. }
  9011. #endif
  9012. TEST(NoScheme, SimpleInterface) {
  9013. Client cli("yahoo.com:80");
  9014. ASSERT_TRUE(cli.is_valid());
  9015. }
  9016. TEST(SendAPI, SimpleInterface_Online) {
  9017. Client cli("http://yahoo.com");
  9018. Request req;
  9019. req.method = "GET";
  9020. req.path = "/";
  9021. auto res = cli.send(req);
  9022. ASSERT_TRUE(res);
  9023. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9024. }
  9025. TEST(SendAPI, WithParamsInRequest) {
  9026. Server svr;
  9027. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  9028. EXPECT_TRUE(req.has_param("test"));
  9029. EXPECT_EQ("test_value", req.get_param_value("test"));
  9030. });
  9031. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  9032. auto se = detail::scope_exit([&] {
  9033. svr.stop();
  9034. t.join();
  9035. ASSERT_FALSE(svr.is_running());
  9036. });
  9037. svr.wait_until_ready();
  9038. Client cli(HOST, PORT);
  9039. {
  9040. Request req;
  9041. req.method = "GET";
  9042. req.path = "/";
  9043. req.params.emplace("test", "test_value");
  9044. auto res = cli.send(req);
  9045. ASSERT_TRUE(res);
  9046. }
  9047. {
  9048. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  9049. ASSERT_TRUE(res);
  9050. }
  9051. }
  9052. TEST(ClientImplMethods, GetSocketTest) {
  9053. httplib::Server svr;
  9054. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9055. res.status = StatusCode::OK_200;
  9056. });
  9057. auto port = svr.bind_to_any_port("127.0.0.1");
  9058. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9059. auto se = detail::scope_exit([&] {
  9060. svr.stop();
  9061. thread.join();
  9062. ASSERT_FALSE(svr.is_running());
  9063. });
  9064. svr.wait_until_ready();
  9065. {
  9066. httplib::Client cli("127.0.0.1", port);
  9067. cli.set_keep_alive(true);
  9068. // Use the behavior of cpp-httplib of opening the connection
  9069. // only when the first request happens. If that changes,
  9070. // this test would be obsolete.
  9071. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9072. // This also implicitly tests the server. But other tests would fail much
  9073. // earlier than this one to be considered.
  9074. auto res = cli.Get("/");
  9075. ASSERT_TRUE(res);
  9076. EXPECT_EQ(StatusCode::OK_200, res->status);
  9077. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9078. }
  9079. }
  9080. #ifdef CPPHTTPLIB_SSL_ENABLED
  9081. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9082. Client cli("http://yahoo.com");
  9083. auto res = cli.Get("/");
  9084. ASSERT_TRUE(res);
  9085. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9086. cli.set_follow_location(true);
  9087. res = cli.Get("/");
  9088. ASSERT_TRUE(res);
  9089. EXPECT_EQ(StatusCode::OK_200, res->status);
  9090. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9091. }
  9092. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9093. Client cli("https://yahoo.com");
  9094. auto res = cli.Get("/");
  9095. ASSERT_TRUE(res);
  9096. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9097. cli.set_follow_location(true);
  9098. res = cli.Get("/");
  9099. ASSERT_TRUE(res);
  9100. EXPECT_EQ(StatusCode::OK_200, res->status);
  9101. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9102. }
  9103. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9104. Client cli("https://yahoo.com");
  9105. auto res = cli.Get("/");
  9106. ASSERT_TRUE(res);
  9107. ASSERT_FALSE(!res);
  9108. ASSERT_TRUE(res);
  9109. ASSERT_FALSE(res == nullptr);
  9110. ASSERT_TRUE(res != nullptr);
  9111. EXPECT_EQ(Error::Success, res.error());
  9112. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9113. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9114. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9115. cli.set_follow_location(true);
  9116. res = cli.Get("/");
  9117. ASSERT_TRUE(res);
  9118. EXPECT_EQ(Error::Success, res.error());
  9119. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9120. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9121. EXPECT_EQ(StatusCode::OK_200, res->status);
  9122. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9123. }
  9124. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9125. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9126. Client cli("https://cdnjs.cloudflare.com");
  9127. auto res =
  9128. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9129. ASSERT_TRUE(res);
  9130. EXPECT_EQ(StatusCode::OK_200, res->status);
  9131. EXPECT_EQ(287630U, res->body.size());
  9132. EXPECT_EQ("application/javascript; charset=utf-8",
  9133. res->get_header_value("Content-Type"));
  9134. }
  9135. #endif
  9136. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9137. #undef REDIR_HOST // Silence compiler warning
  9138. #define REDIR_HOST "https://httpbingo.org"
  9139. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9140. Client cli(REDIR_HOST);
  9141. cli.set_follow_location(true);
  9142. auto res =
  9143. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9144. ASSERT_TRUE(res);
  9145. EXPECT_EQ(StatusCode::OK_200, res->status);
  9146. }
  9147. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9148. Client cli(REDIR_HOST);
  9149. cli.set_follow_location(true);
  9150. Params params;
  9151. params.emplace("url", "http://example.com");
  9152. params.emplace("status_code", "302");
  9153. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9154. ASSERT_TRUE(res);
  9155. EXPECT_EQ(StatusCode::OK_200, res->status);
  9156. }
  9157. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9158. Client cli(REDIR_HOST);
  9159. cli.set_follow_location(true);
  9160. Params params;
  9161. params.emplace("url", "http://example.com");
  9162. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9163. ASSERT_TRUE(res);
  9164. EXPECT_EQ(StatusCode::OK_200, res->status);
  9165. }
  9166. TEST(HttpToHttpsRedirectTest, CertFile) {
  9167. auto ssl_port = PORT + 1;
  9168. Server svr;
  9169. ASSERT_TRUE(svr.is_valid());
  9170. svr.Get("/index", [&](const Request &, Response &res) {
  9171. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9172. "/index");
  9173. svr.stop();
  9174. });
  9175. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9176. ASSERT_TRUE(ssl_svr.is_valid());
  9177. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9178. res.set_content("test", "text/plain");
  9179. ssl_svr.stop();
  9180. });
  9181. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9182. thread t2 =
  9183. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9184. auto se = detail::scope_exit([&] {
  9185. t2.join();
  9186. t.join();
  9187. ASSERT_FALSE(svr.is_running());
  9188. });
  9189. svr.wait_until_ready();
  9190. ssl_svr.wait_until_ready();
  9191. Client cli("127.0.0.1", PORT);
  9192. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9193. cli.enable_server_certificate_verification(true);
  9194. cli.set_follow_location(true);
  9195. cli.set_connection_timeout(30);
  9196. auto res = cli.Get("/index");
  9197. ASSERT_TRUE(res);
  9198. ASSERT_EQ(StatusCode::OK_200, res->status);
  9199. }
  9200. TEST(SSLClientRedirectTest, CertFile) {
  9201. auto ssl_port = PORT + 1;
  9202. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9203. ASSERT_TRUE(ssl_svr1.is_valid());
  9204. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9205. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9206. "/index");
  9207. ssl_svr1.stop();
  9208. });
  9209. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9210. ASSERT_TRUE(ssl_svr2.is_valid());
  9211. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9212. res.set_content("test", "text/plain");
  9213. ssl_svr2.stop();
  9214. });
  9215. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9216. thread t2 =
  9217. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9218. auto se = detail::scope_exit([&] {
  9219. t2.join();
  9220. t.join();
  9221. ASSERT_FALSE(ssl_svr1.is_running());
  9222. });
  9223. ssl_svr1.wait_until_ready();
  9224. ssl_svr2.wait_until_ready();
  9225. SSLClient cli("127.0.0.1", PORT);
  9226. std::string cert;
  9227. read_file(SERVER_CERT2_FILE, cert);
  9228. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9229. cli.enable_server_certificate_verification(true);
  9230. cli.set_follow_location(true);
  9231. cli.set_connection_timeout(30);
  9232. auto res = cli.Get("/index");
  9233. ASSERT_TRUE(res);
  9234. ASSERT_EQ(StatusCode::OK_200, res->status);
  9235. }
  9236. #endif
  9237. #ifdef CPPHTTPLIB_SSL_ENABLED
  9238. // Test that set_ca_cert_store() skips system certs (consistent with
  9239. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9240. // should be trusted - system certs should NOT be loaded.
  9241. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9242. // Load a specific cert that is NOT a system CA cert
  9243. std::string cert;
  9244. read_file(SERVER_CERT2_FILE, cert);
  9245. SSLClient cli("google.com");
  9246. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9247. cli.enable_server_certificate_verification(true);
  9248. // This should FAIL because:
  9249. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9250. // 2. System certs should NOT be loaded when custom store is set
  9251. // If system certs WERE loaded, this would succeed
  9252. auto res = cli.Get("/");
  9253. ASSERT_FALSE(res);
  9254. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9255. }
  9256. TEST(MultipartFormDataTest, LargeData) {
  9257. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9258. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9259. const ContentReader &content_reader) {
  9260. if (req.is_multipart_form_data()) {
  9261. std::vector<FormData> items;
  9262. content_reader(
  9263. [&](const FormData &file) {
  9264. items.push_back(file);
  9265. return true;
  9266. },
  9267. [&](const char *data, size_t data_length) {
  9268. items.back().content.append(data, data_length);
  9269. return true;
  9270. });
  9271. EXPECT_TRUE(std::string(items[0].name) == "document");
  9272. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9273. EXPECT_TRUE(items[0].filename == "2MB_data");
  9274. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9275. EXPECT_TRUE(items[1].name == "hello");
  9276. EXPECT_TRUE(items[1].content == "world");
  9277. EXPECT_TRUE(items[1].filename == "");
  9278. EXPECT_TRUE(items[1].content_type == "");
  9279. } else {
  9280. std::string body;
  9281. content_reader([&](const char *data, size_t data_length) {
  9282. body.append(data, data_length);
  9283. return true;
  9284. });
  9285. }
  9286. });
  9287. auto port = svr.bind_to_any_port(HOST);
  9288. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9289. auto se = detail::scope_exit([&] {
  9290. svr.stop();
  9291. t.join();
  9292. ASSERT_FALSE(svr.is_running());
  9293. });
  9294. svr.wait_until_ready();
  9295. {
  9296. std::string data(1024 * 1024 * 2, '.');
  9297. std::stringstream buffer;
  9298. buffer << data;
  9299. SSLClient cli(HOST, port);
  9300. cli.enable_server_certificate_verification(false);
  9301. UploadFormDataItems items{
  9302. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9303. {"hello", "world", "", ""},
  9304. };
  9305. auto res = cli.Post("/post", items);
  9306. ASSERT_TRUE(res);
  9307. ASSERT_EQ(StatusCode::OK_200, res->status);
  9308. }
  9309. }
  9310. TEST(MultipartFormDataTest, DataProviderItems) {
  9311. std::random_device seed_gen;
  9312. std::mt19937 random(seed_gen());
  9313. std::string rand1;
  9314. rand1.resize(1000);
  9315. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9316. std::string rand2;
  9317. rand2.resize(3000);
  9318. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9319. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9320. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9321. const ContentReader &content_reader) {
  9322. ASSERT_FALSE(req.is_multipart_form_data());
  9323. std::string body;
  9324. content_reader([&](const char *data, size_t data_length) {
  9325. body.append(data, data_length);
  9326. return true;
  9327. });
  9328. EXPECT_EQ(body, "");
  9329. });
  9330. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9331. const ContentReader &content_reader) {
  9332. ASSERT_TRUE(req.is_multipart_form_data());
  9333. std::vector<FormData> items;
  9334. content_reader(
  9335. [&](const FormData &file) {
  9336. items.push_back(file);
  9337. return true;
  9338. },
  9339. [&](const char *data, size_t data_length) {
  9340. items.back().content.append(data, data_length);
  9341. return true;
  9342. });
  9343. ASSERT_TRUE(items.size() == 2);
  9344. EXPECT_EQ(std::string(items[0].name), "name1");
  9345. EXPECT_EQ(items[0].content, "Testing123");
  9346. EXPECT_EQ(items[0].filename, "filename1");
  9347. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9348. EXPECT_EQ(items[1].name, "name2");
  9349. EXPECT_EQ(items[1].content, "Testing456");
  9350. EXPECT_EQ(items[1].filename, "");
  9351. EXPECT_EQ(items[1].content_type, "");
  9352. });
  9353. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9354. const ContentReader &content_reader) {
  9355. ASSERT_TRUE(req.is_multipart_form_data());
  9356. std::vector<FormData> items;
  9357. content_reader(
  9358. [&](const FormData &file) {
  9359. items.push_back(file);
  9360. return true;
  9361. },
  9362. [&](const char *data, size_t data_length) {
  9363. items.back().content.append(data, data_length);
  9364. return true;
  9365. });
  9366. ASSERT_TRUE(items.size() == 2);
  9367. EXPECT_EQ(items[0].name, "name3");
  9368. EXPECT_EQ(items[0].content, rand1);
  9369. EXPECT_EQ(items[0].filename, "filename3");
  9370. EXPECT_EQ(items[0].content_type, "");
  9371. EXPECT_EQ(items[1].name, "name4");
  9372. EXPECT_EQ(items[1].content, rand2);
  9373. EXPECT_EQ(items[1].filename, "filename4");
  9374. EXPECT_EQ(items[1].content_type, "");
  9375. });
  9376. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9377. const ContentReader &content_reader) {
  9378. ASSERT_TRUE(req.is_multipart_form_data());
  9379. std::vector<FormData> items;
  9380. content_reader(
  9381. [&](const FormData &file) {
  9382. items.push_back(file);
  9383. return true;
  9384. },
  9385. [&](const char *data, size_t data_length) {
  9386. items.back().content.append(data, data_length);
  9387. return true;
  9388. });
  9389. ASSERT_TRUE(items.size() == 4);
  9390. EXPECT_EQ(std::string(items[0].name), "name1");
  9391. EXPECT_EQ(items[0].content, "Testing123");
  9392. EXPECT_EQ(items[0].filename, "filename1");
  9393. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9394. EXPECT_EQ(items[1].name, "name2");
  9395. EXPECT_EQ(items[1].content, "Testing456");
  9396. EXPECT_EQ(items[1].filename, "");
  9397. EXPECT_EQ(items[1].content_type, "");
  9398. EXPECT_EQ(items[2].name, "name3");
  9399. EXPECT_EQ(items[2].content, rand1);
  9400. EXPECT_EQ(items[2].filename, "filename3");
  9401. EXPECT_EQ(items[2].content_type, "");
  9402. EXPECT_EQ(items[3].name, "name4");
  9403. EXPECT_EQ(items[3].content, rand2);
  9404. EXPECT_EQ(items[3].filename, "filename4");
  9405. EXPECT_EQ(items[3].content_type, "");
  9406. });
  9407. auto port = svr.bind_to_any_port("localhost");
  9408. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9409. auto se = detail::scope_exit([&] {
  9410. svr.stop();
  9411. t.join();
  9412. ASSERT_FALSE(svr.is_running());
  9413. });
  9414. svr.wait_until_ready();
  9415. {
  9416. SSLClient cli("localhost", port);
  9417. cli.enable_server_certificate_verification(false);
  9418. UploadFormDataItems items{
  9419. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9420. {"name2", "Testing456", "", ""}, // not a file
  9421. };
  9422. {
  9423. auto res = cli.Post("/post-none", {}, {}, {});
  9424. ASSERT_TRUE(res);
  9425. ASSERT_EQ(StatusCode::OK_200, res->status);
  9426. }
  9427. FormDataProviderItems providers;
  9428. {
  9429. auto res =
  9430. cli.Post("/post-items", {}, items, providers); // empty providers
  9431. ASSERT_TRUE(res);
  9432. ASSERT_EQ(StatusCode::OK_200, res->status);
  9433. }
  9434. providers.push_back({"name3",
  9435. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9436. // test the offset is given correctly at each step
  9437. if (!offset)
  9438. sink.os.write(rand1.data(), 30);
  9439. else if (offset == 30)
  9440. sink.os.write(rand1.data() + 30, 300);
  9441. else if (offset == 330)
  9442. sink.os.write(rand1.data() + 330, 670);
  9443. else if (offset == rand1.size())
  9444. sink.done();
  9445. return true;
  9446. },
  9447. "filename3",
  9448. {}});
  9449. providers.push_back({"name4",
  9450. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9451. // test the offset is given correctly at each step
  9452. if (!offset)
  9453. sink.os.write(rand2.data(), 2000);
  9454. else if (offset == 2000)
  9455. sink.os.write(rand2.data() + 2000, 1);
  9456. else if (offset == 2001)
  9457. sink.os.write(rand2.data() + 2001, 999);
  9458. else if (offset == rand2.size())
  9459. sink.done();
  9460. return true;
  9461. },
  9462. "filename4",
  9463. {}});
  9464. {
  9465. auto res = cli.Post("/post-providers", {}, {}, providers);
  9466. ASSERT_TRUE(res);
  9467. ASSERT_EQ(StatusCode::OK_200, res->status);
  9468. }
  9469. {
  9470. auto res = cli.Post("/post-both", {}, items, providers);
  9471. ASSERT_TRUE(res);
  9472. ASSERT_EQ(StatusCode::OK_200, res->status);
  9473. }
  9474. }
  9475. }
  9476. TEST(MultipartFormDataTest, BadHeader) {
  9477. Server svr;
  9478. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9479. res.set_content("ok", "text/plain");
  9480. });
  9481. thread t = thread([&] { svr.listen(HOST, PORT); });
  9482. auto se = detail::scope_exit([&] {
  9483. svr.stop();
  9484. t.join();
  9485. ASSERT_FALSE(svr.is_running());
  9486. });
  9487. svr.wait_until_ready();
  9488. const std::string body =
  9489. "This is the preamble. It is to be ignored, though it\r\n"
  9490. "is a handy place for composition agents to include an\r\n"
  9491. "explanatory note to non-MIME conformant readers.\r\n"
  9492. "\r\n"
  9493. "\r\n"
  9494. "--simple boundary\r\n"
  9495. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9496. ": BAD...\r\n"
  9497. "\r\n"
  9498. "value1\r\n"
  9499. "--simple boundary\r\n"
  9500. "Content-Disposition: form-data; name=\"field2\"; "
  9501. "filename=\"example.txt\"\r\n"
  9502. "\r\n"
  9503. "value2\r\n"
  9504. "--simple boundary--\r\n"
  9505. "This is the epilogue. It is also to be ignored.\r\n";
  9506. std::string content_type =
  9507. R"(multipart/form-data; boundary="simple boundary")";
  9508. Client cli(HOST, PORT);
  9509. auto res = cli.Post("/post", body, content_type.c_str());
  9510. ASSERT_TRUE(res);
  9511. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9512. }
  9513. TEST(MultipartFormDataTest, WithPreamble) {
  9514. Server svr;
  9515. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9516. res.set_content("ok", "text/plain");
  9517. });
  9518. thread t = thread([&] { svr.listen(HOST, PORT); });
  9519. auto se = detail::scope_exit([&] {
  9520. svr.stop();
  9521. t.join();
  9522. ASSERT_FALSE(svr.is_running());
  9523. });
  9524. svr.wait_until_ready();
  9525. const std::string body =
  9526. "This is the preamble. It is to be ignored, though it\r\n"
  9527. "is a handy place for composition agents to include an\r\n"
  9528. "explanatory note to non-MIME conformant readers.\r\n"
  9529. "\r\n"
  9530. "\r\n"
  9531. "--simple boundary\r\n"
  9532. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9533. "\r\n"
  9534. "value1\r\n"
  9535. "--simple boundary\r\n"
  9536. "Content-Disposition: form-data; name=\"field2\"; "
  9537. "filename=\"example.txt\"\r\n"
  9538. "\r\n"
  9539. "value2\r\n"
  9540. "--simple boundary--\r\n"
  9541. "This is the epilogue. It is also to be ignored.\r\n";
  9542. std::string content_type =
  9543. R"(multipart/form-data; boundary="simple boundary")";
  9544. Client cli(HOST, PORT);
  9545. auto res = cli.Post("/post", body, content_type.c_str());
  9546. ASSERT_TRUE(res);
  9547. EXPECT_EQ(StatusCode::OK_200, res->status);
  9548. }
  9549. TEST(MultipartFormDataTest, PostCustomBoundary) {
  9550. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9551. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  9552. const ContentReader &content_reader) {
  9553. if (req.is_multipart_form_data()) {
  9554. std::vector<FormData> items;
  9555. content_reader(
  9556. [&](const FormData &file) {
  9557. items.push_back(file);
  9558. return true;
  9559. },
  9560. [&](const char *data, size_t data_length) {
  9561. items.back().content.append(data, data_length);
  9562. return true;
  9563. });
  9564. EXPECT_TRUE(std::string(items[0].name) == "document");
  9565. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9566. EXPECT_TRUE(items[0].filename == "2MB_data");
  9567. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9568. EXPECT_TRUE(items[1].name == "hello");
  9569. EXPECT_TRUE(items[1].content == "world");
  9570. EXPECT_TRUE(items[1].filename == "");
  9571. EXPECT_TRUE(items[1].content_type == "");
  9572. } else {
  9573. std::string body;
  9574. content_reader([&](const char *data, size_t data_length) {
  9575. body.append(data, data_length);
  9576. return true;
  9577. });
  9578. }
  9579. });
  9580. auto port = svr.bind_to_any_port("localhost");
  9581. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9582. auto se = detail::scope_exit([&] {
  9583. svr.stop();
  9584. t.join();
  9585. ASSERT_FALSE(svr.is_running());
  9586. });
  9587. svr.wait_until_ready();
  9588. {
  9589. std::string data(1024 * 1024 * 2, '.');
  9590. std::stringstream buffer;
  9591. buffer << data;
  9592. SSLClient cli("localhost", port);
  9593. cli.enable_server_certificate_verification(false);
  9594. UploadFormDataItems items{
  9595. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9596. {"hello", "world", "", ""},
  9597. };
  9598. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9599. ASSERT_TRUE(res);
  9600. ASSERT_EQ(StatusCode::OK_200, res->status);
  9601. }
  9602. }
  9603. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9604. std::string data(1024 * 1024 * 2, '&');
  9605. std::stringstream buffer;
  9606. buffer << data;
  9607. Client cli("https://localhost:8080");
  9608. UploadFormDataItems items{
  9609. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9610. {"hello", "world", "", ""},
  9611. };
  9612. for (const char &c : " \t\r\n") {
  9613. auto res =
  9614. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9615. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9616. ASSERT_FALSE(res);
  9617. }
  9618. }
  9619. TEST(MultipartFormDataTest, PutFormData) {
  9620. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9621. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9622. const ContentReader &content_reader) {
  9623. if (req.is_multipart_form_data()) {
  9624. std::vector<FormData> items;
  9625. content_reader(
  9626. [&](const FormData &file) {
  9627. items.push_back(file);
  9628. return true;
  9629. },
  9630. [&](const char *data, size_t data_length) {
  9631. items.back().content.append(data, data_length);
  9632. return true;
  9633. });
  9634. EXPECT_TRUE(std::string(items[0].name) == "document");
  9635. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9636. EXPECT_TRUE(items[0].filename == "2MB_data");
  9637. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9638. EXPECT_TRUE(items[1].name == "hello");
  9639. EXPECT_TRUE(items[1].content == "world");
  9640. EXPECT_TRUE(items[1].filename == "");
  9641. EXPECT_TRUE(items[1].content_type == "");
  9642. } else {
  9643. std::string body;
  9644. content_reader([&](const char *data, size_t data_length) {
  9645. body.append(data, data_length);
  9646. return true;
  9647. });
  9648. }
  9649. });
  9650. auto port = svr.bind_to_any_port("localhost");
  9651. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9652. auto se = detail::scope_exit([&] {
  9653. svr.stop();
  9654. t.join();
  9655. ASSERT_FALSE(svr.is_running());
  9656. });
  9657. svr.wait_until_ready();
  9658. {
  9659. std::string data(1024 * 1024 * 2, '&');
  9660. std::stringstream buffer;
  9661. buffer << data;
  9662. SSLClient cli("localhost", port);
  9663. cli.enable_server_certificate_verification(false);
  9664. UploadFormDataItems items{
  9665. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9666. {"hello", "world", "", ""},
  9667. };
  9668. auto res = cli.Put("/put", items);
  9669. ASSERT_TRUE(res);
  9670. ASSERT_EQ(StatusCode::OK_200, res->status);
  9671. }
  9672. }
  9673. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  9674. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9675. svr.Put("/put_customboundary",
  9676. [&](const Request &req, const Response & /*res*/,
  9677. const ContentReader &content_reader) {
  9678. if (req.is_multipart_form_data()) {
  9679. std::vector<FormData> items;
  9680. content_reader(
  9681. [&](const FormData &file) {
  9682. items.push_back(file);
  9683. return true;
  9684. },
  9685. [&](const char *data, size_t data_length) {
  9686. items.back().content.append(data, data_length);
  9687. return true;
  9688. });
  9689. EXPECT_TRUE(std::string(items[0].name) == "document");
  9690. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9691. EXPECT_TRUE(items[0].filename == "2MB_data");
  9692. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9693. EXPECT_TRUE(items[1].name == "hello");
  9694. EXPECT_TRUE(items[1].content == "world");
  9695. EXPECT_TRUE(items[1].filename == "");
  9696. EXPECT_TRUE(items[1].content_type == "");
  9697. } else {
  9698. std::string body;
  9699. content_reader([&](const char *data, size_t data_length) {
  9700. body.append(data, data_length);
  9701. return true;
  9702. });
  9703. }
  9704. });
  9705. auto port = svr.bind_to_any_port("localhost");
  9706. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9707. auto se = detail::scope_exit([&] {
  9708. svr.stop();
  9709. t.join();
  9710. ASSERT_FALSE(svr.is_running());
  9711. });
  9712. svr.wait_until_ready();
  9713. {
  9714. std::string data(1024 * 1024 * 2, '&');
  9715. std::stringstream buffer;
  9716. buffer << data;
  9717. SSLClient cli("localhost", port);
  9718. cli.enable_server_certificate_verification(false);
  9719. UploadFormDataItems items{
  9720. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9721. {"hello", "world", "", ""},
  9722. };
  9723. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  9724. ASSERT_TRUE(res);
  9725. ASSERT_EQ(StatusCode::OK_200, res->status);
  9726. }
  9727. }
  9728. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  9729. std::string data(1024 * 1024 * 2, '&');
  9730. std::stringstream buffer;
  9731. buffer << data;
  9732. Client cli("https://localhost:8080");
  9733. cli.enable_server_certificate_verification(false);
  9734. UploadFormDataItems items{
  9735. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9736. {"hello", "world", "", ""},
  9737. };
  9738. for (const char &c : " \t\r\n") {
  9739. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  9740. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9741. ASSERT_FALSE(res);
  9742. }
  9743. }
  9744. TEST(MultipartFormDataTest, AlternateFilename) {
  9745. auto handled = false;
  9746. Server svr;
  9747. svr.Post("/test", [&](const Request &req, Response &res) {
  9748. ASSERT_EQ(2u, req.form.files.size());
  9749. ASSERT_EQ(1u, req.form.fields.size());
  9750. // Test files
  9751. const auto &file1 = req.form.get_file("file1");
  9752. ASSERT_EQ("file1", file1.name);
  9753. ASSERT_EQ("A.txt", file1.filename);
  9754. ASSERT_EQ("text/plain", file1.content_type);
  9755. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  9756. const auto &file2 = req.form.get_file("file2");
  9757. ASSERT_EQ("file2", file2.name);
  9758. ASSERT_EQ("a.html", file2.filename);
  9759. ASSERT_EQ("text/html", file2.content_type);
  9760. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  9761. file2.content);
  9762. // Test text field
  9763. const auto &text = req.form.get_field("text");
  9764. ASSERT_EQ("text default", text);
  9765. res.set_content("ok", "text/plain");
  9766. handled = true;
  9767. });
  9768. thread t = thread([&] { svr.listen(HOST, PORT); });
  9769. auto se = detail::scope_exit([&] {
  9770. svr.stop();
  9771. t.join();
  9772. ASSERT_FALSE(svr.is_running());
  9773. ASSERT_TRUE(handled);
  9774. });
  9775. svr.wait_until_ready();
  9776. auto req = "POST /test HTTP/1.1\r\n"
  9777. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9778. "Content-Length: 399\r\n"
  9779. "\r\n"
  9780. "----------\r\n"
  9781. "Content-Disposition: form-data; name=\"text\"\r\n"
  9782. "\r\n"
  9783. "text default\r\n"
  9784. "----------\r\n"
  9785. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  9786. "filename=\"a.txt\"; name=\"file1\"\r\n"
  9787. "Content-Type: text/plain\r\n"
  9788. "\r\n"
  9789. "Content of a.txt.\r\n"
  9790. "\r\n"
  9791. "----------\r\n"
  9792. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  9793. "\"a.html\"\r\n"
  9794. "Content-Type: text/html\r\n"
  9795. "\r\n"
  9796. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  9797. "\r\n"
  9798. "------------\r\n";
  9799. ASSERT_TRUE(send_request(1, req));
  9800. }
  9801. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  9802. auto handled = false;
  9803. Server svr;
  9804. svr.Post("/test", [&](const Request &req, Response &res) {
  9805. // Case-insensitive "utf-8''" prefix with a long value
  9806. const auto &file = req.form.get_file("file1");
  9807. ASSERT_EQ("file1", file.name);
  9808. // 8000 chars exercises both the Content-Disposition parser and the
  9809. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  9810. // Prior to the fix, std::regex_match on this header would cause O(N)
  9811. // stack recursion in libstdc++, leading to SIGSEGV.
  9812. std::string expected_filename(8000, 'A');
  9813. ASSERT_EQ(expected_filename, file.filename);
  9814. res.set_content("ok", "text/plain");
  9815. handled = true;
  9816. });
  9817. thread t = thread([&] { svr.listen(HOST, PORT); });
  9818. auto se = detail::scope_exit([&] {
  9819. svr.stop();
  9820. t.join();
  9821. ASSERT_FALSE(svr.is_running());
  9822. ASSERT_TRUE(handled);
  9823. });
  9824. svr.wait_until_ready();
  9825. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  9826. // Regression test for GHSA-qq6v-r583-3h69
  9827. std::string long_filename(8000, 'A');
  9828. std::string body = "----------\r\n"
  9829. "Content-Disposition: form-data; name=\"file1\"; "
  9830. "filename*=\"Utf-8''" +
  9831. long_filename +
  9832. "\"\r\n"
  9833. "\r\n"
  9834. "hello\r\n"
  9835. "------------\r\n";
  9836. auto req = "POST /test HTTP/1.1\r\n"
  9837. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9838. "Content-Length: " +
  9839. std::to_string(body.size()) + "\r\n\r\n" + body;
  9840. ASSERT_TRUE(send_request(1, req));
  9841. }
  9842. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  9843. auto handled = false;
  9844. Server svr;
  9845. svr.Post("/test", [&](const Request &req, Response &) {
  9846. ASSERT_EQ(2u, req.form.fields.size());
  9847. const auto &text1 = req.form.get_field("text1");
  9848. ASSERT_EQ("text1", text1);
  9849. const auto &text2 = req.form.get_field("text2");
  9850. ASSERT_EQ("text2", text2);
  9851. handled = true;
  9852. });
  9853. thread t = thread([&] { svr.listen(HOST, PORT); });
  9854. auto se = detail::scope_exit([&] {
  9855. svr.stop();
  9856. t.join();
  9857. ASSERT_FALSE(svr.is_running());
  9858. ASSERT_TRUE(handled);
  9859. });
  9860. svr.wait_until_ready();
  9861. auto req = "POST /test HTTP/1.1\r\n"
  9862. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9863. "Content-Length: 146\r\n"
  9864. "\r\n----------\r\n"
  9865. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9866. "\r\n"
  9867. "text1"
  9868. "\r\n----------\r\n"
  9869. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9870. "\r\n"
  9871. "text2"
  9872. "\r\n------------";
  9873. std::string response;
  9874. ASSERT_TRUE(send_request(1, req, &response));
  9875. ASSERT_EQ("200", response.substr(9, 3));
  9876. }
  9877. TEST(MultipartFormDataTest, ContentLength) {
  9878. auto handled = false;
  9879. Server svr;
  9880. svr.Post("/test", [&](const Request &req, Response &) {
  9881. ASSERT_EQ(2u, req.form.fields.size());
  9882. const auto &text1 = req.form.get_field("text1");
  9883. ASSERT_EQ("text1", text1);
  9884. const auto &text2 = req.form.get_field("text2");
  9885. ASSERT_EQ("text2", text2);
  9886. handled = true;
  9887. });
  9888. thread t = thread([&] { svr.listen(HOST, PORT); });
  9889. auto se = detail::scope_exit([&] {
  9890. svr.stop();
  9891. t.join();
  9892. ASSERT_FALSE(svr.is_running());
  9893. ASSERT_TRUE(handled);
  9894. });
  9895. svr.wait_until_ready();
  9896. auto req = "POST /test HTTP/1.1\r\n"
  9897. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9898. "Content-Length: 167\r\n"
  9899. "\r\n----------\r\n"
  9900. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9901. "Content-Length: 5\r\n"
  9902. "\r\n"
  9903. "text1"
  9904. "\r\n----------\r\n"
  9905. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9906. "\r\n"
  9907. "text2"
  9908. "\r\n------------\r\n";
  9909. std::string response;
  9910. ASSERT_TRUE(send_request(1, req, &response));
  9911. ASSERT_EQ("200", response.substr(9, 3));
  9912. }
  9913. TEST(MultipartFormDataTest, AccessPartHeaders) {
  9914. auto handled = false;
  9915. Server svr;
  9916. svr.Post("/test", [&](const Request &req, Response &) {
  9917. ASSERT_EQ(2u, req.form.fields.size());
  9918. const auto &text1 = req.form.get_field("text1");
  9919. ASSERT_EQ("text1", text1);
  9920. // TODO: Add header access for text fields if needed
  9921. const auto &text2 = req.form.get_field("text2");
  9922. ASSERT_EQ("text2", text2);
  9923. // TODO: Header access for text fields needs to be implemented
  9924. // auto &headers = it->second.headers;
  9925. // ASSERT_EQ(3U, headers.size());
  9926. // auto custom_header = headers.find("x-whatever");
  9927. // ASSERT_TRUE(custom_header != headers.end());
  9928. // ASSERT_NE("customvalue", custom_header->second);
  9929. // ASSERT_EQ("CustomValue", custom_header->second);
  9930. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  9931. handled = true;
  9932. });
  9933. thread t = thread([&] { svr.listen(HOST, PORT); });
  9934. auto se = detail::scope_exit([&] {
  9935. svr.stop();
  9936. t.join();
  9937. ASSERT_FALSE(svr.is_running());
  9938. ASSERT_TRUE(handled);
  9939. });
  9940. svr.wait_until_ready();
  9941. auto req = "POST /test HTTP/1.1\r\n"
  9942. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9943. "Content-Length: 232\r\n"
  9944. "\r\n----------\r\n"
  9945. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9946. "Content-Length: 5\r\n"
  9947. "X-Test: 1\r\n"
  9948. "\r\n"
  9949. "text1"
  9950. "\r\n----------\r\n"
  9951. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9952. "Content-Type: text/plain\r\n"
  9953. "X-Whatever: CustomValue\r\n"
  9954. "\r\n"
  9955. "text2"
  9956. "\r\n------------\r\n"
  9957. "That should be disregarded. Not even read";
  9958. std::string response;
  9959. ASSERT_TRUE(send_request(1, req, &response));
  9960. ASSERT_EQ("200", response.substr(9, 3));
  9961. }
  9962. TEST(MultipartFormDataTest, LargeHeader) {
  9963. auto handled = false;
  9964. Server svr;
  9965. svr.Post("/test", [&](const Request &req, Response &) {
  9966. ASSERT_EQ(1u, req.form.fields.size());
  9967. const auto &text = req.form.get_field("name1");
  9968. ASSERT_EQ("text1", text);
  9969. handled = true;
  9970. });
  9971. thread t = thread([&] { svr.listen(HOST, PORT); });
  9972. auto se = detail::scope_exit([&] {
  9973. svr.stop();
  9974. t.join();
  9975. ASSERT_FALSE(svr.is_running());
  9976. ASSERT_TRUE(handled);
  9977. });
  9978. svr.wait_until_ready();
  9979. auto boundary = std::string("cpp-httplib-multipart-data");
  9980. std::string content = "--" + boundary +
  9981. "\r\n"
  9982. "Content-Disposition: form-data; name=\"name1\"\r\n"
  9983. "\r\n"
  9984. "text1\r\n"
  9985. "--" +
  9986. boundary + "--\r\n";
  9987. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  9988. "Content-Type: multipart/form-data;boundary=" +
  9989. boundary +
  9990. "\r\n"
  9991. "Content-Length: " +
  9992. std::to_string(content.size()) +
  9993. "\r\n"
  9994. "Dummy-Header: ";
  9995. std::string header_suffix = "\r\n"
  9996. "\r\n";
  9997. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  9998. size_t header_dummy_size =
  9999. read_buff_size -
  10000. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  10001. auto header_dummy = std::string(header_dummy_size, '@');
  10002. auto req = header_prefix + header_dummy + header_suffix + content;
  10003. std::string response;
  10004. ASSERT_TRUE(send_request(1, req, &response));
  10005. ASSERT_EQ("200", response.substr(9, 3));
  10006. }
  10007. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  10008. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  10009. // (not chunked Transfer-Encoding) after the streaming refactor.
  10010. auto handled = false;
  10011. Server svr;
  10012. svr.Post("/upload", [&](const Request &req, Response &res) {
  10013. auto cl_it = req.headers.find("Content-Length");
  10014. EXPECT_TRUE(cl_it != req.headers.end());
  10015. auto te_it = req.headers.find("Transfer-Encoding");
  10016. EXPECT_TRUE(te_it == req.headers.end());
  10017. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  10018. res.set_content("ok", "text/plain");
  10019. handled = true;
  10020. });
  10021. auto port = svr.bind_to_any_port(HOST);
  10022. auto t = thread([&] { svr.listen_after_bind(); });
  10023. auto se = detail::scope_exit([&] {
  10024. svr.stop();
  10025. t.join();
  10026. ASSERT_FALSE(svr.is_running());
  10027. ASSERT_TRUE(handled);
  10028. });
  10029. svr.wait_until_ready();
  10030. UploadFormDataItems items = {
  10031. {"field1", "hello", "", "text/plain"},
  10032. {"file1", "world", "test.txt", "application/octet-stream"},
  10033. };
  10034. Client cli(HOST, port);
  10035. auto res = cli.Post("/upload", {}, items);
  10036. ASSERT_TRUE(res);
  10037. EXPECT_EQ(StatusCode::OK_200, res->status);
  10038. }
  10039. TEST(MultipartFormDataTest, MakeFileProvider) {
  10040. // Verify make_file_provider sends a file's contents correctly.
  10041. const std::string file_content(4096, 'Z');
  10042. const std::string tmp_path = "/tmp/httplib_test_make_file_provider.bin";
  10043. {
  10044. std::ofstream ofs(tmp_path, std::ios::binary);
  10045. ofs.write(file_content.data(),
  10046. static_cast<std::streamsize>(file_content.size()));
  10047. }
  10048. auto handled = false;
  10049. Server svr;
  10050. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  10051. const ContentReader &content_reader) {
  10052. ASSERT_TRUE(req.is_multipart_form_data());
  10053. std::vector<FormData> items;
  10054. content_reader(
  10055. [&](const FormData &file) {
  10056. items.push_back(file);
  10057. return true;
  10058. },
  10059. [&](const char *data, size_t data_length) {
  10060. items.back().content.append(data, data_length);
  10061. return true;
  10062. });
  10063. ASSERT_EQ(1u, items.size());
  10064. EXPECT_EQ("myfile", items[0].name);
  10065. EXPECT_EQ("data.bin", items[0].filename);
  10066. EXPECT_EQ("application/octet-stream", items[0].content_type);
  10067. EXPECT_EQ(file_content, items[0].content);
  10068. handled = true;
  10069. });
  10070. auto port = svr.bind_to_any_port(HOST);
  10071. auto t = thread([&] { svr.listen_after_bind(); });
  10072. auto se = detail::scope_exit([&] {
  10073. svr.stop();
  10074. t.join();
  10075. ASSERT_FALSE(svr.is_running());
  10076. ASSERT_TRUE(handled);
  10077. std::remove(tmp_path.c_str());
  10078. });
  10079. svr.wait_until_ready();
  10080. FormDataProviderItems providers;
  10081. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  10082. "application/octet-stream"));
  10083. Client cli(HOST, port);
  10084. auto res = cli.Post("/upload", {}, {}, providers);
  10085. ASSERT_TRUE(res);
  10086. EXPECT_EQ(StatusCode::OK_200, res->status);
  10087. }
  10088. TEST(MakeFileBodyTest, Basic) {
  10089. const std::string file_content(4096, 'Z');
  10090. const std::string tmp_path = "/tmp/httplib_test_make_file_body.bin";
  10091. {
  10092. std::ofstream ofs(tmp_path, std::ios::binary);
  10093. ofs.write(file_content.data(),
  10094. static_cast<std::streamsize>(file_content.size()));
  10095. }
  10096. auto handled = false;
  10097. Server svr;
  10098. svr.Post("/upload", [&](const Request &req, Response &res) {
  10099. EXPECT_EQ(file_content, req.body);
  10100. handled = true;
  10101. res.status = StatusCode::OK_200;
  10102. });
  10103. auto port = svr.bind_to_any_port(HOST);
  10104. auto t = thread([&] { svr.listen_after_bind(); });
  10105. auto se = detail::scope_exit([&] {
  10106. svr.stop();
  10107. t.join();
  10108. ASSERT_FALSE(svr.is_running());
  10109. ASSERT_TRUE(handled);
  10110. std::remove(tmp_path.c_str());
  10111. });
  10112. svr.wait_until_ready();
  10113. auto fb = make_file_body(tmp_path);
  10114. ASSERT_GT(fb.first, 0u);
  10115. Client cli(HOST, port);
  10116. auto res =
  10117. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  10118. ASSERT_TRUE(res);
  10119. EXPECT_EQ(StatusCode::OK_200, res->status);
  10120. }
  10121. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  10122. static constexpr unsigned int number_of_tasks{1000000};
  10123. std::atomic_uint count{0};
  10124. std::unique_ptr<TaskQueue> task_queue{
  10125. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  10126. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10127. auto queued = task_queue->enqueue(
  10128. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  10129. EXPECT_TRUE(queued);
  10130. }
  10131. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10132. task_queue->shutdown();
  10133. #else
  10134. EXPECT_NO_THROW(task_queue->shutdown());
  10135. #endif
  10136. EXPECT_EQ(number_of_tasks, count.load());
  10137. }
  10138. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  10139. static constexpr unsigned int number_of_tasks{1000000};
  10140. static constexpr unsigned int qlimit{2};
  10141. unsigned int queued_count{0};
  10142. std::atomic_uint count{0};
  10143. std::unique_ptr<TaskQueue> task_queue{
  10144. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  10145. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10146. if (task_queue->enqueue(
  10147. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  10148. queued_count++;
  10149. }
  10150. }
  10151. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10152. task_queue->shutdown();
  10153. #else
  10154. EXPECT_NO_THROW(task_queue->shutdown());
  10155. #endif
  10156. EXPECT_EQ(queued_count, count.load());
  10157. EXPECT_TRUE(queued_count <= number_of_tasks);
  10158. EXPECT_TRUE(queued_count >= qlimit);
  10159. }
  10160. TEST(TaskQueueTest, MaxQueuedRequests) {
  10161. static constexpr unsigned int qlimit{3};
  10162. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  10163. std::condition_variable sem_cv;
  10164. std::mutex sem_mtx;
  10165. int credits = 0;
  10166. bool queued;
  10167. /* Fill up the queue with tasks that will block until we give them credits to
  10168. * complete. */
  10169. for (unsigned int n = 0; n <= qlimit;) {
  10170. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  10171. std::unique_lock<std::mutex> lock(sem_mtx);
  10172. while (credits <= 0) {
  10173. sem_cv.wait(lock);
  10174. }
  10175. /* Consume the credit and signal the test code if they are all gone. */
  10176. if (--credits == 0) { sem_cv.notify_one(); }
  10177. });
  10178. if (n < qlimit) {
  10179. /* The first qlimit enqueues must succeed. */
  10180. EXPECT_TRUE(queued);
  10181. } else {
  10182. /* The last one will succeed only when the worker thread
  10183. * starts and dequeues the first blocking task. Although
  10184. * not necessary for the correctness of this test, we sleep for
  10185. * a short while to avoid busy waiting. */
  10186. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10187. }
  10188. if (queued) { n++; }
  10189. }
  10190. /* Further enqueues must fail since the queue is full. */
  10191. for (auto i = 0; i < 4; i++) {
  10192. queued = task_queue->enqueue([] {});
  10193. EXPECT_FALSE(queued);
  10194. }
  10195. /* Give the credits to allow the previous tasks to complete. */
  10196. {
  10197. std::unique_lock<std::mutex> lock(sem_mtx);
  10198. credits += qlimit + 1;
  10199. }
  10200. sem_cv.notify_all();
  10201. /* Wait for all the credits to be consumed. */
  10202. {
  10203. std::unique_lock<std::mutex> lock(sem_mtx);
  10204. while (credits > 0) {
  10205. sem_cv.wait(lock);
  10206. }
  10207. }
  10208. /* Check that we are able again to enqueue at least qlimit tasks. */
  10209. for (unsigned int i = 0; i < qlimit; i++) {
  10210. queued = task_queue->enqueue([] {});
  10211. EXPECT_TRUE(queued);
  10212. }
  10213. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10214. task_queue->shutdown();
  10215. #else
  10216. EXPECT_NO_THROW(task_queue->shutdown());
  10217. #endif
  10218. }
  10219. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  10220. Server svr;
  10221. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10222. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  10223. });
  10224. svr.Get("/hello", [](const Request &req, Response &res) {
  10225. res.set_content(req.get_param_value("key"), "text/plain");
  10226. });
  10227. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10228. auto se = detail::scope_exit([&] {
  10229. svr.stop();
  10230. thread.join();
  10231. ASSERT_FALSE(svr.is_running());
  10232. });
  10233. svr.wait_until_ready();
  10234. {
  10235. Client cli(HOST, PORT);
  10236. cli.set_follow_location(true);
  10237. auto res = cli.Get("/");
  10238. ASSERT_TRUE(res);
  10239. EXPECT_EQ(StatusCode::OK_200, res->status);
  10240. EXPECT_EQ("val&key2=val2", res->body);
  10241. }
  10242. }
  10243. #endif
  10244. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  10245. Server svr;
  10246. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10247. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  10248. });
  10249. svr.Get("/hello", [](const Request &req, Response &res) {
  10250. res.set_content(req.get_param_value("key"), "text/plain");
  10251. });
  10252. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10253. auto se = detail::scope_exit([&] {
  10254. svr.stop();
  10255. thread.join();
  10256. ASSERT_FALSE(svr.is_running());
  10257. });
  10258. svr.wait_until_ready();
  10259. {
  10260. Client cli(HOST, PORT);
  10261. cli.set_follow_location(true);
  10262. auto res = cli.Get("/");
  10263. ASSERT_TRUE(res);
  10264. EXPECT_EQ(StatusCode::OK_200, res->status);
  10265. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  10266. }
  10267. }
  10268. #ifdef CPPHTTPLIB_SSL_ENABLED
  10269. TEST(RedirectTest, Issue2185_Online) {
  10270. SSLClient client("github.com");
  10271. client.set_follow_location(true);
  10272. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  10273. "Coollab-Windows.zip");
  10274. ASSERT_TRUE(res);
  10275. EXPECT_EQ(StatusCode::OK_200, res->status);
  10276. EXPECT_EQ(9920427U, res->body.size());
  10277. }
  10278. #endif
  10279. TEST(VulnerabilityTest, CRLFInjection) {
  10280. Server svr;
  10281. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  10282. res.set_content("Hello 1", "text/plain");
  10283. });
  10284. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  10285. res.set_content("Hello 2", "text/plain");
  10286. });
  10287. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  10288. res.set_content("Hello 3", "text/plain");
  10289. });
  10290. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  10291. res.set_content("Hello 4", "text/plain");
  10292. });
  10293. svr.set_logger([](const Request &req, const Response & /*res*/) {
  10294. for (const auto &x : req.headers) {
  10295. auto key = x.first;
  10296. EXPECT_STRNE("evil", key.c_str());
  10297. }
  10298. });
  10299. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10300. auto se = detail::scope_exit([&] {
  10301. svr.stop();
  10302. thread.join();
  10303. ASSERT_FALSE(svr.is_running());
  10304. });
  10305. svr.wait_until_ready();
  10306. {
  10307. Client cli(HOST, PORT);
  10308. cli.Post("/test1", "A=B",
  10309. "application/x-www-form-urlencoded\r\nevil: hello1");
  10310. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  10311. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  10312. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  10313. }
  10314. }
  10315. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  10316. auto server_thread = std::thread([] {
  10317. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10318. default_socket_options(srv);
  10319. sockaddr_in addr{};
  10320. addr.sin_family = AF_INET;
  10321. addr.sin_port = htons(PORT + 1);
  10322. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10323. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10324. ::listen(srv, 1);
  10325. sockaddr_in cli_addr{};
  10326. socklen_t cli_len = sizeof(cli_addr);
  10327. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10328. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  10329. std::string buf_all;
  10330. char buf[2048];
  10331. ssize_t n;
  10332. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  10333. buf_all.append(buf, static_cast<size_t>(n));
  10334. size_t pos;
  10335. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  10336. auto request_block = buf_all.substr(0, pos + 4); // include separator
  10337. auto e = request_block.find("\r\n");
  10338. if (e != std::string::npos) {
  10339. auto request_line = request_block.substr(0, e);
  10340. std::string msg =
  10341. "CRLF injection detected in request line: '" + request_line + "'";
  10342. EXPECT_FALSE(true) << msg;
  10343. }
  10344. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  10345. ::send(cli,
  10346. #ifdef _WIN32
  10347. static_cast<const char *>(resp.c_str()),
  10348. static_cast<int>(resp.size()),
  10349. #else
  10350. resp.c_str(), resp.size(),
  10351. #endif
  10352. 0);
  10353. buf_all.erase(0, pos + 4);
  10354. }
  10355. }
  10356. detail::close_socket(cli);
  10357. detail::close_socket(srv);
  10358. });
  10359. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10360. auto cli = Client("127.0.0.1", PORT + 1);
  10361. auto headers = Headers{
  10362. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  10363. {"Connection", "keep-alive"}};
  10364. auto res = cli.Get("/hi", headers);
  10365. EXPECT_FALSE(res);
  10366. EXPECT_EQ(Error::InvalidHeaders, res.error());
  10367. server_thread.join();
  10368. }
  10369. TEST(PathParamsTest, StaticMatch) {
  10370. const auto pattern = "/users/all";
  10371. detail::PathParamsMatcher matcher(pattern);
  10372. Request request;
  10373. request.path = "/users/all";
  10374. ASSERT_TRUE(matcher.match(request));
  10375. std::unordered_map<std::string, std::string> expected_params = {};
  10376. EXPECT_EQ(request.path_params, expected_params);
  10377. }
  10378. TEST(PathParamsTest, StaticMismatch) {
  10379. const auto pattern = "/users/all";
  10380. detail::PathParamsMatcher matcher(pattern);
  10381. Request request;
  10382. request.path = "/users/1";
  10383. ASSERT_FALSE(matcher.match(request));
  10384. }
  10385. TEST(PathParamsTest, SingleParamInTheMiddle) {
  10386. const auto pattern = "/users/:id/subscriptions";
  10387. detail::PathParamsMatcher matcher(pattern);
  10388. Request request;
  10389. request.path = "/users/42/subscriptions";
  10390. ASSERT_TRUE(matcher.match(request));
  10391. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10392. EXPECT_EQ(request.path_params, expected_params);
  10393. }
  10394. TEST(PathParamsTest, SingleParamInTheEnd) {
  10395. const auto pattern = "/users/:id";
  10396. detail::PathParamsMatcher matcher(pattern);
  10397. Request request;
  10398. request.path = "/users/24";
  10399. ASSERT_TRUE(matcher.match(request));
  10400. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  10401. EXPECT_EQ(request.path_params, expected_params);
  10402. }
  10403. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  10404. const auto pattern = "/users/:id/";
  10405. detail::PathParamsMatcher matcher(pattern);
  10406. Request request;
  10407. request.path = "/users/42/";
  10408. ASSERT_TRUE(matcher.match(request));
  10409. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10410. EXPECT_EQ(request.path_params, expected_params);
  10411. }
  10412. TEST(PathParamsTest, EmptyParam) {
  10413. const auto pattern = "/users/:id/";
  10414. detail::PathParamsMatcher matcher(pattern);
  10415. Request request;
  10416. request.path = "/users//";
  10417. ASSERT_TRUE(matcher.match(request));
  10418. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10419. EXPECT_EQ(request.path_params, expected_params);
  10420. }
  10421. TEST(PathParamsTest, FragmentMismatch) {
  10422. const auto pattern = "/users/:id/";
  10423. detail::PathParamsMatcher matcher(pattern);
  10424. Request request;
  10425. request.path = "/admins/24/";
  10426. ASSERT_FALSE(matcher.match(request));
  10427. }
  10428. TEST(PathParamsTest, ExtraFragments) {
  10429. const auto pattern = "/users/:id";
  10430. detail::PathParamsMatcher matcher(pattern);
  10431. Request request;
  10432. request.path = "/users/42/subscriptions";
  10433. ASSERT_FALSE(matcher.match(request));
  10434. }
  10435. TEST(PathParamsTest, MissingTrailingParam) {
  10436. const auto pattern = "/users/:id";
  10437. detail::PathParamsMatcher matcher(pattern);
  10438. Request request;
  10439. request.path = "/users";
  10440. ASSERT_FALSE(matcher.match(request));
  10441. }
  10442. TEST(PathParamsTest, MissingParamInTheMiddle) {
  10443. const auto pattern = "/users/:id/subscriptions";
  10444. detail::PathParamsMatcher matcher(pattern);
  10445. Request request;
  10446. request.path = "/users/subscriptions";
  10447. ASSERT_FALSE(matcher.match(request));
  10448. }
  10449. TEST(PathParamsTest, MultipleParams) {
  10450. const auto pattern = "/users/:userid/subscriptions/:subid";
  10451. detail::PathParamsMatcher matcher(pattern);
  10452. Request request;
  10453. request.path = "/users/42/subscriptions/2";
  10454. ASSERT_TRUE(matcher.match(request));
  10455. std::unordered_map<std::string, std::string> expected_params = {
  10456. {"userid", "42"}, {"subid", "2"}};
  10457. EXPECT_EQ(request.path_params, expected_params);
  10458. }
  10459. TEST(PathParamsTest, SequenceOfParams) {
  10460. const auto pattern = "/values/:x/:y/:z";
  10461. detail::PathParamsMatcher matcher(pattern);
  10462. Request request;
  10463. request.path = "/values/1/2/3";
  10464. ASSERT_TRUE(matcher.match(request));
  10465. std::unordered_map<std::string, std::string> expected_params = {
  10466. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  10467. EXPECT_EQ(request.path_params, expected_params);
  10468. }
  10469. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  10470. const auto pattern = "/prefix:suffix";
  10471. detail::PathParamsMatcher matcher(pattern);
  10472. Request request;
  10473. request.path = "/prefix:suffix";
  10474. ASSERT_TRUE(matcher.match(request));
  10475. const std::unordered_map<std::string, std::string> expected_params = {};
  10476. EXPECT_EQ(request.path_params, expected_params);
  10477. }
  10478. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  10479. // If ipv6 regex working, regex match codepath is taken.
  10480. // else port will default to 80 in Client impl
  10481. int clientImplMagicPort = 80;
  10482. int port = 4321;
  10483. // above ports must be different to avoid false negative
  10484. EXPECT_NE(clientImplMagicPort, port);
  10485. std::string ipV6TestURL = "http://[ff06::c3]";
  10486. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  10487. CLIENT_PRIVATE_KEY_FILE);
  10488. EXPECT_EQ(cli.port(), port);
  10489. }
  10490. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  10491. auto file_path = "./www/dir/index.html";
  10492. auto dir_path = "./www/dir";
  10493. detail::FileStat stat_file(file_path);
  10494. EXPECT_TRUE(stat_file.is_file());
  10495. EXPECT_FALSE(stat_file.is_dir());
  10496. detail::FileStat stat_dir(dir_path);
  10497. EXPECT_FALSE(stat_dir.is_file());
  10498. EXPECT_TRUE(stat_dir.is_dir());
  10499. }
  10500. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  10501. // IPv4 with default HTTP port (80)
  10502. EXPECT_EQ("example.com",
  10503. detail::make_host_and_port_string("example.com", 80, false));
  10504. // IPv4 with default HTTPS port (443)
  10505. EXPECT_EQ("example.com",
  10506. detail::make_host_and_port_string("example.com", 443, true));
  10507. // IPv4 with non-default HTTP port
  10508. EXPECT_EQ("example.com:8080",
  10509. detail::make_host_and_port_string("example.com", 8080, false));
  10510. // IPv4 with non-default HTTPS port
  10511. EXPECT_EQ("example.com:8443",
  10512. detail::make_host_and_port_string("example.com", 8443, true));
  10513. // IPv6 with default HTTP port (80)
  10514. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  10515. // IPv6 with default HTTPS port (443)
  10516. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  10517. // IPv6 with non-default HTTP port
  10518. EXPECT_EQ("[::1]:8080",
  10519. detail::make_host_and_port_string("::1", 8080, false));
  10520. // IPv6 with non-default HTTPS port
  10521. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  10522. // IPv6 full address with default port
  10523. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  10524. detail::make_host_and_port_string(
  10525. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  10526. // IPv6 full address with non-default port
  10527. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  10528. detail::make_host_and_port_string(
  10529. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  10530. // IPv6 localhost with non-default port
  10531. EXPECT_EQ("[::1]:3000",
  10532. detail::make_host_and_port_string("::1", 3000, false));
  10533. // IPv6 with zone ID (link-local address) with default port
  10534. EXPECT_EQ("[fe80::1%eth0]",
  10535. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  10536. // IPv6 with zone ID (link-local address) with non-default port
  10537. EXPECT_EQ("[fe80::1%eth0]:8080",
  10538. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  10539. // Edge case: Port 443 with is_ssl=false (should add port)
  10540. EXPECT_EQ("example.com:443",
  10541. detail::make_host_and_port_string("example.com", 443, false));
  10542. // Edge case: Port 80 with is_ssl=true (should add port)
  10543. EXPECT_EQ("example.com:80",
  10544. detail::make_host_and_port_string("example.com", 80, true));
  10545. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  10546. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  10547. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  10548. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  10549. // Security fix: Already bracketed IPv6 should not get double brackets
  10550. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  10551. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  10552. EXPECT_EQ("[::1]:8080",
  10553. detail::make_host_and_port_string("[::1]", 8080, false));
  10554. EXPECT_EQ("[2001:db8::1]:8080",
  10555. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  10556. EXPECT_EQ("[fe80::1%eth0]",
  10557. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  10558. EXPECT_EQ("[fe80::1%eth0]:8080",
  10559. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  10560. // Edge case: Empty host (should return as-is)
  10561. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  10562. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  10563. // This is a known limitation but shouldn't crash
  10564. EXPECT_EQ("[host:name]",
  10565. detail::make_host_and_port_string("host:name", 80, false));
  10566. // Port number edge cases (no validation, but should not crash)
  10567. EXPECT_EQ("example.com:0",
  10568. detail::make_host_and_port_string("example.com", 0, false));
  10569. EXPECT_EQ("example.com:-1",
  10570. detail::make_host_and_port_string("example.com", -1, false));
  10571. EXPECT_EQ("example.com:65535",
  10572. detail::make_host_and_port_string("example.com", 65535, false));
  10573. EXPECT_EQ("example.com:65536",
  10574. detail::make_host_and_port_string("example.com", 65536, false));
  10575. }
  10576. #ifdef CPPHTTPLIB_SSL_ENABLED
  10577. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  10578. httplib::SSLClient cli("roblox.com", 443);
  10579. cli.set_follow_location(true);
  10580. auto res = cli.Get("/");
  10581. ASSERT_TRUE(res);
  10582. EXPECT_EQ(StatusCode::OK_200, res->status);
  10583. }
  10584. #endif
  10585. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  10586. Server svr;
  10587. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10588. EXPECT_EQ(res.status, 400);
  10589. });
  10590. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10591. auto se = detail::scope_exit([&] {
  10592. svr.stop();
  10593. thread.join();
  10594. ASSERT_FALSE(svr.is_running());
  10595. });
  10596. svr.wait_until_ready();
  10597. Client cli(HOST, PORT);
  10598. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  10599. }
  10600. TEST(InvalidHeaderCharsTest, is_field_name) {
  10601. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  10602. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  10603. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  10604. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  10605. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  10606. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  10607. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  10608. EXPECT_FALSE(detail::fields::is_field_name(""));
  10609. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  10610. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  10611. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  10612. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  10613. }
  10614. TEST(InvalidHeaderCharsTest, is_field_value) {
  10615. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  10616. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  10617. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  10618. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  10619. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  10620. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  10621. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  10622. EXPECT_TRUE(detail::fields::is_field_value(""));
  10623. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  10624. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  10625. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  10626. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  10627. EXPECT_TRUE(detail::fields::is_field_value("0"));
  10628. }
  10629. TEST(InvalidHeaderCharsTest, OnServer) {
  10630. Server svr;
  10631. svr.Get("/test_name", [&](const Request &req, Response &res) {
  10632. std::string header = "Not Set";
  10633. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10634. res.set_header(header, "value");
  10635. res.set_content("Page Content Page Content", "text/plain");
  10636. });
  10637. svr.Get("/test_value", [&](const Request &req, Response &res) {
  10638. std::string header = "Not Set";
  10639. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10640. res.set_header("X-Test", header);
  10641. res.set_content("Page Content Page Content", "text/plain");
  10642. });
  10643. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10644. auto se = detail::scope_exit([&] {
  10645. svr.stop();
  10646. thread.join();
  10647. ASSERT_FALSE(svr.is_running());
  10648. });
  10649. svr.wait_until_ready();
  10650. Client cli(HOST, PORT);
  10651. {
  10652. auto res = cli.Get(
  10653. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10654. ASSERT_TRUE(res);
  10655. EXPECT_EQ("Page Content Page Content", res->body);
  10656. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10657. }
  10658. {
  10659. auto res = cli.Get(
  10660. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10661. ASSERT_TRUE(res);
  10662. EXPECT_EQ("Page Content Page Content", res->body);
  10663. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10664. }
  10665. }
  10666. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  10667. auto handled = false;
  10668. Server svr;
  10669. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10670. thread t = thread([&] { svr.listen(HOST, PORT); });
  10671. auto se = detail::scope_exit([&] {
  10672. svr.stop();
  10673. t.join();
  10674. ASSERT_FALSE(svr.is_running());
  10675. ASSERT_FALSE(handled);
  10676. });
  10677. svr.wait_until_ready();
  10678. auto req = "POST /test HTTP/1.1\r\n"
  10679. "Content-Length: x\r\n"
  10680. "\r\n";
  10681. std::string response;
  10682. ASSERT_TRUE(send_request(1, req, &response));
  10683. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10684. response.substr(0, response.find("\r\n")));
  10685. }
  10686. #ifndef _WIN32
  10687. TEST(Expect100ContinueTest, ServerClosesConnection) {
  10688. static constexpr char reject[] = "Unauthorized";
  10689. static constexpr char accept[] = "Upload accepted";
  10690. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  10691. Server svr;
  10692. svr.set_expect_100_continue_handler(
  10693. [](const Request & /*req*/, Response &res) {
  10694. res.status = StatusCode::Unauthorized_401;
  10695. res.set_content(reject, "text/plain");
  10696. return res.status;
  10697. });
  10698. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  10699. res.set_content(accept, "text/plain");
  10700. });
  10701. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10702. auto se = detail::scope_exit([&] {
  10703. svr.stop();
  10704. thread.join();
  10705. ASSERT_FALSE(svr.is_running());
  10706. });
  10707. svr.wait_until_ready();
  10708. {
  10709. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  10710. curl_easy_init(), &curl_easy_cleanup};
  10711. ASSERT_NE(curl, nullptr);
  10712. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  10713. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  10714. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  10715. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  10716. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  10717. &curl_slist_free_all};
  10718. ASSERT_NE(list, nullptr);
  10719. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  10720. struct read_data {
  10721. size_t read_size;
  10722. size_t total_size;
  10723. } data = {0, total_size};
  10724. using read_callback_t =
  10725. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10726. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  10727. void *userdata) -> size_t {
  10728. read_data *data = (read_data *)userdata;
  10729. if (!userdata || data->read_size >= data->total_size) { return 0; }
  10730. std::fill_n(ptr, size * nmemb, 'A');
  10731. data->read_size += size * nmemb;
  10732. return size * nmemb;
  10733. };
  10734. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  10735. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  10736. std::vector<char> buffer;
  10737. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  10738. using write_callback_t =
  10739. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10740. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  10741. void *userdata) -> size_t {
  10742. std::vector<char> *buffer = (std::vector<char> *)userdata;
  10743. buffer->reserve(buffer->size() + size * nmemb + 1);
  10744. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  10745. return size * nmemb;
  10746. };
  10747. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  10748. {
  10749. const auto res = curl_easy_perform(curl.get());
  10750. ASSERT_EQ(res, CURLE_OK);
  10751. }
  10752. {
  10753. auto response_code = long{};
  10754. const auto res =
  10755. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  10756. ASSERT_EQ(res, CURLE_OK);
  10757. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  10758. }
  10759. {
  10760. auto dl = curl_off_t{};
  10761. const auto res =
  10762. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  10763. ASSERT_EQ(res, CURLE_OK);
  10764. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  10765. }
  10766. {
  10767. buffer.push_back('\0');
  10768. ASSERT_STRCASEEQ(buffer.data(), reject);
  10769. }
  10770. }
  10771. }
  10772. #endif
  10773. template <typename S, typename C>
  10774. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  10775. svr.Get("/stream", [&](const Request &, Response &res) {
  10776. auto data = new std::string("01234567890123456789");
  10777. res.set_content_provider(
  10778. data->size(), "text/plain",
  10779. [&, data](size_t offset, size_t length, DataSink &sink) {
  10780. const size_t DATA_CHUNK_SIZE = 4;
  10781. const auto &d = *data;
  10782. std::this_thread::sleep_for(std::chrono::seconds(1));
  10783. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  10784. return true;
  10785. },
  10786. [data](bool success) {
  10787. EXPECT_FALSE(success);
  10788. delete data;
  10789. });
  10790. });
  10791. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  10792. auto i = new size_t(0);
  10793. res.set_content_provider(
  10794. "text/plain",
  10795. [i](size_t, DataSink &sink) {
  10796. if (*i < 5) {
  10797. std::this_thread::sleep_for(std::chrono::seconds(1));
  10798. sink.write("abcd", 4);
  10799. (*i)++;
  10800. } else {
  10801. sink.done();
  10802. }
  10803. return true;
  10804. },
  10805. [i](bool success) {
  10806. EXPECT_FALSE(success);
  10807. delete i;
  10808. });
  10809. });
  10810. svr.Get("/chunked", [&](const Request &, Response &res) {
  10811. auto i = new size_t(0);
  10812. res.set_chunked_content_provider(
  10813. "text/plain",
  10814. [i](size_t, DataSink &sink) {
  10815. if (*i < 5) {
  10816. std::this_thread::sleep_for(std::chrono::seconds(1));
  10817. sink.os << "abcd";
  10818. (*i)++;
  10819. } else {
  10820. sink.done();
  10821. }
  10822. return true;
  10823. },
  10824. [i](bool success) {
  10825. EXPECT_FALSE(success);
  10826. delete i;
  10827. });
  10828. });
  10829. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10830. auto se = detail::scope_exit([&] {
  10831. svr.stop();
  10832. listen_thread.join();
  10833. ASSERT_FALSE(svr.is_running());
  10834. });
  10835. svr.wait_until_ready();
  10836. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  10837. {
  10838. auto start = std::chrono::steady_clock::now();
  10839. auto res = cli.Get("/stream");
  10840. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10841. std::chrono::steady_clock::now() - start)
  10842. .count();
  10843. ASSERT_FALSE(res);
  10844. EXPECT_EQ(Error::Read, res.error());
  10845. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10846. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10847. }
  10848. {
  10849. auto start = std::chrono::steady_clock::now();
  10850. auto res = cli.Get("/stream_without_length");
  10851. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10852. std::chrono::steady_clock::now() - start)
  10853. .count();
  10854. ASSERT_FALSE(res);
  10855. EXPECT_EQ(Error::Read, res.error());
  10856. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10857. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10858. }
  10859. {
  10860. auto start = std::chrono::steady_clock::now();
  10861. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  10862. EXPECT_EQ("abcd", string(data, data_length));
  10863. return true;
  10864. });
  10865. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10866. std::chrono::steady_clock::now() - start)
  10867. .count();
  10868. ASSERT_FALSE(res);
  10869. EXPECT_EQ(Error::Read, res.error());
  10870. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10871. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10872. }
  10873. }
  10874. TEST(MaxTimeoutTest, ContentStream) {
  10875. time_t timeout = 2000;
  10876. time_t threshold = 200;
  10877. Server svr;
  10878. Client cli("localhost", PORT);
  10879. max_timeout_test(svr, cli, timeout, threshold);
  10880. }
  10881. #ifdef CPPHTTPLIB_SSL_ENABLED
  10882. TEST(MaxTimeoutTest, ContentStreamSSL) {
  10883. time_t timeout = 2000;
  10884. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  10885. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10886. SSLClient cli("localhost", PORT);
  10887. cli.enable_server_certificate_verification(false);
  10888. max_timeout_test(svr, cli, timeout, threshold);
  10889. }
  10890. #endif
  10891. class EventDispatcher {
  10892. public:
  10893. EventDispatcher() {}
  10894. bool wait_event(DataSink *sink) {
  10895. unique_lock<mutex> lk(m_);
  10896. int id = id_;
  10897. // Wait with timeout to prevent hanging if client disconnects
  10898. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  10899. [&] { return cid_ == id; })) {
  10900. return false; // Timeout occurred
  10901. }
  10902. sink->write(message_.data(), message_.size());
  10903. return true;
  10904. }
  10905. void send_event(const string &message) {
  10906. lock_guard<mutex> lk(m_);
  10907. cid_ = id_++;
  10908. message_ = message;
  10909. cv_.notify_all();
  10910. }
  10911. private:
  10912. mutex m_;
  10913. condition_variable cv_;
  10914. atomic_int id_{0};
  10915. atomic_int cid_{-1};
  10916. string message_;
  10917. };
  10918. TEST(ClientInThreadTest, Issue2068) {
  10919. EventDispatcher ed;
  10920. Server svr;
  10921. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  10922. res.set_chunked_content_provider("text/event-stream",
  10923. [&](size_t /*offset*/, DataSink &sink) {
  10924. return ed.wait_event(&sink);
  10925. });
  10926. });
  10927. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10928. svr.wait_until_ready();
  10929. thread event_thread([&] {
  10930. int id = 0;
  10931. while (svr.is_running()) {
  10932. this_thread::sleep_for(chrono::milliseconds(500));
  10933. std::stringstream ss;
  10934. ss << "data: " << id << "\n\n";
  10935. ed.send_event(ss.str());
  10936. id++;
  10937. }
  10938. });
  10939. auto se = detail::scope_exit([&] {
  10940. svr.stop();
  10941. listen_thread.join();
  10942. event_thread.join();
  10943. ASSERT_FALSE(svr.is_running());
  10944. });
  10945. {
  10946. auto client = detail::make_unique<Client>(HOST, PORT);
  10947. client->set_read_timeout(std::chrono::minutes(10));
  10948. std::atomic<bool> stop{false};
  10949. std::thread t([&] {
  10950. client->Get("/event1",
  10951. [&](const char *, size_t) -> bool { return !stop; });
  10952. });
  10953. std::this_thread::sleep_for(std::chrono::seconds(2));
  10954. stop = true;
  10955. client->stop();
  10956. t.join();
  10957. // Reset client after thread has finished
  10958. client.reset();
  10959. }
  10960. }
  10961. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  10962. auto handled = false;
  10963. Server svr;
  10964. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10965. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10966. auto se = detail::scope_exit([&] {
  10967. svr.stop();
  10968. t.join();
  10969. ASSERT_FALSE(svr.is_running());
  10970. ASSERT_FALSE(handled);
  10971. });
  10972. svr.wait_until_ready();
  10973. // Two Content-Length headers with different values — must be rejected
  10974. auto req = "POST /test HTTP/1.1\r\n"
  10975. "Content-Length: 5\r\n"
  10976. "Content-Length: 10\r\n"
  10977. "\r\n"
  10978. "hello";
  10979. std::string response;
  10980. ASSERT_TRUE(send_request(1, req, &response));
  10981. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10982. response.substr(0, response.find("\r\n")));
  10983. }
  10984. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  10985. auto handled = false;
  10986. Server svr;
  10987. svr.Post("/test", [&](const Request &, Response &res) {
  10988. handled = true;
  10989. res.set_content("ok", "text/plain");
  10990. });
  10991. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10992. auto se = detail::scope_exit([&] {
  10993. svr.stop();
  10994. t.join();
  10995. ASSERT_FALSE(svr.is_running());
  10996. ASSERT_TRUE(handled);
  10997. });
  10998. svr.wait_until_ready();
  10999. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  11000. auto req = "POST /test HTTP/1.1\r\n"
  11001. "Content-Length: 5\r\n"
  11002. "Content-Length: 5\r\n"
  11003. "\r\n"
  11004. "hello";
  11005. std::string response;
  11006. ASSERT_TRUE(send_request(1, req, &response));
  11007. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  11008. }
  11009. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  11010. Server svr;
  11011. svr.Get("/", [](const Request &req, Response &res) {
  11012. EXPECT_EQ(2U, req.trailers.size());
  11013. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  11014. // Denied
  11015. EXPECT_FALSE(req.has_trailer("Content-Length"));
  11016. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  11017. // Accepted
  11018. EXPECT_TRUE(req.has_trailer("X-Hello"));
  11019. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  11020. EXPECT_TRUE(req.has_trailer("X-World"));
  11021. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  11022. res.set_content("ok", "text/plain");
  11023. });
  11024. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11025. auto se = detail::scope_exit([&] {
  11026. svr.stop();
  11027. t.join();
  11028. ASSERT_FALSE(svr.is_running());
  11029. });
  11030. svr.wait_until_ready();
  11031. const std::string req = "GET / HTTP/1.1\r\n"
  11032. "Transfer-Encoding: chunked\r\n"
  11033. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  11034. "\r\n"
  11035. "0\r\n"
  11036. "Content-Length: 10\r\n"
  11037. "Host: internal.local\r\n"
  11038. "Content-Type: malicious/content\r\n"
  11039. "Cookie: any\r\n"
  11040. "Set-Cookie: any\r\n"
  11041. "X-Forwarded-For: attacker.com\r\n"
  11042. "X-Real-Ip: 1.1.1.1\r\n"
  11043. "X-Hello: hello\r\n"
  11044. "X-World: world\r\n"
  11045. "\r\n";
  11046. std::string res;
  11047. ASSERT_TRUE(send_request(1, req, &res));
  11048. }
  11049. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  11050. Server svr;
  11051. std::string observed_remote_addr;
  11052. std::string observed_xff;
  11053. svr.Get("/ip", [&](const Request &req, Response &res) {
  11054. observed_remote_addr = req.remote_addr;
  11055. observed_xff = req.get_header_value("X-Forwarded-For");
  11056. res.set_content("ok", "text/plain");
  11057. });
  11058. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11059. auto se = detail::scope_exit([&] {
  11060. svr.stop();
  11061. t.join();
  11062. ASSERT_FALSE(svr.is_running());
  11063. });
  11064. svr.wait_until_ready();
  11065. Client cli(HOST, PORT);
  11066. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  11067. ASSERT_TRUE(res);
  11068. EXPECT_EQ(StatusCode::OK_200, res->status);
  11069. EXPECT_EQ(observed_xff, "203.0.113.66");
  11070. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11071. observed_remote_addr == "127.0.0.1");
  11072. }
  11073. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  11074. Server svr;
  11075. svr.set_trusted_proxies({"203.0.113.66"});
  11076. std::string observed_remote_addr;
  11077. std::string observed_xff;
  11078. svr.Get("/ip", [&](const Request &req, Response &res) {
  11079. observed_remote_addr = req.remote_addr;
  11080. observed_xff = req.get_header_value("X-Forwarded-For");
  11081. res.set_content("ok", "text/plain");
  11082. });
  11083. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11084. auto se = detail::scope_exit([&] {
  11085. svr.stop();
  11086. t.join();
  11087. ASSERT_FALSE(svr.is_running());
  11088. });
  11089. svr.wait_until_ready();
  11090. Client cli(HOST, PORT);
  11091. auto res = cli.Get("/ip");
  11092. ASSERT_TRUE(res);
  11093. EXPECT_EQ(StatusCode::OK_200, res->status);
  11094. EXPECT_EQ(observed_xff, "");
  11095. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11096. observed_remote_addr == "127.0.0.1");
  11097. }
  11098. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  11099. Server svr;
  11100. svr.set_trusted_proxies({"203.0.113.66"});
  11101. std::string observed_remote_addr;
  11102. std::string observed_xff;
  11103. svr.Get("/ip", [&](const Request &req, Response &res) {
  11104. observed_remote_addr = req.remote_addr;
  11105. observed_xff = req.get_header_value("X-Forwarded-For");
  11106. res.set_content("ok", "text/plain");
  11107. });
  11108. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11109. auto se = detail::scope_exit([&] {
  11110. svr.stop();
  11111. t.join();
  11112. ASSERT_FALSE(svr.is_running());
  11113. });
  11114. svr.wait_until_ready();
  11115. Client cli(HOST, PORT);
  11116. auto res =
  11117. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  11118. ASSERT_TRUE(res);
  11119. EXPECT_EQ(StatusCode::OK_200, res->status);
  11120. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  11121. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11122. }
  11123. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  11124. Server svr;
  11125. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  11126. std::string observed_remote_addr;
  11127. std::string observed_xff;
  11128. svr.Get("/ip", [&](const Request &req, Response &res) {
  11129. observed_remote_addr = req.remote_addr;
  11130. observed_xff = req.get_header_value("X-Forwarded-For");
  11131. res.set_content("ok", "text/plain");
  11132. });
  11133. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11134. auto se = detail::scope_exit([&] {
  11135. svr.stop();
  11136. t.join();
  11137. ASSERT_FALSE(svr.is_running());
  11138. });
  11139. svr.wait_until_ready();
  11140. Client cli(HOST, PORT);
  11141. auto res = cli.Get(
  11142. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11143. ASSERT_TRUE(res);
  11144. EXPECT_EQ(StatusCode::OK_200, res->status);
  11145. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11146. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11147. }
  11148. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  11149. Server svr;
  11150. svr.set_trusted_proxies({"192.0.2.45"});
  11151. std::string observed_remote_addr;
  11152. std::string observed_xff;
  11153. svr.Get("/ip", [&](const Request &req, Response &res) {
  11154. observed_remote_addr = req.remote_addr;
  11155. observed_xff = req.get_header_value("X-Forwarded-For");
  11156. res.set_content("ok", "text/plain");
  11157. });
  11158. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11159. auto se = detail::scope_exit([&] {
  11160. svr.stop();
  11161. t.join();
  11162. ASSERT_FALSE(svr.is_running());
  11163. });
  11164. svr.wait_until_ready();
  11165. Client cli(HOST, PORT);
  11166. auto res =
  11167. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  11168. ASSERT_TRUE(res);
  11169. EXPECT_EQ(StatusCode::OK_200, res->status);
  11170. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  11171. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11172. }
  11173. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  11174. Server svr;
  11175. svr.set_trusted_proxies({"192.0.2.45"});
  11176. std::string observed_remote_addr;
  11177. std::string observed_xff;
  11178. svr.Get("/ip", [&](const Request &req, Response &res) {
  11179. observed_remote_addr = req.remote_addr;
  11180. observed_xff = req.get_header_value("X-Forwarded-For");
  11181. res.set_content("ok", "text/plain");
  11182. });
  11183. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11184. auto se = detail::scope_exit([&] {
  11185. svr.stop();
  11186. t.join();
  11187. ASSERT_FALSE(svr.is_running());
  11188. });
  11189. svr.wait_until_ready();
  11190. Client cli(HOST, PORT);
  11191. auto res = cli.Get(
  11192. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11193. ASSERT_TRUE(res);
  11194. EXPECT_EQ(StatusCode::OK_200, res->status);
  11195. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11196. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11197. }
  11198. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  11199. Server svr;
  11200. svr.set_trusted_proxies({"192.0.2.45"});
  11201. std::string observed_remote_addr;
  11202. std::string observed_xff;
  11203. svr.Get("/ip", [&](const Request &req, Response &res) {
  11204. observed_remote_addr = req.remote_addr;
  11205. observed_xff = req.get_header_value("X-Forwarded-For");
  11206. res.set_content("ok", "text/plain");
  11207. });
  11208. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11209. auto se = detail::scope_exit([&] {
  11210. svr.stop();
  11211. t.join();
  11212. ASSERT_FALSE(svr.is_running());
  11213. });
  11214. svr.wait_until_ready();
  11215. std::string raw_req =
  11216. "GET /ip HTTP/1.1\r\n"
  11217. "Host: localhost\r\n"
  11218. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  11219. "Connection: close\r\n"
  11220. "\r\n";
  11221. std::string out;
  11222. ASSERT_TRUE(send_request(5, raw_req, &out));
  11223. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11224. // Header parser trims surrounding whitespace of the header value
  11225. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  11226. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11227. }
  11228. #ifndef _WIN32
  11229. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  11230. Server svr;
  11231. svr.Post("/post", [&](const Request &req, Response &res) {
  11232. res.set_content(req.body, "text/plain");
  11233. });
  11234. svr.Put("/put", [&](const Request &req, Response &res) {
  11235. res.set_content(req.body, "text/plain");
  11236. });
  11237. svr.Patch("/patch", [&](const Request &req, Response &res) {
  11238. res.set_content(req.body, "text/plain");
  11239. });
  11240. svr.Delete("/delete", [&](const Request &req, Response &res) {
  11241. res.set_content(req.body, "text/plain");
  11242. });
  11243. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11244. auto se = detail::scope_exit([&] {
  11245. svr.stop();
  11246. t.join();
  11247. ASSERT_FALSE(svr.is_running());
  11248. });
  11249. svr.wait_until_ready();
  11250. std::string resp;
  11251. // POST without Content-Length
  11252. ASSERT_TRUE(send_request(5,
  11253. "POST /post HTTP/1.1\r\n"
  11254. "Host: localhost\r\n"
  11255. "Connection: close\r\n"
  11256. "\r\n",
  11257. &resp));
  11258. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11259. // PUT without Content-Length
  11260. resp.clear();
  11261. ASSERT_TRUE(send_request(5,
  11262. "PUT /put HTTP/1.1\r\n"
  11263. "Host: localhost\r\n"
  11264. "Connection: close\r\n"
  11265. "\r\n",
  11266. &resp));
  11267. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11268. // PATCH without Content-Length
  11269. resp.clear();
  11270. ASSERT_TRUE(send_request(5,
  11271. "PATCH /patch HTTP/1.1\r\n"
  11272. "Host: localhost\r\n"
  11273. "Connection: close\r\n"
  11274. "\r\n",
  11275. &resp));
  11276. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11277. // DELETE without Content-Length
  11278. resp.clear();
  11279. ASSERT_TRUE(send_request(5,
  11280. "DELETE /delete HTTP/1.1\r\n"
  11281. "Host: localhost\r\n"
  11282. "Connection: close\r\n"
  11283. "\r\n",
  11284. &resp));
  11285. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11286. }
  11287. #endif
  11288. //==============================================================================
  11289. // open_stream() Tests
  11290. //==============================================================================
  11291. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  11292. std::string result;
  11293. char buf[8192];
  11294. ssize_t n;
  11295. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11296. result.append(buf, static_cast<size_t>(n));
  11297. }
  11298. return result;
  11299. }
  11300. // Mock stream for unit tests
  11301. class MockStream : public Stream {
  11302. public:
  11303. std::string data;
  11304. size_t pos = 0;
  11305. ssize_t error_after = -1; // -1 = no error
  11306. explicit MockStream(const std::string &d, ssize_t err = -1)
  11307. : data(d), error_after(err) {}
  11308. bool is_readable() const override { return true; }
  11309. bool wait_readable() const override { return true; }
  11310. bool wait_writable() const override { return true; }
  11311. ssize_t read(char *ptr, size_t size) override {
  11312. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  11313. if (pos >= data.size()) return 0;
  11314. size_t limit =
  11315. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  11316. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  11317. std::memcpy(ptr, data.data() + pos, to_read);
  11318. pos += to_read;
  11319. return static_cast<ssize_t>(to_read);
  11320. }
  11321. ssize_t write(const char *, size_t) override { return -1; }
  11322. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  11323. ip = "127.0.0.1";
  11324. port = 0;
  11325. }
  11326. void get_local_ip_and_port(std::string &ip, int &port) const override {
  11327. ip = "127.0.0.1";
  11328. port = 0;
  11329. }
  11330. socket_t socket() const override { return INVALID_SOCKET; }
  11331. time_t duration() const override { return 0; }
  11332. };
  11333. TEST(StreamHandleTest, Basic) {
  11334. ClientImpl::StreamHandle handle;
  11335. EXPECT_FALSE(handle.is_valid());
  11336. handle.response = detail::make_unique<Response>();
  11337. handle.error = Error::Connection;
  11338. EXPECT_FALSE(handle.is_valid());
  11339. handle.error = Error::Success;
  11340. EXPECT_TRUE(handle.is_valid());
  11341. }
  11342. TEST(BodyReaderTest, Basic) {
  11343. MockStream stream("Hello, World!");
  11344. detail::BodyReader reader;
  11345. reader.stream = &stream;
  11346. reader.content_length = 13;
  11347. char buf[32];
  11348. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  11349. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  11350. EXPECT_TRUE(reader.eof);
  11351. }
  11352. TEST(BodyReaderTest, NoStream) {
  11353. detail::BodyReader reader;
  11354. char buf[32];
  11355. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11356. EXPECT_EQ(Error::Connection, reader.last_error);
  11357. }
  11358. TEST(BodyReaderTest, Error) {
  11359. MockStream stream("Hello, World!", 5);
  11360. detail::BodyReader reader;
  11361. reader.stream = &stream;
  11362. reader.content_length = 13;
  11363. char buf[32];
  11364. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  11365. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11366. EXPECT_EQ(Error::Read, reader.last_error);
  11367. }
  11368. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  11369. // Mock-based StreamHandle tests relying on private internals are removed.
  11370. class OpenStreamTest : public ::testing::Test {
  11371. protected:
  11372. void SetUp() override {
  11373. svr_.Get("/hello", [](const Request &, Response &res) {
  11374. res.set_content("Hello World!", "text/plain");
  11375. });
  11376. svr_.Get("/large", [](const Request &, Response &res) {
  11377. res.set_content(std::string(10000, 'X'), "text/plain");
  11378. });
  11379. svr_.Get("/chunked", [](const Request &, Response &res) {
  11380. res.set_chunked_content_provider("text/plain",
  11381. [](size_t offset, DataSink &sink) {
  11382. if (offset < 15) {
  11383. sink.write("chunk", 5);
  11384. return true;
  11385. }
  11386. sink.done();
  11387. return true;
  11388. });
  11389. });
  11390. svr_.Get("/compressible", [](const Request &, Response &res) {
  11391. res.set_chunked_content_provider("text/plain", [](size_t offset,
  11392. DataSink &sink) {
  11393. if (offset < 100 * 1024) {
  11394. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  11395. sink.write(chunk.data(), chunk.size());
  11396. return true;
  11397. }
  11398. sink.done();
  11399. return true;
  11400. });
  11401. });
  11402. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  11403. [](const Request & /*req*/, Response &res) {
  11404. auto i = new int(0);
  11405. res.set_header("Trailer", "Content-Length, X-Allowed");
  11406. res.set_chunked_content_provider(
  11407. "text/plain",
  11408. [i](size_t /*offset*/, DataSink &sink) {
  11409. switch (*i) {
  11410. case 0: sink.os << "123"; break;
  11411. case 1: sink.os << "456"; break;
  11412. case 2: sink.os << "789"; break;
  11413. case 3: {
  11414. sink.done_with_trailer(
  11415. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  11416. } break;
  11417. }
  11418. (*i)++;
  11419. return true;
  11420. },
  11421. [i](bool success) {
  11422. EXPECT_TRUE(success);
  11423. delete i;
  11424. });
  11425. });
  11426. // Echo headers endpoint for header-related tests
  11427. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  11428. std::string body;
  11429. for (const auto &h : req.headers) {
  11430. body.append(h.first);
  11431. body.push_back(':');
  11432. body.append(h.second);
  11433. body.push_back('\n');
  11434. }
  11435. res.set_content(body, "text/plain");
  11436. });
  11437. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  11438. std::string body;
  11439. for (const auto &h : req.headers) {
  11440. body.append(h.first);
  11441. body.push_back(':');
  11442. body.append(h.second);
  11443. body.push_back('\n');
  11444. }
  11445. res.set_content(body, "text/plain");
  11446. });
  11447. port_ = svr_.bind_to_any_port("127.0.0.1");
  11448. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11449. svr_.wait_until_ready();
  11450. }
  11451. void TearDown() override {
  11452. svr_.stop();
  11453. if (thread_.joinable()) thread_.join();
  11454. }
  11455. Server svr_;
  11456. std::thread thread_;
  11457. int port_ = 0;
  11458. };
  11459. TEST_F(OpenStreamTest, Basic) {
  11460. Client cli("127.0.0.1", port_);
  11461. auto handle = cli.open_stream("GET", "/hello");
  11462. EXPECT_TRUE(handle.is_valid());
  11463. EXPECT_EQ("Hello World!", read_all(handle));
  11464. }
  11465. TEST_F(OpenStreamTest, SmallBuffer) {
  11466. Client cli("127.0.0.1", port_);
  11467. auto handle = cli.open_stream("GET", "/hello");
  11468. std::string result;
  11469. char buf[4];
  11470. ssize_t n;
  11471. while ((n = handle.read(buf, sizeof(buf))) > 0)
  11472. result.append(buf, static_cast<size_t>(n));
  11473. EXPECT_EQ("Hello World!", result);
  11474. }
  11475. TEST_F(OpenStreamTest, DefaultHeaders) {
  11476. Client cli("127.0.0.1", port_);
  11477. // open_stream GET should include Host, User-Agent and Accept-Encoding
  11478. {
  11479. auto handle = cli.open_stream("GET", "/echo-headers");
  11480. ASSERT_TRUE(handle.is_valid());
  11481. auto body = read_all(handle);
  11482. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  11483. std::string::npos);
  11484. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  11485. std::string::npos);
  11486. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  11487. }
  11488. // open_stream POST with body and no explicit content_type should NOT add
  11489. // text/plain Content-Type (behavior differs from non-streaming path), but
  11490. // should include Content-Length
  11491. {
  11492. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  11493. ASSERT_TRUE(handle.is_valid());
  11494. auto body = read_all(handle);
  11495. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  11496. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  11497. }
  11498. // open_stream POST with explicit Content-Type should preserve it
  11499. {
  11500. auto handle = cli.open_stream("POST", "/echo-headers", {},
  11501. {{"Content-Type", "application/custom"}},
  11502. "{}", "application/custom");
  11503. ASSERT_TRUE(handle.is_valid());
  11504. auto body = read_all(handle);
  11505. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  11506. }
  11507. // User-specified User-Agent must not be overwritten for stream API
  11508. {
  11509. auto handle = cli.open_stream("GET", "/echo-headers", {},
  11510. {{"User-Agent", "MyAgent/1.2"}});
  11511. ASSERT_TRUE(handle.is_valid());
  11512. auto body = read_all(handle);
  11513. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  11514. }
  11515. }
  11516. TEST_F(OpenStreamTest, Large) {
  11517. Client cli("127.0.0.1", port_);
  11518. auto handle = cli.open_stream("GET", "/large");
  11519. EXPECT_EQ(10000u, read_all(handle).size());
  11520. }
  11521. TEST_F(OpenStreamTest, ConnectionError) {
  11522. Client cli("127.0.0.1", 9999);
  11523. auto handle = cli.open_stream("GET", "/hello");
  11524. EXPECT_FALSE(handle.is_valid());
  11525. }
  11526. TEST_F(OpenStreamTest, Chunked) {
  11527. Client cli("127.0.0.1", port_);
  11528. auto handle = cli.open_stream("GET", "/chunked");
  11529. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11530. "Transfer-Encoding") == "chunked");
  11531. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  11532. }
  11533. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  11534. Client cli("127.0.0.1", port_);
  11535. auto handle =
  11536. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  11537. ASSERT_TRUE(handle.is_valid());
  11538. // Consume body to allow trailers to be received/parsed
  11539. auto body = read_all(handle);
  11540. // Explicitly parse trailers (ensure trailers are available for assertion)
  11541. handle.parse_trailers_if_needed();
  11542. EXPECT_EQ(std::string("123456789"), body);
  11543. // The response should include a Trailer header declaring both names
  11544. ASSERT_TRUE(handle.response);
  11545. EXPECT_TRUE(handle.response->has_header("Trailer"));
  11546. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  11547. handle.response->get_header_value("Trailer"));
  11548. // Prohibited trailer must not be present
  11549. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  11550. // Allowed trailer should be present
  11551. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  11552. EXPECT_EQ(std::string("yes"),
  11553. handle.response->get_trailer_value("X-Allowed"));
  11554. // Verify trailers are NOT present as regular headers
  11555. EXPECT_EQ(std::string(""),
  11556. handle.response->get_header_value("Content-Length"));
  11557. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  11558. }
  11559. static std::thread serve_single_response(std::promise<int> &port_promise,
  11560. const std::string &response) {
  11561. return std::thread([&port_promise, response] {
  11562. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11563. default_socket_options(srv);
  11564. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11565. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11566. sockaddr_in addr{};
  11567. addr.sin_family = AF_INET;
  11568. addr.sin_port = htons(0); // Let OS assign a free port
  11569. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11570. int opt = 1;
  11571. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11572. #ifdef _WIN32
  11573. reinterpret_cast<const char *>(&opt),
  11574. #else
  11575. &opt,
  11576. #endif
  11577. sizeof(opt));
  11578. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  11579. ::listen(srv, 1) != 0) {
  11580. port_promise.set_value(-1);
  11581. detail::close_socket(srv);
  11582. return;
  11583. }
  11584. socklen_t addr_len = sizeof(addr);
  11585. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  11586. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  11587. sockaddr_in cli_addr{};
  11588. socklen_t cli_len = sizeof(cli_addr);
  11589. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11590. if (cli != INVALID_SOCKET) {
  11591. char buf[4096];
  11592. ::recv(cli, buf, sizeof(buf), 0);
  11593. ::send(cli,
  11594. #ifdef _WIN32
  11595. static_cast<const char *>(response.c_str()),
  11596. static_cast<int>(response.size()),
  11597. #else
  11598. response.c_str(), response.size(),
  11599. #endif
  11600. 0);
  11601. detail::close_socket(cli);
  11602. }
  11603. detail::close_socket(srv);
  11604. });
  11605. }
  11606. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  11607. #ifndef _WIN32
  11608. signal(SIGPIPE, SIG_IGN);
  11609. #endif
  11610. std::promise<int> port_promise;
  11611. auto port_future = port_promise.get_future();
  11612. auto server_thread =
  11613. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  11614. "Content-Type: text/plain\r\n"
  11615. "Content-Length: not-a-number\r\n"
  11616. "Connection: close\r\n"
  11617. "\r\n"
  11618. "hello");
  11619. auto port = port_future.get();
  11620. ASSERT_GT(port, 0);
  11621. Client cli("127.0.0.1", port);
  11622. auto handle = cli.open_stream("GET", "/");
  11623. EXPECT_FALSE(handle.is_valid());
  11624. server_thread.join();
  11625. }
  11626. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  11627. #ifndef _WIN32
  11628. signal(SIGPIPE, SIG_IGN);
  11629. #endif
  11630. std::promise<int> port_promise;
  11631. auto port_future = port_promise.get_future();
  11632. auto server_thread = serve_single_response(
  11633. port_promise, "HTTP/1.1 200 OK\r\n"
  11634. "Content-Type: text/plain\r\n"
  11635. "Content-Length: 99999999999999999999999999\r\n"
  11636. "Connection: close\r\n"
  11637. "\r\n"
  11638. "hello");
  11639. auto port = port_future.get();
  11640. ASSERT_GT(port, 0);
  11641. // Before the fix, std::stoull would throw std::out_of_range here and
  11642. // crash the process. After the fix, strtoull silently clamps to
  11643. // ULLONG_MAX so the stream opens without crashing. The important thing
  11644. // is that the process does NOT terminate.
  11645. Client cli("127.0.0.1", port);
  11646. auto handle = cli.open_stream("GET", "/");
  11647. EXPECT_TRUE(handle.is_valid());
  11648. server_thread.join();
  11649. }
  11650. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11651. TEST_F(OpenStreamTest, Gzip) {
  11652. Client cli("127.0.0.1", port_);
  11653. auto handle = cli.open_stream("GET", "/compressible", {},
  11654. {{"Accept-Encoding", "gzip"}});
  11655. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  11656. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11657. }
  11658. #endif
  11659. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11660. TEST_F(OpenStreamTest, Brotli) {
  11661. Client cli("127.0.0.1", port_);
  11662. auto handle =
  11663. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  11664. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  11665. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11666. }
  11667. #endif
  11668. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11669. TEST_F(OpenStreamTest, Zstd) {
  11670. Client cli("127.0.0.1", port_);
  11671. auto handle = cli.open_stream("GET", "/compressible", {},
  11672. {{"Accept-Encoding", "zstd"}});
  11673. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  11674. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11675. }
  11676. #endif
  11677. #ifdef CPPHTTPLIB_SSL_ENABLED
  11678. class SSLOpenStreamTest : public ::testing::Test {
  11679. protected:
  11680. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  11681. void SetUp() override {
  11682. svr_.Get("/hello", [](const Request &, Response &res) {
  11683. res.set_content("Hello SSL World!", "text/plain");
  11684. });
  11685. svr_.Get("/chunked", [](const Request &, Response &res) {
  11686. res.set_chunked_content_provider("text/plain",
  11687. [](size_t offset, DataSink &sink) {
  11688. if (offset < 15) {
  11689. sink.write("chunk", 5);
  11690. return true;
  11691. }
  11692. sink.done();
  11693. return true;
  11694. });
  11695. });
  11696. svr_.Post("/echo", [](const Request &req, Response &res) {
  11697. res.set_content(req.body, req.get_header_value("Content-Type"));
  11698. });
  11699. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  11700. std::string body = req.body;
  11701. res.set_chunked_content_provider(
  11702. "text/plain", [body](size_t offset, DataSink &sink) {
  11703. if (offset < body.size()) {
  11704. sink.write(body.data() + offset, body.size() - offset);
  11705. }
  11706. sink.done();
  11707. return true;
  11708. });
  11709. });
  11710. port_ = svr_.bind_to_any_port("127.0.0.1");
  11711. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11712. svr_.wait_until_ready();
  11713. }
  11714. void TearDown() override {
  11715. svr_.stop();
  11716. if (thread_.joinable()) thread_.join();
  11717. }
  11718. SSLServer svr_;
  11719. std::thread thread_;
  11720. int port_ = 0;
  11721. };
  11722. TEST_F(SSLOpenStreamTest, Basic) {
  11723. SSLClient cli("127.0.0.1", port_);
  11724. cli.enable_server_certificate_verification(false);
  11725. auto handle = cli.open_stream("GET", "/hello");
  11726. ASSERT_TRUE(handle.is_valid());
  11727. EXPECT_EQ("Hello SSL World!", read_all(handle));
  11728. }
  11729. TEST_F(SSLOpenStreamTest, Chunked) {
  11730. SSLClient cli("127.0.0.1", port_);
  11731. cli.enable_server_certificate_verification(false);
  11732. auto handle = cli.open_stream("GET", "/chunked");
  11733. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11734. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11735. "Transfer-Encoding") == "chunked");
  11736. auto body = read_all(handle);
  11737. EXPECT_EQ("chunkchunkchunk", body);
  11738. }
  11739. TEST_F(SSLOpenStreamTest, Post) {
  11740. SSLClient cli("127.0.0.1", port_);
  11741. cli.enable_server_certificate_verification(false);
  11742. auto handle =
  11743. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  11744. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11745. EXPECT_EQ(200, handle.response->status);
  11746. auto body = read_all(handle);
  11747. EXPECT_EQ("Hello SSL POST", body);
  11748. }
  11749. TEST_F(SSLOpenStreamTest, PostChunked) {
  11750. SSLClient cli("127.0.0.1", port_);
  11751. cli.enable_server_certificate_verification(false);
  11752. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  11753. "Chunked SSL Data", "text/plain");
  11754. ASSERT_TRUE(handle.is_valid());
  11755. EXPECT_EQ(200, handle.response->status);
  11756. auto body = read_all(handle);
  11757. EXPECT_EQ("Chunked SSL Data", body);
  11758. }
  11759. #endif // CPPHTTPLIB_SSL_ENABLED
  11760. //==============================================================================
  11761. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  11762. // results for various scenarios.
  11763. //==============================================================================
  11764. TEST(ParityTest, GetVsOpenStream) {
  11765. Server svr;
  11766. const std::string path = "/parity";
  11767. const std::string content = "Parity test content: hello world";
  11768. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11769. res.set_content(content, "text/plain");
  11770. });
  11771. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11772. auto se = detail::scope_exit([&] {
  11773. svr.stop();
  11774. t.join();
  11775. ASSERT_FALSE(svr.is_running());
  11776. });
  11777. svr.wait_until_ready();
  11778. Client cli(HOST, PORT);
  11779. // Non-stream path
  11780. auto r1 = cli.Get(path);
  11781. ASSERT_TRUE(r1);
  11782. EXPECT_EQ(StatusCode::OK_200, r1->status);
  11783. // Stream path
  11784. auto h = cli.open_stream("GET", path);
  11785. ASSERT_TRUE(h.is_valid());
  11786. EXPECT_EQ(r1->body, read_all(h));
  11787. }
  11788. // Helper to compress data with provided compressor type T
  11789. template <typename Compressor>
  11790. static std::string compress_payload_for_parity(const std::string &in) {
  11791. std::string out;
  11792. Compressor compressor;
  11793. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  11794. [&](const char *data, size_t n) {
  11795. out.append(data, n);
  11796. return true;
  11797. });
  11798. EXPECT_TRUE(ok);
  11799. return out;
  11800. }
  11801. // Helper function for compression parity tests
  11802. template <typename Compressor>
  11803. static void test_compression_parity(const std::string &original,
  11804. const std::string &path,
  11805. const std::string &encoding) {
  11806. const std::string compressed =
  11807. compress_payload_for_parity<Compressor>(original);
  11808. Server svr;
  11809. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11810. res.set_content(compressed, "application/octet-stream");
  11811. res.set_header("Content-Encoding", encoding);
  11812. });
  11813. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  11814. auto se = detail::scope_exit([&] {
  11815. svr.stop();
  11816. t.join();
  11817. ASSERT_FALSE(svr.is_running());
  11818. });
  11819. svr.wait_until_ready();
  11820. Client cli(HOST, PORT);
  11821. // Non-streaming
  11822. {
  11823. auto res = cli.Get(path);
  11824. ASSERT_TRUE(res);
  11825. EXPECT_EQ(StatusCode::OK_200, res->status);
  11826. EXPECT_EQ(original, res->body);
  11827. }
  11828. // Streaming
  11829. {
  11830. auto h = cli.open_stream("GET", path);
  11831. ASSERT_TRUE(h.is_valid());
  11832. EXPECT_EQ(original, read_all(h));
  11833. }
  11834. }
  11835. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11836. TEST(ParityTest, Gzip) {
  11837. test_compression_parity<detail::gzip_compressor>(
  11838. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  11839. }
  11840. #endif
  11841. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11842. TEST(ParityTest, Brotli) {
  11843. test_compression_parity<detail::brotli_compressor>(
  11844. "Hello, brotli parity test payload", "/parity-br", "br");
  11845. }
  11846. #endif
  11847. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11848. TEST(ParityTest, Zstd) {
  11849. test_compression_parity<detail::zstd_compressor>(
  11850. "Zstandard parity test payload", "/parity-zstd", "zstd");
  11851. }
  11852. #endif
  11853. //==============================================================================
  11854. // New Stream API Tests
  11855. //==============================================================================
  11856. inline std::string read_body(httplib::stream::Result &result) {
  11857. std::string body;
  11858. while (result.next()) {
  11859. body.append(result.data(), result.size());
  11860. }
  11861. return body;
  11862. }
  11863. TEST(ClientConnectionTest, Basic) {
  11864. httplib::ClientConnection conn;
  11865. EXPECT_FALSE(conn.is_open());
  11866. conn.sock = 1;
  11867. EXPECT_TRUE(conn.is_open());
  11868. httplib::ClientConnection conn2(std::move(conn));
  11869. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  11870. conn2.sock = INVALID_SOCKET;
  11871. }
  11872. // Unified test server for all stream::* tests
  11873. class StreamApiTest : public ::testing::Test {
  11874. protected:
  11875. void SetUp() override {
  11876. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11877. res.set_content("Hello World!", "text/plain");
  11878. });
  11879. svr_.Get("/echo-params",
  11880. [](const httplib::Request &req, httplib::Response &res) {
  11881. std::string r;
  11882. for (const auto &p : req.params) {
  11883. if (!r.empty()) r += "&";
  11884. r += p.first + "=" + p.second;
  11885. }
  11886. res.set_content(r, "text/plain");
  11887. });
  11888. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11889. res.set_content(req.body, req.get_header_value("Content-Type"));
  11890. });
  11891. svr_.Post("/echo-headers",
  11892. [](const httplib::Request &req, httplib::Response &res) {
  11893. std::string r;
  11894. for (const auto &h : req.headers)
  11895. r += h.first + ": " + h.second + "\n";
  11896. res.set_content(r, "text/plain");
  11897. });
  11898. svr_.Post("/echo-params",
  11899. [](const httplib::Request &req, httplib::Response &res) {
  11900. std::string r = "params:";
  11901. for (const auto &p : req.params)
  11902. r += p.first + "=" + p.second + ";";
  11903. res.set_content(r + " body:" + req.body, "text/plain");
  11904. });
  11905. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  11906. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  11907. });
  11908. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11909. res.set_content("PUT:" + req.body, "text/plain");
  11910. });
  11911. svr_.Patch("/echo",
  11912. [](const httplib::Request &req, httplib::Response &res) {
  11913. res.set_content("PATCH:" + req.body, "text/plain");
  11914. });
  11915. svr_.Delete(
  11916. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  11917. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  11918. "text/plain");
  11919. });
  11920. svr_.Get("/head-test",
  11921. [](const httplib::Request &, httplib::Response &res) {
  11922. res.set_content("body for HEAD", "text/plain");
  11923. });
  11924. svr_.Options("/options",
  11925. [](const httplib::Request &, httplib::Response &res) {
  11926. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  11927. });
  11928. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  11929. svr_.wait_until_ready();
  11930. }
  11931. void TearDown() override {
  11932. svr_.stop();
  11933. if (thread_.joinable()) thread_.join();
  11934. }
  11935. httplib::Server svr_;
  11936. std::thread thread_;
  11937. };
  11938. // stream::Get tests
  11939. TEST_F(StreamApiTest, GetBasic) {
  11940. httplib::Client cli(HOST, PORT);
  11941. auto result = httplib::stream::Get(cli, "/hello");
  11942. ASSERT_TRUE(result.is_valid());
  11943. EXPECT_EQ(200, result.status());
  11944. EXPECT_EQ("Hello World!", read_body(result));
  11945. }
  11946. TEST_F(StreamApiTest, GetWithParams) {
  11947. httplib::Client cli(HOST, PORT);
  11948. httplib::Params params{{"foo", "bar"}};
  11949. auto result = httplib::stream::Get(cli, "/echo-params", params);
  11950. ASSERT_TRUE(result.is_valid());
  11951. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  11952. }
  11953. TEST_F(StreamApiTest, GetConnectionError) {
  11954. httplib::Client cli(HOST, 9999);
  11955. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  11956. }
  11957. TEST_F(StreamApiTest, Get404) {
  11958. httplib::Client cli(HOST, PORT);
  11959. auto result = httplib::stream::Get(cli, "/nonexistent");
  11960. EXPECT_TRUE(result.is_valid());
  11961. EXPECT_EQ(404, result.status());
  11962. }
  11963. // stream::Post tests
  11964. TEST_F(StreamApiTest, PostBasic) {
  11965. httplib::Client cli(HOST, PORT);
  11966. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  11967. "application/json");
  11968. ASSERT_TRUE(result.is_valid());
  11969. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  11970. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  11971. }
  11972. TEST_F(StreamApiTest, PostWithHeaders) {
  11973. httplib::Client cli(HOST, PORT);
  11974. httplib::Headers headers{{"X-Custom", "value"}};
  11975. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  11976. "text/plain");
  11977. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  11978. }
  11979. TEST_F(StreamApiTest, PostWithParams) {
  11980. httplib::Client cli(HOST, PORT);
  11981. httplib::Params params{{"k", "v"}};
  11982. auto result =
  11983. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  11984. auto body = read_body(result);
  11985. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  11986. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  11987. }
  11988. TEST_F(StreamApiTest, PostLarge) {
  11989. httplib::Client cli(HOST, PORT);
  11990. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  11991. size_t total = 0;
  11992. while (result.next()) {
  11993. total += result.size();
  11994. }
  11995. EXPECT_EQ(100u * 1024u, total);
  11996. }
  11997. // stream::Put/Patch tests
  11998. TEST_F(StreamApiTest, PutAndPatch) {
  11999. httplib::Client cli(HOST, PORT);
  12000. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  12001. EXPECT_EQ("PUT:test", read_body(put));
  12002. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  12003. EXPECT_EQ("PATCH:test", read_body(patch));
  12004. }
  12005. // stream::Delete tests
  12006. TEST_F(StreamApiTest, Delete) {
  12007. httplib::Client cli(HOST, PORT);
  12008. auto del1 = httplib::stream::Delete(cli, "/resource");
  12009. EXPECT_EQ("Deleted", read_body(del1));
  12010. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  12011. EXPECT_EQ("Deleted:data", read_body(del2));
  12012. }
  12013. // stream::Head/Options tests
  12014. TEST_F(StreamApiTest, HeadAndOptions) {
  12015. httplib::Client cli(HOST, PORT);
  12016. auto head = httplib::stream::Head(cli, "/head-test");
  12017. EXPECT_TRUE(head.is_valid());
  12018. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  12019. auto opts = httplib::stream::Options(cli, "/options");
  12020. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  12021. }
  12022. // SSL stream::* tests
  12023. #ifdef CPPHTTPLIB_SSL_ENABLED
  12024. class SSLStreamApiTest : public ::testing::Test {
  12025. protected:
  12026. void SetUp() override {
  12027. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12028. res.set_content("Hello SSL!", "text/plain");
  12029. });
  12030. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12031. res.set_content(req.body, "text/plain");
  12032. });
  12033. port_ = svr_.bind_to_any_port("127.0.0.1");
  12034. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12035. svr_.wait_until_ready();
  12036. }
  12037. void TearDown() override {
  12038. svr_.stop();
  12039. if (thread_.joinable()) thread_.join();
  12040. }
  12041. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  12042. std::thread thread_;
  12043. int port_ = 0;
  12044. };
  12045. TEST_F(SSLStreamApiTest, GetAndPost) {
  12046. httplib::SSLClient cli("127.0.0.1", port_);
  12047. cli.enable_server_certificate_verification(false);
  12048. auto get = httplib::stream::Get(cli, "/hello");
  12049. EXPECT_EQ("Hello SSL!", read_body(get));
  12050. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  12051. EXPECT_EQ("test", read_body(post));
  12052. }
  12053. #endif
  12054. // Tests for Error::Timeout and Error::ConnectionClosed error types
  12055. // These errors are set in SocketStream/SSLSocketStream and propagated through
  12056. // BodyReader
  12057. TEST(ErrorHandlingTest, StreamReadTimeout) {
  12058. // Test that read timeout during streaming is detected
  12059. // Use a large content-length response where server delays mid-stream
  12060. Server svr;
  12061. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12062. // Send a large response with delay in the middle
  12063. res.set_content_provider(
  12064. 1000, // content_length
  12065. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  12066. if (offset < 100) {
  12067. // Send first 100 bytes immediately
  12068. std::string data(100, 'A');
  12069. sink.write(data.c_str(), data.size());
  12070. return true;
  12071. }
  12072. // Then delay longer than client timeout
  12073. std::this_thread::sleep_for(std::chrono::seconds(3));
  12074. std::string data(900, 'B');
  12075. sink.write(data.c_str(), data.size());
  12076. return true;
  12077. });
  12078. });
  12079. auto port = 8091;
  12080. std::thread t([&]() { svr.listen("localhost", port); });
  12081. svr.wait_until_ready();
  12082. Client cli("localhost", port);
  12083. cli.set_read_timeout(1, 0); // 1 second timeout
  12084. auto handle = cli.open_stream("GET", "/slow-stream");
  12085. ASSERT_TRUE(handle.is_valid());
  12086. char buf[256];
  12087. ssize_t total = 0;
  12088. ssize_t n;
  12089. bool got_error = false;
  12090. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12091. total += n;
  12092. }
  12093. if (n < 0) {
  12094. got_error = true;
  12095. // Should be timeout or read error
  12096. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12097. handle.get_read_error() == Error::Read)
  12098. << "Actual error: " << to_string(handle.get_read_error());
  12099. }
  12100. // Either we got an error, or we got less data than expected
  12101. EXPECT_TRUE(got_error || total < 1000)
  12102. << "Expected timeout but got all " << total << " bytes";
  12103. svr.stop();
  12104. t.join();
  12105. }
  12106. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  12107. // Test connection closed detection via BodyReader
  12108. Server svr;
  12109. std::atomic<bool> close_now{false};
  12110. svr.Get("/will-close", [&](const Request &, Response &res) {
  12111. res.set_content_provider(
  12112. 10000, // Large content_length that we won't fully send
  12113. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12114. if (offset < 100) {
  12115. std::string data(100, 'X');
  12116. sink.write(data.c_str(), data.size());
  12117. return true;
  12118. }
  12119. // Wait for signal then abort
  12120. while (!close_now) {
  12121. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12122. }
  12123. return false; // Abort - server will close connection
  12124. });
  12125. });
  12126. auto port = 8092;
  12127. std::thread t([&]() { svr.listen("localhost", port); });
  12128. svr.wait_until_ready();
  12129. Client cli("localhost", port);
  12130. auto handle = cli.open_stream("GET", "/will-close");
  12131. ASSERT_TRUE(handle.is_valid());
  12132. char buf[256];
  12133. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12134. EXPECT_GT(n, 0) << "First read should succeed";
  12135. // Signal server to close
  12136. close_now = true;
  12137. // Keep reading until error or EOF
  12138. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12139. // Keep reading
  12140. }
  12141. // Should get an error since content_length wasn't satisfied
  12142. if (n < 0) {
  12143. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12144. handle.get_read_error() == Error::Read)
  12145. << "Actual error: " << to_string(handle.get_read_error());
  12146. }
  12147. svr.stop();
  12148. t.join();
  12149. }
  12150. #ifdef CPPHTTPLIB_SSL_ENABLED
  12151. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  12152. // Test that read timeout during SSL streaming is detected
  12153. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12154. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12155. res.set_content_provider(
  12156. 1000, "text/plain",
  12157. [](size_t offset, size_t /*length*/, DataSink &sink) {
  12158. if (offset < 100) {
  12159. std::string data(100, 'A');
  12160. sink.write(data.c_str(), data.size());
  12161. return true;
  12162. }
  12163. std::this_thread::sleep_for(std::chrono::seconds(3));
  12164. std::string data(900, 'B');
  12165. sink.write(data.c_str(), data.size());
  12166. return true;
  12167. });
  12168. });
  12169. auto port = 8093;
  12170. std::thread t([&]() { svr.listen("localhost", port); });
  12171. svr.wait_until_ready();
  12172. SSLClient cli("localhost", port);
  12173. cli.enable_server_certificate_verification(false);
  12174. cli.set_read_timeout(1, 0); // 1 second timeout
  12175. auto handle = cli.open_stream("GET", "/slow-stream");
  12176. ASSERT_TRUE(handle.is_valid());
  12177. char buf[256];
  12178. ssize_t total = 0;
  12179. ssize_t n;
  12180. bool got_error = false;
  12181. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12182. total += n;
  12183. }
  12184. if (n < 0) {
  12185. got_error = true;
  12186. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12187. handle.get_read_error() == Error::Read)
  12188. << "Actual error: " << to_string(handle.get_read_error());
  12189. }
  12190. EXPECT_TRUE(got_error || total < 1000)
  12191. << "Expected timeout but got all " << total << " bytes";
  12192. svr.stop();
  12193. t.join();
  12194. }
  12195. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  12196. // Test SSL connection closed detection
  12197. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12198. std::atomic<bool> close_now{false};
  12199. svr.Get("/will-close", [&](const Request &, Response &res) {
  12200. res.set_content_provider(
  12201. 10000, "text/plain",
  12202. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12203. if (offset < 100) {
  12204. std::string data(100, 'X');
  12205. sink.write(data.c_str(), data.size());
  12206. return true;
  12207. }
  12208. while (!close_now) {
  12209. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12210. }
  12211. return false;
  12212. });
  12213. });
  12214. auto port = 8094;
  12215. std::thread t([&]() { svr.listen("localhost", port); });
  12216. svr.wait_until_ready();
  12217. SSLClient cli("localhost", port);
  12218. cli.enable_server_certificate_verification(false);
  12219. auto handle = cli.open_stream("GET", "/will-close");
  12220. ASSERT_TRUE(handle.is_valid());
  12221. char buf[256];
  12222. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12223. EXPECT_GT(n, 0);
  12224. // Signal server to close
  12225. close_now = true;
  12226. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12227. // Keep reading
  12228. }
  12229. if (n < 0) {
  12230. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12231. handle.get_read_error() == Error::Read)
  12232. << "Actual error: " << to_string(handle.get_read_error());
  12233. }
  12234. svr.stop();
  12235. t.join();
  12236. }
  12237. #endif
  12238. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  12239. using namespace httplib;
  12240. // Create a test file
  12241. const char *fname = "etag_testfile.txt";
  12242. const char *content = "etag-content";
  12243. {
  12244. std::ofstream ofs(fname);
  12245. ofs << content;
  12246. ASSERT_TRUE(ofs.good());
  12247. }
  12248. Server svr;
  12249. svr.set_mount_point("/static", ".");
  12250. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12251. svr.wait_until_ready();
  12252. Client cli(HOST, PORT);
  12253. // First request: should get 200 with ETag header
  12254. auto res1 = cli.Get("/static/etag_testfile.txt");
  12255. ASSERT_TRUE(res1);
  12256. ASSERT_EQ(200, res1->status);
  12257. ASSERT_TRUE(res1->has_header("ETag"));
  12258. std::string etag = res1->get_header_value("ETag");
  12259. EXPECT_FALSE(etag.empty());
  12260. // Verify ETag format: W/"hex-hex"
  12261. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  12262. EXPECT_EQ('W', etag[0]);
  12263. EXPECT_EQ('/', etag[1]);
  12264. EXPECT_EQ('"', etag[2]);
  12265. EXPECT_EQ('"', etag.back());
  12266. // Exact match: expect 304 Not Modified
  12267. Headers h2 = {{"If-None-Match", etag}};
  12268. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  12269. ASSERT_TRUE(res2);
  12270. EXPECT_EQ(304, res2->status);
  12271. // Wildcard match: expect 304 Not Modified
  12272. Headers h3 = {{"If-None-Match", "*"}};
  12273. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  12274. ASSERT_TRUE(res3);
  12275. EXPECT_EQ(304, res3->status);
  12276. // Non-matching ETag: expect 200
  12277. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  12278. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  12279. ASSERT_TRUE(res4);
  12280. EXPECT_EQ(200, res4->status);
  12281. // Multiple ETags with one matching: expect 304
  12282. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  12283. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  12284. ASSERT_TRUE(res5);
  12285. EXPECT_EQ(304, res5->status);
  12286. svr.stop();
  12287. t.join();
  12288. std::remove(fname);
  12289. }
  12290. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  12291. using namespace httplib;
  12292. Server svr;
  12293. svr.set_mount_point("/static", ".");
  12294. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12295. svr.wait_until_ready();
  12296. Client cli(HOST, PORT);
  12297. // Send If-None-Match: * to a non-existent file
  12298. Headers h = {{"If-None-Match", "*"}};
  12299. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  12300. ASSERT_TRUE(res);
  12301. EXPECT_EQ(404, res->status);
  12302. svr.stop();
  12303. t.join();
  12304. }
  12305. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  12306. using namespace httplib;
  12307. // Create a test file
  12308. const char *fname = "etag_boundary_testfile.txt";
  12309. const char *content = "boundary-test";
  12310. {
  12311. std::ofstream ofs(fname);
  12312. ofs << content;
  12313. ASSERT_TRUE(ofs.good());
  12314. }
  12315. Server svr;
  12316. svr.set_mount_point("/static", ".");
  12317. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12318. svr.wait_until_ready();
  12319. Client cli(HOST, PORT);
  12320. // Get the actual ETag
  12321. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  12322. ASSERT_TRUE(res1);
  12323. ASSERT_EQ(200, res1->status);
  12324. ASSERT_TRUE(res1->has_header("ETag"));
  12325. std::string etag = res1->get_header_value("ETag");
  12326. // Test 1: Very long ETag value (longer than actual ETag)
  12327. // Should NOT match and return 200 (not trigger out-of-bounds read)
  12328. Headers h1 = {{"If-None-Match", "W/"
  12329. "\"very-long-etag-value-that-is-much-longer-"
  12330. "than-the-actual-etag-value\""}};
  12331. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  12332. ASSERT_TRUE(res2);
  12333. EXPECT_EQ(200, res2->status); // Should not match
  12334. // Test 2: Long string followed by wildcard
  12335. // Should match on "*" and return 304 (without out-of-bounds read on the long
  12336. // string)
  12337. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  12338. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  12339. ASSERT_TRUE(res3);
  12340. EXPECT_EQ(304, res3->status); // Should match on "*"
  12341. // Test 3: Wildcard followed by long string
  12342. // Should match on "*" immediately and return 304
  12343. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  12344. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  12345. ASSERT_TRUE(res4);
  12346. EXPECT_EQ(304, res4->status); // Should match on "*"
  12347. // Test 4: Multiple long non-matching values
  12348. // Should NOT match and return 200 (test that all comparisons are safe)
  12349. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  12350. "W/\"second-long-non-matching-value\", "
  12351. "W/\"third-long-non-matching-value\""}};
  12352. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  12353. ASSERT_TRUE(res5);
  12354. EXPECT_EQ(200, res5->status); // Should not match
  12355. // Test 5: Single character that is not "*" (edge case)
  12356. Headers h5 = {{"If-None-Match", "X"}};
  12357. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  12358. ASSERT_TRUE(res6);
  12359. EXPECT_EQ(200, res6->status); // Should not match
  12360. svr.stop();
  12361. t.join();
  12362. std::remove(fname);
  12363. }
  12364. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  12365. using namespace httplib;
  12366. // Create a test file
  12367. const char *fname = "ims_testfile.txt";
  12368. const char *content = "if-modified-since-test";
  12369. {
  12370. std::ofstream ofs(fname);
  12371. ofs << content;
  12372. ASSERT_TRUE(ofs.good());
  12373. }
  12374. Server svr;
  12375. svr.set_mount_point("/static", ".");
  12376. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12377. svr.wait_until_ready();
  12378. Client cli(HOST, PORT);
  12379. // First request: should get 200 with Last-Modified header
  12380. auto res1 = cli.Get("/static/ims_testfile.txt");
  12381. ASSERT_TRUE(res1);
  12382. ASSERT_EQ(200, res1->status);
  12383. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12384. std::string last_modified = res1->get_header_value("Last-Modified");
  12385. EXPECT_FALSE(last_modified.empty());
  12386. // If-Modified-Since with same time: expect 304
  12387. Headers h2 = {{"If-Modified-Since", last_modified}};
  12388. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  12389. ASSERT_TRUE(res2);
  12390. EXPECT_EQ(304, res2->status);
  12391. // If-Modified-Since with future time: expect 304
  12392. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12393. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  12394. ASSERT_TRUE(res3);
  12395. EXPECT_EQ(304, res3->status);
  12396. // If-Modified-Since with past time: expect 200
  12397. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12398. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  12399. ASSERT_TRUE(res4);
  12400. EXPECT_EQ(200, res4->status);
  12401. // If-None-Match takes precedence over If-Modified-Since
  12402. // (send matching ETag with old If-Modified-Since -> should still be 304)
  12403. ASSERT_TRUE(res1->has_header("ETag"));
  12404. std::string etag = res1->get_header_value("ETag");
  12405. Headers h5 = {{"If-None-Match", etag},
  12406. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12407. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  12408. ASSERT_TRUE(res5);
  12409. EXPECT_EQ(304, res5->status);
  12410. svr.stop();
  12411. t.join();
  12412. std::remove(fname);
  12413. }
  12414. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  12415. using namespace httplib;
  12416. Server svr;
  12417. // Endpoint that returns compressible content
  12418. svr.Get("/compressible", [](const Request &, Response &res) {
  12419. // Return a large enough body to trigger compression
  12420. std::string body(1000, 'a');
  12421. res.set_content(body, "text/plain");
  12422. });
  12423. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12424. svr.wait_until_ready();
  12425. Client cli(HOST, PORT);
  12426. // Request with gzip support: should get Vary header when compressed
  12427. cli.set_compress(true);
  12428. auto res1 = cli.Get("/compressible");
  12429. ASSERT_TRUE(res1);
  12430. EXPECT_EQ(200, res1->status);
  12431. // If Content-Encoding is set, Vary should also be set
  12432. if (res1->has_header("Content-Encoding")) {
  12433. EXPECT_TRUE(res1->has_header("Vary"));
  12434. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  12435. }
  12436. // Request without Accept-Encoding header: should not have compression
  12437. Headers h_no_compress;
  12438. auto res2 = cli.Get("/compressible", h_no_compress);
  12439. ASSERT_TRUE(res2);
  12440. EXPECT_EQ(200, res2->status);
  12441. // Verify Vary header is present when compression is applied
  12442. // (the exact behavior depends on server configuration)
  12443. svr.stop();
  12444. t.join();
  12445. }
  12446. TEST(ETagTest, IfRangeWithETag) {
  12447. using namespace httplib;
  12448. // Create a test file with known content
  12449. const char *fname = "if_range_testfile.txt";
  12450. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  12451. {
  12452. std::ofstream ofs(fname);
  12453. ofs << content;
  12454. ASSERT_TRUE(ofs.good());
  12455. }
  12456. Server svr;
  12457. svr.set_mount_point("/static", ".");
  12458. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12459. svr.wait_until_ready();
  12460. Client cli(HOST, PORT);
  12461. // First request: get ETag
  12462. auto res1 = cli.Get("/static/if_range_testfile.txt");
  12463. ASSERT_TRUE(res1);
  12464. ASSERT_EQ(200, res1->status);
  12465. ASSERT_TRUE(res1->has_header("ETag"));
  12466. std::string etag = res1->get_header_value("ETag");
  12467. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  12468. // Since our server generates weak ETags (W/"..."), If-Range with our
  12469. // ETag should NOT result in partial content - it should return full content.
  12470. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  12471. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  12472. ASSERT_TRUE(res2);
  12473. // Weak ETag in If-Range -> full content (200), not partial (206)
  12474. EXPECT_EQ(200, res2->status);
  12475. EXPECT_EQ(content, res2->body);
  12476. EXPECT_FALSE(res2->has_header("Content-Range"));
  12477. // Range request with non-matching If-Range (ETag): should get 200 (full
  12478. // content)
  12479. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  12480. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  12481. ASSERT_TRUE(res3);
  12482. EXPECT_EQ(200, res3->status);
  12483. EXPECT_EQ(content, res3->body);
  12484. EXPECT_FALSE(res3->has_header("Content-Range"));
  12485. // Range request with strong ETag (hypothetical - our server doesn't generate
  12486. // strong ETags, but if client sends a strong ETag that doesn't match, it
  12487. // should return full content)
  12488. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  12489. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  12490. ASSERT_TRUE(res4);
  12491. EXPECT_EQ(200, res4->status);
  12492. EXPECT_EQ(content, res4->body);
  12493. EXPECT_FALSE(res4->has_header("Content-Range"));
  12494. svr.stop();
  12495. t.join();
  12496. std::remove(fname);
  12497. }
  12498. TEST(ETagTest, IfRangeWithDate) {
  12499. using namespace httplib;
  12500. // Create a test file
  12501. const char *fname = "if_range_date_testfile.txt";
  12502. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  12503. {
  12504. std::ofstream ofs(fname);
  12505. ofs << content;
  12506. ASSERT_TRUE(ofs.good());
  12507. }
  12508. Server svr;
  12509. svr.set_mount_point("/static", ".");
  12510. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12511. svr.wait_until_ready();
  12512. Client cli(HOST, PORT);
  12513. // First request: get Last-Modified
  12514. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  12515. ASSERT_TRUE(res1);
  12516. ASSERT_EQ(200, res1->status);
  12517. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12518. std::string last_modified = res1->get_header_value("Last-Modified");
  12519. // Range request with matching If-Range (date): should get 206
  12520. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  12521. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  12522. ASSERT_TRUE(res2);
  12523. EXPECT_EQ(206, res2->status);
  12524. EXPECT_EQ("FGHIJ", res2->body);
  12525. // Range request with old If-Range date: should get 200 (full content)
  12526. Headers h3 = {{"Range", "bytes=5-9"},
  12527. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12528. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  12529. ASSERT_TRUE(res3);
  12530. EXPECT_EQ(200, res3->status);
  12531. EXPECT_EQ(content, res3->body);
  12532. // Range request with future If-Range date: should get 206
  12533. Headers h4 = {{"Range", "bytes=0-4"},
  12534. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12535. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  12536. ASSERT_TRUE(res4);
  12537. EXPECT_EQ(206, res4->status);
  12538. EXPECT_EQ("ABCDE", res4->body);
  12539. svr.stop();
  12540. t.join();
  12541. std::remove(fname);
  12542. }
  12543. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  12544. using namespace httplib;
  12545. const char *fname = "etag_malformed.txt";
  12546. const char *content = "malformed-etag";
  12547. {
  12548. std::ofstream ofs(fname);
  12549. ofs << content;
  12550. ASSERT_TRUE(ofs.good());
  12551. }
  12552. Server svr;
  12553. svr.set_mount_point("/static", ".");
  12554. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12555. svr.wait_until_ready();
  12556. Client cli(HOST, PORT);
  12557. // baseline: should get 200 and an ETag
  12558. auto res1 = cli.Get("/static/etag_malformed.txt");
  12559. ASSERT_TRUE(res1);
  12560. ASSERT_EQ(200, res1->status);
  12561. ASSERT_TRUE(res1->has_header("ETag"));
  12562. // Malformed ETag value (missing quotes) should be treated as non-matching
  12563. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  12564. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  12565. ASSERT_TRUE(res_bad);
  12566. EXPECT_EQ(200, res_bad->status);
  12567. // Whitespace-only header value should be considered invalid / non-matching
  12568. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  12569. "Host: localhost\r\n"
  12570. "If-None-Match: \r\n"
  12571. "Connection: close\r\n"
  12572. "\r\n";
  12573. std::string out;
  12574. ASSERT_TRUE(send_request(5, raw_req, &out));
  12575. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12576. svr.stop();
  12577. t.join();
  12578. std::remove(fname);
  12579. }
  12580. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  12581. using namespace httplib;
  12582. const char *fname = "ims_invalid_format.txt";
  12583. const char *content = "ims-bad-format";
  12584. {
  12585. std::ofstream ofs(fname);
  12586. ofs << content;
  12587. ASSERT_TRUE(ofs.good());
  12588. }
  12589. Server svr;
  12590. svr.set_mount_point("/static", ".");
  12591. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12592. svr.wait_until_ready();
  12593. Client cli(HOST, PORT);
  12594. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  12595. ASSERT_TRUE(res1);
  12596. ASSERT_EQ(200, res1->status);
  12597. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12598. // If-Modified-Since with invalid format should not result in 304
  12599. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  12600. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  12601. ASSERT_TRUE(res_bad);
  12602. EXPECT_EQ(200, res_bad->status);
  12603. // If-Range with invalid date format should be treated as mismatch -> full
  12604. // content (200)
  12605. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  12606. {"If-Range", "invalid-date"}};
  12607. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  12608. ASSERT_TRUE(res_ifrange);
  12609. EXPECT_EQ(200, res_ifrange->status);
  12610. svr.stop();
  12611. t.join();
  12612. std::remove(fname);
  12613. }
  12614. TEST(ETagTest, IfRangeWithMalformedETag) {
  12615. using namespace httplib;
  12616. const char *fname = "ifrange_malformed.txt";
  12617. const std::string content = "0123456789";
  12618. {
  12619. std::ofstream ofs(fname);
  12620. ofs << content;
  12621. ASSERT_TRUE(ofs.good());
  12622. }
  12623. Server svr;
  12624. svr.set_mount_point("/static", ".");
  12625. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12626. svr.wait_until_ready();
  12627. Client cli(HOST, PORT);
  12628. // First request: get ETag
  12629. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  12630. ASSERT_TRUE(res1);
  12631. ASSERT_EQ(200, res1->status);
  12632. ASSERT_TRUE(res1->has_header("ETag"));
  12633. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  12634. // full content (200)
  12635. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  12636. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  12637. ASSERT_TRUE(res2);
  12638. EXPECT_EQ(200, res2->status);
  12639. EXPECT_EQ(content, res2->body);
  12640. svr.stop();
  12641. t.join();
  12642. std::remove(fname);
  12643. }
  12644. TEST(ETagTest, ExtremeLargeDateValues) {
  12645. using namespace httplib;
  12646. const char *fname = "ims_extreme_date.txt";
  12647. const char *content = "ims-extreme-date";
  12648. {
  12649. std::ofstream ofs(fname);
  12650. ofs << content;
  12651. ASSERT_TRUE(ofs.good());
  12652. }
  12653. Server svr;
  12654. svr.set_mount_point("/static", ".");
  12655. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12656. svr.wait_until_ready();
  12657. Client cli(HOST, PORT);
  12658. auto res1 = cli.Get(std::string("/static/") + fname);
  12659. ASSERT_TRUE(res1);
  12660. ASSERT_EQ(200, res1->status);
  12661. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12662. // Extremely large year that may overflow date parsing routines.
  12663. Headers h_large_date = {
  12664. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12665. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  12666. ASSERT_TRUE(res_bad);
  12667. // Expect server to treat this as invalid/mismatch and return full content
  12668. EXPECT_EQ(200, res_bad->status);
  12669. // If-Range with extremely large date should be treated as mismatch -> full
  12670. // content (200)
  12671. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  12672. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12673. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  12674. ASSERT_TRUE(res_ifrange);
  12675. EXPECT_EQ(200, res_ifrange->status);
  12676. svr.stop();
  12677. t.join();
  12678. std::remove(fname);
  12679. }
  12680. TEST(ETagTest, NegativeFileModificationTime) {
  12681. using namespace httplib;
  12682. const char *fname = "ims_negative_mtime.txt";
  12683. const std::string content = "negative-mtime";
  12684. {
  12685. std::ofstream ofs(fname);
  12686. ofs << content;
  12687. ASSERT_TRUE(ofs.good());
  12688. }
  12689. // Try to set file mtime to a negative value. This may fail on some
  12690. // platforms/filesystems; if it fails, the test will still verify server
  12691. // behaves safely by performing a regular conditional request.
  12692. #if defined(__APPLE__) || defined(__linux__)
  12693. bool set_negative = false;
  12694. do {
  12695. struct timeval times[2];
  12696. // access time: now
  12697. times[0].tv_sec = time(nullptr);
  12698. times[0].tv_usec = 0;
  12699. // modification time: negative (e.g., -1)
  12700. times[1].tv_sec = -1;
  12701. times[1].tv_usec = 0;
  12702. if (utimes(fname, times) == 0) { set_negative = true; }
  12703. } while (0);
  12704. #else
  12705. bool set_negative = false;
  12706. #endif
  12707. Server svr;
  12708. svr.set_mount_point("/static", ".");
  12709. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12710. svr.wait_until_ready();
  12711. Client cli(HOST, PORT);
  12712. auto res1 = cli.Get(std::string("/static/") + fname);
  12713. ASSERT_TRUE(res1);
  12714. ASSERT_EQ(200, res1->status);
  12715. bool has_last_modified = res1->has_header("Last-Modified");
  12716. std::string last_modified;
  12717. if (has_last_modified) {
  12718. last_modified = res1->get_header_value("Last-Modified");
  12719. }
  12720. if (set_negative) {
  12721. // If we successfully set a negative mtime, ensure server returns a
  12722. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  12723. // with an old date and ensure server handles it without crash.
  12724. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  12725. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  12726. ASSERT_TRUE(res2);
  12727. // Behavior may vary; at minimum ensure server responds (200 or 304).
  12728. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  12729. } else {
  12730. // Could not set negative mtime on this platform; fall back to verifying
  12731. // that normal invalid/malformed dates are treated safely (non-304).
  12732. Headers h_bad_date = {
  12733. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12734. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  12735. ASSERT_TRUE(res_bad);
  12736. EXPECT_EQ(200, res_bad->status);
  12737. }
  12738. svr.stop();
  12739. t.join();
  12740. std::remove(fname);
  12741. }
  12742. //==============================================================================
  12743. // SSE Parsing Tests
  12744. //==============================================================================
  12745. class SSEParsingTest : public ::testing::Test {
  12746. protected:
  12747. // Test helper that mimics SSE parsing behavior
  12748. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  12749. int &retry_ms) {
  12750. // Blank line signals end of event
  12751. if (line.empty() || line == "\r") { return true; }
  12752. // Lines starting with ':' are comments (ignored)
  12753. if (!line.empty() && line[0] == ':') { return false; }
  12754. // Find the colon separator
  12755. auto colon_pos = line.find(':');
  12756. if (colon_pos == std::string::npos) {
  12757. // Line with no colon is treated as field name with empty value
  12758. return false;
  12759. }
  12760. std::string field = line.substr(0, colon_pos);
  12761. std::string value;
  12762. // Value starts after colon, skip optional single space
  12763. if (colon_pos + 1 < line.size()) {
  12764. size_t value_start = colon_pos + 1;
  12765. if (line[value_start] == ' ') { value_start++; }
  12766. value = line.substr(value_start);
  12767. // Remove trailing \r if present
  12768. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  12769. }
  12770. // Handle known fields
  12771. if (field == "event") {
  12772. msg.event = value;
  12773. } else if (field == "data") {
  12774. // Multiple data lines are concatenated with newlines
  12775. if (!msg.data.empty()) { msg.data += "\n"; }
  12776. msg.data += value;
  12777. } else if (field == "id") {
  12778. // Empty id is valid (clears the last event ID)
  12779. msg.id = value;
  12780. } else if (field == "retry") {
  12781. // Parse retry interval in milliseconds
  12782. {
  12783. int v = 0;
  12784. auto res =
  12785. detail::from_chars(value.data(), value.data() + value.size(), v);
  12786. if (res.ec == std::errc{}) { retry_ms = v; }
  12787. }
  12788. }
  12789. // Unknown fields are ignored per SSE spec
  12790. return false;
  12791. }
  12792. };
  12793. // Test: Single-line data
  12794. TEST_F(SSEParsingTest, SingleLineData) {
  12795. sse::SSEMessage msg;
  12796. int retry_ms = 3000;
  12797. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  12798. EXPECT_EQ(msg.data, "hello");
  12799. EXPECT_EQ(msg.event, "message");
  12800. // Blank line ends event
  12801. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12802. }
  12803. // Test: Multi-line data
  12804. TEST_F(SSEParsingTest, MultiLineData) {
  12805. sse::SSEMessage msg;
  12806. int retry_ms = 3000;
  12807. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  12808. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  12809. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  12810. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  12811. }
  12812. // Test: Custom event types
  12813. TEST_F(SSEParsingTest, CustomEventType) {
  12814. sse::SSEMessage msg;
  12815. int retry_ms = 3000;
  12816. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  12817. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  12818. EXPECT_EQ(msg.event, "update");
  12819. EXPECT_EQ(msg.data, "payload");
  12820. }
  12821. // Test: Event ID handling
  12822. TEST_F(SSEParsingTest, EventIdHandling) {
  12823. sse::SSEMessage msg;
  12824. int retry_ms = 3000;
  12825. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  12826. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  12827. EXPECT_EQ(msg.id, "12345");
  12828. }
  12829. // Test: Empty event ID (clears last event ID)
  12830. TEST_F(SSEParsingTest, EmptyEventId) {
  12831. sse::SSEMessage msg;
  12832. msg.id = "previous";
  12833. int retry_ms = 3000;
  12834. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  12835. EXPECT_EQ(msg.id, "");
  12836. }
  12837. // Test: Retry field parsing
  12838. TEST_F(SSEParsingTest, RetryFieldParsing) {
  12839. sse::SSEMessage msg;
  12840. int retry_ms = 3000;
  12841. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  12842. EXPECT_EQ(retry_ms, 5000);
  12843. }
  12844. // Test: Invalid retry value
  12845. TEST_F(SSEParsingTest, InvalidRetryValue) {
  12846. sse::SSEMessage msg;
  12847. int retry_ms = 3000;
  12848. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  12849. EXPECT_EQ(retry_ms, 3000); // Unchanged
  12850. }
  12851. // Test: Comments (lines starting with :)
  12852. TEST_F(SSEParsingTest, CommentsIgnored) {
  12853. sse::SSEMessage msg;
  12854. int retry_ms = 3000;
  12855. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  12856. EXPECT_EQ(msg.data, "");
  12857. EXPECT_EQ(msg.event, "message");
  12858. }
  12859. // Test: Colon in value
  12860. TEST_F(SSEParsingTest, ColonInValue) {
  12861. sse::SSEMessage msg;
  12862. int retry_ms = 3000;
  12863. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  12864. EXPECT_EQ(msg.data, "hello:world:test");
  12865. }
  12866. // Test: Line with no colon (field name only)
  12867. TEST_F(SSEParsingTest, FieldNameOnly) {
  12868. sse::SSEMessage msg;
  12869. int retry_ms = 3000;
  12870. // According to SSE spec, this is treated as field name with empty value
  12871. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  12872. // Since we don't recognize "data" without colon, data should be empty
  12873. EXPECT_EQ(msg.data, "");
  12874. }
  12875. // Test: Trailing \r handling
  12876. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  12877. sse::SSEMessage msg;
  12878. int retry_ms = 3000;
  12879. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  12880. EXPECT_EQ(msg.data, "hello");
  12881. }
  12882. // Test: Unknown fields ignored
  12883. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  12884. sse::SSEMessage msg;
  12885. int retry_ms = 3000;
  12886. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  12887. EXPECT_EQ(msg.data, "");
  12888. EXPECT_EQ(msg.event, "message");
  12889. }
  12890. // Test: Space after colon is optional
  12891. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  12892. sse::SSEMessage msg1, msg2;
  12893. int retry_ms = 3000;
  12894. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  12895. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  12896. EXPECT_EQ(msg1.data, "hello");
  12897. EXPECT_EQ(msg2.data, "hello");
  12898. }
  12899. // Test: SSEMessage clear
  12900. TEST_F(SSEParsingTest, MessageClear) {
  12901. sse::SSEMessage msg;
  12902. msg.event = "custom";
  12903. msg.data = "some data";
  12904. msg.id = "123";
  12905. msg.clear();
  12906. EXPECT_EQ(msg.event, "message");
  12907. EXPECT_EQ(msg.data, "");
  12908. EXPECT_EQ(msg.id, "");
  12909. }
  12910. // Test: Complete event parsing
  12911. TEST_F(SSEParsingTest, CompleteEventParsing) {
  12912. sse::SSEMessage msg;
  12913. int retry_ms = 3000;
  12914. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  12915. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  12916. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  12917. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  12918. // Blank line ends event
  12919. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12920. EXPECT_EQ(msg.event, "notification");
  12921. EXPECT_EQ(msg.id, "evt-42");
  12922. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  12923. EXPECT_EQ(retry_ms, 1000);
  12924. }
  12925. //==============================================================================
  12926. // Integration Tests with Server
  12927. //==============================================================================
  12928. class SSEIntegrationTest : public ::testing::Test {
  12929. protected:
  12930. void SetUp() override {
  12931. stop_server_.store(false);
  12932. events_.clear();
  12933. server_ = httplib::detail::make_unique<Server>();
  12934. setup_server();
  12935. start_server();
  12936. }
  12937. void TearDown() override {
  12938. stop_server_.store(true);
  12939. event_cv_.notify_all();
  12940. server_->stop();
  12941. if (server_thread_.joinable()) { server_thread_.join(); }
  12942. }
  12943. void setup_server() {
  12944. // Simple SSE endpoint
  12945. server_->Get("/events", [this](const Request &req, Response &res) {
  12946. auto last_id = req.get_header_value("Last-Event-ID");
  12947. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  12948. res.set_chunked_content_provider(
  12949. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  12950. std::unique_lock<std::mutex> lock(event_mutex_);
  12951. if (event_cv_.wait_for(
  12952. lock, std::chrono::milliseconds(200), [this] {
  12953. return !events_.empty() || stop_server_.load();
  12954. })) {
  12955. if (stop_server_.load()) { return false; }
  12956. if (!events_.empty()) {
  12957. std::string event = events_.front();
  12958. events_.erase(events_.begin());
  12959. sink.write(event.data(), event.size());
  12960. return true;
  12961. }
  12962. }
  12963. return !stop_server_.load();
  12964. });
  12965. });
  12966. // Endpoint that returns error
  12967. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  12968. res.status = 500;
  12969. res.set_content("Internal Server Error", "text/plain");
  12970. });
  12971. // Endpoint for custom event types
  12972. server_->Get("/custom-events", [](const Request &, Response &res) {
  12973. res.set_chunked_content_provider(
  12974. "text/event-stream", [](size_t offset, DataSink &sink) {
  12975. if (offset == 0) {
  12976. std::string event = "event: update\ndata: updated\n\n"
  12977. "event: delete\ndata: deleted\n\n";
  12978. sink.write(event.data(), event.size());
  12979. }
  12980. return false; // End stream after sending
  12981. });
  12982. });
  12983. }
  12984. void start_server() {
  12985. port_ = server_->bind_to_any_port(HOST);
  12986. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  12987. // Wait for server to start
  12988. while (!server_->is_running()) {
  12989. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12990. }
  12991. }
  12992. int get_port() const { return port_; }
  12993. void send_event(const std::string &event) {
  12994. std::lock_guard<std::mutex> lock(event_mutex_);
  12995. events_.push_back(event);
  12996. event_cv_.notify_all();
  12997. }
  12998. std::unique_ptr<Server> server_;
  12999. std::thread server_thread_;
  13000. std::mutex event_mutex_;
  13001. std::condition_variable event_cv_;
  13002. std::vector<std::string> events_;
  13003. std::atomic<bool> stop_server_{false};
  13004. std::string last_received_event_id_;
  13005. int port_ = 0;
  13006. };
  13007. // Test: Successful connection and on_open callback
  13008. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  13009. // Add a simple endpoint that sends one event and closes
  13010. server_->Get("/simple-event", [](const Request &, Response &res) {
  13011. res.set_chunked_content_provider(
  13012. "text/event-stream", [](size_t offset, DataSink &sink) {
  13013. if (offset == 0) {
  13014. std::string event = "data: hello\n\n";
  13015. sink.write(event.data(), event.size());
  13016. }
  13017. return false; // Close stream after sending
  13018. });
  13019. });
  13020. Client client("localhost", get_port());
  13021. sse::SSEClient sse(client, "/simple-event");
  13022. std::atomic<bool> open_called{false};
  13023. std::atomic<bool> message_received{false};
  13024. sse.on_open([&open_called]() { open_called.store(true); });
  13025. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  13026. if (msg.data == "hello") { message_received.store(true); }
  13027. });
  13028. sse.set_reconnect_interval(100);
  13029. sse.set_max_reconnect_attempts(1);
  13030. // Start async
  13031. sse.start_async();
  13032. // Wait for message to be processed
  13033. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13034. sse.stop();
  13035. EXPECT_TRUE(open_called.load());
  13036. EXPECT_TRUE(message_received.load());
  13037. }
  13038. // Test: on_message callback
  13039. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  13040. // Endpoint that sends multiple events then closes
  13041. server_->Get("/multi-event", [](const Request &, Response &res) {
  13042. res.set_chunked_content_provider(
  13043. "text/event-stream", [](size_t offset, DataSink &sink) {
  13044. if (offset == 0) {
  13045. std::string events = "data: message1\n\ndata: message2\n\n";
  13046. sink.write(events.data(), events.size());
  13047. }
  13048. return false;
  13049. });
  13050. });
  13051. Client client("localhost", get_port());
  13052. sse::SSEClient sse(client, "/multi-event");
  13053. std::vector<std::string> received_messages;
  13054. std::mutex messages_mutex;
  13055. sse.on_message([&](const sse::SSEMessage &msg) {
  13056. std::lock_guard<std::mutex> lock(messages_mutex);
  13057. received_messages.push_back(msg.data);
  13058. });
  13059. sse.set_reconnect_interval(100);
  13060. sse.set_max_reconnect_attempts(1);
  13061. sse.start_async();
  13062. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13063. sse.stop();
  13064. std::lock_guard<std::mutex> lock(messages_mutex);
  13065. EXPECT_GE(received_messages.size(), 2u);
  13066. if (received_messages.size() >= 2) {
  13067. EXPECT_EQ(received_messages[0], "message1");
  13068. EXPECT_EQ(received_messages[1], "message2");
  13069. }
  13070. }
  13071. // Test: on_event for specific types
  13072. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  13073. Client client("localhost", get_port());
  13074. sse::SSEClient sse(client, "/custom-events");
  13075. std::atomic<bool> update_received{false};
  13076. std::atomic<bool> delete_received{false};
  13077. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  13078. if (msg.data == "updated") { update_received.store(true); }
  13079. });
  13080. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  13081. if (msg.data == "deleted") { delete_received.store(true); }
  13082. });
  13083. sse.set_max_reconnect_attempts(1);
  13084. sse.start_async();
  13085. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  13086. sse.stop();
  13087. EXPECT_TRUE(update_received.load());
  13088. EXPECT_TRUE(delete_received.load());
  13089. }
  13090. // Test: on_error callback on connection failure
  13091. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  13092. // Connect to a non-existent port
  13093. Client client("localhost", 59999);
  13094. sse::SSEClient sse(client, "/events");
  13095. std::atomic<bool> error_called{false};
  13096. Error received_error = Error::Success;
  13097. sse.on_error([&](Error err) {
  13098. error_called.store(true);
  13099. received_error = err;
  13100. });
  13101. sse.set_reconnect_interval(50);
  13102. sse.set_max_reconnect_attempts(1);
  13103. sse.start_async();
  13104. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13105. sse.stop();
  13106. EXPECT_TRUE(error_called.load());
  13107. EXPECT_NE(received_error, Error::Success);
  13108. }
  13109. // Test: Last-Event-ID header sent on reconnect
  13110. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  13111. // Endpoint that sends event with ID
  13112. server_->Get("/event-with-id", [](const Request &, Response &res) {
  13113. res.set_chunked_content_provider(
  13114. "text/event-stream", [](size_t offset, DataSink &sink) {
  13115. if (offset == 0) {
  13116. std::string event = "id: evt-123\ndata: test\n\n";
  13117. sink.write(event.data(), event.size());
  13118. }
  13119. return false;
  13120. });
  13121. });
  13122. Client client("localhost", get_port());
  13123. sse::SSEClient sse(client, "/event-with-id");
  13124. std::atomic<bool> id_received{false};
  13125. sse.on_message([&](const sse::SSEMessage &msg) {
  13126. if (!msg.id.empty()) { id_received.store(true); }
  13127. });
  13128. sse.set_reconnect_interval(100);
  13129. sse.set_max_reconnect_attempts(1);
  13130. sse.start_async();
  13131. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13132. sse.stop();
  13133. EXPECT_TRUE(id_received.load());
  13134. EXPECT_EQ(sse.last_event_id(), "evt-123");
  13135. }
  13136. // Test: Manual stop
  13137. TEST_F(SSEIntegrationTest, ManualStop) {
  13138. // Endpoint that sends one event and stays open briefly
  13139. std::atomic<bool> handler_running{true};
  13140. server_->Get("/stay-open", [&handler_running](const Request &,
  13141. Response &res) {
  13142. res.set_chunked_content_provider(
  13143. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  13144. if (offset == 0) {
  13145. std::string event = "data: connected\n\n";
  13146. sink.write(event.data(), event.size());
  13147. }
  13148. // Keep connection open while handler_running is true
  13149. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  13150. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13151. }
  13152. return false;
  13153. });
  13154. });
  13155. Client client("localhost", get_port());
  13156. sse::SSEClient sse(client, "/stay-open");
  13157. std::atomic<bool> connected{false};
  13158. sse.on_open([&connected]() { connected.store(true); });
  13159. sse.set_reconnect_interval(100);
  13160. sse.set_max_reconnect_attempts(1);
  13161. sse.start_async();
  13162. // Wait for connection to establish
  13163. for (int i = 0; i < 20 && !connected.load(); ++i) {
  13164. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13165. }
  13166. EXPECT_TRUE(connected.load());
  13167. EXPECT_TRUE(sse.is_connected());
  13168. // Signal handler to stop
  13169. handler_running.store(false);
  13170. // Stop SSE client
  13171. sse.stop();
  13172. EXPECT_FALSE(sse.is_connected());
  13173. }
  13174. // Test: SSEClient with custom headers
  13175. TEST_F(SSEIntegrationTest, CustomHeaders) {
  13176. // Setup a server endpoint that checks for custom header
  13177. std::atomic<bool> header_received{false};
  13178. server_->Get("/header-check", [&](const Request &req, Response &res) {
  13179. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  13180. header_received.store(true);
  13181. }
  13182. res.set_chunked_content_provider("text/event-stream",
  13183. [](size_t, DataSink &) { return false; });
  13184. });
  13185. Client client("localhost", get_port());
  13186. Headers headers = {{"X-Custom-Header", "custom-value"}};
  13187. sse::SSEClient sse(client, "/header-check", headers);
  13188. sse.set_max_reconnect_attempts(1);
  13189. sse.start_async();
  13190. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13191. sse.stop();
  13192. EXPECT_TRUE(header_received.load());
  13193. }
  13194. // Test: Reconnect interval configuration
  13195. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  13196. Client client("localhost", get_port());
  13197. sse::SSEClient sse(client, "/events");
  13198. auto &result = sse.set_reconnect_interval(500);
  13199. // Builder pattern should return reference to self
  13200. EXPECT_EQ(&result, &sse);
  13201. }
  13202. // Test: Max reconnect attempts
  13203. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  13204. // Connect to non-existent port to force reconnects
  13205. Client client("localhost", 59998);
  13206. sse::SSEClient sse(client, "/events");
  13207. std::atomic<int> error_count{0};
  13208. sse.on_error([&](Error) { error_count.fetch_add(1); });
  13209. sse.set_reconnect_interval(50);
  13210. sse.set_max_reconnect_attempts(2);
  13211. auto start = std::chrono::steady_clock::now();
  13212. sse.start(); // Blocking call
  13213. auto end = std::chrono::steady_clock::now();
  13214. // Should have stopped after 2 failed attempts
  13215. EXPECT_GE(error_count.load(), 2);
  13216. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  13217. auto duration =
  13218. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  13219. #ifdef _WIN32
  13220. // Windows is much slower for socket connection failures
  13221. EXPECT_LT(duration.count(), 7000);
  13222. #else
  13223. EXPECT_LT(duration.count(), 1000);
  13224. #endif
  13225. }
  13226. // Test: Multi-line data in integration
  13227. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  13228. // Endpoint with multi-line data
  13229. server_->Get("/multiline-data", [](const Request &, Response &res) {
  13230. res.set_chunked_content_provider(
  13231. "text/event-stream", [](size_t offset, DataSink &sink) {
  13232. if (offset == 0) {
  13233. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  13234. sink.write(event.data(), event.size());
  13235. }
  13236. return false;
  13237. });
  13238. });
  13239. Client client("localhost", get_port());
  13240. sse::SSEClient sse(client, "/multiline-data");
  13241. std::string received_data;
  13242. std::mutex data_mutex;
  13243. sse.on_message([&](const sse::SSEMessage &msg) {
  13244. std::lock_guard<std::mutex> lock(data_mutex);
  13245. received_data = msg.data;
  13246. });
  13247. sse.set_reconnect_interval(100);
  13248. sse.set_max_reconnect_attempts(1);
  13249. sse.start_async();
  13250. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13251. sse.stop();
  13252. std::lock_guard<std::mutex> lock(data_mutex);
  13253. EXPECT_EQ(received_data, "line1\nline2\nline3");
  13254. }
  13255. // Test: Auto-reconnect after server disconnection
  13256. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  13257. std::atomic<int> connection_count{0};
  13258. std::atomic<int> message_count{0};
  13259. // Endpoint that sends one event and closes, forcing reconnect
  13260. server_->Get("/reconnect-test",
  13261. [&connection_count](const Request &, Response &res) {
  13262. connection_count.fetch_add(1);
  13263. res.set_chunked_content_provider(
  13264. "text/event-stream", [](size_t offset, DataSink &sink) {
  13265. if (offset == 0) {
  13266. std::string event = "data: hello\n\n";
  13267. sink.write(event.data(), event.size());
  13268. }
  13269. return false; // Close connection after sending
  13270. });
  13271. });
  13272. Client client("localhost", get_port());
  13273. sse::SSEClient sse(client, "/reconnect-test");
  13274. sse.on_message([&message_count](const sse::SSEMessage &) {
  13275. message_count.fetch_add(1);
  13276. });
  13277. sse.set_reconnect_interval(100);
  13278. sse.set_max_reconnect_attempts(3);
  13279. sse.start_async();
  13280. // Wait long enough for multiple reconnects
  13281. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13282. sse.stop();
  13283. // Should have connected multiple times (initial + reconnects)
  13284. EXPECT_GE(connection_count.load(), 2);
  13285. // Should have received messages from multiple connections
  13286. EXPECT_GE(message_count.load(), 2);
  13287. }
  13288. // Test: Last-Event-ID sent on reconnect
  13289. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  13290. std::atomic<int> connection_count{0};
  13291. std::vector<std::string> received_last_event_ids;
  13292. std::mutex id_mutex;
  13293. // Endpoint that checks Last-Event-ID header and sends event with ID
  13294. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  13295. int conn = connection_count.fetch_add(1);
  13296. // Capture the Last-Event-ID header from each connection
  13297. {
  13298. std::lock_guard<std::mutex> lock(id_mutex);
  13299. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  13300. }
  13301. res.set_chunked_content_provider(
  13302. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  13303. if (offset == 0) {
  13304. std::string event =
  13305. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  13306. sink.write(event.data(), event.size());
  13307. }
  13308. return false;
  13309. });
  13310. });
  13311. Client client("localhost", get_port());
  13312. sse::SSEClient sse(client, "/reconnect-with-id");
  13313. sse.set_reconnect_interval(100);
  13314. sse.set_max_reconnect_attempts(3);
  13315. sse.start_async();
  13316. // Wait for at least 2 connections
  13317. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13318. sse.stop();
  13319. // Verify behavior
  13320. std::lock_guard<std::mutex> lock(id_mutex);
  13321. EXPECT_GE(received_last_event_ids.size(), 2u);
  13322. // First connection should have no Last-Event-ID
  13323. if (!received_last_event_ids.empty()) {
  13324. EXPECT_EQ(received_last_event_ids[0], "");
  13325. }
  13326. // Second connection should have Last-Event-ID from first connection
  13327. if (received_last_event_ids.size() >= 2) {
  13328. EXPECT_EQ(received_last_event_ids[1], "event-0");
  13329. }
  13330. }
  13331. // Test: set_headers updates headers used on reconnect
  13332. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  13333. std::vector<std::string> received_tokens;
  13334. std::mutex token_mutex;
  13335. // Endpoint that captures Authorization header
  13336. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  13337. {
  13338. std::lock_guard<std::mutex> lock(token_mutex);
  13339. received_tokens.push_back(req.get_header_value("Authorization"));
  13340. }
  13341. res.set_chunked_content_provider(
  13342. "text/event-stream", [](size_t offset, DataSink &sink) {
  13343. if (offset == 0) {
  13344. std::string event = "data: hello\n\n";
  13345. sink.write(event.data(), event.size());
  13346. }
  13347. return false; // Close connection to trigger reconnect
  13348. });
  13349. });
  13350. Client client("localhost", get_port());
  13351. Headers headers = {{"Authorization", "Bearer old-token"}};
  13352. sse::SSEClient sse(client, "/auth-check", headers);
  13353. // Update headers on each successful connection
  13354. sse.on_open(
  13355. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  13356. sse.set_reconnect_interval(100);
  13357. sse.set_max_reconnect_attempts(3);
  13358. sse.start_async();
  13359. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13360. sse.stop();
  13361. std::lock_guard<std::mutex> lock(token_mutex);
  13362. ASSERT_GE(received_tokens.size(), 2u);
  13363. // First connection uses original header
  13364. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  13365. // Second connection uses updated header from set_headers
  13366. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  13367. }
  13368. // Test: 401 allows reconnection (so on_error can refresh headers)
  13369. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  13370. std::atomic<int> connection_count{0};
  13371. // Endpoint: returns 401 on first attempt, 200 on second
  13372. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  13373. int conn = connection_count.fetch_add(1);
  13374. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  13375. res.status = StatusCode::Unauthorized_401;
  13376. res.set_content("Unauthorized", "text/plain");
  13377. return;
  13378. }
  13379. res.set_chunked_content_provider(
  13380. "text/event-stream", [](size_t offset, DataSink &sink) {
  13381. if (offset == 0) {
  13382. std::string event = "data: authenticated\n\n";
  13383. sink.write(event.data(), event.size());
  13384. }
  13385. return false;
  13386. });
  13387. });
  13388. Client client("localhost", get_port());
  13389. Headers headers = {{"Authorization", "Bearer expired"}};
  13390. sse::SSEClient sse(client, "/auth-retry", headers);
  13391. std::atomic<bool> message_received{false};
  13392. // Refresh token on error
  13393. sse.on_error(
  13394. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  13395. sse.on_message([&](const sse::SSEMessage &msg) {
  13396. if (msg.data == "authenticated") { message_received.store(true); }
  13397. });
  13398. sse.set_reconnect_interval(100);
  13399. sse.set_max_reconnect_attempts(3);
  13400. sse.start_async();
  13401. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13402. sse.stop();
  13403. // Should have reconnected after 401 and succeeded with new token
  13404. EXPECT_GE(connection_count.load(), 2);
  13405. EXPECT_TRUE(message_received.load());
  13406. }
  13407. TEST(Issue2318Test, EmptyHostString) {
  13408. {
  13409. httplib::Client cli_empty("", PORT);
  13410. auto res = cli_empty.Get("/");
  13411. ASSERT_FALSE(res);
  13412. EXPECT_EQ(httplib::Error::Connection, res.error());
  13413. }
  13414. {
  13415. httplib::Client cli(" ", PORT);
  13416. auto res = cli.Get("/");
  13417. ASSERT_FALSE(res);
  13418. EXPECT_EQ(httplib::Error::Connection, res.error());
  13419. }
  13420. }
  13421. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13422. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  13423. Server svr;
  13424. // Set a small payload limit (1KB)
  13425. svr.set_payload_max_length(1024);
  13426. svr.Post("/test", [&](const Request &req, Response &res) {
  13427. res.set_content("Body size: " + std::to_string(req.body.size()),
  13428. "text/plain");
  13429. });
  13430. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13431. auto se = detail::scope_exit([&] {
  13432. svr.stop();
  13433. listen_thread.join();
  13434. });
  13435. svr.wait_until_ready();
  13436. // Create data that compresses well but exceeds limit when decompressed
  13437. // 8KB of repeated null bytes compresses to a very small size
  13438. std::string original_data(8 * 1024, '\0');
  13439. // Compress the data using gzip
  13440. std::string compressed_data;
  13441. detail::gzip_compressor compressor;
  13442. compressor.compress(original_data.data(), original_data.size(), true,
  13443. [&](const char *data, size_t size) {
  13444. compressed_data.append(data, size);
  13445. return true;
  13446. });
  13447. // Verify compression worked (compressed should be much smaller)
  13448. ASSERT_LT(compressed_data.size(), original_data.size());
  13449. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  13450. // Send compressed data with Content-Encoding: gzip
  13451. Client cli(HOST, PORT);
  13452. Headers headers = {{"Content-Encoding", "gzip"}};
  13453. auto res =
  13454. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  13455. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  13456. ASSERT_TRUE(res);
  13457. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13458. }
  13459. #endif
  13460. // ============================================================================
  13461. // OpenSSL-Specific Tests
  13462. // ============================================================================
  13463. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13464. X509 *readCertificate(const std::string &strFileName) {
  13465. std::ifstream inStream(strFileName);
  13466. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  13467. std::istreambuf_iterator<char>());
  13468. if (strCertPEM.empty()) return (nullptr);
  13469. BIO *pbCert = BIO_new(BIO_s_mem());
  13470. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  13471. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  13472. BIO_free(pbCert);
  13473. return (pCert);
  13474. }
  13475. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  13476. std::ifstream inStream(strFileName);
  13477. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  13478. std::istreambuf_iterator<char>());
  13479. if (strPrivateKeyPEM.empty()) return (nullptr);
  13480. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  13481. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  13482. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  13483. BIO_free(pbPrivKey);
  13484. return (pPrivateKey);
  13485. }
  13486. TEST(BindServerTest, UpdateCerts) {
  13487. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13488. int port = svr.bind_to_any_port("0.0.0.0");
  13489. ASSERT_TRUE(svr.is_valid());
  13490. ASSERT_TRUE(port > 0);
  13491. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13492. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13493. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13494. ASSERT_TRUE(cert != nullptr);
  13495. ASSERT_TRUE(ca_cert != nullptr);
  13496. ASSERT_TRUE(key != nullptr);
  13497. X509_STORE *cert_store = X509_STORE_new();
  13498. X509_STORE_add_cert(cert_store, ca_cert);
  13499. // svr.update_certs(cert, key, cert_store); // deprecated
  13500. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13501. CLIENT_CA_CERT_FILE);
  13502. ASSERT_TRUE(svr.is_valid());
  13503. svr.stop();
  13504. X509_STORE_free(cert_store);
  13505. X509_free(cert);
  13506. X509_free(ca_cert);
  13507. EVP_PKEY_free(key);
  13508. }
  13509. // Test that SSLServer(X509*, EVP_PKEY*, X509_STORE*) constructor sets
  13510. // client CA list correctly for TLS handshake
  13511. TEST(SSLClientServerTest, X509ConstructorSetsClientCAList) {
  13512. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13513. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13514. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13515. ASSERT_TRUE(cert != nullptr);
  13516. ASSERT_TRUE(ca_cert != nullptr);
  13517. ASSERT_TRUE(key != nullptr);
  13518. X509_STORE *cert_store = X509_STORE_new();
  13519. X509_STORE_add_cert(cert_store, ca_cert);
  13520. // Use X509-based constructor (deprecated but should still work correctly)
  13521. #pragma GCC diagnostic push
  13522. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  13523. SSLServer svr(cert, key, cert_store);
  13524. #pragma GCC diagnostic pop
  13525. ASSERT_TRUE(svr.is_valid());
  13526. // Verify that client CA list is set in SSL_CTX
  13527. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13528. ASSERT_TRUE(ssl_ctx != nullptr);
  13529. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13530. ASSERT_TRUE(ca_list != nullptr);
  13531. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13532. X509_free(cert);
  13533. X509_free(ca_cert);
  13534. EVP_PKEY_free(key);
  13535. }
  13536. // Test that update_certs() updates client CA list correctly
  13537. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  13538. // Start with file-based constructor
  13539. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13540. ASSERT_TRUE(svr.is_valid());
  13541. // Initially no client CA list should be set
  13542. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13543. ASSERT_TRUE(ssl_ctx != nullptr);
  13544. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  13545. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  13546. EXPECT_EQ(0, count_before);
  13547. // Now update with client CA (PEM string)
  13548. std::string cert_pem, key_pem, ca_pem;
  13549. read_file(SERVER_CERT_FILE, cert_pem);
  13550. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13551. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13552. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  13553. ASSERT_TRUE(svr.is_valid());
  13554. // Now client CA list should be set
  13555. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  13556. ASSERT_TRUE(ca_list_after != nullptr);
  13557. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  13558. }
  13559. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  13560. // Test that the file-path SSLServer constructor properly sets the client CA
  13561. // list that is sent to clients during the TLS handshake (CertificateRequest)
  13562. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13563. ASSERT_TRUE(svr.is_valid());
  13564. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13565. ASSERT_TRUE(ssl_ctx != nullptr);
  13566. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13567. ASSERT_TRUE(ca_list != nullptr);
  13568. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13569. }
  13570. #endif
  13571. // ============================================================================
  13572. // MbedTLS-Specific Tests
  13573. // ============================================================================
  13574. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  13575. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  13576. using namespace httplib::tls;
  13577. // Track if callback was invoked
  13578. bool callback_invoked = false;
  13579. // The callback receives void* ctx which is actually MbedTlsContext*
  13580. // We can access the mbedtls_ssl_config via the context
  13581. auto setup_callback = [&callback_invoked](void *ctx) {
  13582. callback_invoked = true;
  13583. // Cast to MbedTlsContext* to access the ssl config
  13584. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  13585. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  13586. // Use static variables to hold certificate data (simplified for test)
  13587. static mbedtls_x509_crt own_cert;
  13588. static mbedtls_pk_context own_key;
  13589. static mbedtls_x509_crt ca_chain;
  13590. static bool initialized = false;
  13591. if (!initialized) {
  13592. mbedtls_x509_crt_init(&own_cert);
  13593. mbedtls_pk_init(&own_key);
  13594. mbedtls_x509_crt_init(&ca_chain);
  13595. // Load server certificate
  13596. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  13597. return false;
  13598. }
  13599. // Load server private key
  13600. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  13601. #if MBEDTLS_VERSION_MAJOR >= 3
  13602. ,
  13603. mbedtls_ctr_drbg_random, nullptr
  13604. #endif
  13605. ) != 0) {
  13606. return false;
  13607. }
  13608. // Load CA chain for client verification
  13609. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  13610. return false;
  13611. }
  13612. initialized = true;
  13613. }
  13614. // Configure the SSL config
  13615. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  13616. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  13617. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  13618. // Set minimum TLS version using mbedTLS native API
  13619. #if MBEDTLS_VERSION_MAJOR >= 3
  13620. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  13621. #else
  13622. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  13623. MBEDTLS_SSL_MINOR_VERSION_3);
  13624. #endif
  13625. return true;
  13626. };
  13627. SSLServer svr(setup_callback);
  13628. ASSERT_TRUE(svr.is_valid());
  13629. ASSERT_TRUE(callback_invoked);
  13630. svr.Get("/test", [&](const Request &req, Response &res) {
  13631. res.set_content("test", "text/plain");
  13632. auto cert = req.peer_cert();
  13633. ASSERT_TRUE(static_cast<bool>(cert));
  13634. auto common_name = cert.subject_cn();
  13635. EXPECT_EQ("Common Name", common_name);
  13636. });
  13637. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13638. auto se = detail::scope_exit([&] {
  13639. svr.stop();
  13640. t.join();
  13641. ASSERT_FALSE(svr.is_running());
  13642. });
  13643. svr.wait_until_ready();
  13644. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13645. cli.enable_server_certificate_verification(false);
  13646. cli.set_connection_timeout(30);
  13647. auto res = cli.Get("/test");
  13648. ASSERT_TRUE(res);
  13649. ASSERT_EQ(StatusCode::OK_200, res->status);
  13650. }
  13651. #endif
  13652. // WebSocket Tests
  13653. TEST(WebSocketTest, RSVBitsMustBeZero) {
  13654. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  13655. // defining the meaning of these bits has been negotiated.
  13656. auto make_frame = [](uint8_t first_byte) {
  13657. std::string frame;
  13658. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  13659. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  13660. frame += "Hello";
  13661. return frame;
  13662. };
  13663. // RSV1 set (0x40)
  13664. {
  13665. detail::BufferStream strm;
  13666. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  13667. ws::Opcode opcode;
  13668. std::string payload;
  13669. bool fin;
  13670. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13671. false, 1024));
  13672. }
  13673. // RSV2 set (0x20)
  13674. {
  13675. detail::BufferStream strm;
  13676. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  13677. ws::Opcode opcode;
  13678. std::string payload;
  13679. bool fin;
  13680. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13681. false, 1024));
  13682. }
  13683. // RSV3 set (0x10)
  13684. {
  13685. detail::BufferStream strm;
  13686. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  13687. ws::Opcode opcode;
  13688. std::string payload;
  13689. bool fin;
  13690. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13691. false, 1024));
  13692. }
  13693. // No RSV bits set - should succeed
  13694. {
  13695. detail::BufferStream strm;
  13696. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  13697. ws::Opcode opcode;
  13698. std::string payload;
  13699. bool fin;
  13700. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13701. false, 1024));
  13702. EXPECT_EQ(ws::Opcode::Text, opcode);
  13703. EXPECT_EQ("Hello", payload);
  13704. EXPECT_TRUE(fin);
  13705. }
  13706. }
  13707. TEST(WebSocketTest, ControlFrameValidation) {
  13708. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  13709. // payload length <= 125.
  13710. // Ping with FIN=0 - must be rejected
  13711. {
  13712. detail::BufferStream strm;
  13713. std::string frame;
  13714. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  13715. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13716. strm.write(frame.data(), frame.size());
  13717. ws::Opcode opcode;
  13718. std::string payload;
  13719. bool fin;
  13720. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13721. false, 1024));
  13722. }
  13723. // Close with FIN=0 - must be rejected
  13724. {
  13725. detail::BufferStream strm;
  13726. std::string frame;
  13727. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  13728. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13729. strm.write(frame.data(), frame.size());
  13730. ws::Opcode opcode;
  13731. std::string payload;
  13732. bool fin;
  13733. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13734. false, 1024));
  13735. }
  13736. // Ping with payload_len=126 (extended length) - must be rejected
  13737. {
  13738. detail::BufferStream strm;
  13739. std::string frame;
  13740. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13741. frame += static_cast<char>(126); // payload_len=126 (>125)
  13742. frame += static_cast<char>(0x00); // extended length high byte
  13743. frame += static_cast<char>(126); // extended length low byte
  13744. frame += std::string(126, 'x');
  13745. strm.write(frame.data(), frame.size());
  13746. ws::Opcode opcode;
  13747. std::string payload;
  13748. bool fin;
  13749. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13750. false, 1024));
  13751. }
  13752. // Ping with FIN=1 and payload_len=125 - should succeed
  13753. {
  13754. detail::BufferStream strm;
  13755. std::string frame;
  13756. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13757. frame += static_cast<char>(125); // payload_len=125
  13758. frame += std::string(125, 'x');
  13759. strm.write(frame.data(), frame.size());
  13760. ws::Opcode opcode;
  13761. std::string payload;
  13762. bool fin;
  13763. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13764. false, 1024));
  13765. EXPECT_EQ(ws::Opcode::Ping, opcode);
  13766. EXPECT_EQ(125u, payload.size());
  13767. EXPECT_TRUE(fin);
  13768. }
  13769. }
  13770. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  13771. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  13772. // length MUST be 0.
  13773. // MSB set - must be rejected
  13774. {
  13775. detail::BufferStream strm;
  13776. std::string frame;
  13777. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13778. frame += static_cast<char>(127); // 64-bit extended length
  13779. frame += static_cast<char>(0x80); // MSB set (invalid)
  13780. frame += std::string(7, '\0'); // remaining 7 bytes of length
  13781. strm.write(frame.data(), frame.size());
  13782. ws::Opcode opcode;
  13783. std::string payload;
  13784. bool fin;
  13785. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13786. false, 1024));
  13787. }
  13788. // MSB clear - should pass length parsing (will be rejected by max_len,
  13789. // but that's a different check; use a small length to verify)
  13790. {
  13791. detail::BufferStream strm;
  13792. std::string frame;
  13793. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13794. frame += static_cast<char>(127); // 64-bit extended length
  13795. frame += std::string(7, '\0'); // high bytes = 0
  13796. frame += static_cast<char>(0x03); // length = 3
  13797. frame += "abc";
  13798. strm.write(frame.data(), frame.size());
  13799. ws::Opcode opcode;
  13800. std::string payload;
  13801. bool fin;
  13802. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13803. false, 1024));
  13804. EXPECT_EQ(ws::Opcode::Text, opcode);
  13805. EXPECT_EQ("abc", payload);
  13806. }
  13807. }
  13808. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  13809. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  13810. // Valid UTF-8
  13811. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  13812. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  13813. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  13814. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  13815. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  13816. // Invalid UTF-8
  13817. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  13818. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  13819. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  13820. EXPECT_FALSE(
  13821. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  13822. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  13823. }
  13824. TEST(WebSocketTest, ConnectAndDisconnect) {
  13825. Server svr;
  13826. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  13827. std::string msg;
  13828. while (ws.read(msg)) {}
  13829. });
  13830. auto port = svr.bind_to_any_port(HOST);
  13831. std::thread t([&]() { svr.listen_after_bind(); });
  13832. svr.wait_until_ready();
  13833. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  13834. ASSERT_TRUE(client.connect());
  13835. EXPECT_TRUE(client.is_open());
  13836. client.close();
  13837. EXPECT_FALSE(client.is_open());
  13838. svr.stop();
  13839. t.join();
  13840. }
  13841. TEST(WebSocketTest, ValidURL) {
  13842. ws::WebSocketClient ws1("ws://localhost:8080/path");
  13843. EXPECT_TRUE(ws1.is_valid());
  13844. ws::WebSocketClient ws2("ws://example.com/path");
  13845. EXPECT_TRUE(ws2.is_valid());
  13846. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  13847. EXPECT_TRUE(ws3.is_valid());
  13848. #ifdef CPPHTTPLIB_SSL_ENABLED
  13849. ws::WebSocketClient wss1("wss://example.com/path");
  13850. EXPECT_TRUE(wss1.is_valid());
  13851. ws::WebSocketClient wss2("wss://example.com:443/path");
  13852. EXPECT_TRUE(wss2.is_valid());
  13853. #endif
  13854. }
  13855. TEST(WebSocketTest, InvalidURL) {
  13856. // No scheme
  13857. ws::WebSocketClient ws1("localhost:8080/path");
  13858. EXPECT_FALSE(ws1.is_valid());
  13859. // No path
  13860. ws::WebSocketClient ws2("ws://localhost:8080");
  13861. EXPECT_FALSE(ws2.is_valid());
  13862. // Empty string
  13863. ws::WebSocketClient ws3("");
  13864. EXPECT_FALSE(ws3.is_valid());
  13865. // Missing host
  13866. ws::WebSocketClient ws4("ws://:8080/path");
  13867. EXPECT_FALSE(ws4.is_valid());
  13868. // Port number overflow — should not crash
  13869. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  13870. EXPECT_FALSE(ws5.is_valid());
  13871. // Port out of range
  13872. ws::WebSocketClient ws6("ws://localhost:99999/path");
  13873. EXPECT_FALSE(ws6.is_valid());
  13874. }
  13875. TEST(WebSocketTest, UnsupportedScheme) {
  13876. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13877. ws::WebSocketClient ws1("http://localhost:8080/path");
  13878. EXPECT_FALSE(ws1.is_valid());
  13879. ws::WebSocketClient ws2("https://localhost:8080/path");
  13880. EXPECT_FALSE(ws2.is_valid());
  13881. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  13882. EXPECT_FALSE(ws3.is_valid());
  13883. #else
  13884. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  13885. std::invalid_argument);
  13886. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  13887. std::invalid_argument);
  13888. #endif
  13889. }
  13890. TEST(WebSocketTest, ConnectWhenInvalid) {
  13891. ws::WebSocketClient ws("not a valid url");
  13892. EXPECT_FALSE(ws.is_valid());
  13893. EXPECT_FALSE(ws.connect());
  13894. }
  13895. TEST(WebSocketTest, DefaultPort) {
  13896. ws::WebSocketClient ws1("ws://example.com/path");
  13897. EXPECT_TRUE(ws1.is_valid());
  13898. // ws:// defaults to port 80 (verified by successful parse)
  13899. #ifdef CPPHTTPLIB_SSL_ENABLED
  13900. ws::WebSocketClient ws2("wss://example.com/path");
  13901. EXPECT_TRUE(ws2.is_valid());
  13902. // wss:// defaults to port 443 (verified by successful parse)
  13903. #endif
  13904. }
  13905. TEST(WebSocketTest, IPv6LiteralAddress) {
  13906. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  13907. EXPECT_TRUE(ws1.is_valid());
  13908. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  13909. EXPECT_TRUE(ws2.is_valid());
  13910. }
  13911. TEST(WebSocketTest, ComplexPath) {
  13912. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  13913. EXPECT_TRUE(ws1.is_valid());
  13914. ws::WebSocketClient ws2("ws://localhost:8080/");
  13915. EXPECT_TRUE(ws2.is_valid());
  13916. }
  13917. class WebSocketIntegrationTest : public ::testing::Test {
  13918. protected:
  13919. void SetUp() override {
  13920. server_ = httplib::detail::make_unique<Server>();
  13921. setup_server();
  13922. start_server();
  13923. }
  13924. void TearDown() override {
  13925. server_->stop();
  13926. if (server_thread_.joinable()) { server_thread_.join(); }
  13927. }
  13928. void setup_server() {
  13929. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  13930. std::string msg;
  13931. ws::ReadResult ret;
  13932. while ((ret = ws.read(msg))) {
  13933. if (ret == ws::Binary) {
  13934. ws.send(msg.data(), msg.size());
  13935. } else {
  13936. ws.send(msg);
  13937. }
  13938. }
  13939. });
  13940. server_->WebSocket("/ws-echo-string",
  13941. [](const Request &, ws::WebSocket &ws) {
  13942. std::string msg;
  13943. while (ws.read(msg)) {
  13944. ws.send("echo: " + msg);
  13945. }
  13946. });
  13947. server_->WebSocket(
  13948. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  13949. // Echo back request metadata
  13950. ws.send("path:" + req.path);
  13951. ws.send("header:" + req.get_header_value("X-Test-Header"));
  13952. std::string msg;
  13953. while (ws.read(msg)) {}
  13954. });
  13955. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  13956. std::string msg;
  13957. ws.read(msg); // wait for a message
  13958. ws.close();
  13959. });
  13960. server_->WebSocket("/ws-close-status",
  13961. [](const Request &, ws::WebSocket &ws) {
  13962. std::string msg;
  13963. ws.read(msg); // wait for a message
  13964. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  13965. });
  13966. server_->WebSocket(
  13967. "/ws-subprotocol",
  13968. [](const Request &, ws::WebSocket &ws) {
  13969. std::string msg;
  13970. while (ws.read(msg)) {
  13971. ws.send(msg);
  13972. }
  13973. },
  13974. [](const std::vector<std::string> &protocols) -> std::string {
  13975. for (const auto &p : protocols) {
  13976. if (p == "graphql-ws") { return p; }
  13977. }
  13978. return "";
  13979. });
  13980. }
  13981. void start_server() {
  13982. port_ = server_->bind_to_any_port(HOST);
  13983. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13984. server_->wait_until_ready();
  13985. }
  13986. std::unique_ptr<Server> server_;
  13987. std::thread server_thread_;
  13988. int port_ = 0;
  13989. };
  13990. TEST_F(WebSocketIntegrationTest, TextEcho) {
  13991. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13992. "/ws-echo");
  13993. ASSERT_TRUE(client.connect());
  13994. ASSERT_TRUE(client.is_open());
  13995. ASSERT_TRUE(client.send("Hello WebSocket"));
  13996. std::string msg;
  13997. EXPECT_EQ(ws::Text, client.read(msg));
  13998. EXPECT_EQ("Hello WebSocket", msg);
  13999. client.close();
  14000. }
  14001. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  14002. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14003. "/ws-echo");
  14004. ASSERT_TRUE(client.connect());
  14005. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  14006. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  14007. std::string msg;
  14008. EXPECT_EQ(ws::Binary, client.read(msg));
  14009. EXPECT_EQ(binary_data, msg);
  14010. client.close();
  14011. }
  14012. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  14013. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14014. "/ws-echo");
  14015. ASSERT_TRUE(client.connect());
  14016. for (int i = 0; i < 10; i++) {
  14017. auto text = "message " + std::to_string(i);
  14018. ASSERT_TRUE(client.send(text));
  14019. std::string msg;
  14020. ASSERT_TRUE(client.read(msg));
  14021. EXPECT_EQ(text, msg);
  14022. }
  14023. client.close();
  14024. }
  14025. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  14026. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14027. "/ws-close");
  14028. ASSERT_TRUE(client.connect());
  14029. // Send a message to trigger the server to close
  14030. ASSERT_TRUE(client.send("trigger close"));
  14031. // The server will close, so read should return false
  14032. std::string msg;
  14033. EXPECT_FALSE(client.read(msg));
  14034. EXPECT_FALSE(client.is_open());
  14035. }
  14036. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  14037. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14038. "/ws-echo");
  14039. ASSERT_TRUE(client.connect());
  14040. // 128KB message
  14041. std::string large_data(128 * 1024, 'X');
  14042. ASSERT_TRUE(client.send(large_data));
  14043. std::string msg;
  14044. ASSERT_TRUE(client.read(msg));
  14045. EXPECT_EQ(large_data, msg);
  14046. client.close();
  14047. }
  14048. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  14049. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14050. "/ws-echo");
  14051. ASSERT_TRUE(client.connect());
  14052. const int num_threads = 4;
  14053. std::vector<std::thread> threads;
  14054. std::atomic<int> send_count{0};
  14055. for (int t = 0; t < num_threads; t++) {
  14056. threads.emplace_back([&client, &send_count, t]() {
  14057. for (int i = 0; i < 5; i++) {
  14058. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  14059. if (client.send(text)) { send_count++; }
  14060. }
  14061. });
  14062. }
  14063. for (auto &th : threads) {
  14064. th.join();
  14065. }
  14066. int received = 0;
  14067. std::string msg;
  14068. while (received < send_count.load()) {
  14069. if (!client.read(msg)) { break; }
  14070. received++;
  14071. }
  14072. EXPECT_EQ(send_count.load(), received);
  14073. client.close();
  14074. }
  14075. TEST_F(WebSocketIntegrationTest, ReadString) {
  14076. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14077. "/ws-echo-string");
  14078. ASSERT_TRUE(client.connect());
  14079. ASSERT_TRUE(client.send("hello"));
  14080. std::string msg;
  14081. ASSERT_TRUE(client.read(msg));
  14082. EXPECT_EQ("echo: hello", msg);
  14083. ASSERT_TRUE(client.send("world"));
  14084. ASSERT_TRUE(client.read(msg));
  14085. EXPECT_EQ("echo: world", msg);
  14086. client.close();
  14087. }
  14088. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  14089. Headers headers = {{"X-Test-Header", "test-value"}};
  14090. ws::WebSocketClient client(
  14091. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  14092. ASSERT_TRUE(client.connect());
  14093. std::string msg;
  14094. ASSERT_TRUE(client.read(msg));
  14095. EXPECT_EQ("path:/ws-request-info", msg);
  14096. ASSERT_TRUE(client.read(msg));
  14097. EXPECT_EQ("header:test-value", msg);
  14098. client.close();
  14099. }
  14100. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  14101. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14102. "/ws-echo");
  14103. client.set_read_timeout(1, 0); // 1 second
  14104. ASSERT_TRUE(client.connect());
  14105. // Don't send anything — server echo handler waits for a message,
  14106. // so read() should time out and return false.
  14107. std::string msg;
  14108. EXPECT_FALSE(client.read(msg));
  14109. }
  14110. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  14111. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14112. "/ws-echo");
  14113. client.set_read_timeout(5, 0);
  14114. ASSERT_TRUE(client.connect());
  14115. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14116. // The server should reject it and close the connection.
  14117. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  14118. client.send(oversized);
  14119. // The server's read() should have failed due to payload limit,
  14120. // so our read() should return false (connection closed).
  14121. std::string msg;
  14122. EXPECT_FALSE(client.read(msg));
  14123. }
  14124. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  14125. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14126. "/ws-echo");
  14127. client.set_read_timeout(10, 0);
  14128. ASSERT_TRUE(client.connect());
  14129. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14130. // This should succeed.
  14131. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  14132. ASSERT_TRUE(client.send(at_limit));
  14133. std::string msg;
  14134. ASSERT_TRUE(client.read(msg));
  14135. EXPECT_EQ(at_limit.size(), msg.size());
  14136. client.close();
  14137. }
  14138. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  14139. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14140. "/nonexistent");
  14141. EXPECT_FALSE(client.connect());
  14142. EXPECT_FALSE(client.is_open());
  14143. }
  14144. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  14145. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14146. "/ws-echo");
  14147. ASSERT_TRUE(client.connect());
  14148. ASSERT_TRUE(client.send(""));
  14149. std::string msg;
  14150. EXPECT_EQ(ws::Text, client.read(msg));
  14151. EXPECT_EQ("", msg);
  14152. client.close();
  14153. }
  14154. TEST_F(WebSocketIntegrationTest, Reconnect) {
  14155. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14156. "/ws-echo");
  14157. // First connection
  14158. ASSERT_TRUE(client.connect());
  14159. ASSERT_TRUE(client.send("first"));
  14160. std::string msg;
  14161. ASSERT_TRUE(client.read(msg));
  14162. EXPECT_EQ("first", msg);
  14163. client.close();
  14164. EXPECT_FALSE(client.is_open());
  14165. // Reconnect using the same client object
  14166. ASSERT_TRUE(client.connect());
  14167. ASSERT_TRUE(client.is_open());
  14168. ASSERT_TRUE(client.send("second"));
  14169. ASSERT_TRUE(client.read(msg));
  14170. EXPECT_EQ("second", msg);
  14171. client.close();
  14172. }
  14173. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  14174. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14175. "/ws-close-status");
  14176. ASSERT_TRUE(client.connect());
  14177. // Trigger the server to close with GoingAway status
  14178. ASSERT_TRUE(client.send("trigger"));
  14179. // read() should return false after receiving the close frame
  14180. std::string msg;
  14181. EXPECT_FALSE(client.read(msg));
  14182. EXPECT_FALSE(client.is_open());
  14183. }
  14184. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  14185. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14186. "/ws-echo");
  14187. ASSERT_TRUE(client.connect());
  14188. client.close(ws::CloseStatus::GoingAway, "client leaving");
  14189. EXPECT_FALSE(client.is_open());
  14190. }
  14191. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  14192. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  14193. ws::WebSocketClient client(
  14194. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14195. ASSERT_TRUE(client.connect());
  14196. // Server should have selected graphql-ws
  14197. EXPECT_EQ("graphql-ws", client.subprotocol());
  14198. client.close();
  14199. }
  14200. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  14201. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  14202. ws::WebSocketClient client(
  14203. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14204. ASSERT_TRUE(client.connect());
  14205. // Server should not have selected any subprotocol
  14206. EXPECT_TRUE(client.subprotocol().empty());
  14207. client.close();
  14208. }
  14209. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  14210. // Connect without requesting any subprotocol
  14211. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14212. "/ws-subprotocol");
  14213. ASSERT_TRUE(client.connect());
  14214. EXPECT_TRUE(client.subprotocol().empty());
  14215. client.close();
  14216. }
  14217. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  14218. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14219. "/ws-echo");
  14220. client.set_tcp_nodelay(true);
  14221. client.set_address_family(AF_INET);
  14222. client.set_connection_timeout(3, 0);
  14223. bool socket_options_called = false;
  14224. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  14225. ASSERT_TRUE(client.connect());
  14226. ASSERT_TRUE(client.is_open());
  14227. EXPECT_TRUE(socket_options_called);
  14228. ASSERT_TRUE(client.send("hello"));
  14229. std::string msg;
  14230. auto result = client.read(msg);
  14231. EXPECT_EQ(result, ws::ReadResult::Text);
  14232. EXPECT_EQ(msg, "hello");
  14233. client.close();
  14234. }
  14235. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  14236. Server svr;
  14237. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  14238. if (!req.has_header("Authorization")) {
  14239. res.status = StatusCode::Unauthorized_401;
  14240. res.set_content("Unauthorized", "text/plain");
  14241. return Server::HandlerResponse::Handled;
  14242. }
  14243. return Server::HandlerResponse::Unhandled;
  14244. });
  14245. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14246. std::string msg;
  14247. while (ws.read(msg)) {
  14248. ws.send(msg);
  14249. }
  14250. });
  14251. auto port = svr.bind_to_any_port("localhost");
  14252. std::thread t([&]() { svr.listen_after_bind(); });
  14253. svr.wait_until_ready();
  14254. // Without Authorization header - should be rejected before upgrade
  14255. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  14256. EXPECT_FALSE(client1.connect());
  14257. // With Authorization header - should succeed
  14258. Headers headers = {{"Authorization", "Bearer token123"}};
  14259. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  14260. headers);
  14261. ASSERT_TRUE(client2.connect());
  14262. ASSERT_TRUE(client2.send("hello"));
  14263. std::string msg;
  14264. ASSERT_TRUE(client2.read(msg));
  14265. EXPECT_EQ("hello", msg);
  14266. client2.close();
  14267. svr.stop();
  14268. t.join();
  14269. }
  14270. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14271. class WebSocketSSLIntegrationTest : public ::testing::Test {
  14272. protected:
  14273. void SetUp() override {
  14274. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  14275. SERVER_PRIVATE_KEY_FILE);
  14276. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14277. std::string msg;
  14278. ws::ReadResult ret;
  14279. while ((ret = ws.read(msg))) {
  14280. if (ret == ws::Binary) {
  14281. ws.send(msg.data(), msg.size());
  14282. } else {
  14283. ws.send(msg);
  14284. }
  14285. }
  14286. });
  14287. port_ = server_->bind_to_any_port(HOST);
  14288. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14289. server_->wait_until_ready();
  14290. }
  14291. void TearDown() override {
  14292. server_->stop();
  14293. if (server_thread_.joinable()) { server_thread_.join(); }
  14294. }
  14295. std::unique_ptr<SSLServer> server_;
  14296. std::thread server_thread_;
  14297. int port_ = 0;
  14298. };
  14299. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  14300. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  14301. "/ws-echo");
  14302. client.enable_server_certificate_verification(false);
  14303. ASSERT_TRUE(client.connect());
  14304. ASSERT_TRUE(client.is_open());
  14305. ASSERT_TRUE(client.send("Hello WSS"));
  14306. std::string msg;
  14307. EXPECT_EQ(ws::Text, client.read(msg));
  14308. EXPECT_EQ("Hello WSS", msg);
  14309. client.close();
  14310. }
  14311. #endif
  14312. #if !defined(_WIN32)
  14313. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  14314. auto secret_dir = std::string("./symlink_test_secret");
  14315. auto served_dir = std::string("./symlink_test_served");
  14316. auto secret_file = secret_dir + "/secret.txt";
  14317. auto symlink_path = served_dir + "/escape";
  14318. // Setup: create directories and files
  14319. mkdir(secret_dir.c_str(), 0755);
  14320. mkdir(served_dir.c_str(), 0755);
  14321. {
  14322. std::ofstream ofs(secret_file);
  14323. ofs << "SECRET_DATA";
  14324. }
  14325. // Create symlink using absolute path so it resolves correctly
  14326. char abs_secret[PATH_MAX];
  14327. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  14328. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  14329. auto se = detail::scope_exit([&] {
  14330. unlink(symlink_path.c_str());
  14331. unlink(secret_file.c_str());
  14332. rmdir(served_dir.c_str());
  14333. rmdir(secret_dir.c_str());
  14334. });
  14335. Server svr;
  14336. svr.set_mount_point("/", served_dir);
  14337. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  14338. auto se2 = detail::scope_exit([&] {
  14339. svr.stop();
  14340. listen_thread.join();
  14341. });
  14342. svr.wait_until_ready();
  14343. Client cli("localhost", PORT);
  14344. // Symlink pointing outside base dir should be blocked
  14345. auto res = cli.Get("/escape/secret.txt");
  14346. ASSERT_TRUE(res);
  14347. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  14348. }
  14349. #endif