test.cc 511 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #if __cplusplus >= 202002L
  28. inline std::string u8_to_string(const char8_t *s) {
  29. return std::string(reinterpret_cast<const char *>(s));
  30. }
  31. #define U8(x) u8_to_string(u8##x)
  32. #else
  33. #define U8(x) u8##x
  34. #endif
  35. #define SERVER_CERT_FILE "./cert.pem"
  36. #define SERVER_CERT2_FILE "./cert2.pem"
  37. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  38. #define CA_CERT_FILE "./ca-bundle.crt"
  39. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  40. #define CLIENT_CA_CERT_DIR "."
  41. #define CLIENT_CERT_FILE "./client.cert.pem"
  42. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  43. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  44. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  45. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  46. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  47. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  48. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  49. using namespace std;
  50. using namespace httplib;
  51. const char *HOST = "localhost";
  52. static int get_base_port() {
  53. const char *shard = getenv("GTEST_SHARD_INDEX");
  54. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  55. }
  56. const int PORT = get_base_port();
  57. const string LONG_QUERY_VALUE = string(25000, '@');
  58. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  59. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  60. const string TOO_LONG_QUERY_URL =
  61. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  62. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  63. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  64. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  65. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  66. return file.name == key;
  67. });
  68. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  69. return *it;
  70. #else
  71. if (it != items.end()) { return *it; }
  72. throw std::runtime_error("invalid multipart form data name error");
  73. #endif
  74. }
  75. static void read_file(const std::string &path, std::string &out) {
  76. std::ifstream fs(path, std::ios_base::binary);
  77. if (!fs) {
  78. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  79. return;
  80. #else
  81. throw std::runtime_error("File not found: " + path);
  82. #endif
  83. }
  84. fs.seekg(0, std::ios_base::end);
  85. auto size = fs.tellg();
  86. fs.seekg(0);
  87. out.resize(static_cast<size_t>(size));
  88. fs.read(&out[0], static_cast<std::streamsize>(size));
  89. }
  90. void performance_test(const char *host) {
  91. Server svr;
  92. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  93. res.set_content("Benchmark Response", "text/plain");
  94. });
  95. auto listen_thread = std::thread([&]() { svr.listen(host, PORT); });
  96. auto se = detail::scope_exit([&] {
  97. svr.stop();
  98. listen_thread.join();
  99. ASSERT_FALSE(svr.is_running());
  100. });
  101. svr.wait_until_ready();
  102. Client cli(host, PORT);
  103. // Warm-up request to establish connection and resolve DNS
  104. auto warmup_res = cli.Get("/benchmark");
  105. ASSERT_TRUE(warmup_res); // Ensure server is responding correctly
  106. // Run multiple trials and collect timings
  107. const int num_trials = 20;
  108. std::vector<int64_t> timings;
  109. timings.reserve(num_trials);
  110. for (int i = 0; i < num_trials; i++) {
  111. auto start = std::chrono::high_resolution_clock::now();
  112. auto res = cli.Get("/benchmark");
  113. auto end = std::chrono::high_resolution_clock::now();
  114. auto elapsed =
  115. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  116. .count();
  117. // Assertions after timing measurement to avoid overhead
  118. ASSERT_TRUE(res);
  119. EXPECT_EQ(StatusCode::OK_200, res->status);
  120. timings.push_back(elapsed);
  121. }
  122. // Calculate 25th percentile (lower quartile)
  123. std::sort(timings.begin(), timings.end());
  124. auto p25 = timings[num_trials / 4];
  125. // Format timings for output
  126. std::ostringstream timings_str;
  127. timings_str << "[";
  128. for (size_t i = 0; i < timings.size(); i++) {
  129. if (i > 0) timings_str << ", ";
  130. timings_str << timings[i];
  131. }
  132. timings_str << "]";
  133. // Localhost HTTP GET should be fast even in CI environments
  134. EXPECT_LE(p25, 5) << "25th percentile performance is too slow: " << p25
  135. << "ms (Issue #1777). Timings: " << timings_str.str();
  136. }
  137. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  138. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  139. class UnixSocketTest : public ::testing::Test {
  140. protected:
  141. void TearDown() override { std::remove(pathname_.c_str()); }
  142. void client_GET(const std::string &addr) {
  143. httplib::Client cli{addr};
  144. cli.set_address_family(AF_UNIX);
  145. ASSERT_TRUE(cli.is_valid());
  146. const auto &result = cli.Get(pattern_);
  147. ASSERT_TRUE(result) << "error: " << result.error();
  148. const auto &resp = result.value();
  149. EXPECT_EQ(resp.status, StatusCode::OK_200);
  150. EXPECT_EQ(resp.body, content_);
  151. }
  152. static std::string make_sock_path() {
  153. const char *shard = getenv("GTEST_SHARD_INDEX");
  154. return shard ? std::string("./httplib-server-") + shard + ".sock"
  155. : "./httplib-server.sock";
  156. }
  157. const std::string pathname_{make_sock_path()};
  158. const std::string pattern_{"/hi"};
  159. const std::string content_{"Hello World!"};
  160. };
  161. TEST_F(UnixSocketTest, pathname) {
  162. httplib::Server svr;
  163. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  164. res.set_content(content_, "text/plain");
  165. });
  166. std::thread t{[&] {
  167. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  168. }};
  169. auto se = detail::scope_exit([&] {
  170. svr.stop();
  171. t.join();
  172. ASSERT_FALSE(svr.is_running());
  173. });
  174. svr.wait_until_ready();
  175. ASSERT_TRUE(svr.is_running());
  176. client_GET(pathname_);
  177. }
  178. #if defined(__linux__) || \
  179. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  180. TEST_F(UnixSocketTest, PeerPid) {
  181. httplib::Server svr;
  182. std::string remote_port_val;
  183. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  184. res.set_content(content_, "text/plain");
  185. remote_port_val = std::to_string(req.remote_port);
  186. });
  187. std::thread t{[&] {
  188. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  189. }};
  190. auto se = detail::scope_exit([&] {
  191. svr.stop();
  192. t.join();
  193. ASSERT_FALSE(svr.is_running());
  194. });
  195. svr.wait_until_ready();
  196. ASSERT_TRUE(svr.is_running());
  197. client_GET(pathname_);
  198. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  199. }
  200. #endif
  201. #ifdef __linux__
  202. TEST_F(UnixSocketTest, abstract) {
  203. constexpr char svr_path[]{"\x00httplib-server.sock"};
  204. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  205. httplib::Server svr;
  206. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  207. res.set_content(content_, "text/plain");
  208. });
  209. std::thread t{[&] {
  210. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  211. }};
  212. auto se = detail::scope_exit([&] {
  213. svr.stop();
  214. t.join();
  215. ASSERT_FALSE(svr.is_running());
  216. });
  217. svr.wait_until_ready();
  218. ASSERT_TRUE(svr.is_running());
  219. client_GET(abstract_addr);
  220. }
  221. #endif
  222. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  223. httplib::Server svr;
  224. std::string received_host_header;
  225. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  226. // Capture the Host header sent by the client
  227. auto host_iter = req.headers.find("Host");
  228. if (host_iter != req.headers.end()) {
  229. received_host_header = host_iter->second;
  230. }
  231. res.set_content(content_, "text/plain");
  232. });
  233. std::thread t{[&] {
  234. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  235. }};
  236. auto se = detail::scope_exit([&] {
  237. svr.stop();
  238. t.join();
  239. ASSERT_FALSE(svr.is_running());
  240. });
  241. svr.wait_until_ready();
  242. ASSERT_TRUE(svr.is_running());
  243. // Test that Host header is automatically set to "localhost" for Unix socket
  244. // connections
  245. httplib::Client cli{pathname_};
  246. cli.set_address_family(AF_UNIX);
  247. ASSERT_TRUE(cli.is_valid());
  248. const auto &result = cli.Get(pattern_);
  249. ASSERT_TRUE(result) << "error: " << result.error();
  250. const auto &resp = result.value();
  251. EXPECT_EQ(resp.status, StatusCode::OK_200);
  252. EXPECT_EQ(resp.body, content_);
  253. // Verify that Host header was automatically set to "localhost"
  254. EXPECT_EQ(received_host_header, "localhost");
  255. }
  256. #ifndef _WIN32
  257. TEST(SocketStream, wait_writable_UNIX) {
  258. int fds[2];
  259. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  260. const auto asSocketStream = [&](socket_t fd,
  261. std::function<bool(Stream &)> func) {
  262. return detail::process_client_socket(
  263. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  264. };
  265. asSocketStream(fds[0], [&](Stream &s0) {
  266. EXPECT_EQ(s0.socket(), fds[0]);
  267. EXPECT_TRUE(s0.wait_writable());
  268. EXPECT_TRUE(s0.is_peer_alive());
  269. EXPECT_EQ(0, close(fds[1]));
  270. EXPECT_FALSE(s0.is_peer_alive());
  271. return true;
  272. });
  273. EXPECT_EQ(0, close(fds[0]));
  274. }
  275. TEST(SocketStream, wait_writable_INET) {
  276. sockaddr_in addr;
  277. memset(&addr, 0, sizeof(addr));
  278. addr.sin_family = AF_INET;
  279. addr.sin_port = htons(PORT + 1);
  280. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  281. int disconnected_svr_sock = -1;
  282. std::thread svr{[&] {
  283. const int s = socket(AF_INET, SOCK_STREAM, 0);
  284. ASSERT_LE(0, s);
  285. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  286. ASSERT_EQ(0, listen(s, 1));
  287. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  288. ASSERT_EQ(0, close(s));
  289. }};
  290. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  291. std::thread cli{[&] {
  292. const int s = socket(AF_INET, SOCK_STREAM, 0);
  293. ASSERT_LE(0, s);
  294. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  295. ASSERT_EQ(0, close(s));
  296. }};
  297. cli.join();
  298. svr.join();
  299. ASSERT_NE(disconnected_svr_sock, -1);
  300. const auto asSocketStream = [&](socket_t fd,
  301. std::function<bool(Stream &)> func) {
  302. return detail::process_client_socket(
  303. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  304. };
  305. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  306. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  307. // wait_writable() returns true because select_write() only checks if the
  308. // send buffer has space. Peer disconnection is detected later by send().
  309. EXPECT_TRUE(ss.wait_writable());
  310. return true;
  311. });
  312. ASSERT_EQ(0, close(disconnected_svr_sock));
  313. }
  314. #endif // #ifndef _WIN32
  315. TEST(ClientTest, MoveConstructible) {
  316. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  317. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  318. }
  319. TEST(ClientTest, MoveAssignable) {
  320. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  321. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  322. }
  323. #ifdef _WIN32
  324. TEST(StartupTest, WSAStartup) {
  325. WSADATA wsaData;
  326. int ret = WSAStartup(0x0002, &wsaData);
  327. ASSERT_EQ(0, ret);
  328. }
  329. #endif
  330. TEST(DecodePathTest, PercentCharacter) {
  331. EXPECT_EQ(
  332. decode_path_component(
  333. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  334. U8("descrip=Gastos áéíóúñÑ 6"));
  335. }
  336. TEST(DecodePathTest, PercentCharacterNUL) {
  337. string expected;
  338. expected.push_back('x');
  339. expected.push_back('\0');
  340. expected.push_back('x');
  341. EXPECT_EQ(decode_path_component("x%00x"), expected);
  342. }
  343. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  344. string unescapedCharacters = "-_.!~*'()";
  345. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  346. }
  347. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  348. string reservedCharacters = ";,/?:@&=+$";
  349. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  350. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  351. }
  352. TEST(ClientQueryOrder, PreserveOrder) {
  353. // This test reproduces Issue #2259: client may reorder query parameters
  354. // when sending a GET request. The expected behavior is that the client
  355. // preserves the original query string order when the caller supplied it
  356. // as part of the path.
  357. Server svr;
  358. svr.Get("/", [&](const Request &req, Response &res) {
  359. // Echo back the raw target so the test can assert ordering
  360. res.set_content(req.target, "text/plain");
  361. });
  362. std::thread t{[&] { svr.listen(HOST, PORT); }};
  363. auto se = detail::scope_exit([&] {
  364. svr.stop();
  365. t.join();
  366. ASSERT_FALSE(svr.is_running());
  367. });
  368. svr.wait_until_ready();
  369. Client cli(HOST, PORT);
  370. ASSERT_TRUE(cli.is_valid());
  371. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  372. auto res = cli.Get(original);
  373. ASSERT_TRUE(res);
  374. // Expect the echoed target to exactly match the original path (order
  375. // preserved)
  376. EXPECT_EQ(res->body, original);
  377. }
  378. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  379. string chineseCharacters = U8("中国語");
  380. string russianCharacters = U8("дом");
  381. string brazilianCharacters = U8("óculos");
  382. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  383. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  384. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  385. "%D0%B4%D0%BE%D0%BC");
  386. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  387. }
  388. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  389. string unescapedCharacters = "-_.!~*'()";
  390. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  391. }
  392. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  393. string reservedCharacters = ";,/?:@&=+$";
  394. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  395. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  396. }
  397. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  398. string chineseCharacters = U8("中国語");
  399. string russianCharacters = U8("дом");
  400. string brazilianCharacters = U8("óculos");
  401. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  402. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  403. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  404. "%D0%B4%D0%BE%D0%BC");
  405. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  406. }
  407. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  408. // Issue #2082 use case: encoding path component with ampersand
  409. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  410. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  411. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  412. }
  413. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  414. string unescapedCharacters = "-_.!~*'()";
  415. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  416. }
  417. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  418. string reservedCharacters = ";,/?:@&=+$#";
  419. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  420. }
  421. TEST(EncodeUriTest, TestUTF8Characters) {
  422. string chineseCharacters = U8("中国語");
  423. string russianCharacters = U8("дом");
  424. string brazilianCharacters = U8("óculos");
  425. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  426. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  427. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  428. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  429. }
  430. TEST(EncodeUriTest, TestCompleteUri) {
  431. string uri =
  432. "https://example.com/path/to/resource?query=value&param=test#fragment";
  433. EXPECT_EQ(
  434. httplib::encode_uri(uri),
  435. "https://example.com/path/to/resource?query=value&param=test#fragment");
  436. }
  437. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  438. string uri =
  439. "https://example.com/path with spaces/file name.html?q=hello world";
  440. EXPECT_EQ(httplib::encode_uri(uri),
  441. "https://example.com/path%20with%20spaces/"
  442. "file%20name.html?q=hello%20world");
  443. }
  444. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  445. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  446. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  447. }
  448. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  449. string unescapedCharacters = "-_.!~*'()";
  450. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  451. }
  452. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  453. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  454. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  455. string encodedBrazilian = "%C3%B3culos";
  456. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  457. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  458. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  459. }
  460. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  461. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  462. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  463. "Piri Tommy Villiers - on & on");
  464. }
  465. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  466. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  467. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  468. }
  469. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  470. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  471. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  472. }
  473. TEST(DecodeUriTest, TestUTF8Characters) {
  474. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  475. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  476. string encodedBrazilian = "%C3%B3culos";
  477. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  478. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  479. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  480. }
  481. TEST(DecodeUriTest, TestCompleteUri) {
  482. string encodedUri = "https://example.com/path%20with%20spaces/"
  483. "file%20name.html?q=hello%20world";
  484. EXPECT_EQ(
  485. httplib::decode_uri(encodedUri),
  486. "https://example.com/path with spaces/file name.html?q=hello world");
  487. }
  488. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  489. string original =
  490. "https://example.com/path with spaces/file name.html?q=hello world";
  491. string encoded = httplib::encode_uri(original);
  492. string decoded = httplib::decode_uri(encoded);
  493. EXPECT_EQ(decoded, original);
  494. }
  495. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  496. string original = "Piri Tommy Villiers - on & on";
  497. string encoded = httplib::encode_uri_component(original);
  498. string decoded = httplib::decode_uri_component(encoded);
  499. EXPECT_EQ(decoded, original);
  500. }
  501. TEST(TrimTests, TrimStringTests) {
  502. EXPECT_EQ("abc", detail::trim_copy("abc"));
  503. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  504. EXPECT_TRUE(detail::trim_copy("").empty());
  505. }
  506. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  507. // Simple case without quality values
  508. std::vector<std::string> result1;
  509. EXPECT_TRUE(detail::parse_accept_header(
  510. "text/html,application/json,text/plain", result1));
  511. EXPECT_EQ(result1.size(), 3U);
  512. EXPECT_EQ(result1[0], "text/html");
  513. EXPECT_EQ(result1[1], "application/json");
  514. EXPECT_EQ(result1[2], "text/plain");
  515. // With quality values
  516. std::vector<std::string> result2;
  517. EXPECT_TRUE(detail::parse_accept_header(
  518. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  519. EXPECT_EQ(result2.size(), 3U);
  520. EXPECT_EQ(result2[0], "application/json"); // highest q value
  521. EXPECT_EQ(result2[1], "text/html");
  522. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  523. }
  524. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  525. // Mixed with and without quality values
  526. std::vector<std::string> result;
  527. EXPECT_TRUE(detail::parse_accept_header(
  528. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  529. EXPECT_EQ(result.size(), 3U);
  530. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  531. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  532. EXPECT_EQ(result[2], "application/json"); // q=0.5
  533. }
  534. TEST(ParseAcceptHeaderTest, EdgeCases) {
  535. // Empty header
  536. std::vector<std::string> empty_result;
  537. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  538. EXPECT_TRUE(empty_result.empty());
  539. // Single type
  540. std::vector<std::string> single_result;
  541. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  542. EXPECT_EQ(single_result.size(), 1U);
  543. EXPECT_EQ(single_result[0], "application/json");
  544. // Wildcard types
  545. std::vector<std::string> wildcard_result;
  546. EXPECT_TRUE(detail::parse_accept_header(
  547. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  548. EXPECT_EQ(wildcard_result.size(), 3U);
  549. EXPECT_EQ(wildcard_result[0], "application/json");
  550. EXPECT_EQ(wildcard_result[1], "text/*");
  551. EXPECT_EQ(wildcard_result[2], "*/*");
  552. }
  553. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  554. // Common browser Accept header
  555. std::vector<std::string> browser_result;
  556. EXPECT_TRUE(
  557. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  558. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  559. browser_result));
  560. EXPECT_EQ(browser_result.size(), 6U);
  561. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  562. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  563. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  564. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  565. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  566. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  567. // API client header
  568. std::vector<std::string> api_result;
  569. EXPECT_TRUE(detail::parse_accept_header(
  570. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  571. api_result));
  572. EXPECT_EQ(api_result.size(), 3U);
  573. EXPECT_EQ(api_result[0], "application/json");
  574. EXPECT_EQ(api_result[1], "application/xml");
  575. EXPECT_EQ(api_result[2], "text/plain");
  576. }
  577. TEST(ParseAcceptHeaderTest, SpecialCases) {
  578. // Quality value with 3 decimal places
  579. std::vector<std::string> decimal_result;
  580. EXPECT_TRUE(detail::parse_accept_header(
  581. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  582. EXPECT_EQ(decimal_result.size(), 2U);
  583. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  584. EXPECT_EQ(decimal_result[1], "text/html");
  585. // Zero quality (should still be included but with lowest priority)
  586. std::vector<std::string> zero_q_result;
  587. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  588. zero_q_result));
  589. EXPECT_EQ(zero_q_result.size(), 2U);
  590. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  591. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  592. // No spaces around commas
  593. std::vector<std::string> no_space_result;
  594. EXPECT_TRUE(detail::parse_accept_header(
  595. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  596. no_space_result));
  597. EXPECT_EQ(no_space_result.size(), 3U);
  598. EXPECT_EQ(no_space_result[0], "text/html");
  599. EXPECT_EQ(no_space_result[1], "application/json");
  600. EXPECT_EQ(no_space_result[2], "text/plain");
  601. }
  602. TEST(ParseAcceptHeaderTest, InvalidCases) {
  603. std::vector<std::string> result;
  604. // Invalid quality value (> 1.0)
  605. EXPECT_FALSE(
  606. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  607. // Invalid quality value (< 0.0)
  608. EXPECT_FALSE(
  609. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  610. // Invalid quality value (not a number)
  611. EXPECT_FALSE(detail::parse_accept_header(
  612. "text/html;q=invalid,application/json", result));
  613. // Empty quality value
  614. EXPECT_FALSE(
  615. detail::parse_accept_header("text/html;q=,application/json", result));
  616. // Invalid media type format (no slash and not wildcard)
  617. EXPECT_FALSE(
  618. detail::parse_accept_header("invalidtype,application/json", result));
  619. // Empty media type
  620. result.clear();
  621. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  622. // Only commas
  623. result.clear();
  624. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  625. // Valid cases should still work
  626. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  627. EXPECT_EQ(result.size(), 1U);
  628. EXPECT_EQ(result[0], "*/*");
  629. EXPECT_TRUE(detail::parse_accept_header("*", result));
  630. EXPECT_EQ(result.size(), 1U);
  631. EXPECT_EQ(result[0], "*");
  632. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  633. EXPECT_EQ(result.size(), 1U);
  634. EXPECT_EQ(result[0], "text/*");
  635. }
  636. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  637. Server svr;
  638. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  639. EXPECT_EQ(req.accept_content_types.size(), 3U);
  640. EXPECT_EQ(req.accept_content_types[0], "application/json");
  641. EXPECT_EQ(req.accept_content_types[1], "text/html");
  642. EXPECT_EQ(req.accept_content_types[2], "*/*");
  643. res.set_content("ok", "text/plain");
  644. });
  645. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  646. EXPECT_TRUE(false);
  647. res.set_content("bad request", "text/plain");
  648. });
  649. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  650. auto se = detail::scope_exit([&] {
  651. svr.stop();
  652. listen_thread.join();
  653. ASSERT_FALSE(svr.is_running());
  654. });
  655. svr.wait_until_ready();
  656. Client cli("localhost", PORT);
  657. {
  658. auto res =
  659. cli.Get("/accept_ok",
  660. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  661. ASSERT_TRUE(res);
  662. EXPECT_EQ(StatusCode::OK_200, res->status);
  663. }
  664. {
  665. auto res = cli.Get("/accept_bad_request",
  666. {{"Accept", "text/html;q=abc,application/json"}});
  667. ASSERT_TRUE(res);
  668. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  669. }
  670. }
  671. TEST(DivideTest, DivideStringTests) {
  672. auto divide = [](const std::string &str, char d) {
  673. std::string lhs;
  674. std::string rhs;
  675. detail::divide(str, d,
  676. [&](const char *lhs_data, std::size_t lhs_size,
  677. const char *rhs_data, std::size_t rhs_size) {
  678. lhs.assign(lhs_data, lhs_size);
  679. rhs.assign(rhs_data, rhs_size);
  680. });
  681. return std::make_pair(std::move(lhs), std::move(rhs));
  682. };
  683. {
  684. const auto res = divide("", '=');
  685. EXPECT_EQ(res.first, "");
  686. EXPECT_EQ(res.second, "");
  687. }
  688. {
  689. const auto res = divide("=", '=');
  690. EXPECT_EQ(res.first, "");
  691. EXPECT_EQ(res.second, "");
  692. }
  693. {
  694. const auto res = divide(" ", '=');
  695. EXPECT_EQ(res.first, " ");
  696. EXPECT_EQ(res.second, "");
  697. }
  698. {
  699. const auto res = divide("a", '=');
  700. EXPECT_EQ(res.first, "a");
  701. EXPECT_EQ(res.second, "");
  702. }
  703. {
  704. const auto res = divide("a=", '=');
  705. EXPECT_EQ(res.first, "a");
  706. EXPECT_EQ(res.second, "");
  707. }
  708. {
  709. const auto res = divide("=b", '=');
  710. EXPECT_EQ(res.first, "");
  711. EXPECT_EQ(res.second, "b");
  712. }
  713. {
  714. const auto res = divide("a=b", '=');
  715. EXPECT_EQ(res.first, "a");
  716. EXPECT_EQ(res.second, "b");
  717. }
  718. {
  719. const auto res = divide("a=b=", '=');
  720. EXPECT_EQ(res.first, "a");
  721. EXPECT_EQ(res.second, "b=");
  722. }
  723. {
  724. const auto res = divide("a=b=c", '=');
  725. EXPECT_EQ(res.first, "a");
  726. EXPECT_EQ(res.second, "b=c");
  727. }
  728. }
  729. TEST(SplitTest, ParseQueryString) {
  730. string s = "key1=val1&key2=val2&key3=val3";
  731. Params dic;
  732. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  733. [&](const char *b, const char *e) {
  734. string key, val;
  735. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  736. if (key.empty()) {
  737. key.assign(b2, e2);
  738. } else {
  739. val.assign(b2, e2);
  740. }
  741. });
  742. dic.emplace(key, val);
  743. });
  744. EXPECT_EQ("val1", dic.find("key1")->second);
  745. EXPECT_EQ("val2", dic.find("key2")->second);
  746. EXPECT_EQ("val3", dic.find("key3")->second);
  747. }
  748. TEST(SplitTest, ParseInvalidQueryTests) {
  749. {
  750. string s = " ";
  751. Params dict;
  752. detail::parse_query_text(s, dict);
  753. EXPECT_TRUE(dict.empty());
  754. }
  755. {
  756. string s = " = =";
  757. Params dict;
  758. detail::parse_query_text(s, dict);
  759. EXPECT_TRUE(dict.empty());
  760. }
  761. }
  762. TEST(ParseQueryTest, ParseQueryString) {
  763. {
  764. std::string s = "key1=val1&key2=val2&key3=val3";
  765. Params dic;
  766. detail::parse_query_text(s, dic);
  767. EXPECT_EQ("val1", dic.find("key1")->second);
  768. EXPECT_EQ("val2", dic.find("key2")->second);
  769. EXPECT_EQ("val3", dic.find("key3")->second);
  770. }
  771. {
  772. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  773. Params dic;
  774. detail::parse_query_text(s, dic);
  775. EXPECT_EQ("", dic.find("key1")->second);
  776. EXPECT_EQ("val1", dic.find("key2")->second);
  777. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  778. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  779. }
  780. }
  781. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  782. Params dic;
  783. EXPECT_EQ(detail::params_to_query_str(dic), "");
  784. dic.emplace("key1", "val1");
  785. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  786. dic.emplace("key2", "val2");
  787. dic.emplace("key3", "val3");
  788. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  789. }
  790. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  791. string content_type = "multipart/form-data; boundary=something";
  792. string boundary;
  793. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  794. EXPECT_TRUE(ret);
  795. EXPECT_EQ(boundary, "something");
  796. }
  797. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  798. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  799. string boundary;
  800. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  801. EXPECT_TRUE(ret);
  802. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  803. }
  804. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  805. string content_type =
  806. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  807. string boundary;
  808. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  809. EXPECT_TRUE(ret);
  810. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  811. }
  812. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  813. string content_type =
  814. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  815. string boundary;
  816. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  817. EXPECT_TRUE(ret);
  818. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  819. }
  820. TEST(GetHeaderValueTest, DefaultValue) {
  821. Headers headers = {{"Dummy", "Dummy"}};
  822. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  823. EXPECT_STREQ("text/plain", val);
  824. }
  825. TEST(GetHeaderValueTest, DefaultValueInt) {
  826. Headers headers = {{"Dummy", "Dummy"}};
  827. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  828. EXPECT_EQ(100ull, val);
  829. }
  830. TEST(GetHeaderValueTest, RegularValue) {
  831. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  832. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  833. EXPECT_STREQ("text/html", val);
  834. }
  835. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  836. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  837. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  838. EXPECT_STREQ("text/html", val);
  839. }
  840. TEST(GetHeaderValueTest, SetContent) {
  841. Response res;
  842. res.set_content("html", "text/html");
  843. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  844. res.set_content("text", "text/plain");
  845. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  846. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  847. }
  848. TEST(GetHeaderValueTest, RegularValueInt) {
  849. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  850. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  851. EXPECT_EQ(100ull, val);
  852. }
  853. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  854. Headers headers = {{"Content-Length", "x"}};
  855. auto is_invalid_value = false;
  856. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  857. is_invalid_value);
  858. EXPECT_EQ(0ull, val);
  859. EXPECT_TRUE(is_invalid_value);
  860. }
  861. TEST(GetHeaderValueTest, Range) {
  862. {
  863. Headers headers = {make_range_header({{1, -1}})};
  864. auto val = detail::get_header_value(headers, "Range", 0, 0);
  865. EXPECT_STREQ("bytes=1-", val);
  866. }
  867. {
  868. Headers headers = {make_range_header({{-1, 1}})};
  869. auto val = detail::get_header_value(headers, "Range", 0, 0);
  870. EXPECT_STREQ("bytes=-1", val);
  871. }
  872. {
  873. Headers headers = {make_range_header({{1, 10}})};
  874. auto val = detail::get_header_value(headers, "Range", 0, 0);
  875. EXPECT_STREQ("bytes=1-10", val);
  876. }
  877. {
  878. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  879. auto val = detail::get_header_value(headers, "Range", 0, 0);
  880. EXPECT_STREQ("bytes=1-10, 100-", val);
  881. }
  882. {
  883. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  884. auto val = detail::get_header_value(headers, "Range", 0, 0);
  885. EXPECT_STREQ("bytes=1-10, 100-200", val);
  886. }
  887. {
  888. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  889. auto val = detail::get_header_value(headers, "Range", 0, 0);
  890. EXPECT_STREQ("bytes=0-0, -1", val);
  891. }
  892. }
  893. TEST(ParseHeaderValueTest, Range) {
  894. {
  895. Ranges ranges;
  896. auto ret = detail::parse_range_header("bytes=1-", ranges);
  897. EXPECT_TRUE(ret);
  898. EXPECT_EQ(1u, ranges.size());
  899. EXPECT_EQ(1u, ranges[0].first);
  900. EXPECT_EQ(-1, ranges[0].second);
  901. }
  902. {
  903. Ranges ranges;
  904. auto ret = detail::parse_range_header("bytes=-1", ranges);
  905. EXPECT_TRUE(ret);
  906. EXPECT_EQ(1u, ranges.size());
  907. EXPECT_EQ(-1, ranges[0].first);
  908. EXPECT_EQ(1u, ranges[0].second);
  909. }
  910. {
  911. Ranges ranges;
  912. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  913. EXPECT_TRUE(ret);
  914. EXPECT_EQ(1u, ranges.size());
  915. EXPECT_EQ(1u, ranges[0].first);
  916. EXPECT_EQ(10u, ranges[0].second);
  917. }
  918. {
  919. Ranges ranges;
  920. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  921. EXPECT_FALSE(ret);
  922. }
  923. {
  924. Ranges ranges;
  925. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  926. EXPECT_TRUE(ret);
  927. EXPECT_EQ(2u, ranges.size());
  928. EXPECT_EQ(1u, ranges[0].first);
  929. EXPECT_EQ(10u, ranges[0].second);
  930. EXPECT_EQ(100u, ranges[1].first);
  931. EXPECT_EQ(-1, ranges[1].second);
  932. }
  933. {
  934. Ranges ranges;
  935. auto ret =
  936. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  937. EXPECT_TRUE(ret);
  938. EXPECT_EQ(3u, ranges.size());
  939. EXPECT_EQ(1u, ranges[0].first);
  940. EXPECT_EQ(10u, ranges[0].second);
  941. EXPECT_EQ(100u, ranges[1].first);
  942. EXPECT_EQ(200u, ranges[1].second);
  943. EXPECT_EQ(300u, ranges[2].first);
  944. EXPECT_EQ(400u, ranges[2].second);
  945. }
  946. {
  947. Ranges ranges;
  948. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  949. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  950. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  951. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  952. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  953. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  954. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  955. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  956. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  957. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  958. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  959. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  960. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  961. EXPECT_TRUE(ranges.empty());
  962. }
  963. }
  964. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  965. Request req;
  966. req.set_header("Accept-Encoding", "gzip");
  967. Response res;
  968. res.set_header("Content-Type", "text/plain");
  969. auto ret = detail::encoding_type(req, res);
  970. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  971. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  972. #else
  973. EXPECT_TRUE(ret == detail::EncodingType::None);
  974. #endif
  975. }
  976. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  977. Request req;
  978. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  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(ParseAcceptEncoding3, AcceptEncoding) {
  993. Request req;
  994. req.set_header("Accept-Encoding",
  995. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  996. Response res;
  997. res.set_header("Content-Type", "text/plain");
  998. auto ret = detail::encoding_type(req, res);
  999. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1000. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1001. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1002. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1003. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1004. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1005. #else
  1006. EXPECT_TRUE(ret == detail::EncodingType::None);
  1007. #endif
  1008. }
  1009. TEST(BufferStreamTest, read) {
  1010. detail::BufferStream strm1;
  1011. Stream &strm = strm1;
  1012. EXPECT_EQ(5, strm.write("hello"));
  1013. char buf[512];
  1014. EXPECT_EQ(2, strm.read(buf, 2));
  1015. EXPECT_EQ('h', buf[0]);
  1016. EXPECT_EQ('e', buf[1]);
  1017. EXPECT_EQ(2, strm.read(buf, 2));
  1018. EXPECT_EQ('l', buf[0]);
  1019. EXPECT_EQ('l', buf[1]);
  1020. EXPECT_EQ(1, strm.read(buf, 1));
  1021. EXPECT_EQ('o', buf[0]);
  1022. EXPECT_EQ(0, strm.read(buf, 1));
  1023. }
  1024. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1025. auto host = "www.httpwatch.com";
  1026. auto ip = hosted_at(host);
  1027. EXPECT_EQ("23.96.13.243", ip);
  1028. std::vector<std::string> addrs;
  1029. hosted_at(host, addrs);
  1030. EXPECT_EQ(1u, addrs.size());
  1031. }
  1032. #if 0 // It depends on each test environment...
  1033. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1034. auto host = "www.youtube.com";
  1035. std::vector<std::string> addrs;
  1036. hosted_at(host, addrs);
  1037. EXPECT_EQ(20u, addrs.size());
  1038. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1039. EXPECT_TRUE(it != addrs.end());
  1040. }
  1041. #endif
  1042. class ChunkedEncodingTest : public ::testing::Test {
  1043. protected:
  1044. ChunkedEncodingTest()
  1045. : cli_(HOST, PORT)
  1046. #ifdef CPPHTTPLIB_SSL_ENABLED
  1047. ,
  1048. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1049. #endif
  1050. {
  1051. cli_.set_connection_timeout(2);
  1052. #ifdef CPPHTTPLIB_SSL_ENABLED
  1053. cli_.enable_server_certificate_verification(false);
  1054. #endif
  1055. }
  1056. virtual void SetUp() {
  1057. read_file("./image.jpg", image_data_);
  1058. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1059. res.set_content("Hello World!", "text/plain");
  1060. });
  1061. svr_.Get(
  1062. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1063. res.set_chunked_content_provider(
  1064. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1065. size_t remaining = image_data_.size() - offset;
  1066. if (remaining == 0) {
  1067. sink.done();
  1068. } else {
  1069. constexpr size_t CHUNK_SIZE = 1024;
  1070. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1071. sink.write(&image_data_[offset], send_size);
  1072. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1073. }
  1074. return true;
  1075. });
  1076. });
  1077. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1078. svr_.wait_until_ready();
  1079. }
  1080. virtual void TearDown() {
  1081. svr_.stop();
  1082. if (!request_threads_.empty()) {
  1083. std::this_thread::sleep_for(std::chrono::seconds(1));
  1084. for (auto &t : request_threads_) {
  1085. t.join();
  1086. }
  1087. }
  1088. t_.join();
  1089. }
  1090. #ifdef CPPHTTPLIB_SSL_ENABLED
  1091. SSLClient cli_;
  1092. SSLServer svr_;
  1093. #else
  1094. Client cli_;
  1095. Server svr_;
  1096. #endif
  1097. thread t_;
  1098. std::vector<thread> request_threads_;
  1099. std::string image_data_;
  1100. };
  1101. TEST_F(ChunkedEncodingTest, NormalGet) {
  1102. auto res = cli_.Get("/chunked");
  1103. ASSERT_TRUE(res);
  1104. std::string out;
  1105. read_file("./image.jpg", out);
  1106. EXPECT_EQ(StatusCode::OK_200, res->status);
  1107. EXPECT_EQ(out, res->body);
  1108. }
  1109. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1110. std::string body;
  1111. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1112. body.append(data, data_length);
  1113. return true;
  1114. });
  1115. ASSERT_TRUE(res);
  1116. std::string out;
  1117. read_file("./image.jpg", out);
  1118. EXPECT_EQ(StatusCode::OK_200, res->status);
  1119. EXPECT_EQ(out, body);
  1120. }
  1121. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1122. std::string body;
  1123. auto res = cli_.Get(
  1124. "/chunked",
  1125. [&](const Response &response) {
  1126. EXPECT_EQ(StatusCode::OK_200, response.status);
  1127. return true;
  1128. },
  1129. [&](const char *data, size_t data_length) {
  1130. body.append(data, data_length);
  1131. return true;
  1132. });
  1133. ASSERT_TRUE(res);
  1134. std::string out;
  1135. read_file("./image.jpg", out);
  1136. EXPECT_EQ(StatusCode::OK_200, res->status);
  1137. EXPECT_EQ(out, body);
  1138. }
  1139. TEST(RangeTest, FromHTTPBin_Online) {
  1140. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1141. auto host = "httpcan.org";
  1142. auto path = std::string{"/range/32"};
  1143. #else
  1144. auto host = "nghttp2.org";
  1145. auto path = std::string{"/httpbin/range/32"};
  1146. #endif
  1147. #ifdef CPPHTTPLIB_SSL_ENABLED
  1148. auto port = 443;
  1149. SSLClient cli(host, port);
  1150. #else
  1151. auto port = 80;
  1152. Client cli(host, port);
  1153. #endif
  1154. cli.set_connection_timeout(5);
  1155. {
  1156. auto res = cli.Get(path);
  1157. ASSERT_TRUE(res);
  1158. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1159. EXPECT_EQ(StatusCode::OK_200, res->status);
  1160. }
  1161. {
  1162. Headers headers = {make_range_header({{1, -1}})};
  1163. auto res = cli.Get(path, headers);
  1164. ASSERT_TRUE(res);
  1165. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1166. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1167. }
  1168. {
  1169. Headers headers = {make_range_header({{1, 10}})};
  1170. auto res = cli.Get(path, headers);
  1171. ASSERT_TRUE(res);
  1172. EXPECT_EQ("bcdefghijk", res->body);
  1173. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1174. }
  1175. {
  1176. Headers headers = {make_range_header({{0, 31}})};
  1177. auto res = cli.Get(path, headers);
  1178. ASSERT_TRUE(res);
  1179. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1180. EXPECT_EQ(StatusCode::OK_200, res->status);
  1181. }
  1182. {
  1183. Headers headers = {make_range_header({{0, -1}})};
  1184. auto res = cli.Get(path, headers);
  1185. ASSERT_TRUE(res);
  1186. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1187. EXPECT_EQ(StatusCode::OK_200, res->status);
  1188. }
  1189. {
  1190. Headers headers = {make_range_header({{0, 32}})};
  1191. auto res = cli.Get(path, headers);
  1192. ASSERT_TRUE(res);
  1193. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1194. }
  1195. }
  1196. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1197. auto host = "unresolvableaddress.local";
  1198. auto path = std::string{"/"};
  1199. #ifdef CPPHTTPLIB_SSL_ENABLED
  1200. auto port = 443;
  1201. SSLClient cli(host, port);
  1202. #else
  1203. auto port = 80;
  1204. Client cli(host, port);
  1205. #endif
  1206. cli.set_connection_timeout(1);
  1207. {
  1208. auto res = cli.Get(path);
  1209. ASSERT_FALSE(res);
  1210. }
  1211. std::this_thread::sleep_for(std::chrono::seconds(8));
  1212. }
  1213. TEST(ConnectionErrorTest, InvalidHost) {
  1214. auto host = "-abcde.com";
  1215. #ifdef CPPHTTPLIB_SSL_ENABLED
  1216. auto port = 443;
  1217. SSLClient cli(host, port);
  1218. #else
  1219. auto port = 80;
  1220. Client cli(host, port);
  1221. #endif
  1222. cli.set_connection_timeout(std::chrono::seconds(2));
  1223. auto res = cli.Get("/");
  1224. ASSERT_TRUE(!res);
  1225. EXPECT_EQ(Error::Connection, res.error());
  1226. }
  1227. TEST(ConnectionErrorTest, InvalidHost2) {
  1228. auto host = "httpcan.org/";
  1229. #ifdef CPPHTTPLIB_SSL_ENABLED
  1230. SSLClient cli(host);
  1231. #else
  1232. Client cli(host);
  1233. #endif
  1234. cli.set_connection_timeout(std::chrono::seconds(2));
  1235. auto res = cli.Get("/");
  1236. ASSERT_TRUE(!res);
  1237. EXPECT_EQ(Error::Connection, res.error());
  1238. }
  1239. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1240. auto host = "httpcan.org/";
  1241. #ifdef CPPHTTPLIB_SSL_ENABLED
  1242. SSLClient cli(host);
  1243. #else
  1244. Client cli(host);
  1245. #endif
  1246. cli.set_connection_timeout(std::chrono::seconds(2));
  1247. auto res = cli.Get("/");
  1248. ASSERT_TRUE(!res);
  1249. stringstream s;
  1250. s << "error code: " << res.error();
  1251. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1252. }
  1253. TEST(ConnectionErrorTest, InvalidPort) {
  1254. auto host = "localhost";
  1255. auto port = 44380;
  1256. #ifdef CPPHTTPLIB_SSL_ENABLED
  1257. SSLClient cli(host, port);
  1258. #else
  1259. Client cli(host, port);
  1260. #endif
  1261. cli.set_connection_timeout(std::chrono::seconds(2));
  1262. auto res = cli.Get("/");
  1263. ASSERT_TRUE(!res);
  1264. EXPECT_TRUE(Error::Connection == res.error() ||
  1265. Error::ConnectionTimeout == res.error());
  1266. }
  1267. TEST(ConnectionErrorTest, Timeout_Online) {
  1268. auto host = "google.com";
  1269. #ifdef CPPHTTPLIB_SSL_ENABLED
  1270. auto port = 44380;
  1271. SSLClient cli(host, port);
  1272. #else
  1273. auto port = 8080;
  1274. Client cli(host, port);
  1275. #endif
  1276. cli.set_connection_timeout(std::chrono::seconds(2));
  1277. // only probe one address type so that the error reason
  1278. // correlates to the timed-out IPv4, not the unsupported
  1279. // IPv6 connection attempt
  1280. cli.set_address_family(AF_INET);
  1281. auto res = cli.Get("/");
  1282. ASSERT_TRUE(!res);
  1283. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1284. }
  1285. TEST(CancelTest, NoCancel_Online) {
  1286. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1287. auto host = "httpcan.org";
  1288. auto path = std::string{"/range/32"};
  1289. #else
  1290. auto host = "nghttp2.org";
  1291. auto path = std::string{"/httpbin/range/32"};
  1292. #endif
  1293. #ifdef CPPHTTPLIB_SSL_ENABLED
  1294. auto port = 443;
  1295. SSLClient cli(host, port);
  1296. #else
  1297. auto port = 80;
  1298. Client cli(host, port);
  1299. #endif
  1300. cli.set_connection_timeout(std::chrono::seconds(5));
  1301. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1302. ASSERT_TRUE(res);
  1303. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1304. EXPECT_EQ(StatusCode::OK_200, res->status);
  1305. }
  1306. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1307. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1308. auto host = "httpcan.org";
  1309. auto path = std::string{"/range/32"};
  1310. #else
  1311. auto host = "nghttp2.org";
  1312. auto path = std::string{"/httpbin/range/32"};
  1313. #endif
  1314. #ifdef CPPHTTPLIB_SSL_ENABLED
  1315. auto port = 443;
  1316. SSLClient cli(host, port);
  1317. #else
  1318. auto port = 80;
  1319. Client cli(host, port);
  1320. #endif
  1321. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1322. cli.set_connection_timeout(std::chrono::seconds(5));
  1323. ASSERT_TRUE(!res);
  1324. EXPECT_EQ(Error::Canceled, res.error());
  1325. }
  1326. TEST(CancelTest, WithCancelLargePayload_Online) {
  1327. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1328. auto host = "httpcan.org";
  1329. auto path = std::string{"/range/65536"};
  1330. #else
  1331. auto host = "nghttp2.org";
  1332. auto path = std::string{"/httpbin/range/65536"};
  1333. #endif
  1334. #ifdef CPPHTTPLIB_SSL_ENABLED
  1335. auto port = 443;
  1336. SSLClient cli(host, port);
  1337. #else
  1338. auto port = 80;
  1339. Client cli(host, port);
  1340. #endif
  1341. cli.set_connection_timeout(std::chrono::seconds(5));
  1342. uint32_t count = 0;
  1343. auto res =
  1344. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1345. ASSERT_TRUE(!res);
  1346. EXPECT_EQ(Error::Canceled, res.error());
  1347. }
  1348. TEST(CancelTest, NoCancelPost) {
  1349. Server svr;
  1350. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1351. res.set_content("Hello World!", "text/plain");
  1352. });
  1353. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1354. auto se = detail::scope_exit([&] {
  1355. svr.stop();
  1356. thread.join();
  1357. ASSERT_FALSE(svr.is_running());
  1358. });
  1359. svr.wait_until_ready();
  1360. Client cli(HOST, PORT);
  1361. cli.set_connection_timeout(std::chrono::seconds(5));
  1362. auto res =
  1363. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1364. "application/json", [](uint64_t, uint64_t) { return true; });
  1365. ASSERT_TRUE(res);
  1366. EXPECT_EQ("Hello World!", res->body);
  1367. EXPECT_EQ(StatusCode::OK_200, res->status);
  1368. }
  1369. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1370. Server svr;
  1371. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1372. res.set_content("Hello World!", "text/plain");
  1373. });
  1374. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1375. auto se = detail::scope_exit([&] {
  1376. svr.stop();
  1377. thread.join();
  1378. ASSERT_FALSE(svr.is_running());
  1379. });
  1380. svr.wait_until_ready();
  1381. Client cli(HOST, PORT);
  1382. cli.set_connection_timeout(std::chrono::seconds(5));
  1383. auto res =
  1384. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1385. "application/json", [](uint64_t, uint64_t) { return false; });
  1386. ASSERT_TRUE(!res);
  1387. EXPECT_EQ(Error::Canceled, res.error());
  1388. }
  1389. TEST(CancelTest, WithCancelLargePayloadPost) {
  1390. Server svr;
  1391. svr.set_payload_max_length(200 * 1024 * 1024);
  1392. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1393. res.set_content(LARGE_DATA, "text/plain");
  1394. });
  1395. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1396. auto se = detail::scope_exit([&] {
  1397. svr.stop();
  1398. thread.join();
  1399. ASSERT_FALSE(svr.is_running());
  1400. });
  1401. svr.wait_until_ready();
  1402. Client cli(HOST, PORT);
  1403. cli.set_payload_max_length(200 * 1024 * 1024);
  1404. cli.set_connection_timeout(std::chrono::seconds(5));
  1405. auto res =
  1406. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1407. "application/json", [](uint64_t, uint64_t) { return false; });
  1408. ASSERT_TRUE(!res);
  1409. EXPECT_EQ(Error::Canceled, res.error());
  1410. }
  1411. TEST(CancelTest, NoCancelPut) {
  1412. Server svr;
  1413. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1414. res.set_content("Hello World!", "text/plain");
  1415. });
  1416. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1417. auto se = detail::scope_exit([&] {
  1418. svr.stop();
  1419. thread.join();
  1420. ASSERT_FALSE(svr.is_running());
  1421. });
  1422. svr.wait_until_ready();
  1423. Client cli(HOST, PORT);
  1424. cli.set_connection_timeout(std::chrono::seconds(5));
  1425. auto res =
  1426. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1427. "application/json", [](uint64_t, uint64_t) { return true; });
  1428. ASSERT_TRUE(res);
  1429. EXPECT_EQ("Hello World!", res->body);
  1430. EXPECT_EQ(StatusCode::OK_200, res->status);
  1431. }
  1432. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1433. Server svr;
  1434. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1435. res.set_content("Hello World!", "text/plain");
  1436. });
  1437. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1438. auto se = detail::scope_exit([&] {
  1439. svr.stop();
  1440. thread.join();
  1441. ASSERT_FALSE(svr.is_running());
  1442. });
  1443. svr.wait_until_ready();
  1444. Client cli(HOST, PORT);
  1445. cli.set_connection_timeout(std::chrono::seconds(5));
  1446. auto res =
  1447. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1448. "application/json", [](uint64_t, uint64_t) { return false; });
  1449. ASSERT_TRUE(!res);
  1450. EXPECT_EQ(Error::Canceled, res.error());
  1451. }
  1452. TEST(CancelTest, WithCancelLargePayloadPut) {
  1453. Server svr;
  1454. svr.set_payload_max_length(200 * 1024 * 1024);
  1455. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1456. res.set_content(LARGE_DATA, "text/plain");
  1457. });
  1458. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1459. auto se = detail::scope_exit([&] {
  1460. svr.stop();
  1461. thread.join();
  1462. ASSERT_FALSE(svr.is_running());
  1463. });
  1464. svr.wait_until_ready();
  1465. Client cli(HOST, PORT);
  1466. cli.set_payload_max_length(200 * 1024 * 1024);
  1467. cli.set_connection_timeout(std::chrono::seconds(5));
  1468. auto res =
  1469. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1470. "application/json", [](uint64_t, uint64_t) { return false; });
  1471. ASSERT_TRUE(!res);
  1472. EXPECT_EQ(Error::Canceled, res.error());
  1473. }
  1474. TEST(CancelTest, NoCancelPatch) {
  1475. Server svr;
  1476. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1477. res.set_content("Hello World!", "text/plain");
  1478. });
  1479. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1480. auto se = detail::scope_exit([&] {
  1481. svr.stop();
  1482. thread.join();
  1483. ASSERT_FALSE(svr.is_running());
  1484. });
  1485. svr.wait_until_ready();
  1486. Client cli(HOST, PORT);
  1487. cli.set_connection_timeout(std::chrono::seconds(5));
  1488. auto res =
  1489. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1490. "application/json", [](uint64_t, uint64_t) { return true; });
  1491. ASSERT_TRUE(res);
  1492. EXPECT_EQ("Hello World!", res->body);
  1493. EXPECT_EQ(StatusCode::OK_200, res->status);
  1494. }
  1495. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1496. Server svr;
  1497. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1498. res.set_content("Hello World!", "text/plain");
  1499. });
  1500. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1501. auto se = detail::scope_exit([&] {
  1502. svr.stop();
  1503. thread.join();
  1504. ASSERT_FALSE(svr.is_running());
  1505. });
  1506. svr.wait_until_ready();
  1507. Client cli(HOST, PORT);
  1508. cli.set_connection_timeout(std::chrono::seconds(5));
  1509. auto res =
  1510. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1511. "application/json", [](uint64_t, uint64_t) { return false; });
  1512. ASSERT_TRUE(!res);
  1513. EXPECT_EQ(Error::Canceled, res.error());
  1514. }
  1515. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1516. Server svr;
  1517. svr.set_payload_max_length(200 * 1024 * 1024);
  1518. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1519. res.set_content(LARGE_DATA, "text/plain");
  1520. });
  1521. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1522. auto se = detail::scope_exit([&] {
  1523. svr.stop();
  1524. thread.join();
  1525. ASSERT_FALSE(svr.is_running());
  1526. });
  1527. svr.wait_until_ready();
  1528. Client cli(HOST, PORT);
  1529. cli.set_payload_max_length(200 * 1024 * 1024);
  1530. cli.set_connection_timeout(std::chrono::seconds(5));
  1531. auto res =
  1532. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1533. "application/json", [](uint64_t, uint64_t) { return false; });
  1534. ASSERT_TRUE(!res);
  1535. EXPECT_EQ(Error::Canceled, res.error());
  1536. }
  1537. TEST(CancelTest, NoCancelDelete) {
  1538. Server svr;
  1539. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1540. res.set_content("Hello World!", "text/plain");
  1541. });
  1542. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1543. auto se = detail::scope_exit([&] {
  1544. svr.stop();
  1545. thread.join();
  1546. ASSERT_FALSE(svr.is_running());
  1547. });
  1548. svr.wait_until_ready();
  1549. Client cli(HOST, PORT);
  1550. cli.set_connection_timeout(std::chrono::seconds(5));
  1551. auto res =
  1552. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1553. "application/json", [](uint64_t, uint64_t) { return true; });
  1554. ASSERT_TRUE(res);
  1555. EXPECT_EQ("Hello World!", res->body);
  1556. EXPECT_EQ(StatusCode::OK_200, res->status);
  1557. }
  1558. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1559. Server svr;
  1560. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1561. res.set_content("Hello World!", "text/plain");
  1562. });
  1563. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1564. auto se = detail::scope_exit([&] {
  1565. svr.stop();
  1566. thread.join();
  1567. ASSERT_FALSE(svr.is_running());
  1568. });
  1569. svr.wait_until_ready();
  1570. Client cli(HOST, PORT);
  1571. cli.set_connection_timeout(std::chrono::seconds(5));
  1572. auto res =
  1573. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1574. "application/json", [](uint64_t, uint64_t) { return false; });
  1575. ASSERT_TRUE(!res);
  1576. EXPECT_EQ(Error::Canceled, res.error());
  1577. }
  1578. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1579. Server svr;
  1580. svr.set_payload_max_length(200 * 1024 * 1024);
  1581. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1582. res.set_content(LARGE_DATA, "text/plain");
  1583. });
  1584. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1585. auto se = detail::scope_exit([&] {
  1586. svr.stop();
  1587. thread.join();
  1588. ASSERT_FALSE(svr.is_running());
  1589. });
  1590. svr.wait_until_ready();
  1591. Client cli(HOST, PORT);
  1592. cli.set_payload_max_length(200 * 1024 * 1024);
  1593. cli.set_connection_timeout(std::chrono::seconds(5));
  1594. auto res =
  1595. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1596. "application/json", [](uint64_t, uint64_t) { return false; });
  1597. ASSERT_TRUE(!res);
  1598. EXPECT_EQ(Error::Canceled, res.error());
  1599. }
  1600. static std::string remove_whitespace(const std::string &input) {
  1601. std::string output;
  1602. output.reserve(input.size());
  1603. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1604. [](unsigned char c) { return !std::isspace(c); });
  1605. return output;
  1606. }
  1607. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1608. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1609. auto host = "httpcan.org";
  1610. auto path = std::string{"/basic-auth/hello/world"};
  1611. #else
  1612. auto host = "nghttp2.org";
  1613. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1614. #endif
  1615. #ifdef CPPHTTPLIB_SSL_ENABLED
  1616. auto port = 443;
  1617. SSLClient cli(host, port);
  1618. #else
  1619. auto port = 80;
  1620. Client cli(host, port);
  1621. #endif
  1622. {
  1623. auto res = cli.Get(path);
  1624. ASSERT_TRUE(res);
  1625. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1626. }
  1627. {
  1628. auto res =
  1629. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1630. ASSERT_TRUE(res);
  1631. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1632. remove_whitespace(res->body));
  1633. EXPECT_EQ(StatusCode::OK_200, res->status);
  1634. }
  1635. {
  1636. cli.set_basic_auth("hello", "world");
  1637. auto res = cli.Get(path);
  1638. ASSERT_TRUE(res);
  1639. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1640. remove_whitespace(res->body));
  1641. EXPECT_EQ(StatusCode::OK_200, res->status);
  1642. }
  1643. {
  1644. cli.set_basic_auth("hello", "bad");
  1645. auto res = cli.Get(path);
  1646. ASSERT_TRUE(res);
  1647. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1648. }
  1649. {
  1650. cli.set_basic_auth("bad", "world");
  1651. auto res = cli.Get(path);
  1652. ASSERT_TRUE(res);
  1653. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1654. }
  1655. }
  1656. #ifdef CPPHTTPLIB_SSL_ENABLED
  1657. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1658. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1659. auto host = "httpcan.org";
  1660. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1661. auto paths = std::vector<std::string>{
  1662. "/digest-auth/auth/hello/world/MD5",
  1663. "/digest-auth/auth/hello/world/SHA-256",
  1664. "/digest-auth/auth/hello/world/SHA-512",
  1665. };
  1666. #else
  1667. auto host = "nghttp2.org";
  1668. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1669. auto paths = std::vector<std::string>{
  1670. "/httpbin/digest-auth/auth/hello/world/MD5",
  1671. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1672. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1673. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1674. };
  1675. #endif
  1676. auto port = 443;
  1677. SSLClient cli(host, port);
  1678. {
  1679. auto res = cli.Get(unauth_path);
  1680. ASSERT_TRUE(res);
  1681. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1682. }
  1683. {
  1684. cli.set_digest_auth("hello", "world");
  1685. for (const auto &path : paths) {
  1686. auto res = cli.Get(path.c_str());
  1687. ASSERT_TRUE(res);
  1688. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1689. std::string algo(path.substr(path.rfind('/') + 1));
  1690. EXPECT_EQ(
  1691. remove_whitespace("{\"algorithm\":\"" + algo +
  1692. "\",\"authenticated\":true,\"user\":\"hello\"}\n"),
  1693. remove_whitespace(res->body));
  1694. #else
  1695. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1696. remove_whitespace(res->body));
  1697. #endif
  1698. EXPECT_EQ(StatusCode::OK_200, res->status);
  1699. }
  1700. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1701. cli.set_digest_auth("hello", "bad");
  1702. for (const auto &path : paths) {
  1703. auto res = cli.Get(path.c_str());
  1704. ASSERT_TRUE(res);
  1705. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1706. }
  1707. #endif
  1708. }
  1709. }
  1710. #endif
  1711. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1712. auto host = "google.com";
  1713. auto another_host = "example.com";
  1714. auto wrong_ip = "0.0.0.0";
  1715. #ifdef CPPHTTPLIB_SSL_ENABLED
  1716. SSLClient cli(host);
  1717. #else
  1718. Client cli(host);
  1719. #endif
  1720. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1721. auto res = cli.Get("/");
  1722. ASSERT_TRUE(res);
  1723. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1724. }
  1725. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1726. auto host = "google.com";
  1727. auto wrong_ip = "0.0.0.0";
  1728. #ifdef CPPHTTPLIB_SSL_ENABLED
  1729. SSLClient cli(host);
  1730. #else
  1731. Client cli(host);
  1732. #endif
  1733. cli.set_hostname_addr_map({{host, wrong_ip}});
  1734. auto res = cli.Get("/");
  1735. ASSERT_TRUE(!res);
  1736. EXPECT_EQ(Error::Connection, res.error());
  1737. }
  1738. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1739. auto host = "nghttp2.org";
  1740. #ifdef CPPHTTPLIB_SSL_ENABLED
  1741. SSLClient cli(host);
  1742. #else
  1743. Client cli(host);
  1744. #endif
  1745. cli.set_follow_location(true);
  1746. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1747. ASSERT_TRUE(res);
  1748. EXPECT_EQ(StatusCode::OK_200, res->status);
  1749. }
  1750. TEST(RedirectTest, Redirect_Online) {
  1751. auto host = "nghttp2.org";
  1752. #ifdef CPPHTTPLIB_SSL_ENABLED
  1753. SSLClient cli(host);
  1754. #else
  1755. Client cli(host);
  1756. #endif
  1757. cli.set_follow_location(true);
  1758. auto res = cli.Get("/httpbin/redirect/3");
  1759. ASSERT_TRUE(res);
  1760. EXPECT_EQ(StatusCode::OK_200, res->status);
  1761. }
  1762. TEST(RelativeRedirectTest, Redirect_Online) {
  1763. auto host = "nghttp2.org";
  1764. #ifdef CPPHTTPLIB_SSL_ENABLED
  1765. SSLClient cli(host);
  1766. #else
  1767. Client cli(host);
  1768. #endif
  1769. cli.set_follow_location(true);
  1770. auto res = cli.Get("/httpbin/relative-redirect/3");
  1771. ASSERT_TRUE(res);
  1772. EXPECT_EQ(StatusCode::OK_200, res->status);
  1773. }
  1774. TEST(TooManyRedirectTest, Redirect_Online) {
  1775. auto host = "nghttp2.org";
  1776. #ifdef CPPHTTPLIB_SSL_ENABLED
  1777. SSLClient cli(host);
  1778. #else
  1779. Client cli(host);
  1780. #endif
  1781. cli.set_follow_location(true);
  1782. auto res = cli.Get("/httpbin/redirect/21");
  1783. ASSERT_TRUE(!res);
  1784. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1785. }
  1786. #ifdef CPPHTTPLIB_SSL_ENABLED
  1787. TEST(YahooRedirectTest, Redirect_Online) {
  1788. Client cli("yahoo.com");
  1789. auto res = cli.Get("/");
  1790. ASSERT_TRUE(res);
  1791. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1792. cli.set_follow_location(true);
  1793. res = cli.Get("/");
  1794. ASSERT_TRUE(res);
  1795. EXPECT_EQ(StatusCode::OK_200, res->status);
  1796. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1797. }
  1798. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1799. #define REDIR_HOST "httpbingo.org"
  1800. #define REDIR_PATH "/redirect-to"
  1801. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1802. SSLClient cli(REDIR_HOST);
  1803. cli.set_follow_location(true);
  1804. auto res =
  1805. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1806. ASSERT_TRUE(res);
  1807. EXPECT_EQ(StatusCode::OK_200, res->status);
  1808. }
  1809. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1810. SSLClient cli(REDIR_HOST);
  1811. cli.set_follow_location(true);
  1812. Params params;
  1813. params.emplace("url", "http://example.com");
  1814. params.emplace("status_code", "302");
  1815. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1816. ASSERT_TRUE(res);
  1817. EXPECT_EQ(StatusCode::OK_200, res->status);
  1818. }
  1819. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1820. SSLClient cli(REDIR_HOST);
  1821. cli.set_follow_location(true);
  1822. Params params;
  1823. params.emplace("url", "http://example.com");
  1824. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1825. ASSERT_TRUE(res);
  1826. EXPECT_EQ(StatusCode::OK_200, res->status);
  1827. }
  1828. TEST(UrlWithSpace, Redirect_Online) {
  1829. SSLClient cli("edge.forgecdn.net");
  1830. cli.set_follow_location(true);
  1831. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1832. ASSERT_TRUE(res);
  1833. EXPECT_EQ(StatusCode::OK_200, res->status);
  1834. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1835. }
  1836. #endif
  1837. #if !defined(_WIN32) && !defined(_WIN64)
  1838. TEST(ReceiveSignals, Signal) {
  1839. auto setupSignalHandlers = []() {
  1840. struct sigaction act;
  1841. sigemptyset(&act.sa_mask);
  1842. act.sa_flags = SA_SIGINFO;
  1843. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1844. switch (sig) {
  1845. case SIGINT:
  1846. default: break;
  1847. }
  1848. };
  1849. ::sigaction(SIGINT, &act, nullptr);
  1850. };
  1851. Server svr;
  1852. int port = 0;
  1853. auto thread = std::thread([&]() {
  1854. setupSignalHandlers();
  1855. port = svr.bind_to_any_port(HOST);
  1856. svr.listen_after_bind();
  1857. });
  1858. auto se = detail::scope_exit([&] {
  1859. svr.stop();
  1860. thread.join();
  1861. ASSERT_FALSE(svr.is_running());
  1862. });
  1863. svr.wait_until_ready();
  1864. ASSERT_TRUE(svr.is_running());
  1865. pthread_kill(thread.native_handle(), SIGINT);
  1866. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1867. ASSERT_TRUE(svr.is_running());
  1868. }
  1869. #endif
  1870. TEST(RedirectToDifferentPort, Redirect) {
  1871. Server svr1;
  1872. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1873. res.set_content("Hello World!", "text/plain");
  1874. });
  1875. int svr1_port = 0;
  1876. auto thread1 = std::thread([&]() {
  1877. svr1_port = svr1.bind_to_any_port(HOST);
  1878. svr1.listen_after_bind();
  1879. });
  1880. Server svr2;
  1881. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1882. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1883. });
  1884. int svr2_port = 0;
  1885. auto thread2 = std::thread([&]() {
  1886. svr2_port = svr2.bind_to_any_port(HOST);
  1887. svr2.listen_after_bind();
  1888. });
  1889. auto se = detail::scope_exit([&] {
  1890. svr2.stop();
  1891. thread2.join();
  1892. svr1.stop();
  1893. thread1.join();
  1894. ASSERT_FALSE(svr2.is_running());
  1895. ASSERT_FALSE(svr1.is_running());
  1896. });
  1897. svr1.wait_until_ready();
  1898. svr2.wait_until_ready();
  1899. Client cli("localhost", svr2_port);
  1900. cli.set_follow_location(true);
  1901. auto res = cli.Get("/2");
  1902. ASSERT_TRUE(res);
  1903. EXPECT_EQ(StatusCode::OK_200, res->status);
  1904. EXPECT_EQ("Hello World!", res->body);
  1905. }
  1906. TEST(RedirectFromPageWithContent, Redirect) {
  1907. Server svr;
  1908. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1909. res.set_content("___", "text/plain");
  1910. res.set_redirect("/2");
  1911. });
  1912. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1913. res.set_content("Hello World!", "text/plain");
  1914. });
  1915. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1916. auto se = detail::scope_exit([&] {
  1917. svr.stop();
  1918. th.join();
  1919. ASSERT_FALSE(svr.is_running());
  1920. });
  1921. svr.wait_until_ready();
  1922. {
  1923. Client cli("localhost", PORT);
  1924. cli.set_follow_location(true);
  1925. std::string body;
  1926. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1927. body.append(data, data_length);
  1928. return true;
  1929. });
  1930. ASSERT_TRUE(res);
  1931. EXPECT_EQ(StatusCode::OK_200, res->status);
  1932. EXPECT_EQ("Hello World!", body);
  1933. }
  1934. {
  1935. Client cli("localhost", PORT);
  1936. std::string body;
  1937. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1938. body.append(data, data_length);
  1939. return true;
  1940. });
  1941. ASSERT_TRUE(res);
  1942. EXPECT_EQ(StatusCode::Found_302, res->status);
  1943. EXPECT_EQ("___", body);
  1944. }
  1945. }
  1946. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1947. Server svr;
  1948. auto port_str = std::to_string(PORT);
  1949. auto redirect_url = "http://[::1]:" + port_str + "/2";
  1950. auto expected_host = "[::1]:" + port_str;
  1951. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1952. res.set_content("___", "text/plain");
  1953. // res.set_redirect("/2");
  1954. res.set_redirect(redirect_url);
  1955. });
  1956. svr.Get("/2", [&](const Request &req, Response &res) {
  1957. auto host_header = req.headers.find("Host");
  1958. ASSERT_TRUE(host_header != req.headers.end());
  1959. EXPECT_EQ(expected_host, host_header->second);
  1960. res.set_content("Hello World!", "text/plain");
  1961. });
  1962. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  1963. auto se = detail::scope_exit([&] {
  1964. svr.stop();
  1965. th.join();
  1966. ASSERT_FALSE(svr.is_running());
  1967. });
  1968. // When IPV6 support isn't available svr.listen("::1", PORT) never
  1969. // actually starts anything, so the condition !svr.is_running() will
  1970. // always remain true, and the loop never stops.
  1971. // This basically counts how many milliseconds have passed since the
  1972. // call to svr.listen(), and if after 5 seconds nothing started yet
  1973. // aborts the test.
  1974. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1975. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1976. ASSERT_LT(milliseconds, 5000U);
  1977. }
  1978. {
  1979. Client cli("::1", PORT);
  1980. cli.set_follow_location(true);
  1981. std::string body;
  1982. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1983. body.append(data, data_length);
  1984. return true;
  1985. });
  1986. ASSERT_TRUE(res);
  1987. EXPECT_EQ(StatusCode::OK_200, res->status);
  1988. EXPECT_EQ("Hello World!", body);
  1989. }
  1990. {
  1991. Client cli("::1", PORT);
  1992. std::string body;
  1993. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1994. body.append(data, data_length);
  1995. return true;
  1996. });
  1997. ASSERT_TRUE(res);
  1998. EXPECT_EQ(StatusCode::Found_302, res->status);
  1999. EXPECT_EQ("___", body);
  2000. }
  2001. }
  2002. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2003. Server svr;
  2004. svr.Get("/foo", [](const Request &req, Response &res) {
  2005. auto a = req.params.find("a");
  2006. if (a != req.params.end()) {
  2007. res.set_content((*a).second, "text/plain");
  2008. res.status = StatusCode::OK_200;
  2009. } else {
  2010. res.status = StatusCode::BadRequest_400;
  2011. }
  2012. });
  2013. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2014. auto se = detail::scope_exit([&] {
  2015. svr.stop();
  2016. thread.join();
  2017. ASSERT_FALSE(svr.is_running());
  2018. });
  2019. svr.wait_until_ready();
  2020. {
  2021. Client cli(HOST, PORT);
  2022. cli.set_path_encode(false);
  2023. auto res = cli.Get("/foo?a=explicitly+encoded");
  2024. ASSERT_TRUE(res);
  2025. EXPECT_EQ(StatusCode::OK_200, res->status);
  2026. // This expects it back with a space, as the `+` won't have been
  2027. // url-encoded, and server-side the params get decoded turning `+`
  2028. // into spaces.
  2029. EXPECT_EQ("explicitly encoded", res->body);
  2030. }
  2031. }
  2032. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2033. Server svr;
  2034. svr.Get("/", [](const Request &req, Response &) {
  2035. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2036. });
  2037. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2038. auto se = detail::scope_exit([&] {
  2039. svr.stop();
  2040. thread.join();
  2041. ASSERT_FALSE(svr.is_running());
  2042. });
  2043. svr.wait_until_ready();
  2044. {
  2045. Client cli(HOST, PORT);
  2046. cli.set_path_encode(false);
  2047. auto res = cli.Get("/?something=%0A");
  2048. ASSERT_TRUE(res);
  2049. EXPECT_EQ(StatusCode::OK_200, res->status);
  2050. }
  2051. }
  2052. TEST(BindServerTest, DISABLED_BindDualStack) {
  2053. Server svr;
  2054. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2055. res.set_content("Hello World!", "text/plain");
  2056. });
  2057. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2058. auto se = detail::scope_exit([&] {
  2059. svr.stop();
  2060. thread.join();
  2061. ASSERT_FALSE(svr.is_running());
  2062. });
  2063. svr.wait_until_ready();
  2064. {
  2065. Client cli("127.0.0.1", PORT);
  2066. auto res = cli.Get("/1");
  2067. ASSERT_TRUE(res);
  2068. EXPECT_EQ(StatusCode::OK_200, res->status);
  2069. EXPECT_EQ("Hello World!", res->body);
  2070. }
  2071. {
  2072. Client cli("::1", PORT);
  2073. auto res = cli.Get("/1");
  2074. ASSERT_TRUE(res);
  2075. EXPECT_EQ(StatusCode::OK_200, res->status);
  2076. EXPECT_EQ("Hello World!", res->body);
  2077. }
  2078. }
  2079. TEST(BindServerTest, BindAndListenSeparately) {
  2080. Server svr;
  2081. int port = svr.bind_to_any_port("0.0.0.0");
  2082. ASSERT_TRUE(svr.is_valid());
  2083. ASSERT_TRUE(port > 0);
  2084. svr.stop();
  2085. }
  2086. #ifdef CPPHTTPLIB_SSL_ENABLED
  2087. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2088. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2089. CLIENT_CA_CERT_DIR);
  2090. int port = svr.bind_to_any_port("0.0.0.0");
  2091. ASSERT_TRUE(svr.is_valid());
  2092. ASSERT_TRUE(port > 0);
  2093. svr.stop();
  2094. }
  2095. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2096. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2097. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2098. int port = svr.bind_to_any_port("0.0.0.0");
  2099. ASSERT_TRUE(svr.is_valid());
  2100. ASSERT_TRUE(port > 0);
  2101. svr.stop();
  2102. }
  2103. TEST(BindServerTest, UpdateCertsPem) {
  2104. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2105. int port = svr.bind_to_any_port("0.0.0.0");
  2106. ASSERT_TRUE(svr.is_valid());
  2107. ASSERT_TRUE(port > 0);
  2108. // Read PEM files
  2109. std::string cert_pem, key_pem, ca_pem;
  2110. read_file(SERVER_CERT_FILE, cert_pem);
  2111. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2112. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2113. // Update server certificates using PEM API
  2114. ASSERT_TRUE(
  2115. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2116. ASSERT_TRUE(svr.is_valid());
  2117. svr.stop();
  2118. }
  2119. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2120. // Start server with client CA (enables client auth)
  2121. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2122. ASSERT_TRUE(svr.is_valid());
  2123. bool handler_called = false;
  2124. svr.Get("/test", [&](const Request &req, Response &res) {
  2125. handler_called = true;
  2126. // Verify client certificate is present
  2127. auto cert = req.peer_cert();
  2128. EXPECT_TRUE(static_cast<bool>(cert));
  2129. res.set_content("ok", "text/plain");
  2130. });
  2131. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2132. auto se = detail::scope_exit([&] {
  2133. svr.stop();
  2134. t.join();
  2135. ASSERT_FALSE(svr.is_running());
  2136. });
  2137. svr.wait_until_ready();
  2138. // Read PEM files
  2139. std::string cert_pem, key_pem, ca_pem;
  2140. read_file(SERVER_CERT_FILE, cert_pem);
  2141. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2142. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2143. // Update server certificates and client CA using PEM API while server running
  2144. ASSERT_TRUE(
  2145. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2146. // Connect with client certificate
  2147. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2148. cli.enable_server_certificate_verification(false);
  2149. cli.set_connection_timeout(30);
  2150. auto res = cli.Get("/test");
  2151. ASSERT_TRUE(res);
  2152. ASSERT_EQ(StatusCode::OK_200, res->status);
  2153. ASSERT_TRUE(handler_called);
  2154. EXPECT_EQ("ok", res->body);
  2155. }
  2156. #endif
  2157. TEST(ErrorHandlerTest, ContentLength) {
  2158. Server svr;
  2159. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2160. res.status = StatusCode::OK_200;
  2161. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2162. "text/html"); // <= Content-Length still 13
  2163. });
  2164. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2165. res.set_content("Hello World!\n", "text/plain");
  2166. res.status = 524;
  2167. });
  2168. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2169. auto se = detail::scope_exit([&] {
  2170. svr.stop();
  2171. thread.join();
  2172. ASSERT_FALSE(svr.is_running());
  2173. });
  2174. svr.wait_until_ready();
  2175. {
  2176. Client cli(HOST, PORT);
  2177. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2178. ASSERT_TRUE(res);
  2179. EXPECT_EQ(StatusCode::OK_200, res->status);
  2180. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2181. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2182. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2183. }
  2184. }
  2185. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2186. TEST(ExceptionTest, WithoutExceptionHandler) {
  2187. Server svr;
  2188. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2189. throw std::runtime_error("exception...");
  2190. });
  2191. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2192. throw std::runtime_error("exception\r\n...");
  2193. });
  2194. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2195. auto se = detail::scope_exit([&] {
  2196. svr.stop();
  2197. listen_thread.join();
  2198. ASSERT_FALSE(svr.is_running());
  2199. });
  2200. svr.wait_until_ready();
  2201. Client cli("localhost", PORT);
  2202. {
  2203. auto res = cli.Get("/exception");
  2204. ASSERT_TRUE(res);
  2205. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2206. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2207. }
  2208. {
  2209. auto res = cli.Get("/unknown");
  2210. ASSERT_TRUE(res);
  2211. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2212. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2213. }
  2214. }
  2215. TEST(ExceptionTest, WithExceptionHandler) {
  2216. Server svr;
  2217. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2218. std::exception_ptr ep) {
  2219. EXPECT_FALSE(ep == nullptr);
  2220. try {
  2221. std::rethrow_exception(ep);
  2222. } catch (std::exception &e) {
  2223. EXPECT_EQ("abc", std::string(e.what()));
  2224. } catch (...) {}
  2225. res.status = StatusCode::InternalServerError_500;
  2226. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2227. "text/html"); // <= Content-Length still 13 at this point
  2228. });
  2229. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2230. res.set_content("Hello World!\n", "text/plain");
  2231. throw std::runtime_error("abc");
  2232. });
  2233. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2234. auto se = detail::scope_exit([&] {
  2235. svr.stop();
  2236. thread.join();
  2237. ASSERT_FALSE(svr.is_running());
  2238. });
  2239. svr.wait_until_ready();
  2240. for (size_t i = 0; i < 10; i++) {
  2241. Client cli(HOST, PORT);
  2242. for (size_t j = 0; j < 100; j++) {
  2243. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2244. ASSERT_TRUE(res);
  2245. EXPECT_EQ(StatusCode::InternalServerError_500, 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. cli.set_keep_alive(true);
  2251. for (size_t j = 0; j < 100; j++) {
  2252. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2253. ASSERT_TRUE(res);
  2254. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2255. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2256. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2257. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2258. }
  2259. }
  2260. }
  2261. TEST(ExceptionTest, AndErrorHandler) {
  2262. Server svr;
  2263. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2264. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2265. });
  2266. svr.set_exception_handler(
  2267. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2268. EXPECT_FALSE(ep == nullptr);
  2269. try {
  2270. std::rethrow_exception(ep);
  2271. } catch (std::exception &e) {
  2272. res.set_content(e.what(), "text/html");
  2273. } catch (...) {}
  2274. res.status = StatusCode::InternalServerError_500;
  2275. });
  2276. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2277. throw std::runtime_error("EXCEPTION");
  2278. });
  2279. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2280. res.set_content("ERROR", "text/html");
  2281. res.status = StatusCode::InternalServerError_500;
  2282. });
  2283. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2284. auto se = detail::scope_exit([&] {
  2285. svr.stop();
  2286. thread.join();
  2287. ASSERT_FALSE(svr.is_running());
  2288. });
  2289. svr.wait_until_ready();
  2290. Client cli(HOST, PORT);
  2291. {
  2292. auto res = cli.Get("/exception");
  2293. ASSERT_TRUE(res);
  2294. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2295. EXPECT_EQ("EXCEPTION", res->body);
  2296. }
  2297. {
  2298. auto res = cli.Get("/error");
  2299. ASSERT_TRUE(res);
  2300. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2301. EXPECT_EQ("ERROR", res->body);
  2302. }
  2303. {
  2304. auto res = cli.Get("/invalid");
  2305. ASSERT_TRUE(res);
  2306. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2307. EXPECT_EQ("NOT_FOUND", res->body);
  2308. }
  2309. }
  2310. #endif
  2311. TEST(NoContentTest, ContentLength) {
  2312. Server svr;
  2313. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2314. res.status = StatusCode::NoContent_204;
  2315. });
  2316. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2317. auto se = detail::scope_exit([&] {
  2318. svr.stop();
  2319. thread.join();
  2320. ASSERT_FALSE(svr.is_running());
  2321. });
  2322. svr.wait_until_ready();
  2323. {
  2324. Client cli(HOST, PORT);
  2325. auto res = cli.Get("/hi");
  2326. ASSERT_TRUE(res);
  2327. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2328. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2329. }
  2330. }
  2331. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2332. #ifdef CPPHTTPLIB_SSL_ENABLED
  2333. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2334. ASSERT_TRUE(svr.is_valid());
  2335. #else
  2336. Server svr;
  2337. #endif
  2338. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2339. if (req.path == "/routing_handler") {
  2340. res.set_header("PRE_ROUTING", "on");
  2341. res.set_content("Routing Handler", "text/plain");
  2342. return httplib::Server::HandlerResponse::Handled;
  2343. }
  2344. return httplib::Server::HandlerResponse::Unhandled;
  2345. });
  2346. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2347. res.set_content("Error", "text/html");
  2348. });
  2349. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2350. if (req.path == "/routing_handler") {
  2351. res.set_header("POST_ROUTING", "on");
  2352. }
  2353. });
  2354. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2355. res.set_content("Hello World!\n", "text/plain");
  2356. });
  2357. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2358. auto se = detail::scope_exit([&] {
  2359. svr.stop();
  2360. thread.join();
  2361. ASSERT_FALSE(svr.is_running());
  2362. });
  2363. svr.wait_until_ready();
  2364. {
  2365. #ifdef CPPHTTPLIB_SSL_ENABLED
  2366. SSLClient cli(HOST, PORT);
  2367. cli.enable_server_certificate_verification(false);
  2368. #else
  2369. Client cli(HOST, PORT);
  2370. #endif
  2371. auto res = cli.Get("/routing_handler");
  2372. ASSERT_TRUE(res);
  2373. EXPECT_EQ(StatusCode::OK_200, res->status);
  2374. EXPECT_EQ("Routing Handler", res->body);
  2375. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2376. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2377. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2378. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2379. }
  2380. {
  2381. #ifdef CPPHTTPLIB_SSL_ENABLED
  2382. SSLClient cli(HOST, PORT);
  2383. cli.enable_server_certificate_verification(false);
  2384. #else
  2385. Client cli(HOST, PORT);
  2386. #endif
  2387. auto res = cli.Get("/hi");
  2388. ASSERT_TRUE(res);
  2389. EXPECT_EQ(StatusCode::OK_200, res->status);
  2390. EXPECT_EQ("Hello World!\n", res->body);
  2391. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2392. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2393. }
  2394. {
  2395. #ifdef CPPHTTPLIB_SSL_ENABLED
  2396. SSLClient cli(HOST, PORT);
  2397. cli.enable_server_certificate_verification(false);
  2398. #else
  2399. Client cli(HOST, PORT);
  2400. #endif
  2401. auto res = cli.Get("/aaa");
  2402. ASSERT_TRUE(res);
  2403. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2404. EXPECT_EQ("Error", res->body);
  2405. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2406. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2407. }
  2408. }
  2409. TEST(RequestHandlerTest, PreRequestHandler) {
  2410. auto route_path = "/user/:user";
  2411. Server svr;
  2412. svr.Get("/hi", [](const Request &, Response &res) {
  2413. res.set_content("hi", "text/plain");
  2414. });
  2415. svr.Get(route_path, [](const Request &req, Response &res) {
  2416. res.set_content(req.path_params.at("user"), "text/plain");
  2417. });
  2418. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2419. if (req.matched_route == route_path) {
  2420. auto user = req.path_params.at("user");
  2421. if (user != "john") {
  2422. res.status = StatusCode::Forbidden_403;
  2423. res.set_content("error", "text/html");
  2424. return Server::HandlerResponse::Handled;
  2425. }
  2426. }
  2427. return Server::HandlerResponse::Unhandled;
  2428. });
  2429. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2430. auto se = detail::scope_exit([&] {
  2431. svr.stop();
  2432. thread.join();
  2433. ASSERT_FALSE(svr.is_running());
  2434. });
  2435. svr.wait_until_ready();
  2436. Client cli(HOST, PORT);
  2437. {
  2438. auto res = cli.Get("/hi");
  2439. ASSERT_TRUE(res);
  2440. EXPECT_EQ(StatusCode::OK_200, res->status);
  2441. EXPECT_EQ("hi", res->body);
  2442. }
  2443. {
  2444. auto res = cli.Get("/user/john");
  2445. ASSERT_TRUE(res);
  2446. EXPECT_EQ(StatusCode::OK_200, res->status);
  2447. EXPECT_EQ("john", res->body);
  2448. }
  2449. {
  2450. auto res = cli.Get("/user/invalid-user");
  2451. ASSERT_TRUE(res);
  2452. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2453. EXPECT_EQ("error", res->body);
  2454. }
  2455. }
  2456. TEST(AnyTest, BasicOperations) {
  2457. // Default construction
  2458. httplib::any a;
  2459. EXPECT_FALSE(a.has_value());
  2460. // Value construction and any_cast (pointer form, noexcept)
  2461. httplib::any b(42);
  2462. EXPECT_TRUE(b.has_value());
  2463. auto *p = httplib::any_cast<int>(&b);
  2464. ASSERT_NE(nullptr, p);
  2465. EXPECT_EQ(42, *p);
  2466. // Type mismatch → nullptr
  2467. auto *q = httplib::any_cast<std::string>(&b);
  2468. EXPECT_EQ(nullptr, q);
  2469. // any_cast (value form) succeeds
  2470. EXPECT_EQ(42, httplib::any_cast<int>(b));
  2471. // any_cast (value form) throws on type mismatch
  2472. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2473. EXPECT_THROW(httplib::any_cast<std::string>(b), httplib::bad_any_cast);
  2474. #endif
  2475. // Copy
  2476. httplib::any c = b;
  2477. EXPECT_EQ(42, httplib::any_cast<int>(c));
  2478. // Move
  2479. httplib::any d = std::move(c);
  2480. EXPECT_EQ(42, httplib::any_cast<int>(d));
  2481. // Assignment with different type
  2482. b = std::string("hello");
  2483. EXPECT_EQ("hello", httplib::any_cast<std::string>(b));
  2484. // Reset
  2485. b.reset();
  2486. EXPECT_FALSE(b.has_value());
  2487. }
  2488. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2489. struct AuthCtx {
  2490. std::string user_id;
  2491. };
  2492. Server svr;
  2493. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2494. res.user_data["auth"] = AuthCtx{"alice"};
  2495. return Server::HandlerResponse::Unhandled;
  2496. });
  2497. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2498. auto *ctx = httplib::any_cast<AuthCtx>(&res.user_data["auth"]);
  2499. ASSERT_NE(nullptr, ctx);
  2500. res.set_content("Hello " + ctx->user_id, "text/plain");
  2501. });
  2502. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2503. auto se = detail::scope_exit([&] {
  2504. svr.stop();
  2505. thread.join();
  2506. ASSERT_FALSE(svr.is_running());
  2507. });
  2508. svr.wait_until_ready();
  2509. Client cli(HOST, PORT);
  2510. auto res = cli.Get("/me");
  2511. ASSERT_TRUE(res);
  2512. EXPECT_EQ(StatusCode::OK_200, res->status);
  2513. EXPECT_EQ("Hello alice", res->body);
  2514. }
  2515. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2516. struct RoleCtx {
  2517. std::string role;
  2518. };
  2519. Server svr;
  2520. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2521. res.user_data["role"] = RoleCtx{"admin"};
  2522. return Server::HandlerResponse::Unhandled;
  2523. });
  2524. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2525. auto *ctx = httplib::any_cast<RoleCtx>(&res.user_data["role"]);
  2526. ASSERT_NE(nullptr, ctx);
  2527. res.set_content(ctx->role, "text/plain");
  2528. });
  2529. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2530. auto se = detail::scope_exit([&] {
  2531. svr.stop();
  2532. thread.join();
  2533. ASSERT_FALSE(svr.is_running());
  2534. });
  2535. svr.wait_until_ready();
  2536. Client cli(HOST, PORT);
  2537. auto res = cli.Get("/role");
  2538. ASSERT_TRUE(res);
  2539. EXPECT_EQ(StatusCode::OK_200, res->status);
  2540. EXPECT_EQ("admin", res->body);
  2541. }
  2542. TEST(InvalidFormatTest, StatusCode) {
  2543. Server svr;
  2544. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2545. res.set_content("Hello World!\n", "text/plain");
  2546. res.status = 9999; // Status should be a three-digit code...
  2547. });
  2548. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2549. auto se = detail::scope_exit([&] {
  2550. svr.stop();
  2551. thread.join();
  2552. ASSERT_FALSE(svr.is_running());
  2553. });
  2554. svr.wait_until_ready();
  2555. {
  2556. Client cli(HOST, PORT);
  2557. auto res = cli.Get("/hi");
  2558. ASSERT_FALSE(res);
  2559. }
  2560. }
  2561. TEST(URLFragmentTest, WithFragment) {
  2562. Server svr;
  2563. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2564. EXPECT_TRUE(req.target == "/hi");
  2565. });
  2566. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2567. auto se = detail::scope_exit([&] {
  2568. svr.stop();
  2569. thread.join();
  2570. ASSERT_FALSE(svr.is_running());
  2571. });
  2572. svr.wait_until_ready();
  2573. {
  2574. Client cli(HOST, PORT);
  2575. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2576. EXPECT_TRUE(res);
  2577. EXPECT_EQ(StatusCode::OK_200, res->status);
  2578. res = cli.Get("/hi%23key1=val1=key2=val2");
  2579. EXPECT_TRUE(res);
  2580. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2581. }
  2582. }
  2583. TEST(HeaderWriter, SetHeaderWriter) {
  2584. Server svr;
  2585. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2586. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2587. return detail::write_headers(strm, hdrs);
  2588. });
  2589. svr.Get("/hi", [](const Request &req, Response &res) {
  2590. auto it = req.headers.find("CustomClientHeader");
  2591. EXPECT_TRUE(it != req.headers.end());
  2592. EXPECT_EQ(it->second, "CustomClientValue");
  2593. res.set_content("Hello World!\n", "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. {
  2603. Client cli(HOST, PORT);
  2604. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2605. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2606. return detail::write_headers(strm, hdrs);
  2607. });
  2608. auto res = cli.Get("/hi");
  2609. EXPECT_TRUE(res);
  2610. EXPECT_EQ(StatusCode::OK_200, res->status);
  2611. auto it = res->headers.find("CustomServerHeader");
  2612. EXPECT_TRUE(it != res->headers.end());
  2613. EXPECT_EQ(it->second, "CustomServerValue");
  2614. }
  2615. }
  2616. class ServerTest : public ::testing::Test {
  2617. protected:
  2618. ServerTest()
  2619. : cli_(HOST, PORT)
  2620. #ifdef CPPHTTPLIB_SSL_ENABLED
  2621. ,
  2622. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2623. #endif
  2624. {
  2625. #ifdef CPPHTTPLIB_SSL_ENABLED
  2626. cli_.enable_server_certificate_verification(false);
  2627. #endif
  2628. // Allow LARGE_DATA (100MB) responses
  2629. cli_.set_payload_max_length(200 * 1024 * 1024);
  2630. }
  2631. virtual void SetUp() {
  2632. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2633. svr_.set_payload_max_length(200 * 1024 * 1024);
  2634. svr_.set_mount_point("/", "./www");
  2635. svr_.set_mount_point("/mount", "./www2");
  2636. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2637. svr_.Get("/hi",
  2638. [&](const Request & /*req*/, Response &res) {
  2639. res.set_content("Hello World!", "text/plain");
  2640. })
  2641. .Get("/file_content",
  2642. [&](const Request & /*req*/, Response &res) {
  2643. res.set_file_content("./www/dir/test.html");
  2644. })
  2645. .Get("/file_content_with_content_type",
  2646. [&](const Request & /*req*/, Response &res) {
  2647. res.set_file_content("./www/file", "text/plain");
  2648. })
  2649. .Get("/invalid_file_content",
  2650. [&](const Request & /*req*/, Response &res) {
  2651. res.set_file_content("./www/dir/invalid_file_path");
  2652. })
  2653. .Get("/http_response_splitting",
  2654. [&](const Request & /*req*/, Response &res) {
  2655. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2656. EXPECT_EQ(0U, res.headers.size());
  2657. EXPECT_FALSE(res.has_header("a"));
  2658. res.set_header("a", "1\nSet-Cookie: a=1");
  2659. EXPECT_EQ(0U, res.headers.size());
  2660. EXPECT_FALSE(res.has_header("a"));
  2661. res.set_header("a", "1\rSet-Cookie: a=1");
  2662. EXPECT_EQ(0U, res.headers.size());
  2663. EXPECT_FALSE(res.has_header("a"));
  2664. res.set_header("a\r\nb", "0");
  2665. EXPECT_EQ(0U, res.headers.size());
  2666. EXPECT_FALSE(res.has_header("a"));
  2667. res.set_header("a\rb", "0");
  2668. EXPECT_EQ(0U, res.headers.size());
  2669. EXPECT_FALSE(res.has_header("a"));
  2670. res.set_header("a\nb", "0");
  2671. EXPECT_EQ(0U, res.headers.size());
  2672. EXPECT_FALSE(res.has_header("a"));
  2673. res.set_redirect("1\r\nSet-Cookie: a=1");
  2674. EXPECT_EQ(0U, res.headers.size());
  2675. EXPECT_FALSE(res.has_header("Location"));
  2676. })
  2677. .Get("/slow",
  2678. [&](const Request & /*req*/, Response &res) {
  2679. std::this_thread::sleep_for(std::chrono::seconds(2));
  2680. res.set_content("slow", "text/plain");
  2681. })
  2682. #if 0
  2683. .Post("/slowpost",
  2684. [&](const Request & /*req*/, Response &res) {
  2685. std::this_thread::sleep_for(std::chrono::seconds(2));
  2686. res.set_content("slow", "text/plain");
  2687. })
  2688. #endif
  2689. .Get("/remote_addr",
  2690. [&](const Request &req, Response &res) {
  2691. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2692. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2693. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2694. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2695. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2696. #endif
  2697. res.set_content(req.remote_addr, "text/plain");
  2698. })
  2699. .Get("/local_addr",
  2700. [&](const Request &req, Response &res) {
  2701. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2702. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2703. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2704. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2705. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2706. #endif
  2707. auto local_addr = req.local_addr;
  2708. auto local_port = std::to_string(req.local_port);
  2709. res.set_content(local_addr.append(":").append(local_port),
  2710. "text/plain");
  2711. })
  2712. .Get("/endwith%",
  2713. [&](const Request & /*req*/, Response &res) {
  2714. res.set_content("Hello World!", "text/plain");
  2715. })
  2716. .Get("/a\\+\\+b",
  2717. [&](const Request &req, Response &res) {
  2718. ASSERT_TRUE(req.has_param("a +b"));
  2719. auto val = req.get_param_value("a +b");
  2720. res.set_content(val, "text/plain");
  2721. })
  2722. .Get("/", [&](const Request & /*req*/,
  2723. Response &res) { res.set_redirect("/hi"); })
  2724. .Post("/1",
  2725. [](const Request & /*req*/, Response &res) {
  2726. res.set_redirect("/2", StatusCode::SeeOther_303);
  2727. })
  2728. .Get("/2",
  2729. [](const Request & /*req*/, Response &res) {
  2730. res.set_content("redirected.", "text/plain");
  2731. res.status = StatusCode::OK_200;
  2732. })
  2733. .Post("/person",
  2734. [&](const Request &req, Response &res) {
  2735. if (req.has_param("name") && req.has_param("note")) {
  2736. persons_[req.get_param_value("name")] =
  2737. req.get_param_value("note");
  2738. } else {
  2739. res.status = StatusCode::BadRequest_400;
  2740. }
  2741. })
  2742. .Put("/person",
  2743. [&](const Request &req, Response &res) {
  2744. if (req.has_param("name") && req.has_param("note")) {
  2745. persons_[req.get_param_value("name")] =
  2746. req.get_param_value("note");
  2747. } else {
  2748. res.status = StatusCode::BadRequest_400;
  2749. }
  2750. })
  2751. .Get("/person/(.*)",
  2752. [&](const Request &req, Response &res) {
  2753. string name = req.matches[1];
  2754. if (persons_.find(name) != persons_.end()) {
  2755. auto note = persons_[name];
  2756. res.set_content(note, "text/plain");
  2757. } else {
  2758. res.status = StatusCode::NotFound_404;
  2759. }
  2760. })
  2761. .Delete("/person",
  2762. [&](const Request &req, Response &res) {
  2763. if (req.has_param("name")) {
  2764. string name = req.get_param_value("name");
  2765. if (persons_.find(name) != persons_.end()) {
  2766. persons_.erase(name);
  2767. res.set_content("DELETED", "text/plain");
  2768. } else {
  2769. res.status = StatusCode::NotFound_404;
  2770. }
  2771. } else {
  2772. res.status = StatusCode::BadRequest_400;
  2773. }
  2774. })
  2775. .Post("/x-www-form-urlencoded-json",
  2776. [&](const Request &req, Response &res) {
  2777. auto json = req.get_param_value("json");
  2778. ASSERT_EQ(JSON_DATA, json);
  2779. res.set_content(json, "appliation/json");
  2780. res.status = StatusCode::OK_200;
  2781. })
  2782. .Get("/streamed-chunked",
  2783. [&](const Request & /*req*/, Response &res) {
  2784. res.set_chunked_content_provider(
  2785. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2786. sink.os << "123";
  2787. sink.os << "456";
  2788. sink.os << "789";
  2789. sink.done();
  2790. return true;
  2791. });
  2792. })
  2793. .Get("/streamed-chunked-with-prohibited-trailer",
  2794. [&](const Request & /*req*/, Response &res) {
  2795. auto i = new int(0);
  2796. // Declare both a prohibited trailer (Content-Length) and an
  2797. // allowed one
  2798. res.set_header("Trailer", "Content-Length, X-Allowed");
  2799. res.set_chunked_content_provider(
  2800. "text/plain",
  2801. [i](size_t /*offset*/, DataSink &sink) {
  2802. switch (*i) {
  2803. case 0: sink.os << "123"; break;
  2804. case 1: sink.os << "456"; break;
  2805. case 2: sink.os << "789"; break;
  2806. case 3: {
  2807. sink.done_with_trailer(
  2808. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2809. } break;
  2810. }
  2811. (*i)++;
  2812. return true;
  2813. },
  2814. [i](bool success) {
  2815. EXPECT_TRUE(success);
  2816. delete i;
  2817. });
  2818. })
  2819. .Get("/streamed-chunked2",
  2820. [&](const Request & /*req*/, Response &res) {
  2821. auto i = new int(0);
  2822. res.set_chunked_content_provider(
  2823. "text/plain",
  2824. [i](size_t /*offset*/, DataSink &sink) {
  2825. switch (*i) {
  2826. case 0: sink.os << "123"; break;
  2827. case 1: sink.os << "456"; break;
  2828. case 2: sink.os << "789"; break;
  2829. case 3: sink.done(); break;
  2830. }
  2831. (*i)++;
  2832. return true;
  2833. },
  2834. [i](bool success) {
  2835. EXPECT_TRUE(success);
  2836. delete i;
  2837. });
  2838. })
  2839. .Get("/streamed-chunked-with-trailer",
  2840. [&](const Request & /*req*/, Response &res) {
  2841. auto i = new int(0);
  2842. res.set_header("Trailer", "Dummy1, Dummy2");
  2843. res.set_chunked_content_provider(
  2844. "text/plain",
  2845. [i](size_t /*offset*/, DataSink &sink) {
  2846. switch (*i) {
  2847. case 0: sink.os << "123"; break;
  2848. case 1: sink.os << "456"; break;
  2849. case 2: sink.os << "789"; break;
  2850. case 3: {
  2851. sink.done_with_trailer(
  2852. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2853. } break;
  2854. }
  2855. (*i)++;
  2856. return true;
  2857. },
  2858. [i](bool success) {
  2859. EXPECT_TRUE(success);
  2860. delete i;
  2861. });
  2862. })
  2863. .Get("/streamed",
  2864. [&](const Request & /*req*/, Response &res) {
  2865. res.set_content_provider(
  2866. 6, "text/plain",
  2867. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2868. sink.os << (offset < 3 ? "a" : "b");
  2869. return true;
  2870. });
  2871. })
  2872. .Get("/streamed-with-range",
  2873. [&](const Request &req, Response &res) {
  2874. auto data = new std::string("abcdefg");
  2875. res.set_content_provider(
  2876. data->size(), "text/plain",
  2877. [data](size_t offset, size_t length, DataSink &sink) {
  2878. size_t DATA_CHUNK_SIZE = 4;
  2879. const auto &d = *data;
  2880. auto out_len =
  2881. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2882. auto ret =
  2883. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2884. EXPECT_TRUE(ret);
  2885. return true;
  2886. },
  2887. [data, &req](bool success) {
  2888. EXPECT_EQ(success, !req.has_param("error"));
  2889. delete data;
  2890. });
  2891. })
  2892. .Get("/streamed-cancel",
  2893. [&](const Request & /*req*/, Response &res) {
  2894. res.set_content_provider(
  2895. size_t(-1), "text/plain",
  2896. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2897. sink.os << "data_chunk";
  2898. return true;
  2899. });
  2900. })
  2901. .Get("/regex-with-delimiter",
  2902. [&](const Request &req, Response & /*res*/) {
  2903. ASSERT_TRUE(req.has_param("key"));
  2904. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2905. })
  2906. .Get("/with-range",
  2907. [&](const Request & /*req*/, Response &res) {
  2908. res.set_content("abcdefg", "text/plain");
  2909. })
  2910. .Get("/test-start-time",
  2911. [&](const Request &req, Response & /*res*/) {
  2912. EXPECT_NE(req.start_time_,
  2913. std::chrono::steady_clock::time_point::min());
  2914. })
  2915. .Get("/with-range-customized-response",
  2916. [&](const Request & /*req*/, Response &res) {
  2917. res.status = StatusCode::BadRequest_400;
  2918. res.set_content(JSON_DATA, "application/json");
  2919. })
  2920. .Post("/chunked",
  2921. [&](const Request &req, Response & /*res*/) {
  2922. EXPECT_EQ(req.body, "dechunked post body");
  2923. })
  2924. .Post("/large-chunked",
  2925. [&](const Request &req, Response & /*res*/) {
  2926. std::string expected(6 * 30 * 1024u, 'a');
  2927. EXPECT_EQ(req.body, expected);
  2928. })
  2929. .Post("/multipart",
  2930. [&](const Request &req, Response & /*res*/) {
  2931. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2932. req.form.get_field_count("text2") +
  2933. req.form.get_field_count("file3") +
  2934. req.form.get_field_count("file4"));
  2935. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2936. req.form.get_file_count("file2"));
  2937. ASSERT_TRUE(!req.form.has_file("???"));
  2938. ASSERT_TRUE(!req.form.has_field("???"));
  2939. ASSERT_TRUE(req.body.empty());
  2940. {
  2941. const auto &text = req.form.get_field("text1");
  2942. EXPECT_EQ("text default", text);
  2943. }
  2944. {
  2945. const auto &text = req.form.get_field("text2");
  2946. EXPECT_EQ("aωb", text);
  2947. }
  2948. {
  2949. const auto &file = req.form.get_file("file1");
  2950. EXPECT_EQ("hello.txt", file.filename);
  2951. EXPECT_EQ("text/plain", file.content_type);
  2952. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2953. }
  2954. {
  2955. const auto &file = req.form.get_file("file2");
  2956. EXPECT_EQ("world.json", file.filename);
  2957. EXPECT_EQ("application/json", file.content_type);
  2958. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2959. }
  2960. {
  2961. const auto &text = req.form.get_field("file3");
  2962. EXPECT_EQ(0u, text.size());
  2963. }
  2964. {
  2965. const auto &text = req.form.get_field("file4");
  2966. EXPECT_EQ(0u, text.size());
  2967. }
  2968. })
  2969. .Post("/multipart/multi_file_values",
  2970. [&](const Request &req, Response & /*res*/) {
  2971. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2972. req.form.get_field_count("multi_text1"));
  2973. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2974. ASSERT_TRUE(!req.form.has_file("???"));
  2975. ASSERT_TRUE(!req.form.has_field("???"));
  2976. ASSERT_TRUE(req.body.empty());
  2977. {
  2978. const auto &text = req.form.get_field("text");
  2979. EXPECT_EQ("default text", text);
  2980. }
  2981. {
  2982. const auto &text1_values = req.form.get_fields("multi_text1");
  2983. EXPECT_EQ(2u, text1_values.size());
  2984. EXPECT_EQ("aaaaa", text1_values[0]);
  2985. EXPECT_EQ("bbbbb", text1_values[1]);
  2986. }
  2987. {
  2988. const auto &file1_values = req.form.get_files("multi_file1");
  2989. EXPECT_EQ(2u, file1_values.size());
  2990. auto file1 = file1_values[0];
  2991. EXPECT_EQ(file1.filename, "hello.txt");
  2992. EXPECT_EQ(file1.content_type, "text/plain");
  2993. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2994. auto file2 = file1_values[1];
  2995. EXPECT_EQ(file2.filename, "world.json");
  2996. EXPECT_EQ(file2.content_type, "application/json");
  2997. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2998. }
  2999. })
  3000. .Post("/empty",
  3001. [&](const Request &req, Response &res) {
  3002. EXPECT_EQ(req.body, "");
  3003. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3004. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3005. res.set_content("empty", "text/plain");
  3006. })
  3007. .Post("/empty-no-content-type",
  3008. [&](const Request &req, Response &res) {
  3009. EXPECT_EQ(req.body, "");
  3010. EXPECT_FALSE(req.has_header("Content-Type"));
  3011. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3012. res.set_content("empty-no-content-type", "text/plain");
  3013. })
  3014. .Post("/path-only",
  3015. [&](const Request &req, Response &res) {
  3016. EXPECT_EQ(req.body, "");
  3017. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3018. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3019. res.set_content("path-only", "text/plain");
  3020. })
  3021. .Post("/path-headers-only",
  3022. [&](const Request &req, Response &res) {
  3023. EXPECT_EQ(req.body, "");
  3024. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3025. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3026. EXPECT_EQ("world", req.get_header_value("hello"));
  3027. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3028. res.set_content("path-headers-only", "text/plain");
  3029. })
  3030. .Post("/post-large",
  3031. [&](const Request &req, Response &res) {
  3032. EXPECT_EQ(req.body, LARGE_DATA);
  3033. res.set_content(req.body, "text/plain");
  3034. })
  3035. .Post("/post-loopback",
  3036. [&](const Request &, Response &res,
  3037. ContentReader const &content_reader) {
  3038. std::string body;
  3039. content_reader([&](const char *data, size_t data_length) {
  3040. body.append(data, data_length);
  3041. return true;
  3042. });
  3043. res.set_content(body, "text/plain");
  3044. })
  3045. .Put("/put-loopback",
  3046. [&](const Request &, Response &res,
  3047. ContentReader const &content_reader) {
  3048. std::string body;
  3049. content_reader([&](const char *data, size_t data_length) {
  3050. body.append(data, data_length);
  3051. return true;
  3052. });
  3053. res.set_content(body, "text/plain");
  3054. })
  3055. .Patch("/patch-loopback",
  3056. [&](const Request &, Response &res,
  3057. ContentReader const &content_reader) {
  3058. std::string body;
  3059. content_reader([&](const char *data, size_t data_length) {
  3060. body.append(data, data_length);
  3061. return true;
  3062. });
  3063. res.set_content(body, "text/plain");
  3064. })
  3065. .Put("/empty-no-content-type",
  3066. [&](const Request &req, Response &res) {
  3067. EXPECT_EQ(req.body, "");
  3068. EXPECT_FALSE(req.has_header("Content-Type"));
  3069. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3070. res.set_content("empty-no-content-type", "text/plain");
  3071. })
  3072. .Put("/put",
  3073. [&](const Request &req, Response &res) {
  3074. EXPECT_EQ(req.body, "PUT");
  3075. res.set_content(req.body, "text/plain");
  3076. })
  3077. .Put("/put-large",
  3078. [&](const Request &req, Response &res) {
  3079. EXPECT_EQ(req.body, LARGE_DATA);
  3080. res.set_content(req.body, "text/plain");
  3081. })
  3082. .Patch("/patch",
  3083. [&](const Request &req, Response &res) {
  3084. EXPECT_EQ(req.body, "PATCH");
  3085. res.set_content(req.body, "text/plain");
  3086. })
  3087. .Delete("/delete",
  3088. [&](const Request & /*req*/, Response &res) {
  3089. res.set_content("DELETE", "text/plain");
  3090. })
  3091. .Delete("/delete-body",
  3092. [&](const Request &req, Response &res) {
  3093. EXPECT_EQ(req.body, "content");
  3094. res.set_content(req.body, "text/plain");
  3095. })
  3096. .Options(R"(\*)",
  3097. [&](const Request & /*req*/, Response &res) {
  3098. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3099. })
  3100. .Get("/request-target",
  3101. [&](const Request &req, Response & /*res*/) {
  3102. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3103. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3104. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3105. })
  3106. .Get("/long-query-value",
  3107. [&](const Request &req, Response & /*res*/) {
  3108. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3109. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3110. })
  3111. .Get("/too-long-query-value",
  3112. [&](const Request &req, Response & /*res*/) {
  3113. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3114. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3115. })
  3116. .Get("/array-param",
  3117. [&](const Request &req, Response & /*res*/) {
  3118. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3119. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3120. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3121. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3122. })
  3123. .Post("/validate-no-multiple-headers",
  3124. [&](const Request &req, Response & /*res*/) {
  3125. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3126. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3127. })
  3128. .Post("/content_receiver",
  3129. [&](const Request &req, Response &res,
  3130. const ContentReader &content_reader) {
  3131. if (req.is_multipart_form_data()) {
  3132. std::vector<FormData> items;
  3133. content_reader(
  3134. [&](const FormData &file) {
  3135. items.push_back(file);
  3136. return true;
  3137. },
  3138. [&](const char *data, size_t data_length) {
  3139. items.back().content.append(data, data_length);
  3140. return true;
  3141. });
  3142. EXPECT_EQ(5u, items.size());
  3143. {
  3144. const auto &file = get_file_value(items, "text1");
  3145. EXPECT_TRUE(file.filename.empty());
  3146. EXPECT_EQ("text default", file.content);
  3147. }
  3148. {
  3149. const auto &file = get_file_value(items, "text2");
  3150. EXPECT_TRUE(file.filename.empty());
  3151. EXPECT_EQ("aωb", file.content);
  3152. }
  3153. {
  3154. const auto &file = get_file_value(items, "file1");
  3155. EXPECT_EQ("hello.txt", file.filename);
  3156. EXPECT_EQ("text/plain", file.content_type);
  3157. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3158. }
  3159. {
  3160. const auto &file = get_file_value(items, "file2");
  3161. EXPECT_EQ("world.json", file.filename);
  3162. EXPECT_EQ("application/json", file.content_type);
  3163. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3164. }
  3165. {
  3166. const auto &file = get_file_value(items, "file3");
  3167. EXPECT_TRUE(file.filename.empty());
  3168. EXPECT_EQ("application/octet-stream", file.content_type);
  3169. EXPECT_EQ(0u, file.content.size());
  3170. }
  3171. } else {
  3172. std::string body;
  3173. content_reader([&](const char *data, size_t data_length) {
  3174. EXPECT_EQ(7U, data_length);
  3175. body.append(data, data_length);
  3176. return true;
  3177. });
  3178. EXPECT_EQ(body, "content");
  3179. res.set_content(body, "text/plain");
  3180. }
  3181. })
  3182. .Put("/content_receiver",
  3183. [&](const Request & /*req*/, Response &res,
  3184. const ContentReader &content_reader) {
  3185. std::string body;
  3186. content_reader([&](const char *data, size_t data_length) {
  3187. body.append(data, data_length);
  3188. return true;
  3189. });
  3190. EXPECT_EQ(body, "content");
  3191. res.set_content(body, "text/plain");
  3192. })
  3193. .Patch("/content_receiver",
  3194. [&](const Request & /*req*/, Response &res,
  3195. const ContentReader &content_reader) {
  3196. std::string body;
  3197. content_reader([&](const char *data, size_t data_length) {
  3198. body.append(data, data_length);
  3199. return true;
  3200. });
  3201. EXPECT_EQ(body, "content");
  3202. res.set_content(body, "text/plain");
  3203. })
  3204. .Post("/query-string-and-body",
  3205. [&](const Request &req, Response & /*res*/) {
  3206. ASSERT_TRUE(req.has_param("key"));
  3207. EXPECT_EQ(req.get_param_value("key"), "value");
  3208. EXPECT_EQ(req.body, "content");
  3209. })
  3210. .Get("/last-request",
  3211. [&](const Request &req, Response & /*res*/) {
  3212. EXPECT_EQ("close", req.get_header_value("Connection"));
  3213. })
  3214. .Get(R"(/redirect/(\d+))",
  3215. [&](const Request &req, Response &res) {
  3216. auto num = std::stoi(req.matches[1]) + 1;
  3217. std::string url = "/redirect/" + std::to_string(num);
  3218. res.set_redirect(url);
  3219. })
  3220. .Post("/binary",
  3221. [&](const Request &req, Response &res) {
  3222. EXPECT_EQ(4U, req.body.size());
  3223. EXPECT_EQ("application/octet-stream",
  3224. req.get_header_value("Content-Type"));
  3225. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3226. res.set_content(req.body, "application/octet-stream");
  3227. })
  3228. .Put("/binary",
  3229. [&](const Request &req, Response &res) {
  3230. EXPECT_EQ(4U, req.body.size());
  3231. EXPECT_EQ("application/octet-stream",
  3232. req.get_header_value("Content-Type"));
  3233. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3234. res.set_content(req.body, "application/octet-stream");
  3235. })
  3236. .Patch("/binary",
  3237. [&](const Request &req, Response &res) {
  3238. EXPECT_EQ(4U, req.body.size());
  3239. EXPECT_EQ("application/octet-stream",
  3240. req.get_header_value("Content-Type"));
  3241. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3242. res.set_content(req.body, "application/octet-stream");
  3243. })
  3244. .Delete("/binary",
  3245. [&](const Request &req, Response &res) {
  3246. EXPECT_EQ(4U, req.body.size());
  3247. EXPECT_EQ("application/octet-stream",
  3248. req.get_header_value("Content-Type"));
  3249. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3250. res.set_content(req.body, "application/octet-stream");
  3251. })
  3252. .Get("/issue1772",
  3253. [&](const Request & /*req*/, Response &res) {
  3254. res.status = 401;
  3255. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3256. })
  3257. .Delete("/issue609",
  3258. [](const httplib::Request &, httplib::Response &res,
  3259. const httplib::ContentReader &) {
  3260. res.set_content("ok", "text/plain");
  3261. })
  3262. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3263. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3264. .Get("/compress",
  3265. [&](const Request & /*req*/, Response &res) {
  3266. res.set_content(
  3267. "12345678901234567890123456789012345678901234567890123456789"
  3268. "01234567890123456789012345678901234567890",
  3269. "text/plain");
  3270. })
  3271. .Get("/nocompress",
  3272. [&](const Request & /*req*/, Response &res) {
  3273. res.set_content(
  3274. "12345678901234567890123456789012345678901234567890123456789"
  3275. "01234567890123456789012345678901234567890",
  3276. "application/octet-stream");
  3277. })
  3278. .Post("/compress-multipart",
  3279. [&](const Request &req, Response & /*res*/) {
  3280. EXPECT_EQ(2u, req.form.fields.size());
  3281. ASSERT_TRUE(!req.form.has_field("???"));
  3282. {
  3283. const auto &text = req.form.get_field("key1");
  3284. EXPECT_EQ("test", text);
  3285. }
  3286. {
  3287. const auto &text = req.form.get_field("key2");
  3288. EXPECT_EQ("--abcdefg123", text);
  3289. }
  3290. })
  3291. #endif
  3292. ;
  3293. persons_["john"] = "programmer";
  3294. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3295. svr_.wait_until_ready();
  3296. }
  3297. virtual void TearDown() {
  3298. svr_.stop();
  3299. if (!request_threads_.empty()) {
  3300. std::this_thread::sleep_for(std::chrono::seconds(1));
  3301. for (auto &t : request_threads_) {
  3302. t.join();
  3303. }
  3304. }
  3305. t_.join();
  3306. }
  3307. map<string, string> persons_;
  3308. #ifdef CPPHTTPLIB_SSL_ENABLED
  3309. SSLClient cli_;
  3310. SSLServer svr_;
  3311. #else
  3312. Client cli_;
  3313. Server svr_;
  3314. #endif
  3315. thread t_;
  3316. std::vector<thread> request_threads_;
  3317. };
  3318. TEST_F(ServerTest, GetMethod200) {
  3319. auto res = cli_.Get("/hi");
  3320. ASSERT_TRUE(res);
  3321. EXPECT_EQ("HTTP/1.1", res->version);
  3322. EXPECT_EQ(StatusCode::OK_200, res->status);
  3323. EXPECT_EQ("OK", res->reason);
  3324. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3325. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3326. EXPECT_EQ("Hello World!", res->body);
  3327. }
  3328. TEST_F(ServerTest, GetEmptyFile) {
  3329. auto res = cli_.Get("/empty_file");
  3330. ASSERT_TRUE(res);
  3331. EXPECT_EQ(StatusCode::OK_200, res->status);
  3332. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3333. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3334. EXPECT_EQ("", res->body);
  3335. }
  3336. TEST_F(ServerTest, GetFileContent) {
  3337. auto res = cli_.Get("/file_content");
  3338. ASSERT_TRUE(res);
  3339. EXPECT_EQ(StatusCode::OK_200, res->status);
  3340. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3341. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3342. EXPECT_EQ("test.html", res->body);
  3343. }
  3344. TEST_F(ServerTest, GetFileContentWithRange) {
  3345. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3346. ASSERT_TRUE(res);
  3347. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3348. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3349. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3350. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3351. EXPECT_EQ("est", res->body);
  3352. }
  3353. TEST_F(ServerTest, GetFileContentWithContentType) {
  3354. auto res = cli_.Get("/file_content_with_content_type");
  3355. ASSERT_TRUE(res);
  3356. EXPECT_EQ(StatusCode::OK_200, res->status);
  3357. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3358. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3359. EXPECT_EQ("file\n", res->body);
  3360. }
  3361. TEST_F(ServerTest, GetInvalidFileContent) {
  3362. auto res = cli_.Get("/invalid_file_content");
  3363. ASSERT_TRUE(res);
  3364. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3365. }
  3366. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3367. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3368. ASSERT_TRUE(res);
  3369. EXPECT_EQ("HTTP/1.1", res->version);
  3370. EXPECT_EQ(StatusCode::OK_200, res->status);
  3371. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3372. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3373. EXPECT_EQ("Hello World!", res->body);
  3374. }
  3375. TEST_F(ServerTest, GetMethod302) {
  3376. auto res = cli_.Get("/");
  3377. ASSERT_TRUE(res);
  3378. EXPECT_EQ(StatusCode::Found_302, res->status);
  3379. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3380. }
  3381. TEST_F(ServerTest, GetMethod302Redirect) {
  3382. cli_.set_follow_location(true);
  3383. auto res = cli_.Get("/");
  3384. ASSERT_TRUE(res);
  3385. EXPECT_EQ(StatusCode::OK_200, res->status);
  3386. EXPECT_EQ("Hello World!", res->body);
  3387. EXPECT_EQ("/hi", res->location);
  3388. }
  3389. TEST_F(ServerTest, GetMethod404) {
  3390. auto res = cli_.Get("/invalid");
  3391. ASSERT_TRUE(res);
  3392. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3393. }
  3394. TEST_F(ServerTest, HeadMethod200) {
  3395. auto res = cli_.Head("/hi");
  3396. ASSERT_TRUE(res);
  3397. EXPECT_EQ(StatusCode::OK_200, res->status);
  3398. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3399. EXPECT_TRUE(res->body.empty());
  3400. }
  3401. TEST_F(ServerTest, HeadMethod200Static) {
  3402. auto res = cli_.Head("/mount/dir/index.html");
  3403. ASSERT_TRUE(res);
  3404. EXPECT_EQ(StatusCode::OK_200, res->status);
  3405. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3406. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3407. EXPECT_TRUE(res->body.empty());
  3408. }
  3409. TEST_F(ServerTest, HeadMethod404) {
  3410. auto res = cli_.Head("/invalid");
  3411. ASSERT_TRUE(res);
  3412. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3413. EXPECT_TRUE(res->body.empty());
  3414. }
  3415. TEST_F(ServerTest, GetMethodPersonJohn) {
  3416. auto res = cli_.Get("/person/john");
  3417. ASSERT_TRUE(res);
  3418. EXPECT_EQ(StatusCode::OK_200, res->status);
  3419. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3420. EXPECT_EQ("programmer", res->body);
  3421. }
  3422. TEST_F(ServerTest, PostMethod1) {
  3423. auto res = cli_.Get("/person/john1");
  3424. ASSERT_TRUE(res);
  3425. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3426. res = cli_.Post("/person", "name=john1&note=coder",
  3427. "application/x-www-form-urlencoded");
  3428. ASSERT_TRUE(res);
  3429. ASSERT_EQ(StatusCode::OK_200, res->status);
  3430. res = cli_.Get("/person/john1");
  3431. ASSERT_TRUE(res);
  3432. ASSERT_EQ(StatusCode::OK_200, res->status);
  3433. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3434. ASSERT_EQ("coder", res->body);
  3435. }
  3436. TEST_F(ServerTest, PostMethod2) {
  3437. auto res = cli_.Get("/person/john2");
  3438. ASSERT_TRUE(res);
  3439. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3440. Params params;
  3441. params.emplace("name", "john2");
  3442. params.emplace("note", "coder");
  3443. res = cli_.Post("/person", params);
  3444. ASSERT_TRUE(res);
  3445. ASSERT_EQ(StatusCode::OK_200, res->status);
  3446. res = cli_.Get("/person/john2");
  3447. ASSERT_TRUE(res);
  3448. ASSERT_EQ(StatusCode::OK_200, res->status);
  3449. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3450. ASSERT_EQ("coder", res->body);
  3451. }
  3452. TEST_F(ServerTest, PutMethod3) {
  3453. auto res = cli_.Get("/person/john3");
  3454. ASSERT_TRUE(res);
  3455. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3456. Params params;
  3457. params.emplace("name", "john3");
  3458. params.emplace("note", "coder");
  3459. res = cli_.Put("/person", params);
  3460. ASSERT_TRUE(res);
  3461. ASSERT_EQ(StatusCode::OK_200, res->status);
  3462. res = cli_.Get("/person/john3");
  3463. ASSERT_TRUE(res);
  3464. ASSERT_EQ(StatusCode::OK_200, res->status);
  3465. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3466. ASSERT_EQ("coder", res->body);
  3467. }
  3468. TEST_F(ServerTest, DeleteMethod1) {
  3469. auto res = cli_.Get("/person/john4");
  3470. ASSERT_TRUE(res);
  3471. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3472. Params params;
  3473. params.emplace("name", "john4");
  3474. params.emplace("note", "coder");
  3475. res = cli_.Post("/person", params);
  3476. ASSERT_TRUE(res);
  3477. ASSERT_EQ(StatusCode::OK_200, res->status);
  3478. res = cli_.Get("/person/john4");
  3479. ASSERT_TRUE(res);
  3480. ASSERT_EQ(StatusCode::OK_200, res->status);
  3481. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3482. ASSERT_EQ("coder", res->body);
  3483. Params delete_params;
  3484. delete_params.emplace("name", "john4");
  3485. res = cli_.Delete("/person", delete_params);
  3486. ASSERT_TRUE(res);
  3487. ASSERT_EQ(StatusCode::OK_200, res->status);
  3488. ASSERT_EQ("DELETED", res->body);
  3489. res = cli_.Get("/person/john4");
  3490. ASSERT_TRUE(res);
  3491. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3492. }
  3493. TEST_F(ServerTest, DeleteMethod2) {
  3494. auto res = cli_.Get("/person/john5");
  3495. ASSERT_TRUE(res);
  3496. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3497. Params params;
  3498. params.emplace("name", "john5");
  3499. params.emplace("note", "developer");
  3500. res = cli_.Post("/person", params);
  3501. ASSERT_TRUE(res);
  3502. ASSERT_EQ(StatusCode::OK_200, res->status);
  3503. res = cli_.Get("/person/john5");
  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("developer", res->body);
  3508. Params delete_params;
  3509. delete_params.emplace("name", "john5");
  3510. Headers headers;
  3511. headers.emplace("Custom-Header", "test-value");
  3512. res = cli_.Delete("/person", headers, delete_params);
  3513. ASSERT_TRUE(res);
  3514. ASSERT_EQ(StatusCode::OK_200, res->status);
  3515. ASSERT_EQ("DELETED", res->body);
  3516. res = cli_.Get("/person/john5");
  3517. ASSERT_TRUE(res);
  3518. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3519. }
  3520. TEST_F(ServerTest, DeleteMethod3) {
  3521. auto res = cli_.Get("/person/john6");
  3522. ASSERT_TRUE(res);
  3523. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3524. Params params;
  3525. params.emplace("name", "john6");
  3526. params.emplace("note", "tester");
  3527. res = cli_.Post("/person", params);
  3528. ASSERT_TRUE(res);
  3529. ASSERT_EQ(StatusCode::OK_200, res->status);
  3530. res = cli_.Get("/person/john6");
  3531. ASSERT_TRUE(res);
  3532. ASSERT_EQ(StatusCode::OK_200, res->status);
  3533. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3534. ASSERT_EQ("tester", res->body);
  3535. Params delete_params;
  3536. delete_params.emplace("name", "john6");
  3537. Headers headers;
  3538. headers.emplace("Custom-Header", "test-value");
  3539. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3540. ASSERT_TRUE(res);
  3541. ASSERT_EQ(StatusCode::OK_200, res->status);
  3542. ASSERT_EQ("DELETED", res->body);
  3543. res = cli_.Get("/person/john6");
  3544. ASSERT_TRUE(res);
  3545. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3546. }
  3547. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3548. Params params;
  3549. params.emplace("json", JSON_DATA);
  3550. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3551. ASSERT_TRUE(res);
  3552. ASSERT_EQ(StatusCode::OK_200, res->status);
  3553. ASSERT_EQ(JSON_DATA, res->body);
  3554. }
  3555. TEST_F(ServerTest, PostEmptyContent) {
  3556. auto res = cli_.Post("/empty", "", "text/plain");
  3557. ASSERT_TRUE(res);
  3558. ASSERT_EQ(StatusCode::OK_200, res->status);
  3559. ASSERT_EQ("empty", res->body);
  3560. }
  3561. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3562. auto res = cli_.Post("/empty-no-content-type");
  3563. ASSERT_TRUE(res);
  3564. ASSERT_EQ(StatusCode::OK_200, res->status);
  3565. ASSERT_EQ("empty-no-content-type", res->body);
  3566. }
  3567. TEST_F(ServerTest, PostPathOnly) {
  3568. auto res = cli_.Post("/path-only");
  3569. ASSERT_TRUE(res);
  3570. ASSERT_EQ(StatusCode::OK_200, res->status);
  3571. ASSERT_EQ("path-only", res->body);
  3572. }
  3573. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3574. auto res = cli_.Post("/path-headers-only",
  3575. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3576. ASSERT_TRUE(res);
  3577. ASSERT_EQ(StatusCode::OK_200, res->status);
  3578. ASSERT_EQ("path-headers-only", res->body);
  3579. }
  3580. TEST_F(ServerTest, PostLarge) {
  3581. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3582. ASSERT_TRUE(res);
  3583. ASSERT_EQ(StatusCode::OK_200, res->status);
  3584. EXPECT_EQ(LARGE_DATA, res->body);
  3585. }
  3586. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3587. auto res = cli_.Put("/empty-no-content-type");
  3588. ASSERT_TRUE(res);
  3589. ASSERT_EQ(StatusCode::OK_200, res->status);
  3590. ASSERT_EQ("empty-no-content-type", res->body);
  3591. }
  3592. TEST_F(ServerTest, GetMethodDir) {
  3593. auto res = cli_.Get("/dir/");
  3594. ASSERT_TRUE(res);
  3595. EXPECT_EQ(StatusCode::OK_200, res->status);
  3596. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3597. auto body = R"(<html>
  3598. <head>
  3599. </head>
  3600. <body>
  3601. <a href="/dir/test.html">Test</a>
  3602. <a href="/hi">hi</a>
  3603. </body>
  3604. </html>
  3605. )";
  3606. EXPECT_EQ(body, res->body);
  3607. }
  3608. TEST_F(ServerTest, GetMethodDirTest) {
  3609. auto res = cli_.Get("/dir/test.html");
  3610. ASSERT_TRUE(res);
  3611. EXPECT_EQ(StatusCode::OK_200, res->status);
  3612. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3613. EXPECT_EQ("test.html", res->body);
  3614. }
  3615. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3616. auto res = cli_.Get("/dir/../dir/test.html");
  3617. ASSERT_TRUE(res);
  3618. EXPECT_EQ(StatusCode::OK_200, res->status);
  3619. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3620. EXPECT_EQ("test.html", res->body);
  3621. }
  3622. TEST_F(ServerTest, GetMethodInvalidPath) {
  3623. auto res = cli_.Get("/dir/../test.html");
  3624. ASSERT_TRUE(res);
  3625. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3626. }
  3627. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3628. auto res = cli_.Get("/../www/dir/test.html");
  3629. ASSERT_TRUE(res);
  3630. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3631. }
  3632. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3633. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3634. ASSERT_TRUE(res);
  3635. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3636. }
  3637. TEST_F(ServerTest, GetMethodDirMountTest) {
  3638. auto res = cli_.Get("/mount/dir/test.html");
  3639. ASSERT_TRUE(res);
  3640. EXPECT_EQ(StatusCode::OK_200, res->status);
  3641. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3642. EXPECT_EQ("test.html", res->body);
  3643. }
  3644. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3645. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3646. ASSERT_TRUE(res);
  3647. EXPECT_EQ(StatusCode::OK_200, res->status);
  3648. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3649. EXPECT_EQ("test.html", res->body);
  3650. }
  3651. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3652. auto res = cli_.Get("/mount/dir/../test.html");
  3653. ASSERT_TRUE(res);
  3654. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3655. }
  3656. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3657. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3658. ASSERT_TRUE(res);
  3659. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3660. }
  3661. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3662. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3663. ASSERT_TRUE(res);
  3664. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3665. }
  3666. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3667. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3668. ASSERT_TRUE(res);
  3669. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3670. }
  3671. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3672. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3673. ASSERT_TRUE(res);
  3674. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3675. }
  3676. TEST_F(ServerTest, PostMethod303) {
  3677. auto res = cli_.Post("/1", "body", "text/plain");
  3678. ASSERT_TRUE(res);
  3679. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3680. EXPECT_EQ("/2", res->get_header_value("Location"));
  3681. }
  3682. TEST_F(ServerTest, PostMethod303Redirect) {
  3683. cli_.set_follow_location(true);
  3684. auto res = cli_.Post("/1", "body", "text/plain");
  3685. ASSERT_TRUE(res);
  3686. EXPECT_EQ(StatusCode::OK_200, res->status);
  3687. EXPECT_EQ("redirected.", res->body);
  3688. EXPECT_EQ("/2", res->location);
  3689. }
  3690. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3691. auto res = cli_.Get("/dir/test.abcde");
  3692. ASSERT_TRUE(res);
  3693. EXPECT_EQ(StatusCode::OK_200, res->status);
  3694. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3695. EXPECT_EQ("abcde", res->body);
  3696. }
  3697. TEST_F(ServerTest, StaticFileRange) {
  3698. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3699. ASSERT_TRUE(res);
  3700. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3701. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3702. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3703. EXPECT_EQ(true, res->has_header("Content-Range"));
  3704. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3705. EXPECT_EQ(std::string("cd"), res->body);
  3706. }
  3707. TEST_F(ServerTest, StaticFileRanges) {
  3708. auto res =
  3709. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3710. ASSERT_TRUE(res);
  3711. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3712. EXPECT_TRUE(
  3713. res->get_header_value("Content-Type")
  3714. .find(
  3715. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3716. 0);
  3717. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3718. }
  3719. TEST_F(ServerTest, StaticFileRangeHead) {
  3720. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3721. ASSERT_TRUE(res);
  3722. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3723. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3724. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3725. EXPECT_EQ(true, res->has_header("Content-Range"));
  3726. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3727. }
  3728. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3729. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3730. ASSERT_TRUE(res);
  3731. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3732. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3733. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3734. EXPECT_EQ(true, res->has_header("Content-Range"));
  3735. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3736. res->get_header_value("Content-Range"));
  3737. EXPECT_EQ("LAST\n", res->body);
  3738. }
  3739. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3740. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3741. ASSERT_TRUE(res);
  3742. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3743. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3744. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3745. EXPECT_EQ(true, res->has_header("Content-Range"));
  3746. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3747. }
  3748. TEST_F(ServerTest, StaticFileBigFile) {
  3749. auto res = cli_.Get("/dir/1MB.txt");
  3750. ASSERT_TRUE(res);
  3751. EXPECT_EQ(StatusCode::OK_200, res->status);
  3752. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3753. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3754. }
  3755. TEST_F(ServerTest, InvalidBaseDirMount) {
  3756. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3757. }
  3758. TEST_F(ServerTest, Binary) {
  3759. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3760. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3761. "application/octet-stream");
  3762. ASSERT_TRUE(res);
  3763. ASSERT_EQ(StatusCode::OK_200, res->status);
  3764. ASSERT_EQ(4U, res->body.size());
  3765. res = cli_.Put("/binary", binary.data(), binary.size(),
  3766. "application/octet-stream");
  3767. ASSERT_TRUE(res);
  3768. ASSERT_EQ(StatusCode::OK_200, res->status);
  3769. ASSERT_EQ(4U, res->body.size());
  3770. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3771. "application/octet-stream");
  3772. ASSERT_TRUE(res);
  3773. ASSERT_EQ(StatusCode::OK_200, res->status);
  3774. ASSERT_EQ(4U, res->body.size());
  3775. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3776. "application/octet-stream");
  3777. ASSERT_TRUE(res);
  3778. ASSERT_EQ(StatusCode::OK_200, res->status);
  3779. ASSERT_EQ(4U, res->body.size());
  3780. }
  3781. TEST_F(ServerTest, BinaryString) {
  3782. auto binary = std::string("\x00\x01\x02\x03", 4);
  3783. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3784. ASSERT_TRUE(res);
  3785. ASSERT_EQ(StatusCode::OK_200, res->status);
  3786. ASSERT_EQ(4U, res->body.size());
  3787. res = cli_.Put("/binary", binary, "application/octet-stream");
  3788. ASSERT_TRUE(res);
  3789. ASSERT_EQ(StatusCode::OK_200, res->status);
  3790. ASSERT_EQ(4U, res->body.size());
  3791. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3792. ASSERT_TRUE(res);
  3793. ASSERT_EQ(StatusCode::OK_200, res->status);
  3794. ASSERT_EQ(4U, res->body.size());
  3795. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3796. ASSERT_TRUE(res);
  3797. ASSERT_EQ(StatusCode::OK_200, res->status);
  3798. ASSERT_EQ(4U, res->body.size());
  3799. }
  3800. TEST_F(ServerTest, EmptyRequest) {
  3801. auto res = cli_.Get("");
  3802. ASSERT_TRUE(!res);
  3803. EXPECT_EQ(Error::Connection, res.error());
  3804. }
  3805. TEST_F(ServerTest, LongRequest) {
  3806. std::string request;
  3807. for (size_t i = 0; i < 545; i++) {
  3808. request += "/TooLongRequest";
  3809. }
  3810. request += "OK";
  3811. auto res = cli_.Get(request.c_str());
  3812. ASSERT_TRUE(res);
  3813. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3814. }
  3815. TEST_F(ServerTest, TooLongRequest) {
  3816. std::string request;
  3817. for (size_t i = 0; i < 546; i++) {
  3818. request += "/TooLongRequest";
  3819. }
  3820. request += "_NG";
  3821. auto start = std::chrono::high_resolution_clock::now();
  3822. cli_.set_keep_alive(true);
  3823. auto res = cli_.Get(request.c_str());
  3824. auto end = std::chrono::high_resolution_clock::now();
  3825. auto elapsed =
  3826. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3827. .count();
  3828. ASSERT_TRUE(res);
  3829. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3830. EXPECT_LE(elapsed, 1000);
  3831. EXPECT_EQ("close", res->get_header_value("Connection"));
  3832. EXPECT_FALSE(cli_.is_socket_open());
  3833. }
  3834. TEST_F(ServerTest, AlmostTooLongRequest) {
  3835. // test for #2046 - URI length check shouldn't include other content on req
  3836. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3837. // leading /, space, HTTP/1.1)
  3838. std::string request =
  3839. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3840. auto res = cli_.Get(request.c_str());
  3841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3842. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3843. }
  3844. TEST_F(ServerTest, LongHeader) {
  3845. Request req;
  3846. req.method = "GET";
  3847. req.path = "/hi";
  3848. std::string host_and_port;
  3849. host_and_port += HOST;
  3850. host_and_port += ":";
  3851. host_and_port += std::to_string(PORT);
  3852. req.headers.emplace("Host", host_and_port.c_str());
  3853. req.headers.emplace("Accept", "*/*");
  3854. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3855. req.headers.emplace(
  3856. "Header-Name",
  3857. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3858. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3859. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3860. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3861. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3862. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3863. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3864. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3865. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3866. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3867. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3868. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3869. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3870. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3871. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3872. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3873. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3874. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3875. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3876. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3877. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3878. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3879. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3880. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3881. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3882. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3883. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3884. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3885. "@@@@@@@@@@@@@@@@");
  3886. auto res = std::make_shared<Response>();
  3887. auto error = Error::Success;
  3888. auto ret = cli_.send(req, *res, error);
  3889. ASSERT_TRUE(ret);
  3890. EXPECT_EQ(StatusCode::OK_200, res->status);
  3891. }
  3892. TEST_F(ServerTest, LongQueryValue) {
  3893. auto start = std::chrono::high_resolution_clock::now();
  3894. cli_.set_keep_alive(true);
  3895. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3896. auto end = std::chrono::high_resolution_clock::now();
  3897. auto elapsed =
  3898. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3899. .count();
  3900. ASSERT_TRUE(res);
  3901. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3902. EXPECT_LE(elapsed, 1000);
  3903. EXPECT_EQ("close", res->get_header_value("Connection"));
  3904. EXPECT_FALSE(cli_.is_socket_open());
  3905. }
  3906. TEST_F(ServerTest, TooLongQueryValue) {
  3907. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3908. ASSERT_FALSE(res);
  3909. EXPECT_EQ(Error::Read, res.error());
  3910. }
  3911. TEST_F(ServerTest, TooLongHeader) {
  3912. Request req;
  3913. req.method = "GET";
  3914. req.path = "/hi";
  3915. std::string host_and_port;
  3916. host_and_port += HOST;
  3917. host_and_port += ":";
  3918. host_and_port += std::to_string(PORT);
  3919. req.headers.emplace("Host", host_and_port.c_str());
  3920. req.headers.emplace("Accept", "*/*");
  3921. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3922. req.headers.emplace(
  3923. "Header-Name",
  3924. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3925. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3926. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3927. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3928. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3929. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3930. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3931. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3932. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3933. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3934. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3935. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3936. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3937. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3938. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3939. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3940. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3941. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3942. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3943. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3944. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3945. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3946. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3947. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3948. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3949. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3950. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3951. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3952. "@@@@@@@@@@@@@@@@@");
  3953. auto res = std::make_shared<Response>();
  3954. auto error = Error::Success;
  3955. auto ret = cli_.send(req, *res, error);
  3956. ASSERT_TRUE(ret);
  3957. EXPECT_EQ(StatusCode::OK_200, res->status);
  3958. }
  3959. TEST_F(ServerTest, HeaderCountAtLimit) {
  3960. // Test with headers just under the 100 limit
  3961. httplib::Headers headers;
  3962. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3963. // This should keep us just under the 100 header limit
  3964. for (int i = 0; i < 95; i++) {
  3965. std::string name = "X-Test-Header-" + std::to_string(i);
  3966. std::string value = "value" + std::to_string(i);
  3967. headers.emplace(name, value);
  3968. }
  3969. // This should work fine as we're under the limit
  3970. auto res = cli_.Get("/hi", headers);
  3971. EXPECT_TRUE(res);
  3972. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3973. }
  3974. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3975. // Test with many headers to exceed the 100 limit
  3976. httplib::Headers headers;
  3977. // Add 150 headers to definitely exceed the 100 limit
  3978. for (int i = 0; i < 150; i++) {
  3979. std::string name = "X-Test-Header-" + std::to_string(i);
  3980. std::string value = "value" + std::to_string(i);
  3981. headers.emplace(name, value);
  3982. }
  3983. // This should fail due to exceeding header count limit
  3984. cli_.set_keep_alive(true);
  3985. auto res = cli_.Get("/hi", headers);
  3986. // The server should respond with 400 Bad Request
  3987. ASSERT_TRUE(res);
  3988. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3989. EXPECT_EQ("close", res->get_header_value("Connection"));
  3990. EXPECT_FALSE(cli_.is_socket_open());
  3991. }
  3992. TEST_F(ServerTest, PercentEncoding) {
  3993. auto res = cli_.Get("/e%6edwith%");
  3994. ASSERT_TRUE(res);
  3995. EXPECT_EQ(StatusCode::OK_200, res->status);
  3996. }
  3997. TEST_F(ServerTest, PercentEncodingUnicode) {
  3998. auto res = cli_.Get("/e%u006edwith%");
  3999. ASSERT_TRUE(res);
  4000. EXPECT_EQ(StatusCode::OK_200, res->status);
  4001. }
  4002. TEST_F(ServerTest, InvalidPercentEncoding) {
  4003. auto res = cli_.Get("/%endwith%");
  4004. ASSERT_TRUE(res);
  4005. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4006. }
  4007. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4008. auto res = cli_.Get("/%uendwith%");
  4009. ASSERT_TRUE(res);
  4010. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4011. }
  4012. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4013. auto res = cli_.Get("/hello?aaa=bbb%");
  4014. ASSERT_TRUE(res);
  4015. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4016. }
  4017. TEST_F(ServerTest, PlusSignEncoding) {
  4018. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4019. ASSERT_TRUE(res);
  4020. EXPECT_EQ(StatusCode::OK_200, res->status);
  4021. EXPECT_EQ("a +b", res->body);
  4022. }
  4023. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4024. // This test simulates a potential DoS attack using many headers
  4025. // to verify our security fix prevents memory exhaustion
  4026. httplib::Headers attack_headers;
  4027. // Attempt to add many headers like an attacker would (200 headers to far
  4028. // exceed limit)
  4029. for (int i = 0; i < 200; i++) {
  4030. std::string name = "X-Attack-Header-" + std::to_string(i);
  4031. std::string value = "attack_payload_" + std::to_string(i);
  4032. attack_headers.emplace(name, value);
  4033. }
  4034. // Try to POST with excessive headers
  4035. cli_.set_keep_alive(true);
  4036. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4037. // Should either fail or return 400 Bad Request due to security limit
  4038. if (res) {
  4039. // If we get a response, it should be 400 Bad Request
  4040. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4041. EXPECT_EQ("close", res->get_header_value("Connection"));
  4042. }
  4043. EXPECT_FALSE(cli_.is_socket_open());
  4044. }
  4045. TEST_F(ServerTest, MultipartFormData) {
  4046. UploadFormDataItems items = {
  4047. {"text1", "text default", "", ""},
  4048. {"text2", "aωb", "", ""},
  4049. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4050. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4051. {"file3", "", "", "application/octet-stream"},
  4052. {"file4", "", "", " application/json tmp-string "}};
  4053. auto res = cli_.Post("/multipart", items);
  4054. ASSERT_TRUE(res);
  4055. EXPECT_EQ(StatusCode::OK_200, res->status);
  4056. }
  4057. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4058. UploadFormDataItems items = {
  4059. {"text", "default text", "", ""},
  4060. {"multi_text1", "aaaaa", "", ""},
  4061. {"multi_text1", "bbbbb", "", ""},
  4062. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4063. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4064. "application/json"},
  4065. };
  4066. auto res = cli_.Post("/multipart/multi_file_values", items);
  4067. ASSERT_TRUE(res);
  4068. EXPECT_EQ(StatusCode::OK_200, res->status);
  4069. }
  4070. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4071. auto res = cli_.Get("/hi");
  4072. ASSERT_TRUE(res);
  4073. EXPECT_EQ(StatusCode::OK_200, res->status);
  4074. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4075. EXPECT_EQ("Hello World!", res->body);
  4076. }
  4077. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4078. Request req;
  4079. req.method = "POST";
  4080. req.path = "/chunked";
  4081. std::string host_and_port;
  4082. host_and_port += HOST;
  4083. host_and_port += ":";
  4084. host_and_port += std::to_string(PORT);
  4085. req.headers.emplace("Host", host_and_port.c_str());
  4086. req.headers.emplace("Accept", "*/*");
  4087. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4088. req.headers.emplace("Content-Type", "text/plain");
  4089. req.headers.emplace("Content-Length", "0");
  4090. req.headers.emplace(
  4091. "Transfer-Encoding",
  4092. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4093. // Client does not chunk, so make a chunked body manually.
  4094. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4095. auto res = std::make_shared<Response>();
  4096. auto error = Error::Success;
  4097. auto ret = cli_.send(req, *res, error);
  4098. ASSERT_TRUE(ret);
  4099. EXPECT_EQ(StatusCode::OK_200, res->status);
  4100. }
  4101. TEST_F(ServerTest, GetStreamed2) {
  4102. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4103. ASSERT_TRUE(res);
  4104. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4105. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4106. EXPECT_EQ(true, res->has_header("Content-Range"));
  4107. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4108. EXPECT_EQ(std::string("ab"), res->body);
  4109. }
  4110. TEST_F(ServerTest, GetStreamed) {
  4111. auto res = cli_.Get("/streamed");
  4112. ASSERT_TRUE(res);
  4113. EXPECT_EQ(StatusCode::OK_200, res->status);
  4114. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4115. EXPECT_EQ(std::string("aaabbb"), res->body);
  4116. }
  4117. TEST_F(ServerTest, GetStreamedWithRange1) {
  4118. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4119. ASSERT_TRUE(res);
  4120. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4121. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4122. EXPECT_EQ(true, res->has_header("Content-Range"));
  4123. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4124. EXPECT_EQ(std::string("def"), res->body);
  4125. }
  4126. TEST_F(ServerTest, GetStreamedWithRange2) {
  4127. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4128. ASSERT_TRUE(res);
  4129. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4130. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4131. EXPECT_EQ(true, res->has_header("Content-Range"));
  4132. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4133. EXPECT_EQ(std::string("bcdefg"), res->body);
  4134. }
  4135. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4136. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4137. ASSERT_TRUE(res);
  4138. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4139. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4140. EXPECT_EQ(true, res->has_header("Content-Range"));
  4141. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4142. EXPECT_EQ(std::string("efg"), res->body);
  4143. }
  4144. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4145. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4146. ASSERT_TRUE(res);
  4147. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4148. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4149. EXPECT_EQ(false, res->has_header("Content-Range"));
  4150. EXPECT_EQ(0U, res->body.size());
  4151. }
  4152. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4153. auto res = cli_.Get("/streamed-with-range",
  4154. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4155. "92233720368547758079223372036854775807"}});
  4156. ASSERT_TRUE(res);
  4157. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4158. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4159. EXPECT_EQ(false, res->has_header("Content-Range"));
  4160. EXPECT_EQ(0U, res->body.size());
  4161. }
  4162. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4163. auto res = cli_.Get(
  4164. "/with-range",
  4165. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4166. {"Accept-Encoding", ""}});
  4167. ASSERT_TRUE(res);
  4168. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4169. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4170. EXPECT_EQ(true, res->has_header("Content-Range"));
  4171. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4172. EXPECT_EQ(std::string("abcdefg"), res->body);
  4173. }
  4174. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4175. auto res = cli_.Get("/with-range", {
  4176. {"Range", "bytes=0-"},
  4177. {"Accept-Encoding", ""},
  4178. });
  4179. ASSERT_TRUE(res);
  4180. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4181. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4182. EXPECT_EQ(true, res->has_header("Content-Range"));
  4183. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4184. EXPECT_EQ(std::string("abcdefg"), res->body);
  4185. }
  4186. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4187. auto res =
  4188. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4189. ASSERT_TRUE(res);
  4190. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4191. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4192. EXPECT_EQ(false, res->has_header("Content-Range"));
  4193. EXPECT_EQ(267U, res->body.size());
  4194. // Check that both range contents are present
  4195. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4196. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4197. // Check that Content-Range headers are present for both ranges
  4198. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4199. std::string::npos);
  4200. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4201. std::string::npos);
  4202. }
  4203. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4204. Ranges ranges;
  4205. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4206. ranges.emplace_back(0, -1);
  4207. }
  4208. auto res =
  4209. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4210. ASSERT_TRUE(res);
  4211. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4212. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4213. EXPECT_EQ(false, res->has_header("Content-Range"));
  4214. EXPECT_EQ(0U, res->body.size());
  4215. }
  4216. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4217. auto res =
  4218. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4219. ASSERT_TRUE(res);
  4220. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4221. EXPECT_EQ(5U, res->body.size());
  4222. // Check that overlapping ranges are coalesced into a single range
  4223. EXPECT_EQ("bcdef", res->body);
  4224. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4225. // Should be single range, not multipart
  4226. EXPECT_TRUE(res->has_header("Content-Range"));
  4227. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4228. }
  4229. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4230. auto res =
  4231. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4232. ASSERT_TRUE(res);
  4233. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4234. EXPECT_EQ(268U, res->body.size());
  4235. // Check that both range contents are present
  4236. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4237. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4238. // Check that Content-Range headers are present for both ranges
  4239. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4240. std::string::npos);
  4241. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4242. std::string::npos);
  4243. }
  4244. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4245. auto res =
  4246. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4247. ASSERT_TRUE(res);
  4248. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4249. EXPECT_EQ(269U, res->body.size());
  4250. // Check that both duplicate range contents are present
  4251. size_t first_abc = res->body.find("abc\r\n");
  4252. EXPECT_TRUE(first_abc != std::string::npos);
  4253. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4254. EXPECT_TRUE(second_abc != std::string::npos);
  4255. // Check that Content-Range headers are present for both ranges
  4256. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4257. EXPECT_TRUE(first_range != std::string::npos);
  4258. size_t second_range =
  4259. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4260. EXPECT_TRUE(second_range != std::string::npos);
  4261. }
  4262. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4263. auto res = cli_.Get("/streamed-with-range?error",
  4264. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4265. ASSERT_TRUE(res);
  4266. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4267. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4268. EXPECT_EQ(false, res->has_header("Content-Range"));
  4269. EXPECT_EQ(0U, res->body.size());
  4270. }
  4271. TEST_F(ServerTest, GetStreamedEndless) {
  4272. uint64_t offset = 0;
  4273. auto res = cli_.Get("/streamed-cancel",
  4274. [&](const char * /*data*/, uint64_t data_length) {
  4275. if (offset < 100) {
  4276. offset += data_length;
  4277. return true;
  4278. }
  4279. return false;
  4280. });
  4281. ASSERT_TRUE(!res);
  4282. EXPECT_EQ(Error::Canceled, res.error());
  4283. }
  4284. TEST_F(ServerTest, ClientStop) {
  4285. std::atomic_size_t count{4};
  4286. std::vector<std::thread> threads;
  4287. for (auto i = count.load(); i != 0; --i) {
  4288. threads.emplace_back([&]() {
  4289. auto res = cli_.Get("/streamed-cancel",
  4290. [&](const char *, uint64_t) { return true; });
  4291. --count;
  4292. ASSERT_TRUE(!res);
  4293. EXPECT_TRUE(res.error() == Error::Canceled ||
  4294. res.error() == Error::Read || res.error() == Error::Write);
  4295. });
  4296. }
  4297. std::this_thread::sleep_for(std::chrono::seconds(2));
  4298. while (count != 0) {
  4299. cli_.stop();
  4300. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4301. }
  4302. for (auto &t : threads) {
  4303. t.join();
  4304. }
  4305. }
  4306. TEST_F(ServerTest, GetWithRange1) {
  4307. auto res = cli_.Get("/with-range", {
  4308. make_range_header({{3, 5}}),
  4309. {"Accept-Encoding", ""},
  4310. });
  4311. ASSERT_TRUE(res);
  4312. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4313. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4314. EXPECT_EQ(true, res->has_header("Content-Range"));
  4315. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4316. EXPECT_EQ(std::string("def"), res->body);
  4317. }
  4318. TEST_F(ServerTest, GetWithRange2) {
  4319. auto res = cli_.Get("/with-range", {
  4320. make_range_header({{1, -1}}),
  4321. {"Accept-Encoding", ""},
  4322. });
  4323. ASSERT_TRUE(res);
  4324. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4325. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4326. EXPECT_EQ(true, res->has_header("Content-Range"));
  4327. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4328. EXPECT_EQ(std::string("bcdefg"), res->body);
  4329. }
  4330. TEST_F(ServerTest, GetWithRange3) {
  4331. auto res = cli_.Get("/with-range", {
  4332. make_range_header({{0, 0}}),
  4333. {"Accept-Encoding", ""},
  4334. });
  4335. ASSERT_TRUE(res);
  4336. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4337. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4338. EXPECT_EQ(true, res->has_header("Content-Range"));
  4339. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4340. EXPECT_EQ(std::string("a"), res->body);
  4341. }
  4342. TEST_F(ServerTest, GetWithRange4) {
  4343. auto res = cli_.Get("/with-range", {
  4344. make_range_header({{-1, 2}}),
  4345. {"Accept-Encoding", ""},
  4346. });
  4347. ASSERT_TRUE(res);
  4348. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4349. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4350. EXPECT_EQ(true, res->has_header("Content-Range"));
  4351. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4352. EXPECT_EQ(std::string("fg"), res->body);
  4353. }
  4354. TEST_F(ServerTest, GetWithRange5) {
  4355. auto res = cli_.Get("/with-range", {
  4356. make_range_header({{0, 5}}),
  4357. {"Accept-Encoding", ""},
  4358. });
  4359. ASSERT_TRUE(res);
  4360. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4361. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4362. EXPECT_EQ(true, res->has_header("Content-Range"));
  4363. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4364. EXPECT_EQ(std::string("abcdef"), res->body);
  4365. }
  4366. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4367. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4368. ASSERT_TRUE(res);
  4369. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4370. }
  4371. TEST_F(ServerTest, GetWithRangeMultipart) {
  4372. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4373. ASSERT_TRUE(res);
  4374. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4375. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4376. EXPECT_EQ(false, res->has_header("Content-Range"));
  4377. EXPECT_EQ(267U, res->body.size());
  4378. }
  4379. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4380. auto res =
  4381. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4382. ASSERT_TRUE(res);
  4383. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4384. }
  4385. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4386. auto res = cli_.Get("/with-range-customized-response",
  4387. {{make_range_header({{1, 2}})}});
  4388. ASSERT_TRUE(res);
  4389. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4390. EXPECT_EQ(true, res->has_header("Content-Length"));
  4391. EXPECT_EQ(false, res->has_header("Content-Range"));
  4392. EXPECT_EQ(JSON_DATA, res->body);
  4393. }
  4394. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4395. auto res = cli_.Get("/with-range-customized-response",
  4396. {{make_range_header({{1, 2}, {4, 5}})}});
  4397. ASSERT_TRUE(res);
  4398. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4399. EXPECT_EQ(true, res->has_header("Content-Length"));
  4400. EXPECT_EQ(false, res->has_header("Content-Range"));
  4401. EXPECT_EQ(JSON_DATA, res->body);
  4402. }
  4403. TEST_F(ServerTest, Issue1772) {
  4404. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4405. ASSERT_TRUE(res);
  4406. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4407. }
  4408. TEST_F(ServerTest, Issue609) {
  4409. auto res = cli_.Delete("/issue609");
  4410. ASSERT_TRUE(res);
  4411. EXPECT_EQ(StatusCode::OK_200, res->status);
  4412. EXPECT_EQ(std::string("ok"), res->body);
  4413. }
  4414. TEST_F(ServerTest, GetStreamedChunked) {
  4415. auto res = cli_.Get("/streamed-chunked");
  4416. ASSERT_TRUE(res);
  4417. EXPECT_EQ(StatusCode::OK_200, res->status);
  4418. EXPECT_EQ(std::string("123456789"), res->body);
  4419. }
  4420. TEST_F(ServerTest, GetStreamedChunked2) {
  4421. auto res = cli_.Get("/streamed-chunked2");
  4422. ASSERT_TRUE(res);
  4423. EXPECT_EQ(StatusCode::OK_200, res->status);
  4424. EXPECT_EQ(std::string("123456789"), res->body);
  4425. }
  4426. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4427. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4428. ASSERT_TRUE(res);
  4429. EXPECT_EQ(StatusCode::OK_200, res->status);
  4430. EXPECT_EQ(std::string("123456789"), res->body);
  4431. EXPECT_TRUE(res->has_header("Trailer"));
  4432. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4433. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4434. // Trailers are now stored separately from headers (security fix)
  4435. EXPECT_EQ(2U, res->trailers.size());
  4436. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4437. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4438. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4439. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4440. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4441. // Verify trailers are NOT in headers (security verification)
  4442. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4443. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4444. }
  4445. TEST_F(ServerTest, LargeChunkedPost) {
  4446. Request req;
  4447. req.method = "POST";
  4448. req.path = "/large-chunked";
  4449. std::string host_and_port;
  4450. host_and_port += HOST;
  4451. host_and_port += ":";
  4452. host_and_port += std::to_string(PORT);
  4453. req.headers.emplace("Host", host_and_port.c_str());
  4454. req.headers.emplace("Accept", "*/*");
  4455. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4456. req.headers.emplace("Content-Type", "text/plain");
  4457. req.headers.emplace("Content-Length", "0");
  4458. req.headers.emplace("Transfer-Encoding", "chunked");
  4459. std::string long_string(30 * 1024u, 'a');
  4460. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4461. // Attempt to make a large enough post to exceed OS buffers, to test that
  4462. // the server handles short reads if the full chunk data isn't available.
  4463. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4464. auto res = std::make_shared<Response>();
  4465. auto error = Error::Success;
  4466. auto ret = cli_.send(req, *res, error);
  4467. ASSERT_TRUE(ret);
  4468. EXPECT_EQ(StatusCode::OK_200, res->status);
  4469. }
  4470. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4471. auto res = cli_.Get("/remote_addr");
  4472. ASSERT_TRUE(res);
  4473. EXPECT_EQ(StatusCode::OK_200, res->status);
  4474. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4475. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4476. }
  4477. TEST_F(ServerTest, GetMethodLocalAddr) {
  4478. auto res = cli_.Get("/local_addr");
  4479. ASSERT_TRUE(res);
  4480. EXPECT_EQ(StatusCode::OK_200, res->status);
  4481. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4482. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4483. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4484. }
  4485. TEST_F(ServerTest, HTTPResponseSplitting) {
  4486. auto res = cli_.Get("/http_response_splitting");
  4487. ASSERT_TRUE(res);
  4488. EXPECT_EQ(StatusCode::OK_200, res->status);
  4489. }
  4490. TEST_F(ServerTest, SlowRequest) {
  4491. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4492. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4493. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4494. }
  4495. #if 0
  4496. TEST_F(ServerTest, SlowPost) {
  4497. char buffer[64 * 1024];
  4498. memset(buffer, 0x42, sizeof(buffer));
  4499. auto res = cli_.Post(
  4500. "/slowpost", 64 * 1024 * 1024,
  4501. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4502. auto ret = sink.write(buffer, sizeof(buffer));
  4503. EXPECT_TRUE(ret);
  4504. return true;
  4505. },
  4506. "text/plain");
  4507. ASSERT_TRUE(res);
  4508. EXPECT_EQ(StatusCode::OK_200, res->status);
  4509. }
  4510. TEST_F(ServerTest, SlowPostFail) {
  4511. char buffer[64 * 1024];
  4512. memset(buffer, 0x42, sizeof(buffer));
  4513. cli_.set_write_timeout(std::chrono::seconds(0));
  4514. auto res = cli_.Post(
  4515. "/slowpost", 64 * 1024 * 1024,
  4516. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4517. sink.write(buffer, sizeof(buffer));
  4518. return true;
  4519. },
  4520. "text/plain");
  4521. ASSERT_TRUE(!res);
  4522. EXPECT_EQ(Error::Write, res.error());
  4523. }
  4524. #endif
  4525. TEST_F(ServerTest, Put) {
  4526. auto res = cli_.Put("/put", "PUT", "text/plain");
  4527. ASSERT_TRUE(res);
  4528. EXPECT_EQ(StatusCode::OK_200, res->status);
  4529. EXPECT_EQ("PUT", res->body);
  4530. }
  4531. TEST_F(ServerTest, PutWithContentProvider) {
  4532. auto res = cli_.Put(
  4533. "/put", 3,
  4534. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4535. sink.os << "PUT";
  4536. return true;
  4537. },
  4538. "text/plain");
  4539. ASSERT_TRUE(res);
  4540. EXPECT_EQ(StatusCode::OK_200, res->status);
  4541. EXPECT_EQ("PUT", res->body);
  4542. }
  4543. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4544. auto res = cli_.Post(
  4545. "/post", 42,
  4546. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4547. return false;
  4548. },
  4549. "text/plain");
  4550. ASSERT_TRUE(!res);
  4551. EXPECT_EQ(Error::Canceled, res.error());
  4552. }
  4553. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4554. auto res = cli_.Put(
  4555. "/put",
  4556. [](size_t /*offset*/, DataSink &sink) {
  4557. sink.os << "PUT";
  4558. sink.done();
  4559. return true;
  4560. },
  4561. "text/plain");
  4562. ASSERT_TRUE(res);
  4563. EXPECT_EQ(StatusCode::OK_200, res->status);
  4564. EXPECT_EQ("PUT", res->body);
  4565. }
  4566. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4567. auto res = cli_.Post(
  4568. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4569. "text/plain");
  4570. ASSERT_TRUE(!res);
  4571. EXPECT_EQ(Error::Canceled, res.error());
  4572. }
  4573. TEST_F(ServerTest, PostLoopBack) {
  4574. std::string body;
  4575. auto res = cli_.Post(
  4576. "/post-loopback", 9,
  4577. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4578. EXPECT_EQ(9u, length);
  4579. sink.write("123", 3);
  4580. sink.write("456", 3);
  4581. sink.write("789", 3);
  4582. return true;
  4583. },
  4584. "text/plain",
  4585. [&body](const char *data, size_t data_length) {
  4586. body.append(data, data_length);
  4587. return true;
  4588. });
  4589. ASSERT_TRUE(res);
  4590. EXPECT_EQ(StatusCode::OK_200, res->status);
  4591. EXPECT_EQ("123456789", body);
  4592. }
  4593. TEST_F(ServerTest, PutLoopBack) {
  4594. std::string body;
  4595. auto res = cli_.Put(
  4596. "/put-loopback", 9,
  4597. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4598. EXPECT_EQ(9u, length);
  4599. sink.write("123", 3);
  4600. sink.write("456", 3);
  4601. sink.write("789", 3);
  4602. return true;
  4603. },
  4604. "text/plain",
  4605. [&body](const char *data, size_t data_length) {
  4606. body.append(data, data_length);
  4607. return true;
  4608. });
  4609. ASSERT_TRUE(res);
  4610. EXPECT_EQ(StatusCode::OK_200, res->status);
  4611. EXPECT_EQ("123456789", body);
  4612. }
  4613. TEST_F(ServerTest, PatchLoopBack) {
  4614. std::string body;
  4615. auto res = cli_.Patch(
  4616. "/patch-loopback", 9,
  4617. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4618. EXPECT_EQ(9u, length);
  4619. sink.write("123", 3);
  4620. sink.write("456", 3);
  4621. sink.write("789", 3);
  4622. return true;
  4623. },
  4624. "text/plain",
  4625. [&body](const char *data, size_t data_length) {
  4626. body.append(data, data_length);
  4627. return true;
  4628. });
  4629. ASSERT_TRUE(res);
  4630. EXPECT_EQ(StatusCode::OK_200, res->status);
  4631. EXPECT_EQ("123456789", body);
  4632. }
  4633. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4634. std::string body;
  4635. auto res = cli_.Post(
  4636. "/post-loopback",
  4637. [](size_t /*offset*/, DataSink &sink) {
  4638. sink.write("123", 3);
  4639. sink.write("456", 3);
  4640. sink.write("789", 3);
  4641. sink.done();
  4642. return true;
  4643. },
  4644. "text/plain",
  4645. [&body](const char *data, size_t data_length) {
  4646. body.append(data, data_length);
  4647. return true;
  4648. });
  4649. ASSERT_TRUE(res);
  4650. EXPECT_EQ(StatusCode::OK_200, res->status);
  4651. EXPECT_EQ("123456789", body);
  4652. }
  4653. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4654. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4655. cli_.set_compress(true);
  4656. auto res = cli_.Put(
  4657. "/put", 3,
  4658. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4659. sink.os << "PUT";
  4660. return true;
  4661. },
  4662. "text/plain");
  4663. ASSERT_TRUE(res);
  4664. EXPECT_EQ(StatusCode::OK_200, res->status);
  4665. EXPECT_EQ("PUT", res->body);
  4666. }
  4667. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4668. cli_.set_compress(true);
  4669. auto res = cli_.Post(
  4670. "/post", 42,
  4671. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4672. return false;
  4673. },
  4674. "text/plain");
  4675. ASSERT_TRUE(!res);
  4676. EXPECT_EQ(Error::Canceled, res.error());
  4677. }
  4678. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4679. cli_.set_compress(true);
  4680. auto res = cli_.Put(
  4681. "/put",
  4682. [](size_t /*offset*/, DataSink &sink) {
  4683. sink.os << "PUT";
  4684. sink.done();
  4685. return true;
  4686. },
  4687. "text/plain");
  4688. ASSERT_TRUE(res);
  4689. EXPECT_EQ(StatusCode::OK_200, res->status);
  4690. EXPECT_EQ("PUT", res->body);
  4691. }
  4692. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4693. cli_.set_compress(true);
  4694. auto res = cli_.Post(
  4695. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4696. "text/plain");
  4697. ASSERT_TRUE(!res);
  4698. EXPECT_EQ(Error::Canceled, res.error());
  4699. }
  4700. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4701. cli_.set_compress(true);
  4702. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4703. ASSERT_TRUE(res);
  4704. EXPECT_EQ(StatusCode::OK_200, res->status);
  4705. EXPECT_EQ(LARGE_DATA, res->body);
  4706. }
  4707. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4708. #ifdef CPPHTTPLIB_SSL_ENABLED
  4709. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4710. Client cli(s.c_str());
  4711. cli.enable_server_certificate_verification(false);
  4712. #else
  4713. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4714. Client cli(s.c_str());
  4715. #endif
  4716. cli.set_compress(true);
  4717. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4718. ASSERT_TRUE(res);
  4719. EXPECT_EQ(StatusCode::OK_200, res->status);
  4720. EXPECT_EQ(LARGE_DATA, res->body);
  4721. // The compressed size should be less than a 10th of the original. May vary
  4722. // depending on the zlib library.
  4723. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4724. static_cast<uint64_t>(10 * 1024 * 1024));
  4725. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4726. }
  4727. TEST_F(ServerTest, PutContentWithDeflate) {
  4728. cli_.set_compress(false);
  4729. Headers headers;
  4730. headers.emplace("Content-Encoding", "deflate");
  4731. // PUT in deflate format:
  4732. auto res = cli_.Put("/put", headers,
  4733. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4734. ASSERT_TRUE(res);
  4735. EXPECT_EQ(StatusCode::OK_200, res->status);
  4736. EXPECT_EQ("PUT", res->body);
  4737. }
  4738. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4739. Headers headers;
  4740. headers.emplace("Accept-Encoding", "gzip, deflate");
  4741. auto res = cli_.Get("/streamed-chunked", headers);
  4742. ASSERT_TRUE(res);
  4743. EXPECT_EQ(StatusCode::OK_200, res->status);
  4744. EXPECT_EQ(std::string("123456789"), res->body);
  4745. }
  4746. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4747. Headers headers;
  4748. headers.emplace("Accept-Encoding", "gzip, deflate");
  4749. auto res = cli_.Get("/streamed-chunked2", headers);
  4750. ASSERT_TRUE(res);
  4751. EXPECT_EQ(StatusCode::OK_200, res->status);
  4752. EXPECT_EQ(std::string("123456789"), res->body);
  4753. }
  4754. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4755. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4756. ASSERT_TRUE(res);
  4757. EXPECT_EQ(StatusCode::OK_200, res->status);
  4758. }
  4759. TEST(GzipDecompressor, ChunkedDecompression) {
  4760. std::string data;
  4761. for (size_t i = 0; i < 32 * 1024; ++i) {
  4762. data.push_back(static_cast<char>('a' + i % 26));
  4763. }
  4764. std::string compressed_data;
  4765. {
  4766. httplib::detail::gzip_compressor compressor;
  4767. bool result = compressor.compress(
  4768. data.data(), data.size(),
  4769. /*last=*/true,
  4770. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4771. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4772. compressed_data_size);
  4773. return true;
  4774. });
  4775. ASSERT_TRUE(result);
  4776. }
  4777. std::string decompressed_data;
  4778. {
  4779. httplib::detail::gzip_decompressor decompressor;
  4780. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4781. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4782. size_t chunk_size = 130;
  4783. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4784. chunk_begin += chunk_size) {
  4785. size_t current_chunk_size =
  4786. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4787. bool result = decompressor.decompress(
  4788. compressed_data.data() + chunk_begin, current_chunk_size,
  4789. [&](const char *decompressed_data_chunk,
  4790. size_t decompressed_data_chunk_size) {
  4791. decompressed_data.insert(decompressed_data.size(),
  4792. decompressed_data_chunk,
  4793. decompressed_data_chunk_size);
  4794. return true;
  4795. });
  4796. ASSERT_TRUE(result);
  4797. }
  4798. }
  4799. ASSERT_EQ(data, decompressed_data);
  4800. }
  4801. TEST(GzipDecompressor, DeflateDecompression) {
  4802. std::string original_text = "Raw deflate without gzip";
  4803. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4804. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4805. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4806. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4807. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4808. std::string decompressed_data;
  4809. {
  4810. httplib::detail::gzip_decompressor decompressor;
  4811. bool result = decompressor.decompress(
  4812. compressed_data.data(), compressed_data.size(),
  4813. [&](const char *decompressed_data_chunk,
  4814. size_t decompressed_data_chunk_size) {
  4815. decompressed_data.insert(decompressed_data.size(),
  4816. decompressed_data_chunk,
  4817. decompressed_data_chunk_size);
  4818. return true;
  4819. });
  4820. ASSERT_TRUE(result);
  4821. }
  4822. ASSERT_EQ(original_text, decompressed_data);
  4823. }
  4824. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4825. std::string original_text = "Raw deflate without gzip";
  4826. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4827. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4828. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4829. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4830. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4831. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4832. std::string decompressed_data;
  4833. {
  4834. httplib::detail::gzip_decompressor decompressor;
  4835. bool result = decompressor.decompress(
  4836. compressed_data.data(), compressed_data.size(),
  4837. [&](const char *decompressed_data_chunk,
  4838. size_t decompressed_data_chunk_size) {
  4839. decompressed_data.insert(decompressed_data.size(),
  4840. decompressed_data_chunk,
  4841. decompressed_data_chunk_size);
  4842. return true;
  4843. });
  4844. ASSERT_TRUE(result);
  4845. }
  4846. ASSERT_EQ(original_text, decompressed_data);
  4847. }
  4848. #ifdef _WIN32
  4849. TEST(GzipDecompressor, LargeRandomData) {
  4850. // prepare large random data that is difficult to be compressed and is
  4851. // expected to have large size even when compressed
  4852. std::random_device seed_gen;
  4853. std::mt19937 random(seed_gen());
  4854. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4855. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4856. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4857. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4858. // compress data over 4GiB
  4859. std::string compressed_data;
  4860. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4861. httplib::detail::gzip_compressor compressor;
  4862. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4863. data.size() * sizeof(std::uint32_t), true,
  4864. [&](const char *data, size_t size) {
  4865. compressed_data.insert(
  4866. compressed_data.size(), data, size);
  4867. return true;
  4868. });
  4869. ASSERT_TRUE(result);
  4870. // FIXME: compressed data size is expected to be greater than 4GiB,
  4871. // but there is no guarantee
  4872. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4873. // decompress data over 4GiB
  4874. std::string decompressed_data;
  4875. decompressed_data.reserve(data_size);
  4876. httplib::detail::gzip_decompressor decompressor;
  4877. result = decompressor.decompress(
  4878. compressed_data.data(), compressed_data.size(),
  4879. [&](const char *data, size_t size) {
  4880. decompressed_data.insert(decompressed_data.size(), data, size);
  4881. return true;
  4882. });
  4883. ASSERT_TRUE(result);
  4884. // compare
  4885. ASSERT_EQ(data_size, decompressed_data.size());
  4886. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4887. 0);
  4888. }
  4889. #endif
  4890. #endif
  4891. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4892. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4893. Headers headers;
  4894. headers.emplace("Accept-Encoding", "br");
  4895. auto res = cli_.Get("/streamed-chunked", headers);
  4896. ASSERT_TRUE(res);
  4897. EXPECT_EQ(StatusCode::OK_200, res->status);
  4898. EXPECT_EQ(std::string("123456789"), res->body);
  4899. }
  4900. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4901. Headers headers;
  4902. headers.emplace("Accept-Encoding", "br");
  4903. auto res = cli_.Get("/streamed-chunked2", headers);
  4904. ASSERT_TRUE(res);
  4905. EXPECT_EQ(StatusCode::OK_200, res->status);
  4906. EXPECT_EQ(std::string("123456789"), res->body);
  4907. }
  4908. #endif
  4909. TEST_F(ServerTest, Patch) {
  4910. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4911. ASSERT_TRUE(res);
  4912. EXPECT_EQ(StatusCode::OK_200, res->status);
  4913. EXPECT_EQ("PATCH", res->body);
  4914. }
  4915. TEST_F(ServerTest, Delete) {
  4916. auto res = cli_.Delete("/delete");
  4917. ASSERT_TRUE(res);
  4918. EXPECT_EQ(StatusCode::OK_200, res->status);
  4919. EXPECT_EQ("DELETE", res->body);
  4920. }
  4921. TEST_F(ServerTest, DeleteContentReceiver) {
  4922. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4923. ASSERT_TRUE(res);
  4924. EXPECT_EQ(StatusCode::OK_200, res->status);
  4925. EXPECT_EQ("content", res->body);
  4926. }
  4927. TEST_F(ServerTest, Options) {
  4928. auto res = cli_.Options("*");
  4929. ASSERT_TRUE(res);
  4930. EXPECT_EQ(StatusCode::OK_200, res->status);
  4931. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4932. EXPECT_TRUE(res->body.empty());
  4933. }
  4934. TEST_F(ServerTest, URL) {
  4935. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4936. ASSERT_TRUE(res);
  4937. EXPECT_EQ(StatusCode::OK_200, res->status);
  4938. }
  4939. TEST_F(ServerTest, ArrayParam) {
  4940. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4941. ASSERT_TRUE(res);
  4942. EXPECT_EQ(StatusCode::OK_200, res->status);
  4943. }
  4944. TEST_F(ServerTest, NoMultipleHeaders) {
  4945. Headers headers = {{"Content-Length", "5"}};
  4946. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4947. "text/plain");
  4948. ASSERT_TRUE(res);
  4949. EXPECT_EQ(StatusCode::OK_200, res->status);
  4950. }
  4951. TEST_F(ServerTest, PostContentReceiver) {
  4952. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4953. ASSERT_TRUE(res);
  4954. ASSERT_EQ(StatusCode::OK_200, res->status);
  4955. ASSERT_EQ("content", res->body);
  4956. }
  4957. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4958. UploadFormDataItems items = {
  4959. {"text1", "text default", "", ""},
  4960. {"text2", "aωb", "", ""},
  4961. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4962. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4963. {"file3", "", "", "application/octet-stream"},
  4964. };
  4965. auto res = cli_.Post("/content_receiver", items);
  4966. ASSERT_TRUE(res);
  4967. EXPECT_EQ(StatusCode::OK_200, res->status);
  4968. }
  4969. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4970. UploadFormDataItems items = {
  4971. {"text1", "text default", "", ""},
  4972. {"text2", "aωb", "", ""},
  4973. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4974. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4975. {"file3", "", "", "application/octet-stream"},
  4976. };
  4977. auto boundary = std::string("+++++");
  4978. std::string body;
  4979. for (const auto &item : items) {
  4980. body += "--" + boundary + "\r\n";
  4981. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4982. if (!item.filename.empty()) {
  4983. body += "; filename=\"" + item.filename + "\"";
  4984. }
  4985. body += "\r\n";
  4986. if (!item.content_type.empty()) {
  4987. body += "Content-Type: " + item.content_type + "\r\n";
  4988. }
  4989. body += "\r\n";
  4990. body += item.content + "\r\n";
  4991. }
  4992. body += "--" + boundary + "--\r\n";
  4993. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4994. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4995. ASSERT_TRUE(res);
  4996. EXPECT_EQ(StatusCode::OK_200, res->status);
  4997. }
  4998. TEST_F(ServerTest, PostContentReceiverGzip) {
  4999. cli_.set_compress(true);
  5000. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5001. ASSERT_TRUE(res);
  5002. ASSERT_EQ(StatusCode::OK_200, res->status);
  5003. ASSERT_EQ("content", res->body);
  5004. }
  5005. TEST_F(ServerTest, PutContentReceiver) {
  5006. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5007. ASSERT_TRUE(res);
  5008. ASSERT_EQ(StatusCode::OK_200, res->status);
  5009. ASSERT_EQ("content", res->body);
  5010. }
  5011. TEST_F(ServerTest, PatchContentReceiver) {
  5012. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5013. ASSERT_TRUE(res);
  5014. ASSERT_EQ(StatusCode::OK_200, res->status);
  5015. ASSERT_EQ("content", res->body);
  5016. }
  5017. template <typename ClientType>
  5018. void TestWithHeadersAndContentReceiver(
  5019. ClientType &cli,
  5020. std::function<Result(ClientType &, const std::string &, const Headers &,
  5021. const std::string &, const std::string &,
  5022. ContentReceiver, DownloadProgress)>
  5023. request_func) {
  5024. Headers headers;
  5025. headers.emplace("X-Custom-Header", "test-value");
  5026. std::string received_body;
  5027. auto res = request_func(
  5028. cli, "/content_receiver", headers, "content", "application/json",
  5029. [&](const char *data, size_t data_length) {
  5030. received_body.append(data, data_length);
  5031. return true;
  5032. },
  5033. nullptr);
  5034. ASSERT_TRUE(res);
  5035. EXPECT_EQ(StatusCode::OK_200, res->status);
  5036. EXPECT_EQ("content", received_body);
  5037. }
  5038. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5039. #ifdef CPPHTTPLIB_SSL_ENABLED
  5040. using ClientT = SSLClient;
  5041. #else
  5042. using ClientT = Client;
  5043. #endif
  5044. TestWithHeadersAndContentReceiver<ClientT>(
  5045. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5046. const std::string &body, const std::string &content_type,
  5047. ContentReceiver receiver, DownloadProgress progress) {
  5048. return cli.Post(path, headers, body, content_type, receiver, progress);
  5049. });
  5050. }
  5051. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5052. #ifdef CPPHTTPLIB_SSL_ENABLED
  5053. using ClientT = SSLClient;
  5054. #else
  5055. using ClientT = Client;
  5056. #endif
  5057. TestWithHeadersAndContentReceiver<ClientT>(
  5058. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5059. const std::string &body, const std::string &content_type,
  5060. ContentReceiver receiver, DownloadProgress progress) {
  5061. return cli.Put(path, headers, body, content_type, receiver, progress);
  5062. });
  5063. }
  5064. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5065. #ifdef CPPHTTPLIB_SSL_ENABLED
  5066. using ClientT = SSLClient;
  5067. #else
  5068. using ClientT = Client;
  5069. #endif
  5070. TestWithHeadersAndContentReceiver<ClientT>(
  5071. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5072. const std::string &body, const std::string &content_type,
  5073. ContentReceiver receiver, DownloadProgress progress) {
  5074. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5075. });
  5076. }
  5077. template <typename ClientType>
  5078. void TestWithHeadersAndContentReceiverWithProgress(
  5079. ClientType &cli,
  5080. std::function<Result(ClientType &, const std::string &, const Headers &,
  5081. const std::string &, const std::string &,
  5082. ContentReceiver, DownloadProgress)>
  5083. request_func) {
  5084. Headers headers;
  5085. headers.emplace("X-Test-Header", "progress-test");
  5086. std::string received_body;
  5087. auto progress_called = false;
  5088. auto res = request_func(
  5089. cli, "/content_receiver", headers, "content", "text/plain",
  5090. [&](const char *data, size_t data_length) {
  5091. received_body.append(data, data_length);
  5092. return true;
  5093. },
  5094. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5095. progress_called = true;
  5096. return true;
  5097. });
  5098. ASSERT_TRUE(res);
  5099. EXPECT_EQ(StatusCode::OK_200, res->status);
  5100. EXPECT_EQ("content", received_body);
  5101. EXPECT_TRUE(progress_called);
  5102. }
  5103. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5104. #ifdef CPPHTTPLIB_SSL_ENABLED
  5105. using ClientT = SSLClient;
  5106. #else
  5107. using ClientT = Client;
  5108. #endif
  5109. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5110. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5111. const std::string &body, const std::string &content_type,
  5112. ContentReceiver receiver, DownloadProgress progress) {
  5113. return cli.Post(path, headers, body, content_type, receiver, progress);
  5114. });
  5115. }
  5116. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5117. #ifdef CPPHTTPLIB_SSL_ENABLED
  5118. using ClientT = SSLClient;
  5119. #else
  5120. using ClientT = Client;
  5121. #endif
  5122. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5123. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5124. const std::string &body, const std::string &content_type,
  5125. ContentReceiver receiver, DownloadProgress progress) {
  5126. return cli.Put(path, headers, body, content_type, receiver, progress);
  5127. });
  5128. }
  5129. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5130. #ifdef CPPHTTPLIB_SSL_ENABLED
  5131. using ClientT = SSLClient;
  5132. #else
  5133. using ClientT = Client;
  5134. #endif
  5135. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5136. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5137. const std::string &body, const std::string &content_type,
  5138. ContentReceiver receiver, DownloadProgress progress) {
  5139. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5140. });
  5141. }
  5142. template <typename ClientType>
  5143. void TestWithHeadersAndContentReceiverError(
  5144. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5145. const Headers &, const std::string &,
  5146. const std::string &, ContentReceiver)>
  5147. request_func) {
  5148. Headers headers;
  5149. headers.emplace("X-Error-Test", "true");
  5150. std::string received_body;
  5151. auto receiver_failed = false;
  5152. auto res =
  5153. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5154. [&](const char *data, size_t data_length) {
  5155. received_body.append(data, data_length);
  5156. receiver_failed = true;
  5157. return false;
  5158. });
  5159. ASSERT_FALSE(res);
  5160. EXPECT_TRUE(receiver_failed);
  5161. }
  5162. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5163. #ifdef CPPHTTPLIB_SSL_ENABLED
  5164. using ClientT = SSLClient;
  5165. #else
  5166. using ClientT = Client;
  5167. #endif
  5168. TestWithHeadersAndContentReceiverError<ClientT>(
  5169. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5170. const std::string &body, const std::string &content_type,
  5171. ContentReceiver receiver) {
  5172. return cli.Post(path, headers, body, content_type, receiver);
  5173. });
  5174. }
  5175. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5176. #ifdef CPPHTTPLIB_SSL_ENABLED
  5177. using ClientT = SSLClient;
  5178. #else
  5179. using ClientT = Client;
  5180. #endif
  5181. TestWithHeadersAndContentReceiverError<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) {
  5185. return cli.Put(path, headers, body, content_type, receiver);
  5186. });
  5187. }
  5188. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5189. #ifdef CPPHTTPLIB_SSL_ENABLED
  5190. using ClientT = SSLClient;
  5191. #else
  5192. using ClientT = Client;
  5193. #endif
  5194. TestWithHeadersAndContentReceiverError<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) {
  5198. return cli.Patch(path, headers, body, content_type, receiver);
  5199. });
  5200. }
  5201. TEST_F(ServerTest, PostQueryStringAndBody) {
  5202. auto res =
  5203. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5204. ASSERT_TRUE(res);
  5205. ASSERT_EQ(StatusCode::OK_200, res->status);
  5206. }
  5207. TEST_F(ServerTest, HTTP2Magic) {
  5208. Request req;
  5209. req.method = "PRI";
  5210. req.path = "*";
  5211. req.body = "SM";
  5212. auto res = std::make_shared<Response>();
  5213. auto error = Error::Success;
  5214. auto ret = cli_.send(req, *res, error);
  5215. ASSERT_TRUE(ret);
  5216. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5217. }
  5218. TEST_F(ServerTest, KeepAlive) {
  5219. auto res = cli_.Get("/hi");
  5220. ASSERT_TRUE(res);
  5221. EXPECT_EQ(StatusCode::OK_200, res->status);
  5222. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5223. EXPECT_EQ("Hello World!", res->body);
  5224. res = cli_.Get("/hi");
  5225. ASSERT_TRUE(res);
  5226. EXPECT_EQ(StatusCode::OK_200, res->status);
  5227. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5228. EXPECT_EQ("Hello World!", res->body);
  5229. res = cli_.Get("/hi");
  5230. ASSERT_TRUE(res);
  5231. EXPECT_EQ(StatusCode::OK_200, res->status);
  5232. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5233. EXPECT_EQ("Hello World!", res->body);
  5234. res = cli_.Get("/not-exist");
  5235. ASSERT_TRUE(res);
  5236. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5237. res = cli_.Post("/empty", "", "text/plain");
  5238. ASSERT_TRUE(res);
  5239. EXPECT_EQ(StatusCode::OK_200, res->status);
  5240. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5241. EXPECT_EQ("empty", res->body);
  5242. EXPECT_EQ("close", res->get_header_value("Connection"));
  5243. res = cli_.Post(
  5244. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5245. "text/plain");
  5246. ASSERT_TRUE(res);
  5247. EXPECT_EQ(StatusCode::OK_200, res->status);
  5248. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5249. EXPECT_EQ("empty", res->body);
  5250. cli_.set_keep_alive(false);
  5251. res = cli_.Get("/last-request");
  5252. ASSERT_TRUE(res);
  5253. EXPECT_EQ(StatusCode::OK_200, res->status);
  5254. EXPECT_EQ("close", res->get_header_value("Connection"));
  5255. }
  5256. TEST_F(ServerTest, TooManyRedirect) {
  5257. cli_.set_follow_location(true);
  5258. auto res = cli_.Get("/redirect/0");
  5259. ASSERT_TRUE(!res);
  5260. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5261. }
  5262. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5263. Request req;
  5264. req.method = "FOOBAR";
  5265. req.path = "/hi";
  5266. cli_.set_keep_alive(true);
  5267. auto res = cli_.send(req);
  5268. ASSERT_TRUE(res);
  5269. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5270. EXPECT_EQ("close", res->get_header_value("Connection"));
  5271. EXPECT_FALSE(cli_.is_socket_open());
  5272. }
  5273. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5274. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5275. TEST_F(ServerTest, Gzip) {
  5276. Headers headers;
  5277. headers.emplace("Accept-Encoding", "gzip, deflate");
  5278. auto res = cli_.Get("/compress", headers);
  5279. ASSERT_TRUE(res);
  5280. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5281. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5282. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5283. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5284. "7890123456789012345678901234567890",
  5285. res->body);
  5286. EXPECT_EQ(StatusCode::OK_200, res->status);
  5287. }
  5288. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5289. Headers headers;
  5290. headers.emplace("Accept-Encoding", "");
  5291. auto res = cli_.Get("/compress", headers);
  5292. ASSERT_TRUE(res);
  5293. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5294. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5295. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5296. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5297. "7890123456789012345678901234567890",
  5298. res->body);
  5299. EXPECT_EQ(StatusCode::OK_200, res->status);
  5300. }
  5301. TEST_F(ServerTest, GzipWithContentReceiver) {
  5302. Headers headers;
  5303. headers.emplace("Accept-Encoding", "gzip, deflate");
  5304. std::string body;
  5305. auto res = cli_.Get("/compress", headers,
  5306. [&](const char *data, uint64_t data_length) {
  5307. EXPECT_EQ(100U, data_length);
  5308. body.append(data, data_length);
  5309. return true;
  5310. });
  5311. ASSERT_TRUE(res);
  5312. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5313. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5314. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5315. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5316. "7890123456789012345678901234567890",
  5317. body);
  5318. EXPECT_EQ(StatusCode::OK_200, res->status);
  5319. }
  5320. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5321. Headers headers;
  5322. headers.emplace("Accept-Encoding", "gzip, deflate");
  5323. cli_.set_decompress(false);
  5324. auto res = cli_.Get("/compress", headers);
  5325. ASSERT_TRUE(res);
  5326. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5327. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5328. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5329. EXPECT_EQ(33U, res->body.size());
  5330. EXPECT_EQ(StatusCode::OK_200, res->status);
  5331. }
  5332. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5333. Headers headers;
  5334. headers.emplace("Accept-Encoding", "");
  5335. std::string body;
  5336. auto res = cli_.Get("/compress", headers,
  5337. [&](const char *data, uint64_t data_length) {
  5338. EXPECT_EQ(100U, data_length);
  5339. body.append(data, data_length);
  5340. return true;
  5341. });
  5342. ASSERT_TRUE(res);
  5343. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5344. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5345. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5346. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5347. "7890123456789012345678901234567890",
  5348. body);
  5349. EXPECT_EQ(StatusCode::OK_200, res->status);
  5350. }
  5351. TEST_F(ServerTest, NoGzip) {
  5352. Headers headers;
  5353. headers.emplace("Accept-Encoding", "gzip, deflate");
  5354. auto res = cli_.Get("/nocompress", headers);
  5355. ASSERT_TRUE(res);
  5356. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5357. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5358. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5359. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5360. "7890123456789012345678901234567890",
  5361. res->body);
  5362. EXPECT_EQ(StatusCode::OK_200, res->status);
  5363. }
  5364. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5365. Headers headers;
  5366. headers.emplace("Accept-Encoding", "gzip, deflate");
  5367. std::string body;
  5368. auto res = cli_.Get("/nocompress", headers,
  5369. [&](const char *data, uint64_t data_length) {
  5370. EXPECT_EQ(100U, data_length);
  5371. body.append(data, data_length);
  5372. return true;
  5373. });
  5374. ASSERT_TRUE(res);
  5375. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5376. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5377. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5378. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5379. "7890123456789012345678901234567890",
  5380. body);
  5381. EXPECT_EQ(StatusCode::OK_200, res->status);
  5382. }
  5383. TEST_F(ServerTest, MultipartFormDataGzip) {
  5384. UploadFormDataItems items = {
  5385. {"key1", "test", "", ""},
  5386. {"key2", "--abcdefg123", "", ""},
  5387. };
  5388. cli_.set_compress(true);
  5389. auto res = cli_.Post("/compress-multipart", items);
  5390. ASSERT_TRUE(res);
  5391. EXPECT_EQ(StatusCode::OK_200, res->status);
  5392. }
  5393. #endif
  5394. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5395. TEST_F(ServerTest, Brotli) {
  5396. Headers headers;
  5397. headers.emplace("Accept-Encoding", "br");
  5398. auto res = cli_.Get("/compress", headers);
  5399. ASSERT_TRUE(res);
  5400. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5401. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5402. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5403. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5404. "7890123456789012345678901234567890",
  5405. res->body);
  5406. EXPECT_EQ(StatusCode::OK_200, res->status);
  5407. }
  5408. #endif
  5409. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5410. TEST_F(ServerTest, Zstd) {
  5411. Headers headers;
  5412. headers.emplace("Accept-Encoding", "zstd");
  5413. auto res = cli_.Get("/compress", headers);
  5414. ASSERT_TRUE(res);
  5415. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5416. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5417. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5418. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5419. "7890123456789012345678901234567890",
  5420. res->body);
  5421. EXPECT_EQ(StatusCode::OK_200, res->status);
  5422. }
  5423. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5424. Headers headers;
  5425. headers.emplace("Accept-Encoding", "");
  5426. auto res = cli_.Get("/compress", headers);
  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. res->body);
  5434. EXPECT_EQ(StatusCode::OK_200, res->status);
  5435. }
  5436. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5437. Headers headers;
  5438. headers.emplace("Accept-Encoding", "zstd");
  5439. std::string body;
  5440. auto res = cli_.Get("/compress", headers,
  5441. [&](const char *data, uint64_t data_length) {
  5442. EXPECT_EQ(100U, data_length);
  5443. body.append(data, data_length);
  5444. return true;
  5445. });
  5446. ASSERT_TRUE(res);
  5447. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5448. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5449. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5450. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5451. "7890123456789012345678901234567890",
  5452. body);
  5453. EXPECT_EQ(StatusCode::OK_200, res->status);
  5454. }
  5455. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5456. Headers headers;
  5457. headers.emplace("Accept-Encoding", "zstd");
  5458. cli_.set_decompress(false);
  5459. auto res = cli_.Get("/compress", headers);
  5460. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5461. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5462. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5463. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5464. ASSERT_TRUE(res);
  5465. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5466. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5467. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5468. EXPECT_EQ(StatusCode::OK_200, res->status);
  5469. ASSERT_EQ(26U, res->body.size());
  5470. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5471. 0);
  5472. }
  5473. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5474. Headers headers;
  5475. headers.emplace("Accept-Encoding", "");
  5476. std::string body;
  5477. auto res = cli_.Get("/compress", headers,
  5478. [&](const char *data, uint64_t data_length) {
  5479. EXPECT_EQ(100U, data_length);
  5480. body.append(data, data_length);
  5481. return true;
  5482. });
  5483. ASSERT_TRUE(res);
  5484. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5485. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5486. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5487. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5488. "7890123456789012345678901234567890",
  5489. body);
  5490. EXPECT_EQ(StatusCode::OK_200, res->status);
  5491. }
  5492. TEST_F(ServerTest, NoZstd) {
  5493. Headers headers;
  5494. headers.emplace("Accept-Encoding", "zstd");
  5495. auto res = cli_.Get("/nocompress", headers);
  5496. ASSERT_TRUE(res);
  5497. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5498. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5499. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5500. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5501. "7890123456789012345678901234567890",
  5502. res->body);
  5503. EXPECT_EQ(StatusCode::OK_200, res->status);
  5504. }
  5505. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5506. Headers headers;
  5507. headers.emplace("Accept-Encoding", "zstd");
  5508. std::string body;
  5509. auto res = cli_.Get("/nocompress", headers,
  5510. [&](const char *data, uint64_t data_length) {
  5511. EXPECT_EQ(100U, data_length);
  5512. body.append(data, data_length);
  5513. return true;
  5514. });
  5515. ASSERT_TRUE(res);
  5516. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5517. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5518. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5519. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5520. "7890123456789012345678901234567890",
  5521. body);
  5522. EXPECT_EQ(StatusCode::OK_200, res->status);
  5523. }
  5524. // TODO: How to enable zstd ??
  5525. TEST_F(ServerTest, MultipartFormDataZstd) {
  5526. UploadFormDataItems items = {
  5527. {"key1", "test", "", ""},
  5528. {"key2", "--abcdefg123", "", ""},
  5529. };
  5530. Headers headers;
  5531. headers.emplace("Accept-Encoding", "zstd");
  5532. cli_.set_compress(true);
  5533. auto res = cli_.Post("/compress-multipart", headers, items);
  5534. ASSERT_TRUE(res);
  5535. EXPECT_EQ(StatusCode::OK_200, res->status);
  5536. }
  5537. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5538. Headers headers;
  5539. headers.emplace("Accept-Encoding", "zstd");
  5540. cli_.set_compress(true);
  5541. auto res = cli_.Put(
  5542. "/put", headers, 3,
  5543. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5544. sink.os << "PUT";
  5545. return true;
  5546. },
  5547. "text/plain");
  5548. ASSERT_TRUE(res);
  5549. EXPECT_EQ(StatusCode::OK_200, res->status);
  5550. EXPECT_EQ("PUT", res->body);
  5551. }
  5552. // Pre-compression logging tests
  5553. TEST_F(ServerTest, PreCompressionLogging) {
  5554. // Test data for compression (matches the actual /compress endpoint content)
  5555. const std::string test_content =
  5556. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5557. "3456789012345678901234567890";
  5558. // Variables to capture logging data
  5559. std::string pre_compression_body;
  5560. std::string pre_compression_content_type;
  5561. std::string pre_compression_content_encoding;
  5562. std::string post_compression_body;
  5563. std::string post_compression_content_type;
  5564. std::string post_compression_content_encoding;
  5565. // Set up pre-compression logger
  5566. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5567. const Response &res) {
  5568. pre_compression_body = res.body;
  5569. pre_compression_content_type = res.get_header_value("Content-Type");
  5570. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5571. });
  5572. // Set up post-compression logger
  5573. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5574. post_compression_body = res.body;
  5575. post_compression_content_type = res.get_header_value("Content-Type");
  5576. post_compression_content_encoding =
  5577. res.get_header_value("Content-Encoding");
  5578. });
  5579. // Test with gzip compression
  5580. Headers headers;
  5581. headers.emplace("Accept-Encoding", "gzip");
  5582. auto res = cli_.Get("/compress", headers);
  5583. // Verify response was compressed
  5584. ASSERT_TRUE(res);
  5585. EXPECT_EQ(StatusCode::OK_200, res->status);
  5586. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5587. // Verify pre-compression logger captured uncompressed content
  5588. EXPECT_EQ(test_content, pre_compression_body);
  5589. EXPECT_EQ("text/plain", pre_compression_content_type);
  5590. EXPECT_TRUE(pre_compression_content_encoding
  5591. .empty()); // No encoding header before compression
  5592. // Verify post-compression logger captured compressed content
  5593. EXPECT_NE(test_content,
  5594. post_compression_body); // Should be different after compression
  5595. EXPECT_EQ("text/plain", post_compression_content_type);
  5596. EXPECT_EQ("gzip", post_compression_content_encoding);
  5597. // Verify compressed content is smaller
  5598. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5599. }
  5600. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5601. const std::string test_content =
  5602. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5603. "3456789012345678901234567890";
  5604. std::string pre_compression_body;
  5605. std::string post_compression_body;
  5606. svr_.set_pre_compression_logger(
  5607. [&](const Request & /*req*/, const Response &res) {
  5608. pre_compression_body = res.body;
  5609. });
  5610. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5611. post_compression_body = res.body;
  5612. });
  5613. Headers headers;
  5614. headers.emplace("Accept-Encoding", "br");
  5615. auto res = cli_.Get("/compress", headers);
  5616. ASSERT_TRUE(res);
  5617. EXPECT_EQ(StatusCode::OK_200, res->status);
  5618. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5619. // Verify pre-compression content is uncompressed
  5620. EXPECT_EQ(test_content, pre_compression_body);
  5621. // Verify post-compression content is compressed
  5622. EXPECT_NE(test_content, post_compression_body);
  5623. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5624. }
  5625. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5626. const std::string test_content =
  5627. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5628. "3456789012345678901234567890";
  5629. std::string pre_compression_body;
  5630. std::string post_compression_body;
  5631. svr_.set_pre_compression_logger(
  5632. [&](const Request & /*req*/, const Response &res) {
  5633. pre_compression_body = res.body;
  5634. });
  5635. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5636. post_compression_body = res.body;
  5637. });
  5638. // Request without compression (use /nocompress endpoint)
  5639. Headers headers;
  5640. auto res = cli_.Get("/nocompress", headers);
  5641. ASSERT_TRUE(res);
  5642. EXPECT_EQ(StatusCode::OK_200, res->status);
  5643. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5644. // Pre-compression logger should not be called when no compression is applied
  5645. EXPECT_TRUE(
  5646. pre_compression_body.empty()); // Pre-compression logger not called
  5647. EXPECT_EQ(
  5648. test_content,
  5649. post_compression_body); // Post-compression logger captures final content
  5650. }
  5651. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5652. const std::string test_content =
  5653. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5654. "3456789012345678901234567890";
  5655. std::string pre_compression_body;
  5656. bool pre_logger_called = false;
  5657. // Set only pre-compression logger
  5658. svr_.set_pre_compression_logger(
  5659. [&](const Request & /*req*/, const Response &res) {
  5660. pre_compression_body = res.body;
  5661. pre_logger_called = true;
  5662. });
  5663. Headers headers;
  5664. headers.emplace("Accept-Encoding", "gzip");
  5665. auto res = cli_.Get("/compress", headers);
  5666. ASSERT_TRUE(res);
  5667. EXPECT_EQ(StatusCode::OK_200, res->status);
  5668. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5669. // Verify pre-compression logger was called
  5670. EXPECT_TRUE(pre_logger_called);
  5671. EXPECT_EQ(test_content, pre_compression_body);
  5672. }
  5673. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5674. {
  5675. // Test with Expect: 100-continue header - success case
  5676. // Server returns 100 Continue, client sends body, server returns 200 OK
  5677. Request req;
  5678. req.method = "POST";
  5679. req.path = "/post-large";
  5680. req.set_header("Expect", "100-continue");
  5681. req.body = LARGE_DATA;
  5682. Response res;
  5683. auto error = Error::Success;
  5684. cli_.set_keep_alive(true);
  5685. auto ret = cli_.send(req, res, error);
  5686. EXPECT_TRUE(ret);
  5687. EXPECT_EQ(StatusCode::OK_200, res.status);
  5688. EXPECT_EQ(LARGE_DATA, res.body);
  5689. }
  5690. {
  5691. // Test with Expect: 100-continue header - error case
  5692. // Client should not send the body when server returns an error
  5693. Request req;
  5694. req.method = "POST";
  5695. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5696. req.set_header("Expect", "100-continue");
  5697. req.body = LARGE_DATA;
  5698. Response res;
  5699. auto error = Error::Success;
  5700. auto start = std::chrono::high_resolution_clock::now();
  5701. cli_.set_keep_alive(true);
  5702. auto ret = cli_.send(req, res, error);
  5703. auto end = std::chrono::high_resolution_clock::now();
  5704. auto elapsed =
  5705. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5706. .count();
  5707. // With Expect: 100-continue, request completes successfully but with error
  5708. EXPECT_TRUE(ret);
  5709. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5710. EXPECT_EQ("close", res.get_header_value("Connection"));
  5711. EXPECT_FALSE(cli_.is_socket_open());
  5712. EXPECT_LE(elapsed, 200);
  5713. }
  5714. {
  5715. // Send an extra GET request to ensure error recovery without hanging
  5716. Request req;
  5717. req.method = "GET";
  5718. req.path = "/hi";
  5719. auto start = std::chrono::high_resolution_clock::now();
  5720. auto res = cli_.send(req);
  5721. auto end = std::chrono::high_resolution_clock::now();
  5722. auto elapsed =
  5723. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5724. .count();
  5725. ASSERT_TRUE(res);
  5726. EXPECT_EQ(StatusCode::OK_200, res->status);
  5727. EXPECT_EQ("Hello World!", res->body);
  5728. EXPECT_LE(elapsed, 500);
  5729. }
  5730. }
  5731. TEST(ZstdDecompressor, ChunkedDecompression) {
  5732. std::string data;
  5733. for (size_t i = 0; i < 32 * 1024; ++i) {
  5734. data.push_back(static_cast<char>('a' + i % 26));
  5735. }
  5736. std::string compressed_data;
  5737. {
  5738. httplib::detail::zstd_compressor compressor;
  5739. bool result = compressor.compress(
  5740. data.data(), data.size(),
  5741. /*last=*/true,
  5742. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5743. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5744. compressed_data_size);
  5745. return true;
  5746. });
  5747. ASSERT_TRUE(result);
  5748. }
  5749. std::string decompressed_data;
  5750. {
  5751. httplib::detail::zstd_decompressor decompressor;
  5752. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5753. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5754. size_t chunk_size = 130;
  5755. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5756. chunk_begin += chunk_size) {
  5757. size_t current_chunk_size =
  5758. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5759. bool result = decompressor.decompress(
  5760. compressed_data.data() + chunk_begin, current_chunk_size,
  5761. [&](const char *decompressed_data_chunk,
  5762. size_t decompressed_data_chunk_size) {
  5763. decompressed_data.insert(decompressed_data.size(),
  5764. decompressed_data_chunk,
  5765. decompressed_data_chunk_size);
  5766. return true;
  5767. });
  5768. ASSERT_TRUE(result);
  5769. }
  5770. }
  5771. ASSERT_EQ(data, decompressed_data);
  5772. }
  5773. TEST(ZstdDecompressor, Decompress) {
  5774. std::string original_text = "Compressed with ZSTD";
  5775. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5776. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5777. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5778. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5779. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5780. std::string decompressed_data;
  5781. {
  5782. httplib::detail::zstd_decompressor decompressor;
  5783. bool result = decompressor.decompress(
  5784. compressed_data.data(), compressed_data.size(),
  5785. [&](const char *decompressed_data_chunk,
  5786. size_t decompressed_data_chunk_size) {
  5787. decompressed_data.insert(decompressed_data.size(),
  5788. decompressed_data_chunk,
  5789. decompressed_data_chunk_size);
  5790. return true;
  5791. });
  5792. ASSERT_TRUE(result);
  5793. }
  5794. ASSERT_EQ(original_text, decompressed_data);
  5795. }
  5796. #endif
  5797. // Sends a raw request to a server listening at HOST:PORT.
  5798. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5799. std::string *resp = nullptr) {
  5800. auto error = Error::Success;
  5801. auto client_sock = detail::create_client_socket(
  5802. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5803. /*connection_timeout_sec=*/5, 0,
  5804. /*read_timeout_sec=*/5, 0,
  5805. /*write_timeout_sec=*/5, 0, std::string(), error);
  5806. if (client_sock == INVALID_SOCKET) { return false; }
  5807. auto ret = detail::process_client_socket(
  5808. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5809. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5810. if (req.size() !=
  5811. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5812. return false;
  5813. }
  5814. char buf[512];
  5815. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5816. while (line_reader.getline()) {
  5817. if (resp) { *resp += line_reader.ptr(); }
  5818. }
  5819. return true;
  5820. });
  5821. detail::close_socket(client_sock);
  5822. return ret;
  5823. }
  5824. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5825. Server svr;
  5826. std::string header_value;
  5827. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5828. header_value = req.get_header_value("foo");
  5829. res.set_content("ok", "text/plain");
  5830. });
  5831. thread t = thread([&] { svr.listen(HOST, PORT); });
  5832. auto se = detail::scope_exit([&] {
  5833. svr.stop();
  5834. t.join();
  5835. ASSERT_FALSE(svr.is_running());
  5836. });
  5837. svr.wait_until_ready();
  5838. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5839. // like characters are not treated the same - use vertical tab and escape.
  5840. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5841. "foo: \t \v bar \x1B\t \r\n"
  5842. "Connection: close\r\n"
  5843. "\r\n";
  5844. std::string res;
  5845. ASSERT_TRUE(send_request(5, req, &res));
  5846. EXPECT_EQ(header_value, "");
  5847. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5848. }
  5849. // Sends a raw request and verifies that there isn't a crash or exception.
  5850. static void test_raw_request(const std::string &req,
  5851. std::string *out = nullptr) {
  5852. Server svr;
  5853. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5854. res.set_content("ok", "text/plain");
  5855. });
  5856. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5857. res.set_content("ok", "text/plain");
  5858. });
  5859. svr.Get("/header_field_value_check",
  5860. [&](const Request & /*req*/, Response &res) {
  5861. res.set_content("ok", "text/plain");
  5862. });
  5863. // Server read timeout must be longer than the client read timeout for the
  5864. // bug to reproduce, probably to force the server to process a request
  5865. // without a trailing blank line.
  5866. const time_t client_read_timeout_sec = 1;
  5867. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5868. bool listen_thread_ok = false;
  5869. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5870. auto se = detail::scope_exit([&] {
  5871. svr.stop();
  5872. t.join();
  5873. ASSERT_FALSE(svr.is_running());
  5874. EXPECT_TRUE(listen_thread_ok);
  5875. });
  5876. svr.wait_until_ready();
  5877. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5878. }
  5879. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5880. // A certain header line causes an exception if the header property is parsed
  5881. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5882. test_raw_request(
  5883. "GET /hi HTTP/1.1\r\n"
  5884. " : "
  5885. " "
  5886. " ");
  5887. }
  5888. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5889. // A certain header line causes an exception if the header property *name* is
  5890. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5891. // greedy matcher and requires backtracking when there are a lot of ":"
  5892. // characters.
  5893. // This occurs with libc++ but not libstdc++.
  5894. test_raw_request(
  5895. "GET /hi HTTP/1.1\r\n"
  5896. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5897. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5898. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5899. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5900. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5901. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5902. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5903. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5904. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5905. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5906. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5907. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5908. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5909. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5910. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5911. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5912. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5913. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5914. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5915. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5916. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5917. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5918. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5919. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5920. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5921. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5922. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5923. "&&&%%%");
  5924. }
  5925. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5926. // Make sure this doesn't crash the server.
  5927. // In a previous version of the header line regex, the "\r" rendered the line
  5928. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5929. // a new position where the leading white space ended and the field value
  5930. // began.
  5931. // The crash occurs with libc++ but not libstdc++.
  5932. test_raw_request("GET /hi HTTP/1.1\r\n"
  5933. "a:" +
  5934. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5935. "\r\n"
  5936. "\r\n");
  5937. }
  5938. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5939. std::string out;
  5940. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5941. "Content-Type: text/plain\r\n"
  5942. "Transfer-Encoding: chunked\r\n"
  5943. "\r\n"
  5944. "nothex\r\n",
  5945. &out);
  5946. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5947. }
  5948. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5949. std::string out;
  5950. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5951. "Content-Type: text/plain\r\n"
  5952. "Transfer-Encoding: chunked\r\n"
  5953. "\r\n"
  5954. "3\r\n"
  5955. "xyz\r\n"
  5956. "NaN\r\n",
  5957. &out);
  5958. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5959. }
  5960. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5961. std::string out;
  5962. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5963. "Content-Type: text/plain\r\n"
  5964. "Transfer-Encoding: chunked\r\n"
  5965. "\r\n"
  5966. // Length is too large for 64 bits.
  5967. "1ffffffffffffffff\r\n"
  5968. "xyz\r\n",
  5969. &out);
  5970. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5971. }
  5972. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5973. test_raw_request("GET /hi HTTP/1.1\r\n"
  5974. "Content-Type: text/plain\r\n\r");
  5975. }
  5976. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5977. std::string out;
  5978. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5979. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5980. }
  5981. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  5982. Server svr;
  5983. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  5984. EXPECT_TRUE(!req.remote_addr.empty());
  5985. });
  5986. thread t = thread([&] { svr.listen(HOST, PORT); });
  5987. auto se = detail::scope_exit([&] {
  5988. svr.stop();
  5989. t.join();
  5990. ASSERT_FALSE(svr.is_running());
  5991. });
  5992. svr.wait_until_ready();
  5993. // Send an invalid request line to trigger Bad Request
  5994. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  5995. std::string out;
  5996. ASSERT_TRUE(send_request(5, bad_req, &out));
  5997. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5998. }
  5999. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6000. std::string out;
  6001. std::string request(
  6002. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6003. test_raw_request(request, &out);
  6004. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6005. }
  6006. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6007. std::string out;
  6008. std::string request(
  6009. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6010. test_raw_request(request, &out);
  6011. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6012. }
  6013. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6014. std::string out;
  6015. std::string request(
  6016. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6017. test_raw_request(request, &out);
  6018. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6019. }
  6020. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6021. std::string out;
  6022. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6023. "Test: \r\n\r\n",
  6024. &out);
  6025. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6026. }
  6027. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6028. Server svr;
  6029. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6030. res.set_header("Cache-Control", "no-cache");
  6031. res.set_chunked_content_provider(
  6032. "text/event-stream", [](size_t offset, DataSink &sink) {
  6033. std::string s = "data:";
  6034. s += std::to_string(offset);
  6035. s += "\n\n";
  6036. auto ret = sink.write(s.data(), s.size());
  6037. EXPECT_TRUE(ret);
  6038. std::this_thread::sleep_for(std::chrono::seconds(1));
  6039. return true;
  6040. });
  6041. });
  6042. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6043. svr.wait_until_ready();
  6044. Client client(HOST, PORT);
  6045. const Headers headers = {{"Accept", "text/event-stream"}};
  6046. auto get_thread = std::thread([&client, &headers]() {
  6047. auto res = client.Get(
  6048. "/events", headers,
  6049. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6050. });
  6051. auto se = detail::scope_exit([&] {
  6052. svr.stop();
  6053. get_thread.join();
  6054. listen_thread.join();
  6055. ASSERT_FALSE(svr.is_running());
  6056. });
  6057. // Give GET time to get a few messages.
  6058. std::this_thread::sleep_for(std::chrono::seconds(2));
  6059. }
  6060. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6061. httplib::Server svr;
  6062. svr.Post("/hi",
  6063. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6064. res.status = StatusCode::OK_200;
  6065. });
  6066. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6067. svr.wait_until_ready();
  6068. Client cli(HOST, PORT);
  6069. auto res = cli.Post("/hi", "data", "text/plain");
  6070. ASSERT_TRUE(res);
  6071. EXPECT_EQ(StatusCode::OK_200, res->status);
  6072. svr.stop();
  6073. thread.join();
  6074. ASSERT_FALSE(svr.is_running());
  6075. res = cli.Post("/hi", "data", "text/plain");
  6076. ASSERT_FALSE(res);
  6077. }
  6078. TEST(ServerStopTest, ListenFailure) {
  6079. Server svr;
  6080. auto t = thread([&]() {
  6081. auto ret = svr.listen("????", PORT);
  6082. EXPECT_FALSE(ret);
  6083. });
  6084. svr.wait_until_ready();
  6085. svr.stop();
  6086. t.join();
  6087. }
  6088. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6089. TEST(ServerStopTest, Decommision) {
  6090. Server svr;
  6091. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6092. for (int i = 0; i < 4; i++) {
  6093. auto is_even = !(i % 2);
  6094. std::thread t{[&] {
  6095. try {
  6096. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6097. if (is_even) {
  6098. throw std::runtime_error("Some thing that happens to go wrong.");
  6099. }
  6100. svr.listen(HOST, PORT);
  6101. } catch (...) { svr.decommission(); }
  6102. }};
  6103. svr.wait_until_ready();
  6104. // Server is up
  6105. {
  6106. Client cli(HOST, PORT);
  6107. auto res = cli.Get("/hi");
  6108. if (is_even) {
  6109. EXPECT_FALSE(res);
  6110. } else {
  6111. EXPECT_TRUE(res);
  6112. EXPECT_EQ("hi...", res->body);
  6113. }
  6114. }
  6115. svr.stop();
  6116. t.join();
  6117. // Server is down...
  6118. {
  6119. Client cli(HOST, PORT);
  6120. auto res = cli.Get("/hi");
  6121. EXPECT_FALSE(res);
  6122. }
  6123. }
  6124. }
  6125. #endif
  6126. // Helper function for string body upload progress tests
  6127. template <typename SetupHandler, typename ClientCall>
  6128. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6129. ClientCall &&client_call,
  6130. const string &body) {
  6131. Server svr;
  6132. setup_handler(svr);
  6133. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6134. auto se = detail::scope_exit([&] {
  6135. svr.stop();
  6136. t.join();
  6137. });
  6138. svr.wait_until_ready();
  6139. Client cli(HOST, PORT);
  6140. vector<uint64_t> progress_values;
  6141. bool progress_called = false;
  6142. auto res =
  6143. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6144. progress_values.push_back(current);
  6145. progress_called = true;
  6146. return true;
  6147. });
  6148. ASSERT_TRUE(res);
  6149. EXPECT_EQ(200, res->status);
  6150. EXPECT_TRUE(progress_called);
  6151. }
  6152. TEST(UploadProgressTest, PostStringBodyBasic) {
  6153. TestStringBodyUploadProgress(
  6154. [](Server &svr) {
  6155. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6156. res.set_content("received", "text/plain");
  6157. });
  6158. },
  6159. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6160. return cli.Post("/test", body, "text/plain", progress_callback);
  6161. },
  6162. "test data for upload progress");
  6163. }
  6164. TEST(UploadProgressTest, PutStringBodyBasic) {
  6165. TestStringBodyUploadProgress(
  6166. [](Server &svr) {
  6167. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6168. res.set_content("put received", "text/plain");
  6169. });
  6170. },
  6171. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6172. return cli.Put("/test", body, "text/plain", progress_callback);
  6173. },
  6174. "put test data for upload progress");
  6175. }
  6176. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6177. TestStringBodyUploadProgress(
  6178. [](Server &svr) {
  6179. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6180. res.set_content("patch received", "text/plain");
  6181. });
  6182. },
  6183. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6184. return cli.Patch("/test", body, "text/plain", progress_callback);
  6185. },
  6186. "patch test data for upload progress");
  6187. }
  6188. // Helper function for content provider upload progress tests
  6189. template <typename SetupHandler, typename ClientCall>
  6190. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6191. ClientCall &&client_call) {
  6192. Server svr;
  6193. setup_handler(svr);
  6194. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6195. auto se = detail::scope_exit([&] {
  6196. svr.stop();
  6197. t.join();
  6198. });
  6199. svr.wait_until_ready();
  6200. Client cli(HOST, PORT);
  6201. vector<uint64_t> progress_values;
  6202. auto res =
  6203. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6204. progress_values.push_back(current);
  6205. return true;
  6206. });
  6207. ASSERT_TRUE(res);
  6208. EXPECT_EQ(200, res->status);
  6209. EXPECT_FALSE(progress_values.empty());
  6210. }
  6211. TEST(UploadProgressTest, PostContentProviderProgress) {
  6212. TestContentProviderUploadProgress(
  6213. [](Server &svr) {
  6214. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6215. res.set_content("provider received", "text/plain");
  6216. });
  6217. },
  6218. [](Client &cli, UploadProgress progress_callback) {
  6219. return cli.Post(
  6220. "/test", 10,
  6221. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6222. sink.os << "test data";
  6223. return true;
  6224. },
  6225. "text/plain", progress_callback);
  6226. });
  6227. }
  6228. // Helper function for multipart upload progress tests
  6229. template <typename SetupHandler, typename ClientCall>
  6230. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6231. ClientCall &&client_call,
  6232. const string &endpoint) {
  6233. Server svr;
  6234. setup_handler(svr);
  6235. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6236. auto se = detail::scope_exit([&] {
  6237. svr.stop();
  6238. t.join();
  6239. });
  6240. svr.wait_until_ready();
  6241. Client cli(HOST, PORT);
  6242. vector<uint64_t> progress_values;
  6243. UploadFormDataItems items = {
  6244. {"field1", "value1", "", ""},
  6245. {"field2", "longer value for progress tracking test", "", ""},
  6246. {"file1", "file content data for upload progress", "test.txt",
  6247. "text/plain"}};
  6248. auto res = client_call(cli, endpoint, items,
  6249. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6250. progress_values.push_back(current);
  6251. return true;
  6252. });
  6253. ASSERT_TRUE(res);
  6254. EXPECT_EQ(200, res->status);
  6255. EXPECT_FALSE(progress_values.empty());
  6256. }
  6257. TEST(UploadProgressTest, PostMultipartProgress) {
  6258. TestMultipartUploadProgress(
  6259. [](Server &svr) {
  6260. svr.Post("/multipart", [](const Request &req, Response &res) {
  6261. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6262. res.set_content("multipart received", "text/plain");
  6263. });
  6264. },
  6265. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6266. UploadProgress progress_callback) {
  6267. return cli.Post(endpoint, items, progress_callback);
  6268. },
  6269. "/multipart");
  6270. }
  6271. // Helper function for basic download progress tests
  6272. template <typename SetupHandler, typename ClientCall>
  6273. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6274. ClientCall &&client_call, const string &endpoint,
  6275. size_t expected_content_size) {
  6276. Server svr;
  6277. setup_handler(svr);
  6278. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6279. auto se = detail::scope_exit([&] {
  6280. svr.stop();
  6281. t.join();
  6282. });
  6283. svr.wait_until_ready();
  6284. Client cli(HOST, PORT);
  6285. vector<uint64_t> progress_values;
  6286. auto res = client_call(cli, endpoint,
  6287. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6288. progress_values.push_back(current);
  6289. return true;
  6290. });
  6291. ASSERT_TRUE(res);
  6292. EXPECT_EQ(200, res->status);
  6293. EXPECT_FALSE(progress_values.empty());
  6294. EXPECT_EQ(expected_content_size, res->body.size());
  6295. }
  6296. TEST(DownloadProgressTest, GetBasic) {
  6297. TestBasicDownloadProgress(
  6298. [](Server &svr) {
  6299. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6300. string content(1000, 'D');
  6301. res.set_content(content, "text/plain");
  6302. });
  6303. },
  6304. [](Client &cli, const string &endpoint,
  6305. DownloadProgress progress_callback) {
  6306. return cli.Get(endpoint, progress_callback);
  6307. },
  6308. "/download", 1000u);
  6309. }
  6310. // Helper function for content receiver download progress tests
  6311. template <typename SetupHandler, typename ClientCall>
  6312. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6313. ClientCall &&client_call,
  6314. const string &endpoint,
  6315. size_t expected_content_size) {
  6316. Server svr;
  6317. setup_handler(svr);
  6318. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6319. auto se = detail::scope_exit([&] {
  6320. svr.stop();
  6321. t.join();
  6322. });
  6323. svr.wait_until_ready();
  6324. Client cli(HOST, PORT);
  6325. vector<uint64_t> progress_values;
  6326. string received_body;
  6327. auto res = client_call(
  6328. cli, endpoint,
  6329. [&](const char *data, size_t data_length) -> bool {
  6330. received_body.append(data, data_length);
  6331. return true;
  6332. },
  6333. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6334. progress_values.push_back(current);
  6335. return true;
  6336. });
  6337. ASSERT_TRUE(res);
  6338. EXPECT_EQ(200, res->status);
  6339. EXPECT_FALSE(progress_values.empty());
  6340. EXPECT_EQ(expected_content_size, received_body.size());
  6341. EXPECT_TRUE(res->body.empty());
  6342. }
  6343. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6344. TestContentReceiverDownloadProgress(
  6345. [](Server &svr) {
  6346. svr.Get("/download-receiver",
  6347. [](const Request & /*req*/, Response &res) {
  6348. string content(2000, 'R');
  6349. res.set_content(content, "text/plain");
  6350. });
  6351. },
  6352. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6353. DownloadProgress progress_callback) {
  6354. return cli.Get(endpoint, content_receiver, progress_callback);
  6355. },
  6356. "/download-receiver", 2000u);
  6357. }
  6358. TEST(StreamingTest, NoContentLengthStreaming) {
  6359. Server svr;
  6360. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6361. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6362. if (offset < 6) {
  6363. sink.os << (offset < 3 ? "a" : "b");
  6364. } else {
  6365. sink.done();
  6366. }
  6367. return true;
  6368. });
  6369. });
  6370. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6371. auto listen_se = detail::scope_exit([&] {
  6372. svr.stop();
  6373. listen_thread.join();
  6374. ASSERT_FALSE(svr.is_running());
  6375. });
  6376. svr.wait_until_ready();
  6377. Client client(HOST, PORT);
  6378. auto get_thread = std::thread([&client]() {
  6379. std::string s;
  6380. auto res =
  6381. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6382. s += std::string(data, len);
  6383. return true;
  6384. });
  6385. ASSERT_TRUE(res);
  6386. EXPECT_EQ(StatusCode::OK_200, res->status);
  6387. EXPECT_EQ("aaabbb", s);
  6388. });
  6389. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6390. // Give GET time to get a few messages.
  6391. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6392. }
  6393. TEST(MountTest, Unmount) {
  6394. Server svr;
  6395. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6396. auto se = detail::scope_exit([&] {
  6397. svr.stop();
  6398. listen_thread.join();
  6399. ASSERT_FALSE(svr.is_running());
  6400. });
  6401. svr.wait_until_ready();
  6402. Client cli("localhost", PORT);
  6403. svr.set_mount_point("/mount2", "./www2");
  6404. auto res = cli.Get("/");
  6405. ASSERT_TRUE(res);
  6406. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6407. res = cli.Get("/mount2/dir/test.html");
  6408. ASSERT_TRUE(res);
  6409. EXPECT_EQ(StatusCode::OK_200, res->status);
  6410. svr.set_mount_point("/", "./www");
  6411. res = cli.Get("/dir/");
  6412. ASSERT_TRUE(res);
  6413. EXPECT_EQ(StatusCode::OK_200, res->status);
  6414. svr.remove_mount_point("/");
  6415. res = cli.Get("/dir/");
  6416. ASSERT_TRUE(res);
  6417. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6418. svr.remove_mount_point("/mount2");
  6419. res = cli.Get("/mount2/dir/test.html");
  6420. ASSERT_TRUE(res);
  6421. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6422. }
  6423. TEST(MountTest, Redicect) {
  6424. Server svr;
  6425. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6426. auto se = detail::scope_exit([&] {
  6427. svr.stop();
  6428. listen_thread.join();
  6429. ASSERT_FALSE(svr.is_running());
  6430. });
  6431. svr.set_mount_point("/", "./www");
  6432. svr.wait_until_ready();
  6433. Client cli("localhost", PORT);
  6434. auto res = cli.Get("/dir/");
  6435. ASSERT_TRUE(res);
  6436. EXPECT_EQ(StatusCode::OK_200, res->status);
  6437. res = cli.Get("/dir");
  6438. ASSERT_TRUE(res);
  6439. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6440. res = cli.Get("/file");
  6441. ASSERT_TRUE(res);
  6442. EXPECT_EQ(StatusCode::OK_200, res->status);
  6443. res = cli.Get("/file/");
  6444. ASSERT_TRUE(res);
  6445. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6446. cli.set_follow_location(true);
  6447. res = cli.Get("/dir");
  6448. ASSERT_TRUE(res);
  6449. EXPECT_EQ(StatusCode::OK_200, res->status);
  6450. }
  6451. TEST(MountTest, MultibytesPathName) {
  6452. Server svr;
  6453. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6454. auto se = detail::scope_exit([&] {
  6455. svr.stop();
  6456. listen_thread.join();
  6457. ASSERT_FALSE(svr.is_running());
  6458. });
  6459. svr.set_mount_point("/", "./www");
  6460. svr.wait_until_ready();
  6461. Client cli("localhost", PORT);
  6462. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6463. ASSERT_TRUE(res);
  6464. EXPECT_EQ(StatusCode::OK_200, res->status);
  6465. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6466. }
  6467. TEST(KeepAliveTest, ReadTimeout) {
  6468. Server svr;
  6469. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6470. std::this_thread::sleep_for(std::chrono::seconds(2));
  6471. res.set_content("a", "text/plain");
  6472. });
  6473. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6474. res.set_content("b", "text/plain");
  6475. });
  6476. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6477. auto se = detail::scope_exit([&] {
  6478. svr.stop();
  6479. listen_thread.join();
  6480. ASSERT_FALSE(svr.is_running());
  6481. });
  6482. svr.wait_until_ready();
  6483. Client cli("localhost", PORT);
  6484. cli.set_keep_alive(true);
  6485. cli.set_read_timeout(std::chrono::seconds(1));
  6486. auto resa = cli.Get("/a");
  6487. ASSERT_FALSE(resa);
  6488. EXPECT_EQ(Error::Read, resa.error());
  6489. auto resb = cli.Get("/b");
  6490. ASSERT_TRUE(resb);
  6491. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6492. EXPECT_EQ("b", resb->body);
  6493. }
  6494. TEST(KeepAliveTest, MaxCount) {
  6495. size_t keep_alive_max_count = 3;
  6496. Server svr;
  6497. svr.set_keep_alive_max_count(keep_alive_max_count);
  6498. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6499. res.set_content("Hello World!", "text/plain");
  6500. });
  6501. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6502. auto se = detail::scope_exit([&] {
  6503. svr.stop();
  6504. listen_thread.join();
  6505. ASSERT_FALSE(svr.is_running());
  6506. });
  6507. svr.wait_until_ready();
  6508. Client cli(HOST, PORT);
  6509. cli.set_keep_alive(true);
  6510. for (size_t i = 0; i < 5; i++) {
  6511. auto result = cli.Get("/hi");
  6512. ASSERT_TRUE(result);
  6513. EXPECT_EQ(StatusCode::OK_200, result->status);
  6514. if (i == keep_alive_max_count - 1) {
  6515. EXPECT_EQ("close", result->get_header_value("Connection"));
  6516. } else {
  6517. EXPECT_FALSE(result->has_header("Connection"));
  6518. }
  6519. }
  6520. }
  6521. TEST(KeepAliveTest, Issue1041) {
  6522. Server svr;
  6523. svr.set_keep_alive_timeout(3);
  6524. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6525. res.set_content("Hello World!", "text/plain");
  6526. });
  6527. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6528. auto se = detail::scope_exit([&] {
  6529. svr.stop();
  6530. listen_thread.join();
  6531. ASSERT_FALSE(svr.is_running());
  6532. });
  6533. svr.wait_until_ready();
  6534. Client cli(HOST, PORT);
  6535. cli.set_keep_alive(true);
  6536. auto result = cli.Get("/hi");
  6537. ASSERT_TRUE(result);
  6538. EXPECT_EQ(StatusCode::OK_200, result->status);
  6539. std::this_thread::sleep_for(std::chrono::seconds(5));
  6540. result = cli.Get("/hi");
  6541. ASSERT_TRUE(result);
  6542. EXPECT_EQ(StatusCode::OK_200, result->status);
  6543. }
  6544. TEST(KeepAliveTest, Issue1959) {
  6545. Server svr;
  6546. svr.set_keep_alive_timeout(5);
  6547. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6548. res.set_content("a", "text/plain");
  6549. });
  6550. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6551. auto se = detail::scope_exit([&] {
  6552. if (!svr.is_running()) return;
  6553. svr.stop();
  6554. listen_thread.join();
  6555. ASSERT_FALSE(svr.is_running());
  6556. });
  6557. svr.wait_until_ready();
  6558. Client cli("localhost", PORT);
  6559. cli.set_keep_alive(true);
  6560. using namespace std::chrono;
  6561. auto start = steady_clock::now();
  6562. cli.Get("/a");
  6563. svr.stop();
  6564. listen_thread.join();
  6565. auto end = steady_clock::now();
  6566. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6567. EXPECT_LT(elapsed, 5000);
  6568. }
  6569. #ifdef CPPHTTPLIB_SSL_ENABLED
  6570. TEST(KeepAliveTest, SSLClientReconnection) {
  6571. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6572. ASSERT_TRUE(svr.is_valid());
  6573. svr.set_keep_alive_timeout(1);
  6574. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6575. res.set_content("Hello World!", "text/plain");
  6576. });
  6577. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6578. auto se = detail::scope_exit([&] {
  6579. svr.stop();
  6580. listen_thread.join();
  6581. ASSERT_FALSE(svr.is_running());
  6582. });
  6583. svr.wait_until_ready();
  6584. SSLClient cli(HOST, PORT);
  6585. cli.enable_server_certificate_verification(false);
  6586. cli.set_keep_alive(true);
  6587. auto result = cli.Get("/hi");
  6588. ASSERT_TRUE(result);
  6589. EXPECT_EQ(StatusCode::OK_200, result->status);
  6590. result = cli.Get("/hi");
  6591. ASSERT_TRUE(result);
  6592. EXPECT_EQ(StatusCode::OK_200, result->status);
  6593. std::this_thread::sleep_for(std::chrono::seconds(2));
  6594. // Recoonect
  6595. result = cli.Get("/hi");
  6596. ASSERT_TRUE(result);
  6597. EXPECT_EQ(StatusCode::OK_200, result->status);
  6598. result = cli.Get("/hi");
  6599. ASSERT_TRUE(result);
  6600. EXPECT_EQ(StatusCode::OK_200, result->status);
  6601. }
  6602. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6603. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6604. ASSERT_TRUE(svr.is_valid());
  6605. svr.set_keep_alive_timeout(1);
  6606. std::string content = "reconnect";
  6607. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6608. res.set_content("Hello World!", "text/plain");
  6609. });
  6610. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6611. auto se = detail::scope_exit([&] {
  6612. svr.stop();
  6613. listen_thread.join();
  6614. ASSERT_FALSE(svr.is_running());
  6615. });
  6616. svr.wait_until_ready();
  6617. SSLClient cli(HOST, PORT);
  6618. cli.enable_server_certificate_verification(false);
  6619. cli.set_keep_alive(true);
  6620. auto result = cli.Post(
  6621. "/hi", content.size(),
  6622. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6623. sink.write(content.c_str(), content.size());
  6624. return true;
  6625. },
  6626. "text/plain");
  6627. ASSERT_TRUE(result);
  6628. EXPECT_EQ(200, result->status);
  6629. std::this_thread::sleep_for(std::chrono::seconds(2));
  6630. // Recoonect
  6631. result = cli.Post(
  6632. "/hi", content.size(),
  6633. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6634. sink.write(content.c_str(), content.size());
  6635. return true;
  6636. },
  6637. "text/plain");
  6638. ASSERT_TRUE(result);
  6639. EXPECT_EQ(200, result->status);
  6640. result = cli.Post(
  6641. "/hi", content.size(),
  6642. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6643. sink.write(content.c_str(), content.size());
  6644. return true;
  6645. },
  6646. "text/plain");
  6647. ASSERT_TRUE(result);
  6648. EXPECT_EQ(200, result->status);
  6649. }
  6650. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6651. using namespace httplib::tls;
  6652. {
  6653. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6654. ASSERT_TRUE(svr.is_valid());
  6655. svr.Get("/sni", [&](const Request &req, Response &res) {
  6656. std::string expected = req.sni();
  6657. EXPECT_EQ(expected, req.get_param_value("expected"));
  6658. res.set_content("ok", "text/plain");
  6659. });
  6660. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6661. auto se = detail::scope_exit([&] {
  6662. svr.stop();
  6663. listen_thread.join();
  6664. ASSERT_FALSE(svr.is_running());
  6665. });
  6666. svr.wait_until_ready();
  6667. {
  6668. SSLClient cli("localhost", PORT);
  6669. cli.enable_server_certificate_verification(false);
  6670. auto res = cli.Get("/sni?expected=localhost");
  6671. ASSERT_TRUE(res);
  6672. }
  6673. {
  6674. SSLClient cli("::1", PORT);
  6675. cli.enable_server_certificate_verification(false);
  6676. auto res = cli.Get("/sni?expected=");
  6677. // NOTE: This may fail if the server is listening on IPv4 only
  6678. // (e.g., when localhost resolves to 127.0.0.1 only)
  6679. if (res) {
  6680. EXPECT_EQ(StatusCode::OK_200, res->status);
  6681. } else {
  6682. EXPECT_EQ(Error::Connection, res.error());
  6683. }
  6684. }
  6685. }
  6686. }
  6687. #endif
  6688. TEST(ClientProblemDetectionTest, ContentProvider) {
  6689. Server svr;
  6690. size_t content_length = 1024 * 1024;
  6691. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6692. res.set_content_provider(
  6693. content_length, "text/plain",
  6694. [&](size_t offset, size_t length, DataSink &sink) {
  6695. auto out_len = std::min(length, static_cast<size_t>(1024));
  6696. std::string out(out_len, '@');
  6697. sink.write(out.data(), out_len);
  6698. return offset < 4096;
  6699. },
  6700. [](bool success) { ASSERT_FALSE(success); });
  6701. });
  6702. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6703. res.set_content_provider(
  6704. 0, "text/plain",
  6705. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6706. EXPECT_TRUE(false);
  6707. return true;
  6708. },
  6709. [](bool success) { ASSERT_FALSE(success); });
  6710. });
  6711. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6712. auto se = detail::scope_exit([&] {
  6713. svr.stop();
  6714. listen_thread.join();
  6715. ASSERT_FALSE(svr.is_running());
  6716. });
  6717. svr.wait_until_ready();
  6718. Client cli("localhost", PORT);
  6719. {
  6720. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6721. size_t /*data_length*/) { return false; });
  6722. ASSERT_FALSE(res);
  6723. }
  6724. {
  6725. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6726. size_t /*data_length*/) { return false; });
  6727. ASSERT_TRUE(res);
  6728. }
  6729. }
  6730. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6731. Server svr;
  6732. svr.set_error_handler([](Request const &, Response &res) -> void {
  6733. res.set_chunked_content_provider(
  6734. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6735. sink.os << "hello";
  6736. sink.os << "world";
  6737. sink.done();
  6738. return true;
  6739. });
  6740. });
  6741. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6742. auto se = detail::scope_exit([&] {
  6743. svr.stop();
  6744. listen_thread.join();
  6745. ASSERT_FALSE(svr.is_running());
  6746. });
  6747. svr.wait_until_ready();
  6748. Client cli("localhost", PORT);
  6749. auto res = cli.Get("/");
  6750. ASSERT_TRUE(res);
  6751. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6752. EXPECT_EQ("helloworld", res->body);
  6753. }
  6754. TEST(LongPollingTest, ClientCloseDetection) {
  6755. Server svr;
  6756. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6757. res.set_chunked_content_provider(
  6758. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6759. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6760. sink.os << "hello";
  6761. auto count = 10;
  6762. while (count > 0 && sink.is_writable()) {
  6763. this_thread::sleep_for(chrono::milliseconds(10));
  6764. count--;
  6765. }
  6766. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6767. return true;
  6768. });
  6769. });
  6770. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6771. auto se = detail::scope_exit([&] {
  6772. svr.stop();
  6773. listen_thread.join();
  6774. ASSERT_FALSE(svr.is_running());
  6775. });
  6776. svr.wait_until_ready();
  6777. Client cli("localhost", PORT);
  6778. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6779. EXPECT_EQ("hello", string(data, data_length));
  6780. return false; // close the socket immediately.
  6781. });
  6782. ASSERT_FALSE(res);
  6783. }
  6784. TEST(GetWithParametersTest, GetWithParameters) {
  6785. Server svr;
  6786. svr.Get("/", [&](const Request &req, Response &) {
  6787. EXPECT_EQ("world", req.get_param_value("hello"));
  6788. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6789. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6790. });
  6791. svr.Get("/params", [&](const Request &req, Response &) {
  6792. EXPECT_EQ("world", req.get_param_value("hello"));
  6793. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6794. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6795. });
  6796. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6797. EXPECT_EQ("resource-id", req.matches[1]);
  6798. EXPECT_EQ("foo", req.get_param_value("param1"));
  6799. EXPECT_EQ("bar", req.get_param_value("param2"));
  6800. });
  6801. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6802. EXPECT_EQ("user-id", req.path_params.at("id"));
  6803. EXPECT_EQ("foo", req.get_param_value("param1"));
  6804. EXPECT_EQ("bar", req.get_param_value("param2"));
  6805. });
  6806. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6807. auto se = detail::scope_exit([&] {
  6808. svr.stop();
  6809. listen_thread.join();
  6810. ASSERT_FALSE(svr.is_running());
  6811. });
  6812. svr.wait_until_ready();
  6813. {
  6814. Client cli(HOST, PORT);
  6815. Params params;
  6816. params.emplace("hello", "world");
  6817. params.emplace("hello2", "world2");
  6818. params.emplace("hello3", "world3");
  6819. auto res = cli.Get("/", params, Headers{});
  6820. ASSERT_TRUE(res);
  6821. EXPECT_EQ(StatusCode::OK_200, res->status);
  6822. }
  6823. {
  6824. Client cli(HOST, PORT);
  6825. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6826. ASSERT_TRUE(res);
  6827. EXPECT_EQ(StatusCode::OK_200, res->status);
  6828. }
  6829. {
  6830. Client cli(HOST, PORT);
  6831. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6832. ASSERT_TRUE(res);
  6833. EXPECT_EQ(StatusCode::OK_200, res->status);
  6834. }
  6835. {
  6836. Client cli(HOST, PORT);
  6837. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6838. ASSERT_TRUE(res);
  6839. EXPECT_EQ(StatusCode::OK_200, res->status);
  6840. }
  6841. }
  6842. TEST(GetWithParametersTest, GetWithParameters2) {
  6843. Server svr;
  6844. svr.Get("/", [&](const Request &req, Response &res) {
  6845. auto text = req.get_param_value("hello");
  6846. res.set_content(text, "text/plain");
  6847. });
  6848. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6849. auto se = detail::scope_exit([&] {
  6850. svr.stop();
  6851. listen_thread.join();
  6852. ASSERT_FALSE(svr.is_running());
  6853. });
  6854. svr.wait_until_ready();
  6855. Client cli("localhost", PORT);
  6856. Params params;
  6857. params.emplace("hello", "world");
  6858. std::string body;
  6859. auto res = cli.Get("/", params, Headers{},
  6860. [&](const char *data, size_t data_length) {
  6861. body.append(data, data_length);
  6862. return true;
  6863. });
  6864. ASSERT_TRUE(res);
  6865. EXPECT_EQ(StatusCode::OK_200, res->status);
  6866. EXPECT_EQ("world", body);
  6867. }
  6868. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6869. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6870. auto host = "httpcan.org";
  6871. auto path = std::string{"/range/32"};
  6872. #else
  6873. auto host = "nghttp2.org";
  6874. auto path = std::string{"/httpbin/range/32"};
  6875. #endif
  6876. #ifdef CPPHTTPLIB_SSL_ENABLED
  6877. SSLClient cli(host);
  6878. #else
  6879. Client cli(host);
  6880. #endif
  6881. cli.set_default_headers({make_range_header({{1, 10}})});
  6882. cli.set_connection_timeout(5);
  6883. {
  6884. auto res = cli.Get(path);
  6885. ASSERT_TRUE(res);
  6886. EXPECT_EQ("bcdefghijk", res->body);
  6887. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6888. }
  6889. {
  6890. auto res = cli.Get(path);
  6891. ASSERT_TRUE(res);
  6892. EXPECT_EQ("bcdefghijk", res->body);
  6893. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6894. }
  6895. }
  6896. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6897. Server svr;
  6898. svr.set_default_headers({{"Hello", "World"}});
  6899. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6900. res.set_content("ok", "text/plain");
  6901. });
  6902. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6903. auto se = detail::scope_exit([&] {
  6904. svr.stop();
  6905. listen_thread.join();
  6906. ASSERT_FALSE(svr.is_running());
  6907. });
  6908. svr.wait_until_ready();
  6909. Client cli("localhost", PORT);
  6910. auto res = cli.Get("/");
  6911. ASSERT_TRUE(res);
  6912. EXPECT_EQ(StatusCode::OK_200, res->status);
  6913. EXPECT_EQ("ok", res->body);
  6914. EXPECT_EQ("World", res->get_header_value("Hello"));
  6915. }
  6916. #ifdef CPPHTTPLIB_SSL_ENABLED
  6917. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6918. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6919. ASSERT_TRUE(svr.is_valid());
  6920. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6921. std::this_thread::sleep_for(std::chrono::seconds(2));
  6922. res.set_content("a", "text/plain");
  6923. });
  6924. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6925. res.set_content("b", "text/plain");
  6926. });
  6927. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6928. auto se = detail::scope_exit([&] {
  6929. svr.stop();
  6930. listen_thread.join();
  6931. ASSERT_FALSE(svr.is_running());
  6932. });
  6933. svr.wait_until_ready();
  6934. SSLClient cli("localhost", PORT);
  6935. cli.enable_server_certificate_verification(false);
  6936. cli.set_keep_alive(true);
  6937. cli.set_read_timeout(std::chrono::seconds(1));
  6938. auto resa = cli.Get("/a");
  6939. ASSERT_TRUE(!resa);
  6940. EXPECT_EQ(Error::Read, resa.error());
  6941. auto resb = cli.Get("/b");
  6942. ASSERT_TRUE(resb);
  6943. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6944. EXPECT_EQ("b", resb->body);
  6945. }
  6946. #endif
  6947. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6948. protected:
  6949. ServerTestWithAI_PASSIVE()
  6950. : cli_(HOST, PORT)
  6951. #ifdef CPPHTTPLIB_SSL_ENABLED
  6952. ,
  6953. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6954. #endif
  6955. {
  6956. #ifdef CPPHTTPLIB_SSL_ENABLED
  6957. cli_.enable_server_certificate_verification(false);
  6958. #endif
  6959. }
  6960. virtual void SetUp() {
  6961. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6962. res.set_content("Hello World!", "text/plain");
  6963. });
  6964. t_ = thread(
  6965. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6966. svr_.wait_until_ready();
  6967. }
  6968. virtual void TearDown() {
  6969. svr_.stop();
  6970. t_.join();
  6971. }
  6972. #ifdef CPPHTTPLIB_SSL_ENABLED
  6973. SSLClient cli_;
  6974. SSLServer svr_;
  6975. #else
  6976. Client cli_;
  6977. Server svr_;
  6978. #endif
  6979. thread t_;
  6980. };
  6981. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6982. auto res = cli_.Get("/hi");
  6983. ASSERT_TRUE(res);
  6984. EXPECT_EQ(StatusCode::OK_200, res->status);
  6985. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6986. EXPECT_EQ("Hello World!", res->body);
  6987. }
  6988. class ServerUpDownTest : public ::testing::Test {
  6989. protected:
  6990. ServerUpDownTest() : cli_(HOST, PORT) {}
  6991. virtual void SetUp() {
  6992. t_ = thread([&]() {
  6993. svr_.bind_to_any_port(HOST);
  6994. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6995. ASSERT_TRUE(svr_.listen_after_bind());
  6996. });
  6997. svr_.wait_until_ready();
  6998. }
  6999. virtual void TearDown() {
  7000. svr_.stop();
  7001. t_.join();
  7002. }
  7003. Client cli_;
  7004. Server svr_;
  7005. thread t_;
  7006. };
  7007. TEST_F(ServerUpDownTest, QuickStartStop) {
  7008. // Should not crash, especially when run with
  7009. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7010. }
  7011. class PayloadMaxLengthTest : public ::testing::Test {
  7012. protected:
  7013. PayloadMaxLengthTest()
  7014. : cli_(HOST, PORT)
  7015. #ifdef CPPHTTPLIB_SSL_ENABLED
  7016. ,
  7017. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7018. #endif
  7019. {
  7020. #ifdef CPPHTTPLIB_SSL_ENABLED
  7021. cli_.enable_server_certificate_verification(false);
  7022. #endif
  7023. }
  7024. virtual void SetUp() {
  7025. svr_.set_payload_max_length(8);
  7026. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7027. res.set_content("test", "text/plain");
  7028. });
  7029. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7030. svr_.wait_until_ready();
  7031. }
  7032. virtual void TearDown() {
  7033. svr_.stop();
  7034. t_.join();
  7035. }
  7036. #ifdef CPPHTTPLIB_SSL_ENABLED
  7037. SSLClient cli_;
  7038. SSLServer svr_;
  7039. #else
  7040. Client cli_;
  7041. Server svr_;
  7042. #endif
  7043. thread t_;
  7044. };
  7045. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7046. auto res = cli_.Post("/test", "123456789", "text/plain");
  7047. ASSERT_TRUE(res);
  7048. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7049. res = cli_.Post("/test", "12345678", "text/plain");
  7050. ASSERT_TRUE(res);
  7051. EXPECT_EQ(StatusCode::OK_200, res->status);
  7052. }
  7053. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7054. // Test chunked encoding with payload exceeding the 8-byte limit
  7055. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7056. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7057. ASSERT_TRUE(res);
  7058. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7059. }
  7060. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7061. // Test chunked encoding with payload within the 8-byte limit
  7062. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7063. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7064. ASSERT_TRUE(res);
  7065. EXPECT_EQ(StatusCode::OK_200, res->status);
  7066. }
  7067. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7068. // Test using send_request to send chunked data exceeding payload limit
  7069. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7070. "Host: " +
  7071. std::string(HOST) + ":" + std::to_string(PORT) +
  7072. "\r\n"
  7073. "Transfer-Encoding: chunked\r\n"
  7074. "Connection: close\r\n"
  7075. "\r\n"
  7076. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7077. "0123456789\r\n"
  7078. "0\r\n" // End chunk
  7079. "\r\n";
  7080. std::string response;
  7081. bool result = send_request(1, chunked_request, &response);
  7082. if (!result) {
  7083. // If send_request fails, it might be because the server closed the
  7084. // connection due to payload limit enforcement, which is acceptable
  7085. SUCCEED()
  7086. << "Server rejected oversized chunked request (connection closed)";
  7087. } else {
  7088. // If we got a response, check if it's an error response or connection was
  7089. // closed early Short response length indicates connection was closed due to
  7090. // payload limit
  7091. if (response.length() <= 10) {
  7092. SUCCEED() << "Server closed connection for oversized chunked request";
  7093. } else {
  7094. // Check for error status codes
  7095. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7096. response.find("Payload Too Large") != std::string::npos ||
  7097. response.find("400") != std::string::npos);
  7098. }
  7099. }
  7100. }
  7101. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7102. // Test request without Content-Length header exceeding payload limit
  7103. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7104. "Host: " +
  7105. std::string(HOST) + ":" +
  7106. std::to_string(PORT) +
  7107. "\r\n"
  7108. "Connection: close\r\n"
  7109. "\r\n";
  7110. // Add payload exceeding the 8-byte limit
  7111. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7112. request_without_content_length += large_payload;
  7113. std::string response;
  7114. bool result = send_request(1, request_without_content_length, &response);
  7115. if (!result) {
  7116. // If send_request fails, server likely closed connection due to payload
  7117. // limit
  7118. SUCCEED() << "Server rejected oversized request without Content-Length "
  7119. "(connection closed)";
  7120. } else {
  7121. // Check if server responded with error or closed connection early
  7122. if (response.length() <= 10) {
  7123. SUCCEED() << "Server closed connection for oversized request without "
  7124. "Content-Length";
  7125. } else {
  7126. // Check for error status codes
  7127. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7128. response.find("Payload Too Large") != std::string::npos ||
  7129. response.find("400") != std::string::npos);
  7130. }
  7131. }
  7132. }
  7133. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7134. // Test request without Content-Length header within payload limit
  7135. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7136. "Host: " +
  7137. std::string(HOST) + ":" +
  7138. std::to_string(PORT) +
  7139. "\r\n"
  7140. "Connection: close\r\n"
  7141. "\r\n";
  7142. // Add payload within the 8-byte limit
  7143. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7144. request_without_content_length += small_payload;
  7145. std::string response;
  7146. bool result = send_request(1, request_without_content_length, &response);
  7147. // For requests without Content-Length, the server may have different behavior
  7148. // The key is that it should not reject due to payload limit for small
  7149. // payloads
  7150. if (result) {
  7151. // Check for any HTTP response (success or error, but not connection closed)
  7152. if (response.length() > 10) {
  7153. SUCCEED()
  7154. << "Server processed request without Content-Length within limit";
  7155. } else {
  7156. // Short response might indicate connection closed, which is acceptable
  7157. SUCCEED() << "Server closed connection for request without "
  7158. "Content-Length (acceptable behavior)";
  7159. }
  7160. } else {
  7161. // Connection failure might be due to protocol requirements
  7162. SUCCEED() << "Connection issue with request without Content-Length "
  7163. "(environment-specific)";
  7164. }
  7165. }
  7166. class LargePayloadMaxLengthTest : public ::testing::Test {
  7167. protected:
  7168. LargePayloadMaxLengthTest()
  7169. : cli_(HOST, PORT)
  7170. #ifdef CPPHTTPLIB_SSL_ENABLED
  7171. ,
  7172. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7173. #endif
  7174. {
  7175. #ifdef CPPHTTPLIB_SSL_ENABLED
  7176. cli_.enable_server_certificate_verification(false);
  7177. #endif
  7178. }
  7179. virtual void SetUp() {
  7180. // Set 10MB payload limit
  7181. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7182. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7183. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7184. res.set_content("Large payload test", "text/plain");
  7185. });
  7186. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7187. svr_.wait_until_ready();
  7188. }
  7189. virtual void TearDown() {
  7190. svr_.stop();
  7191. t_.join();
  7192. }
  7193. #ifdef CPPHTTPLIB_SSL_ENABLED
  7194. SSLClient cli_;
  7195. SSLServer svr_;
  7196. #else
  7197. Client cli_;
  7198. Server svr_;
  7199. #endif
  7200. thread t_;
  7201. };
  7202. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7203. // Test chunked encoding with payload within 10MB limit
  7204. std::string medium_payload(5 * 1024 * 1024,
  7205. 'A'); // 5MB payload, within 10MB limit
  7206. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7207. ASSERT_TRUE(res);
  7208. EXPECT_EQ(StatusCode::OK_200, res->status);
  7209. }
  7210. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7211. // Test chunked encoding with payload exceeding 10MB limit
  7212. std::string large_payload(12 * 1024 * 1024,
  7213. 'B'); // 12MB payload, exceeds 10MB limit
  7214. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7215. // Server may either return 413 or close the connection
  7216. if (res) {
  7217. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7218. } else {
  7219. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7220. }
  7221. }
  7222. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7223. // Test request without Content-Length header within 10MB limit
  7224. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7225. "Host: " +
  7226. std::string(HOST) + ":" +
  7227. std::to_string(PORT) +
  7228. "\r\n"
  7229. "Connection: close\r\n"
  7230. "\r\n";
  7231. // Add 1MB payload (within 10MB limit)
  7232. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7233. request_without_content_length += medium_payload;
  7234. std::string response;
  7235. bool result = send_request(5, request_without_content_length, &response);
  7236. if (result) {
  7237. // Should get a proper HTTP response for payloads within limit
  7238. if (response.length() > 10) {
  7239. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7240. "10MB limit";
  7241. } else {
  7242. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7243. "Content-Length)";
  7244. }
  7245. } else {
  7246. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7247. }
  7248. }
  7249. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7250. // Test request without Content-Length header exceeding 10MB limit
  7251. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7252. "Host: " +
  7253. std::string(HOST) + ":" +
  7254. std::to_string(PORT) +
  7255. "\r\n"
  7256. "Connection: close\r\n"
  7257. "\r\n";
  7258. // Add 12MB payload (exceeds 10MB limit)
  7259. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7260. request_without_content_length += large_payload;
  7261. std::string response;
  7262. bool result = send_request(10, request_without_content_length, &response);
  7263. if (!result) {
  7264. // Server should close connection due to payload limit
  7265. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7266. "(connection closed)";
  7267. } else {
  7268. // Check for error response
  7269. if (response.length() <= 10) {
  7270. SUCCEED()
  7271. << "Server closed connection for 12MB request exceeding 10MB limit";
  7272. } else {
  7273. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7274. response.find("Payload Too Large") != std::string::npos ||
  7275. response.find("400") != std::string::npos);
  7276. }
  7277. }
  7278. }
  7279. // Regression test for DoS vulnerability: a malicious server sending a response
  7280. // without Content-Length header must not cause unbounded memory consumption on
  7281. // the client side. The client should stop reading after a reasonable limit,
  7282. // similar to the server-side set_payload_max_length protection.
  7283. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7284. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7285. #ifndef _WIN32
  7286. signal(SIGPIPE, SIG_IGN);
  7287. #endif
  7288. auto server_thread = std::thread([] {
  7289. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7290. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7291. default_socket_options(srv);
  7292. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7293. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7294. sockaddr_in addr{};
  7295. addr.sin_family = AF_INET;
  7296. addr.sin_port = htons(PORT + 2);
  7297. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7298. int opt = 1;
  7299. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7300. #ifdef _WIN32
  7301. reinterpret_cast<const char *>(&opt),
  7302. #else
  7303. &opt,
  7304. #endif
  7305. sizeof(opt));
  7306. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7307. ::listen(srv, 1);
  7308. sockaddr_in cli_addr{};
  7309. socklen_t cli_len = sizeof(cli_addr);
  7310. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7311. if (cli != INVALID_SOCKET) {
  7312. char buf[4096];
  7313. ::recv(cli, buf, sizeof(buf), 0);
  7314. // Malicious response: no Content-Length, no chunked encoding
  7315. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7316. "Connection: close\r\n"
  7317. "\r\n";
  7318. ::send(cli,
  7319. #ifdef _WIN32
  7320. static_cast<const char *>(response_header.c_str()),
  7321. static_cast<int>(response_header.size()),
  7322. #else
  7323. response_header.c_str(), response_header.size(),
  7324. #endif
  7325. 0);
  7326. // Send 10MB of data
  7327. std::string chunk(64 * 1024, 'A');
  7328. size_t total_sent = 0;
  7329. while (total_sent < MALICIOUS_DATA_SIZE) {
  7330. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7331. auto sent = ::send(cli,
  7332. #ifdef _WIN32
  7333. static_cast<const char *>(chunk.c_str()),
  7334. static_cast<int>(to_send),
  7335. #else
  7336. chunk.c_str(), to_send,
  7337. #endif
  7338. 0);
  7339. if (sent <= 0) break;
  7340. total_sent += static_cast<size_t>(sent);
  7341. }
  7342. detail::close_socket(cli);
  7343. }
  7344. detail::close_socket(srv);
  7345. });
  7346. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7347. size_t total_read = 0;
  7348. {
  7349. Client cli("127.0.0.1", PORT + 2);
  7350. cli.set_read_timeout(5, 0);
  7351. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7352. auto stream = cli.open_stream("GET", "/malicious");
  7353. ASSERT_TRUE(stream.is_valid());
  7354. char buffer[64 * 1024];
  7355. ssize_t n;
  7356. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7357. total_read += static_cast<size_t>(n);
  7358. }
  7359. } // StreamHandle and Client destroyed here, closing the socket
  7360. server_thread.join();
  7361. // With set_payload_max_length, the client must stop reading before consuming
  7362. // all 10MB. The read loop should be cut off at or near the configured limit.
  7363. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7364. << "Client read " << total_read << " bytes, exceeding the configured "
  7365. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7366. }
  7367. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7368. // the entire response body without truncation.
  7369. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7370. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7371. #ifndef _WIN32
  7372. signal(SIGPIPE, SIG_IGN);
  7373. #endif
  7374. auto server_thread = std::thread([] {
  7375. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7376. default_socket_options(srv);
  7377. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7378. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7379. sockaddr_in addr{};
  7380. addr.sin_family = AF_INET;
  7381. addr.sin_port = htons(PORT + 2);
  7382. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7383. int opt = 1;
  7384. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7385. #ifdef _WIN32
  7386. reinterpret_cast<const char *>(&opt),
  7387. #else
  7388. &opt,
  7389. #endif
  7390. sizeof(opt));
  7391. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7392. ::listen(srv, 1);
  7393. sockaddr_in cli_addr{};
  7394. socklen_t cli_len = sizeof(cli_addr);
  7395. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7396. if (cli != INVALID_SOCKET) {
  7397. char buf[4096];
  7398. ::recv(cli, buf, sizeof(buf), 0);
  7399. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7400. "Connection: close\r\n"
  7401. "\r\n";
  7402. ::send(cli,
  7403. #ifdef _WIN32
  7404. static_cast<const char *>(response_header.c_str()),
  7405. static_cast<int>(response_header.size()),
  7406. #else
  7407. response_header.c_str(), response_header.size(),
  7408. #endif
  7409. 0);
  7410. std::string chunk(64 * 1024, 'A');
  7411. size_t total_sent = 0;
  7412. while (total_sent < DATA_SIZE) {
  7413. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7414. auto sent = ::send(cli,
  7415. #ifdef _WIN32
  7416. static_cast<const char *>(chunk.c_str()),
  7417. static_cast<int>(to_send),
  7418. #else
  7419. chunk.c_str(), to_send,
  7420. #endif
  7421. 0);
  7422. if (sent <= 0) break;
  7423. total_sent += static_cast<size_t>(sent);
  7424. }
  7425. #ifdef _WIN32
  7426. ::shutdown(cli, SD_SEND);
  7427. #else
  7428. ::shutdown(cli, SHUT_WR);
  7429. #endif
  7430. // Drain until the client closes its end, ensuring all data is delivered
  7431. char drain[1024];
  7432. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7433. detail::close_socket(cli);
  7434. }
  7435. detail::close_socket(srv);
  7436. });
  7437. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7438. size_t total_read = 0;
  7439. {
  7440. Client cli("127.0.0.1", PORT + 2);
  7441. cli.set_read_timeout(5, 0);
  7442. cli.set_payload_max_length(0); // 0 means no limit
  7443. auto stream = cli.open_stream("GET", "/data");
  7444. ASSERT_TRUE(stream.is_valid());
  7445. char buffer[64 * 1024];
  7446. ssize_t n;
  7447. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7448. total_read += static_cast<size_t>(n);
  7449. }
  7450. }
  7451. server_thread.join();
  7452. EXPECT_EQ(total_read, DATA_SIZE)
  7453. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7454. << " bytes without truncation, but only read " << total_read << " bytes.";
  7455. }
  7456. // Verify that content_receiver bypasses the default payload_max_length,
  7457. // allowing streaming downloads larger than 100MB without requiring an explicit
  7458. // set_payload_max_length call.
  7459. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  7460. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7461. #ifndef _WIN32
  7462. signal(SIGPIPE, SIG_IGN);
  7463. #endif
  7464. auto server_thread = std::thread([] {
  7465. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7466. default_socket_options(srv);
  7467. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7468. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7469. sockaddr_in addr{};
  7470. addr.sin_family = AF_INET;
  7471. addr.sin_port = htons(PORT + 2);
  7472. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7473. int opt = 1;
  7474. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7475. #ifdef _WIN32
  7476. reinterpret_cast<const char *>(&opt),
  7477. #else
  7478. &opt,
  7479. #endif
  7480. sizeof(opt));
  7481. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7482. ::listen(srv, 1);
  7483. sockaddr_in cli_addr{};
  7484. socklen_t cli_len = sizeof(cli_addr);
  7485. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7486. if (cli != INVALID_SOCKET) {
  7487. char buf[4096];
  7488. ::recv(cli, buf, sizeof(buf), 0);
  7489. // Response with Content-Length larger than default 100MB limit
  7490. auto content_length = std::to_string(DATA_SIZE);
  7491. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7492. "Content-Length: " +
  7493. content_length +
  7494. "\r\n"
  7495. "Connection: close\r\n"
  7496. "\r\n";
  7497. ::send(cli,
  7498. #ifdef _WIN32
  7499. static_cast<const char *>(response_header.c_str()),
  7500. static_cast<int>(response_header.size()),
  7501. #else
  7502. response_header.c_str(), response_header.size(),
  7503. #endif
  7504. 0);
  7505. std::string chunk(64 * 1024, 'A');
  7506. size_t total_sent = 0;
  7507. while (total_sent < DATA_SIZE) {
  7508. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7509. auto sent = ::send(cli,
  7510. #ifdef _WIN32
  7511. static_cast<const char *>(chunk.c_str()),
  7512. static_cast<int>(to_send),
  7513. #else
  7514. chunk.c_str(), to_send,
  7515. #endif
  7516. 0);
  7517. if (sent <= 0) break;
  7518. total_sent += static_cast<size_t>(sent);
  7519. }
  7520. detail::close_socket(cli);
  7521. }
  7522. detail::close_socket(srv);
  7523. });
  7524. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7525. size_t total_received = 0;
  7526. {
  7527. Client cli("127.0.0.1", PORT + 2);
  7528. cli.set_read_timeout(10, 0);
  7529. // Do NOT call set_payload_max_length — use the default 100MB limit
  7530. auto res =
  7531. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7532. total_received += data_length;
  7533. return true;
  7534. });
  7535. ASSERT_TRUE(res);
  7536. EXPECT_EQ(StatusCode::OK_200, res->status);
  7537. }
  7538. server_thread.join();
  7539. EXPECT_EQ(total_received, DATA_SIZE)
  7540. << "With content_receiver, the client should read all " << DATA_SIZE
  7541. << " bytes despite the default 100MB payload_max_length, but only read "
  7542. << total_received << " bytes.";
  7543. }
  7544. // Verify that an explicit set_payload_max_length smaller than the response is
  7545. // enforced even when a content_receiver is used.
  7546. TEST(ClientVulnerabilityTest,
  7547. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  7548. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7549. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  7550. #ifndef _WIN32
  7551. signal(SIGPIPE, SIG_IGN);
  7552. #endif
  7553. auto server_thread = std::thread([] {
  7554. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7555. default_socket_options(srv);
  7556. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7557. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7558. sockaddr_in addr{};
  7559. addr.sin_family = AF_INET;
  7560. addr.sin_port = htons(PORT + 2);
  7561. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7562. int opt = 1;
  7563. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7564. #ifdef _WIN32
  7565. reinterpret_cast<const char *>(&opt),
  7566. #else
  7567. &opt,
  7568. #endif
  7569. sizeof(opt));
  7570. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7571. ::listen(srv, 1);
  7572. sockaddr_in cli_addr{};
  7573. socklen_t cli_len = sizeof(cli_addr);
  7574. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7575. if (cli != INVALID_SOCKET) {
  7576. char buf[4096];
  7577. ::recv(cli, buf, sizeof(buf), 0);
  7578. auto content_length = std::to_string(DATA_SIZE);
  7579. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7580. "Content-Length: " +
  7581. content_length +
  7582. "\r\n"
  7583. "Connection: close\r\n"
  7584. "\r\n";
  7585. ::send(cli,
  7586. #ifdef _WIN32
  7587. static_cast<const char *>(response_header.c_str()),
  7588. static_cast<int>(response_header.size()),
  7589. #else
  7590. response_header.c_str(), response_header.size(),
  7591. #endif
  7592. 0);
  7593. std::string chunk(64 * 1024, 'A');
  7594. size_t total_sent = 0;
  7595. while (total_sent < DATA_SIZE) {
  7596. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7597. auto sent = ::send(cli,
  7598. #ifdef _WIN32
  7599. static_cast<const char *>(chunk.c_str()),
  7600. static_cast<int>(to_send),
  7601. #else
  7602. chunk.c_str(), to_send,
  7603. #endif
  7604. 0);
  7605. if (sent <= 0) break;
  7606. total_sent += static_cast<size_t>(sent);
  7607. }
  7608. detail::close_socket(cli);
  7609. }
  7610. detail::close_socket(srv);
  7611. });
  7612. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7613. size_t total_received = 0;
  7614. {
  7615. Client cli("127.0.0.1", PORT + 2);
  7616. cli.set_read_timeout(10, 0);
  7617. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  7618. auto res =
  7619. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7620. total_received += data_length;
  7621. return true;
  7622. });
  7623. // Should fail because 200MB exceeds the explicit 150MB limit
  7624. EXPECT_FALSE(res);
  7625. }
  7626. server_thread.join();
  7627. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  7628. << "Client with content_receiver should respect the explicit "
  7629. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  7630. << total_received << " bytes.";
  7631. }
  7632. // Verify that an explicit set_payload_max_length larger than the response
  7633. // allows the content_receiver to read all data successfully.
  7634. TEST(ClientVulnerabilityTest,
  7635. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  7636. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7637. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  7638. #ifndef _WIN32
  7639. signal(SIGPIPE, SIG_IGN);
  7640. #endif
  7641. auto server_thread = std::thread([] {
  7642. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7643. default_socket_options(srv);
  7644. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7645. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7646. sockaddr_in addr{};
  7647. addr.sin_family = AF_INET;
  7648. addr.sin_port = htons(PORT + 2);
  7649. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7650. int opt = 1;
  7651. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7652. #ifdef _WIN32
  7653. reinterpret_cast<const char *>(&opt),
  7654. #else
  7655. &opt,
  7656. #endif
  7657. sizeof(opt));
  7658. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7659. ::listen(srv, 1);
  7660. sockaddr_in cli_addr{};
  7661. socklen_t cli_len = sizeof(cli_addr);
  7662. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7663. if (cli != INVALID_SOCKET) {
  7664. char buf[4096];
  7665. ::recv(cli, buf, sizeof(buf), 0);
  7666. auto content_length = std::to_string(DATA_SIZE);
  7667. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7668. "Content-Length: " +
  7669. content_length +
  7670. "\r\n"
  7671. "Connection: close\r\n"
  7672. "\r\n";
  7673. ::send(cli,
  7674. #ifdef _WIN32
  7675. static_cast<const char *>(response_header.c_str()),
  7676. static_cast<int>(response_header.size()),
  7677. #else
  7678. response_header.c_str(), response_header.size(),
  7679. #endif
  7680. 0);
  7681. std::string chunk(64 * 1024, 'A');
  7682. size_t total_sent = 0;
  7683. while (total_sent < DATA_SIZE) {
  7684. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7685. auto sent = ::send(cli,
  7686. #ifdef _WIN32
  7687. static_cast<const char *>(chunk.c_str()),
  7688. static_cast<int>(to_send),
  7689. #else
  7690. chunk.c_str(), to_send,
  7691. #endif
  7692. 0);
  7693. if (sent <= 0) break;
  7694. total_sent += static_cast<size_t>(sent);
  7695. }
  7696. #ifdef _WIN32
  7697. ::shutdown(cli, SD_SEND);
  7698. #else
  7699. ::shutdown(cli, SHUT_WR);
  7700. #endif
  7701. char drain[1024];
  7702. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7703. detail::close_socket(cli);
  7704. }
  7705. detail::close_socket(srv);
  7706. });
  7707. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7708. size_t total_received = 0;
  7709. {
  7710. Client cli("127.0.0.1", PORT + 2);
  7711. cli.set_read_timeout(10, 0);
  7712. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  7713. auto res =
  7714. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7715. total_received += data_length;
  7716. return true;
  7717. });
  7718. ASSERT_TRUE(res);
  7719. EXPECT_EQ(StatusCode::OK_200, res->status);
  7720. }
  7721. server_thread.join();
  7722. EXPECT_EQ(total_received, DATA_SIZE)
  7723. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  7724. << " bytes (larger than " << DATA_SIZE
  7725. << " bytes response), content_receiver should read all data, but only "
  7726. "read "
  7727. << total_received << " bytes.";
  7728. }
  7729. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  7730. // Regression test for "zip bomb" attack on the client side: a malicious server
  7731. // sends a small gzip-compressed response that decompresses to a huge payload.
  7732. // The client must enforce payload_max_length on the decompressed size.
  7733. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  7734. constexpr size_t DECOMPRESSED_SIZE =
  7735. 10 * 1024 * 1024; // 10MB after decompression
  7736. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7737. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  7738. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  7739. std::string compressed;
  7740. {
  7741. httplib::detail::gzip_compressor compressor;
  7742. bool ok =
  7743. compressor.compress(uncompressed.data(), uncompressed.size(),
  7744. /*last=*/true, [&](const char *buf, size_t len) {
  7745. compressed.append(buf, len);
  7746. return true;
  7747. });
  7748. ASSERT_TRUE(ok);
  7749. }
  7750. // Sanity: compressed data should be much smaller than the decompressed size
  7751. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  7752. #ifndef _WIN32
  7753. signal(SIGPIPE, SIG_IGN);
  7754. #endif
  7755. // Set up the listening socket in the main thread so the server is guaranteed
  7756. // to be ready before the client connects (eliminates race condition).
  7757. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7758. default_socket_options(srv);
  7759. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7760. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7761. sockaddr_in addr{};
  7762. addr.sin_family = AF_INET;
  7763. addr.sin_port = htons(PORT + 3);
  7764. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7765. int opt = 1;
  7766. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7767. #ifdef _WIN32
  7768. reinterpret_cast<const char *>(&opt),
  7769. #else
  7770. &opt,
  7771. #endif
  7772. sizeof(opt));
  7773. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  7774. ASSERT_EQ(0, ::listen(srv, 1));
  7775. auto server_thread = std::thread([&compressed, srv] {
  7776. sockaddr_in cli_addr{};
  7777. socklen_t cli_len = sizeof(cli_addr);
  7778. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7779. if (cli != INVALID_SOCKET) {
  7780. // Read the full HTTP request (until \r\n\r\n)
  7781. char buf[4096];
  7782. size_t total = 0;
  7783. while (total < sizeof(buf)) {
  7784. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  7785. if (n <= 0) break;
  7786. total += static_cast<size_t>(n);
  7787. // Check for end of headers
  7788. if (total >= 4) {
  7789. std::string req(buf, total);
  7790. if (req.find("\r\n\r\n") != std::string::npos) break;
  7791. }
  7792. }
  7793. // Malicious response: gzip-compressed body, no Content-Length
  7794. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7795. "Content-Encoding: gzip\r\n"
  7796. "Connection: close\r\n"
  7797. "\r\n";
  7798. ::send(cli,
  7799. #ifdef _WIN32
  7800. static_cast<const char *>(response_header.c_str()),
  7801. static_cast<int>(response_header.size()),
  7802. #else
  7803. response_header.c_str(), response_header.size(),
  7804. #endif
  7805. 0);
  7806. // Send the compressed payload (small on the wire, huge when decompressed)
  7807. size_t total_sent = 0;
  7808. while (total_sent < compressed.size()) {
  7809. auto to_send = std::min(compressed.size() - total_sent,
  7810. static_cast<size_t>(64 * 1024));
  7811. auto sent =
  7812. ::send(cli,
  7813. #ifdef _WIN32
  7814. static_cast<const char *>(compressed.c_str() + total_sent),
  7815. static_cast<int>(to_send),
  7816. #else
  7817. compressed.c_str() + total_sent, to_send,
  7818. #endif
  7819. 0);
  7820. if (sent <= 0) break;
  7821. total_sent += static_cast<size_t>(sent);
  7822. }
  7823. detail::close_socket(cli);
  7824. }
  7825. });
  7826. auto se = detail::scope_exit([&] {
  7827. detail::close_socket(srv);
  7828. server_thread.join();
  7829. });
  7830. size_t total_decompressed = 0;
  7831. {
  7832. Client cli("127.0.0.1", PORT + 3);
  7833. cli.set_read_timeout(5, 0);
  7834. cli.set_decompress(true);
  7835. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7836. auto stream = cli.open_stream("GET", "/zipbomb");
  7837. ASSERT_TRUE(stream.is_valid());
  7838. char buffer[64 * 1024];
  7839. ssize_t n;
  7840. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7841. total_decompressed += static_cast<size_t>(n);
  7842. }
  7843. }
  7844. // The decompressed size must be capped by payload_max_length. Without
  7845. // protection, the client would decompress the full 10MB from a tiny
  7846. // compressed payload, enabling a zip bomb DoS attack.
  7847. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  7848. << "Client decompressed " << total_decompressed
  7849. << " bytes from a gzip response. The decompressed size should be "
  7850. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  7851. }
  7852. #endif
  7853. TEST(HostAndPortPropertiesTest, NoSSL) {
  7854. httplib::Client cli("www.google.com", 1234);
  7855. ASSERT_EQ("www.google.com", cli.host());
  7856. ASSERT_EQ(1234, cli.port());
  7857. }
  7858. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7859. httplib::Client cli("www.google.com:1234");
  7860. ASSERT_EQ("www.google.com", cli.host());
  7861. ASSERT_EQ(1234, cli.port());
  7862. }
  7863. #ifdef CPPHTTPLIB_SSL_ENABLED
  7864. TEST(HostAndPortPropertiesTest, SSL) {
  7865. httplib::SSLClient cli("www.google.com");
  7866. ASSERT_EQ("www.google.com", cli.host());
  7867. ASSERT_EQ(443, cli.port());
  7868. }
  7869. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  7870. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  7871. std::string cert;
  7872. read_file(CA_CERT_FILE, cert);
  7873. httplib::SSLClient httplib_client("www.google.com");
  7874. // Load CA store first time
  7875. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  7876. // Load CA store second time (update)
  7877. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  7878. // Verify client is still valid and can make connections
  7879. httplib_client.enable_server_certificate_verification(true);
  7880. auto res = httplib_client.Get("/");
  7881. ASSERT_TRUE(res);
  7882. // Google may return 200 or 301 depending on various factors
  7883. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  7884. res->status == StatusCode::MovedPermanently_301);
  7885. }
  7886. TEST(SSLClientTest, ServerNameIndication_Online) {
  7887. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7888. auto host = "httpcan.org";
  7889. auto path = std::string{"/get"};
  7890. #else
  7891. auto host = "nghttp2.org";
  7892. auto path = std::string{"/httpbin/get"};
  7893. #endif
  7894. SSLClient cli(host, 443);
  7895. auto res = cli.Get(path);
  7896. ASSERT_TRUE(res);
  7897. ASSERT_EQ(StatusCode::OK_200, res->status);
  7898. }
  7899. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  7900. // Use a site that will cause SSL verification failure due to self-signed cert
  7901. SSLClient cli("self-signed.badssl.com", 443);
  7902. cli.enable_server_certificate_verification(true);
  7903. auto res = cli.Get("/");
  7904. ASSERT_TRUE(!res);
  7905. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7906. // Verify backend error is captured for SSLServerVerification
  7907. // This occurs when certificate verification fails
  7908. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  7909. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  7910. EXPECT_NE(0UL, res.ssl_backend_error());
  7911. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7912. // For OpenSSL, ssl_error is 0 for verification errors
  7913. EXPECT_EQ(0, res.ssl_error());
  7914. #if !defined(_WIN32) || \
  7915. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  7916. // On non-Windows or when Windows Schannel is disabled, the error comes
  7917. // from OpenSSL's verification
  7918. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  7919. res.ssl_backend_error());
  7920. #endif
  7921. #endif
  7922. }
  7923. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  7924. // Use a site where hostname doesn't match the certificate
  7925. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  7926. SSLClient cli("wrong.host.badssl.com", 443);
  7927. cli.enable_server_certificate_verification(true);
  7928. cli.enable_server_hostname_verification(true);
  7929. auto res = cli.Get("/");
  7930. ASSERT_TRUE(!res);
  7931. // The error type depends on when hostname verification occurs:
  7932. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  7933. // - Mbed TLS: SSLServerVerification (during handshake)
  7934. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  7935. res.error() == Error::SSLServerVerification);
  7936. // Verify backend error is captured for hostname verification failure
  7937. EXPECT_NE(0UL, res.ssl_backend_error());
  7938. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7939. // For OpenSSL, ssl_error is 0 for verification errors
  7940. EXPECT_EQ(0, res.ssl_error());
  7941. #if !defined(_WIN32) || \
  7942. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  7943. // On non-Windows or when Windows Schannel is disabled, the error comes
  7944. // from OpenSSL's hostname verification
  7945. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  7946. res.ssl_backend_error());
  7947. #endif
  7948. #endif
  7949. }
  7950. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  7951. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  7952. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  7953. SSLClient cli("www.google.com", 443);
  7954. cli.enable_server_certificate_verification(true);
  7955. auto res = cli.Get("/");
  7956. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  7957. }
  7958. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  7959. SSLClient cli("www.google.com", 443);
  7960. cli.enable_server_certificate_verification(true);
  7961. cli.enable_windows_certificate_verification(false);
  7962. auto res = cli.Get("/");
  7963. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  7964. }
  7965. #endif
  7966. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  7967. Client cli("https://google.com");
  7968. auto res = cli.Get("/");
  7969. ASSERT_TRUE(res);
  7970. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7971. }
  7972. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  7973. SSLClient cli("google.com");
  7974. cli.set_ca_cert_path(CA_CERT_FILE);
  7975. auto res = cli.Get("/");
  7976. ASSERT_TRUE(res);
  7977. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7978. }
  7979. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  7980. SSLClient cli("google.com");
  7981. cli.enable_server_certificate_verification(true);
  7982. cli.set_ca_cert_path("hello");
  7983. auto res = cli.Get("/");
  7984. ASSERT_TRUE(!res);
  7985. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  7986. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  7987. // should be set
  7988. EXPECT_EQ(0, res.ssl_error());
  7989. // Verify backend error is captured for SSLLoadingCerts
  7990. // This error occurs when loading CA certificates fails
  7991. EXPECT_NE(0UL, res.ssl_backend_error());
  7992. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7993. // OpenSSL specific error codes:
  7994. // > openssl errstr 0x80000002
  7995. // error:80000002:system library::No such file or directory
  7996. // > openssl errstr 0xA000126
  7997. // error:0A000126:SSL routines::unexpected eof while reading
  7998. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  7999. res.ssl_backend_error() == 0xA000126);
  8000. #endif
  8001. }
  8002. TEST(SSLClientTest, ServerCertificateVerification4) {
  8003. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8004. ASSERT_TRUE(svr.is_valid());
  8005. svr.Get("/test", [&](const Request &, Response &res) {
  8006. res.set_content("test", "text/plain");
  8007. svr.stop();
  8008. ASSERT_TRUE(true);
  8009. });
  8010. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8011. auto se = detail::scope_exit([&] {
  8012. t.join();
  8013. ASSERT_FALSE(svr.is_running());
  8014. });
  8015. svr.wait_until_ready();
  8016. SSLClient cli("127.0.0.1", PORT);
  8017. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8018. cli.enable_server_certificate_verification(true);
  8019. cli.set_connection_timeout(30);
  8020. auto res = cli.Get("/test");
  8021. ASSERT_TRUE(res);
  8022. ASSERT_EQ(StatusCode::OK_200, res->status);
  8023. }
  8024. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8025. std::string cert;
  8026. read_file(CA_CERT_FILE, cert);
  8027. SSLClient cli("google.com");
  8028. cli.load_ca_cert_store(cert.data(), cert.size());
  8029. const auto res = cli.Get("/");
  8030. ASSERT_TRUE(res);
  8031. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8032. }
  8033. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8034. // clang-format off
  8035. static constexpr char cert[] =
  8036. "GlobalSign Root CA\n"
  8037. "==================\n"
  8038. "-----BEGIN CERTIFICATE-----\n"
  8039. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8040. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8041. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8042. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8043. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8044. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8045. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8046. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8047. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8048. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8049. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8050. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8051. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8052. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8053. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8054. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8055. "-----END CERTIFICATE-----\n";
  8056. // clang-format on
  8057. SSLClient cli("google.com");
  8058. cli.load_ca_cert_store(cert, sizeof(cert));
  8059. const auto res = cli.Get("/");
  8060. ASSERT_TRUE(res);
  8061. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8062. }
  8063. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8064. SSLClient cli("www.youtube.com");
  8065. cli.set_ca_cert_path(CA_CERT_FILE);
  8066. cli.enable_server_certificate_verification(true);
  8067. cli.set_follow_location(true);
  8068. auto res = cli.Get("/");
  8069. ASSERT_TRUE(res);
  8070. ASSERT_EQ(StatusCode::OK_200, res->status);
  8071. }
  8072. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8073. SSLClient cli("wWw.YouTube.Com");
  8074. cli.set_ca_cert_path(CA_CERT_FILE);
  8075. cli.enable_server_certificate_verification(true);
  8076. cli.enable_server_hostname_verification(true);
  8077. cli.set_follow_location(true);
  8078. auto res = cli.Get("/");
  8079. ASSERT_TRUE(res);
  8080. ASSERT_EQ(StatusCode::OK_200, res->status);
  8081. }
  8082. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8083. SSLClient cli("gOoGlE.COm");
  8084. cli.enable_server_certificate_verification(true);
  8085. cli.enable_server_hostname_verification(true);
  8086. cli.set_follow_location(true);
  8087. auto res = cli.Get("/");
  8088. ASSERT_TRUE(res);
  8089. ASSERT_EQ(StatusCode::OK_200, res->status);
  8090. }
  8091. TEST(SSLClientTest, Issue2004_Online) {
  8092. Client client("https://google.com");
  8093. client.set_follow_location(true);
  8094. auto res = client.Get("/");
  8095. ASSERT_TRUE(res);
  8096. ASSERT_EQ(StatusCode::OK_200, res->status);
  8097. auto body = res->body;
  8098. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8099. }
  8100. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8101. // Create SSLClient with invalid cert/key to make is_valid() return false
  8102. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8103. "nonexistent_key.pem");
  8104. // is_valid() should be false due to cert loading failure
  8105. ASSERT_FALSE(cli.is_valid());
  8106. auto res = cli.Get("/");
  8107. ASSERT_FALSE(res);
  8108. EXPECT_EQ(Error::SSLConnection, res.error());
  8109. }
  8110. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8111. // Test for Issue #2251: SSL error not properly reported when client cert
  8112. // and key paths are swapped or mismatched
  8113. // This simulates the scenario where user accidentally swaps the cert and key
  8114. // files
  8115. // Using client cert file as private key and vice versa (completely wrong)
  8116. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8117. // Should fail validation due to cert/key mismatch
  8118. ASSERT_FALSE(cli.is_valid());
  8119. // Attempt to make a request should fail with proper error
  8120. auto res = cli.Get("/");
  8121. ASSERT_FALSE(res);
  8122. EXPECT_EQ(Error::SSLConnection, res.error());
  8123. // SSL error should be recorded in the Result object (this is the key fix for
  8124. // Issue #2251)
  8125. auto backend_error = res.ssl_backend_error();
  8126. EXPECT_NE(0u, backend_error);
  8127. }
  8128. // Tests cert/key mismatch detection at the TLS context level
  8129. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8130. // Test that using mismatched cert/key causes connection failure.
  8131. // We verify this at the SSLClient level rather than through internal
  8132. // TLS API functions.
  8133. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8134. cli.enable_server_certificate_verification(false);
  8135. cli.set_connection_timeout(2);
  8136. // The mismatch should cause a connection or handshake error
  8137. auto res = cli.Get("/test");
  8138. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8139. // Either way, the request should fail
  8140. EXPECT_FALSE(res);
  8141. }
  8142. #endif
  8143. #if 0
  8144. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8145. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8146. ASSERT_TRUE(cli != nullptr);
  8147. cli->set_address_family(AF_INET6);
  8148. cli->set_interface("en0");
  8149. auto res = cli->Get("/get");
  8150. ASSERT_TRUE(res);
  8151. ASSERT_EQ(StatusCode::OK_200, res->status);
  8152. }
  8153. #endif
  8154. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8155. #ifdef CPPHTTPLIB_SSL_ENABLED
  8156. void ClientCertPresent(
  8157. const std::string &client_cert_file,
  8158. const std::string &client_private_key_file,
  8159. const std::string &client_encrypted_private_key_pass = std::string()) {
  8160. using namespace httplib::tls;
  8161. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8162. CLIENT_CA_CERT_DIR);
  8163. ASSERT_TRUE(svr.is_valid());
  8164. svr.Get("/test", [&](const Request &req, Response &res) {
  8165. res.set_content("test", "text/plain");
  8166. auto cert = req.peer_cert();
  8167. ASSERT_TRUE(static_cast<bool>(cert));
  8168. std::string common_name = cert.subject_cn();
  8169. EXPECT_EQ("Common Name", common_name);
  8170. });
  8171. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8172. auto se = detail::scope_exit([&] {
  8173. svr.stop();
  8174. t.join();
  8175. ASSERT_FALSE(svr.is_running());
  8176. });
  8177. svr.wait_until_ready();
  8178. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8179. client_encrypted_private_key_pass);
  8180. cli.enable_server_certificate_verification(false);
  8181. cli.set_connection_timeout(30);
  8182. auto res = cli.Get("/test");
  8183. ASSERT_TRUE(res);
  8184. ASSERT_EQ(StatusCode::OK_200, res->status);
  8185. }
  8186. TEST(SSLClientServerTest, ClientCertPresent) {
  8187. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8188. }
  8189. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8190. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8191. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8192. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8193. }
  8194. // PEM memory-based constructor tests (works with all TLS backends)
  8195. void PemMemoryClientCertPresent(
  8196. const std::string &client_cert_file,
  8197. const std::string &client_private_key_file,
  8198. const std::string &client_encrypted_private_key_pass = std::string()) {
  8199. // Read PEM files into memory
  8200. std::string server_cert_pem, server_key_pem;
  8201. std::string client_ca_pem;
  8202. std::string client_cert_pem, client_key_pem;
  8203. read_file(SERVER_CERT_FILE, server_cert_pem);
  8204. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8205. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8206. read_file(client_cert_file, client_cert_pem);
  8207. read_file(client_private_key_file, client_key_pem);
  8208. // Create server with PEM memory
  8209. SSLServer::PemMemory server_pem = {
  8210. server_cert_pem.c_str(),
  8211. server_cert_pem.size(),
  8212. server_key_pem.c_str(),
  8213. server_key_pem.size(),
  8214. client_ca_pem.c_str(),
  8215. client_ca_pem.size(),
  8216. nullptr // no password for server key
  8217. };
  8218. SSLServer svr(server_pem);
  8219. ASSERT_TRUE(svr.is_valid());
  8220. svr.Get("/test", [&](const Request &, Response &res) {
  8221. res.set_content("test", "text/plain");
  8222. });
  8223. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8224. auto se = detail::scope_exit([&] {
  8225. svr.stop();
  8226. t.join();
  8227. ASSERT_FALSE(svr.is_running());
  8228. });
  8229. svr.wait_until_ready();
  8230. // Create client with PEM memory
  8231. const char *password = client_encrypted_private_key_pass.empty()
  8232. ? nullptr
  8233. : client_encrypted_private_key_pass.c_str();
  8234. SSLClient::PemMemory client_pem = {
  8235. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8236. client_key_pem.size(), password};
  8237. SSLClient cli(HOST, PORT, client_pem);
  8238. cli.enable_server_certificate_verification(false);
  8239. cli.set_connection_timeout(30);
  8240. auto res = cli.Get("/test");
  8241. ASSERT_TRUE(res);
  8242. ASSERT_EQ(StatusCode::OK_200, res->status);
  8243. }
  8244. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8245. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8246. }
  8247. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8248. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8249. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8250. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8251. }
  8252. TEST(SSLClientServerTest, ClientCertMissing) {
  8253. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8254. CLIENT_CA_CERT_DIR);
  8255. ASSERT_TRUE(svr.is_valid());
  8256. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8257. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8258. auto se = detail::scope_exit([&] {
  8259. svr.stop();
  8260. t.join();
  8261. ASSERT_FALSE(svr.is_running());
  8262. });
  8263. svr.wait_until_ready();
  8264. SSLClient cli(HOST, PORT);
  8265. cli.set_connection_timeout(30);
  8266. auto res = cli.Get("/test");
  8267. ASSERT_TRUE(!res);
  8268. // When client cert is missing and server requires it, connection fails
  8269. // Error type depends on backend implementation
  8270. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8271. res.error() == Error::SSLConnection);
  8272. // Verify backend error is captured
  8273. // Note: This test may have different error codes depending on the exact
  8274. // verification failure
  8275. EXPECT_NE(0UL, res.ssl_backend_error());
  8276. }
  8277. TEST(SSLClientServerTest, TrustDirOptional) {
  8278. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8279. ASSERT_TRUE(svr.is_valid());
  8280. svr.Get("/test", [&](const Request &, Response &res) {
  8281. res.set_content("test", "text/plain");
  8282. });
  8283. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8284. auto se = detail::scope_exit([&] {
  8285. svr.stop();
  8286. t.join();
  8287. ASSERT_FALSE(svr.is_running());
  8288. });
  8289. svr.wait_until_ready();
  8290. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8291. cli.enable_server_certificate_verification(false);
  8292. cli.set_connection_timeout(30);
  8293. auto res = cli.Get("/test");
  8294. ASSERT_TRUE(res);
  8295. ASSERT_EQ(StatusCode::OK_200, res->status);
  8296. }
  8297. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8298. class NoListenSSLServer : public SSLServer {
  8299. public:
  8300. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8301. const char *client_ca_cert_file_path,
  8302. const char *client_ca_cert_dir_path = nullptr)
  8303. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8304. client_ca_cert_dir_path),
  8305. stop_(false) {}
  8306. std::atomic_bool stop_;
  8307. private:
  8308. bool process_and_close_socket(socket_t /*sock*/) override {
  8309. // Don't create SSL context
  8310. while (!stop_.load()) {
  8311. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8312. }
  8313. return true;
  8314. }
  8315. };
  8316. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8317. CLIENT_CA_CERT_FILE);
  8318. ASSERT_TRUE(svr.is_valid());
  8319. svr.Get("/test", [&](const Request &, Response &res) {
  8320. res.set_content("test", "text/plain");
  8321. });
  8322. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8323. auto se = detail::scope_exit([&] {
  8324. svr.stop_ = true;
  8325. svr.stop();
  8326. t.join();
  8327. ASSERT_FALSE(svr.is_running());
  8328. });
  8329. svr.wait_until_ready();
  8330. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8331. cli.enable_server_certificate_verification(false);
  8332. cli.set_connection_timeout(1);
  8333. auto res = cli.Get("/test");
  8334. ASSERT_TRUE(!res);
  8335. EXPECT_EQ(Error::SSLConnection, res.error());
  8336. // Timeout results in WantRead error code (maps to backend-specific value)
  8337. EXPECT_NE(0, res.ssl_error());
  8338. }
  8339. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8340. // Test SSLServer with client certificate verification using the standard
  8341. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8342. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8343. CLIENT_CA_CERT_DIR);
  8344. ASSERT_TRUE(svr.is_valid());
  8345. svr.Get("/test", [&](const Request &req, Response &res) {
  8346. res.set_content("test", "text/plain");
  8347. auto cert = req.peer_cert();
  8348. ASSERT_TRUE(static_cast<bool>(cert));
  8349. auto common_name = cert.subject_cn();
  8350. EXPECT_EQ("Common Name", common_name);
  8351. });
  8352. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8353. auto se = detail::scope_exit([&] {
  8354. svr.stop();
  8355. t.join();
  8356. ASSERT_FALSE(svr.is_running());
  8357. });
  8358. svr.wait_until_ready();
  8359. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8360. cli.enable_server_certificate_verification(false);
  8361. cli.set_connection_timeout(30);
  8362. auto res = cli.Get("/test");
  8363. ASSERT_TRUE(res);
  8364. ASSERT_EQ(StatusCode::OK_200, res->status);
  8365. }
  8366. // Test verify_hostname for both OpenSSL and MbedTLS backends
  8367. // Verifies that wildcard matching and exact matching work consistently
  8368. TEST(SSLClientServerTest, TlsVerifyHostname) {
  8369. using namespace httplib::tls;
  8370. // We need a running server to test against
  8371. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8372. ASSERT_TRUE(svr.is_valid());
  8373. svr.Get("/test", [](const Request &, Response &res) {
  8374. res.set_content("ok", "text/plain");
  8375. });
  8376. thread t([&]() { svr.listen(HOST, PORT); });
  8377. auto se = detail::scope_exit([&] {
  8378. svr.stop();
  8379. t.join();
  8380. });
  8381. svr.wait_until_ready();
  8382. bool verify_callback_called = false;
  8383. bool verify_result_wrong = false;
  8384. SSLClient cli(HOST, PORT);
  8385. cli.enable_server_certificate_verification(true);
  8386. cli.set_ca_cert_path(CA_CERT_FILE);
  8387. cli.set_connection_timeout(5);
  8388. // Note: Test certificate has CN="Common Name", not "localhost"
  8389. bool verify_result_cn = false;
  8390. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8391. verify_callback_called = true;
  8392. if (!ctx.cert) return false;
  8393. // Test 1: "Common Name" should match (our test server cert CN)
  8394. verify_result_cn = ctx.check_hostname("Common Name");
  8395. // Test 2: wrong hostname should not match
  8396. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  8397. return true; // Accept for the purpose of this test
  8398. });
  8399. auto res = cli.Get("/test");
  8400. // The request may succeed or fail depending on cert configuration
  8401. // but the callback should have been called
  8402. ASSERT_TRUE(verify_callback_called)
  8403. << "Verify callback should have been called";
  8404. // CN="Common Name" should match our test certificate
  8405. EXPECT_TRUE(verify_result_cn)
  8406. << "verify_hostname should match 'Common Name' (certificate CN)";
  8407. // Wrong hostname should not match
  8408. EXPECT_FALSE(verify_result_wrong)
  8409. << "verify_hostname should not match 'wronghost.example.com'";
  8410. }
  8411. #endif
  8412. // mbedTLS-specific callback constructor test
  8413. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8414. #ifdef CPPHTTPLIB_SSL_ENABLED
  8415. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8416. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8417. ASSERT_TRUE(svr.is_valid());
  8418. // Set up a handler to verify client certificate is present
  8419. bool client_cert_verified = false;
  8420. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8421. // Verify that client certificate was provided
  8422. client_cert_verified = true;
  8423. res.set_content("success", "text/plain");
  8424. });
  8425. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8426. auto se = detail::scope_exit([&] {
  8427. svr.stop();
  8428. t.join();
  8429. ASSERT_FALSE(svr.is_running());
  8430. });
  8431. svr.wait_until_ready();
  8432. // Client with certificate
  8433. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8434. cli.enable_server_certificate_verification(false);
  8435. cli.set_connection_timeout(30);
  8436. auto res = cli.Get("/test");
  8437. ASSERT_TRUE(res);
  8438. ASSERT_EQ(StatusCode::OK_200, res->status);
  8439. ASSERT_TRUE(client_cert_verified);
  8440. EXPECT_EQ("success", res->body);
  8441. }
  8442. #endif
  8443. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  8444. // backends
  8445. #ifdef CPPHTTPLIB_SSL_ENABLED
  8446. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  8447. using namespace httplib::tls;
  8448. // Test that when client CA cert file is provided,
  8449. // the server properly requests and validates client certificates
  8450. // Create a server with client authentication
  8451. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8452. ASSERT_TRUE(svr.is_valid());
  8453. bool handler_called = false;
  8454. svr.Get("/test", [&](const Request &req, Response &res) {
  8455. handler_called = true;
  8456. // Verify that a client certificate was provided
  8457. auto cert = req.peer_cert();
  8458. ASSERT_TRUE(static_cast<bool>(cert));
  8459. // Get the issuer name
  8460. std::string issuer_str = cert.issuer_name();
  8461. ASSERT_FALSE(issuer_str.empty());
  8462. // The client certificate should be issued by our test CA
  8463. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  8464. res.set_content("authenticated", "text/plain");
  8465. });
  8466. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8467. auto se = detail::scope_exit([&] {
  8468. svr.stop();
  8469. t.join();
  8470. ASSERT_FALSE(svr.is_running());
  8471. });
  8472. svr.wait_until_ready();
  8473. // Connect with a client certificate issued by the CA
  8474. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8475. cli.enable_server_certificate_verification(false);
  8476. cli.set_connection_timeout(30);
  8477. auto res = cli.Get("/test");
  8478. ASSERT_TRUE(res);
  8479. ASSERT_EQ(StatusCode::OK_200, res->status);
  8480. ASSERT_TRUE(handler_called);
  8481. EXPECT_EQ("authenticated", res->body);
  8482. }
  8483. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  8484. using namespace httplib::tls;
  8485. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8486. ASSERT_TRUE(svr.is_valid());
  8487. svr.Get("/test", [](const Request &, Response &res) {
  8488. res.set_content("ok", "text/plain");
  8489. });
  8490. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8491. auto se = detail::scope_exit([&] {
  8492. svr.stop();
  8493. t.join();
  8494. });
  8495. svr.wait_until_ready();
  8496. SSLClient cli(HOST, PORT);
  8497. cli.enable_server_certificate_verification(false);
  8498. cli.set_connection_timeout(30);
  8499. bool cert_checked = false;
  8500. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8501. if (ctx.cert) {
  8502. auto sans = ctx.sans();
  8503. // Test certificate may or may not have SANs - just verify the API
  8504. // works If SANs exist, verify the types are valid
  8505. for (const auto &san : sans) {
  8506. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  8507. san.type == SanType::EMAIL || san.type == SanType::URI ||
  8508. san.type == SanType::OTHER);
  8509. EXPECT_FALSE(san.value.empty());
  8510. }
  8511. cert_checked = true;
  8512. }
  8513. return true;
  8514. });
  8515. auto res = cli.Get("/test");
  8516. ASSERT_TRUE(res);
  8517. EXPECT_TRUE(cert_checked);
  8518. }
  8519. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  8520. using namespace httplib::tls;
  8521. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8522. ASSERT_TRUE(svr.is_valid());
  8523. svr.Get("/test", [](const Request &, Response &res) {
  8524. res.set_content("ok", "text/plain");
  8525. });
  8526. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8527. auto se = detail::scope_exit([&] {
  8528. svr.stop();
  8529. t.join();
  8530. });
  8531. svr.wait_until_ready();
  8532. SSLClient cli(HOST, PORT);
  8533. cli.enable_server_certificate_verification(false);
  8534. cli.set_connection_timeout(30);
  8535. bool validity_checked = false;
  8536. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8537. if (ctx.cert) {
  8538. time_t not_before = 0, not_after = 0;
  8539. bool result = ctx.validity(not_before, not_after);
  8540. EXPECT_TRUE(result);
  8541. // Verify that not_before < now < not_after for a valid cert
  8542. time_t now = time(nullptr);
  8543. EXPECT_LT(not_before, now);
  8544. EXPECT_GT(not_after, now);
  8545. validity_checked = true;
  8546. }
  8547. return true;
  8548. });
  8549. auto res = cli.Get("/test");
  8550. ASSERT_TRUE(res);
  8551. EXPECT_TRUE(validity_checked);
  8552. }
  8553. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  8554. using namespace httplib::tls;
  8555. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8556. ASSERT_TRUE(svr.is_valid());
  8557. svr.Get("/test", [](const Request &, Response &res) {
  8558. res.set_content("ok", "text/plain");
  8559. });
  8560. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8561. auto se = detail::scope_exit([&] {
  8562. svr.stop();
  8563. t.join();
  8564. });
  8565. svr.wait_until_ready();
  8566. SSLClient cli(HOST, PORT);
  8567. cli.enable_server_certificate_verification(false);
  8568. cli.set_connection_timeout(30);
  8569. bool serial_checked = false;
  8570. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8571. if (ctx.cert) {
  8572. std::string serial = ctx.serial();
  8573. EXPECT_FALSE(serial.empty());
  8574. // Serial should be a hex string
  8575. for (char c : serial) {
  8576. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  8577. (c >= 'a' && c <= 'f'));
  8578. }
  8579. serial_checked = true;
  8580. }
  8581. return true;
  8582. });
  8583. auto res = cli.Get("/test");
  8584. ASSERT_TRUE(res);
  8585. EXPECT_TRUE(serial_checked);
  8586. }
  8587. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  8588. // Test 1: Valid CA file - no error should be recorded
  8589. {
  8590. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8591. CLIENT_CA_CERT_FILE);
  8592. ASSERT_TRUE(svr.is_valid());
  8593. // With valid setup, last_ssl_error should be 0
  8594. EXPECT_EQ(0, svr.ssl_last_error());
  8595. }
  8596. // Test 2: Invalid CA file content
  8597. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  8598. {
  8599. // Create a temporary file with completely invalid content
  8600. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  8601. {
  8602. std::ofstream ofs(temp_invalid_ca);
  8603. ofs << "This is not a certificate file at all\n";
  8604. ofs << "Just plain text content\n";
  8605. }
  8606. // Create server with invalid CA file
  8607. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  8608. // Clean up temporary file
  8609. std::remove(temp_invalid_ca);
  8610. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  8611. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  8612. // Note: SSL_CTX_load_verify_locations typically fails first,
  8613. // but our error handling code path is still exercised
  8614. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  8615. }
  8616. }
  8617. TEST(VerifyCallbackTest, VerifyContextFields) {
  8618. using namespace httplib::tls;
  8619. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8620. ASSERT_TRUE(svr.is_valid());
  8621. svr.Get("/test", [](const Request &, Response &res) {
  8622. res.set_content("ok", "text/plain");
  8623. });
  8624. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8625. auto se = detail::scope_exit([&] {
  8626. svr.stop();
  8627. t.join();
  8628. });
  8629. svr.wait_until_ready();
  8630. SSLClient cli(HOST, PORT);
  8631. cli.enable_server_certificate_verification(false);
  8632. cli.set_connection_timeout(30);
  8633. int callback_count = 0;
  8634. bool saw_leaf_cert = false;
  8635. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8636. if (ctx.cert) {
  8637. callback_count++;
  8638. // We should see at least one certificate (the leaf)
  8639. std::string cn = ctx.subject_cn();
  8640. if (!cn.empty()) { saw_leaf_cert = true; }
  8641. // Verify context fields are populated
  8642. EXPECT_NE(ctx.session, nullptr);
  8643. EXPECT_GE(ctx.depth, 0);
  8644. }
  8645. return true;
  8646. });
  8647. auto res = cli.Get("/test");
  8648. ASSERT_TRUE(res);
  8649. EXPECT_GT(callback_count, 0);
  8650. EXPECT_TRUE(saw_leaf_cert);
  8651. }
  8652. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  8653. using httplib::tls::TlsError;
  8654. // Test that verify_error_to_string returns empty for success
  8655. std::string success_str = TlsError::verify_error_to_string(0);
  8656. EXPECT_TRUE(success_str.empty());
  8657. // Test that verify_error_to_string returns non-empty for error codes
  8658. // Using a common error code (certificate expired)
  8659. std::string error_str =
  8660. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  8661. EXPECT_FALSE(error_str.empty());
  8662. }
  8663. TEST(SessionVerifierTest, CertificateAccepted) {
  8664. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8665. ASSERT_TRUE(svr.is_valid());
  8666. svr.Get("/test", [](const Request &, Response &res) {
  8667. res.set_content("ok", "text/plain");
  8668. });
  8669. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8670. auto se = detail::scope_exit([&] {
  8671. svr.stop();
  8672. t.join();
  8673. });
  8674. svr.wait_until_ready();
  8675. SSLClient cli(HOST, PORT);
  8676. cli.enable_server_certificate_verification(false);
  8677. cli.set_connection_timeout(30);
  8678. bool callback_called = false;
  8679. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8680. EXPECT_NE(session, nullptr);
  8681. callback_called = true;
  8682. return SSLVerifierResponse::CertificateAccepted;
  8683. });
  8684. auto res = cli.Get("/test");
  8685. ASSERT_TRUE(res);
  8686. EXPECT_EQ(200, res->status);
  8687. EXPECT_TRUE(callback_called);
  8688. }
  8689. TEST(SessionVerifierTest, CertificateRejected) {
  8690. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8691. ASSERT_TRUE(svr.is_valid());
  8692. svr.Get("/test", [](const Request &, Response &res) {
  8693. res.set_content("ok", "text/plain");
  8694. });
  8695. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8696. auto se = detail::scope_exit([&] {
  8697. svr.stop();
  8698. t.join();
  8699. });
  8700. svr.wait_until_ready();
  8701. SSLClient cli(HOST, PORT);
  8702. cli.enable_server_certificate_verification(false);
  8703. cli.set_connection_timeout(30);
  8704. bool callback_called = false;
  8705. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8706. EXPECT_NE(session, nullptr);
  8707. callback_called = true;
  8708. return SSLVerifierResponse::CertificateRejected;
  8709. });
  8710. auto res = cli.Get("/test");
  8711. EXPECT_FALSE(res);
  8712. EXPECT_TRUE(callback_called);
  8713. }
  8714. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  8715. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8716. ASSERT_TRUE(svr.is_valid());
  8717. svr.Get("/test", [](const Request &, Response &res) {
  8718. res.set_content("ok", "text/plain");
  8719. });
  8720. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8721. auto se = detail::scope_exit([&] {
  8722. svr.stop();
  8723. t.join();
  8724. });
  8725. svr.wait_until_ready();
  8726. // NoDecisionMade with verification disabled should succeed (no default check)
  8727. SSLClient cli(HOST, PORT);
  8728. cli.enable_server_certificate_verification(false);
  8729. cli.set_connection_timeout(30);
  8730. bool callback_called = false;
  8731. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8732. EXPECT_NE(session, nullptr);
  8733. callback_called = true;
  8734. return SSLVerifierResponse::NoDecisionMade;
  8735. });
  8736. auto res = cli.Get("/test");
  8737. ASSERT_TRUE(res);
  8738. EXPECT_EQ(200, res->status);
  8739. EXPECT_TRUE(callback_called);
  8740. }
  8741. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  8742. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8743. ASSERT_TRUE(svr.is_valid());
  8744. svr.Get("/test", [](const Request &, Response &res) {
  8745. res.set_content("ok", "text/plain");
  8746. });
  8747. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8748. auto se = detail::scope_exit([&] {
  8749. svr.stop();
  8750. t.join();
  8751. });
  8752. svr.wait_until_ready();
  8753. // NoDecisionMade with verification enabled should fail (self-signed cert).
  8754. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  8755. // so we only check that the request fails, not whether the callback was
  8756. // called.
  8757. SSLClient cli(HOST, PORT);
  8758. cli.enable_server_certificate_verification(true);
  8759. cli.set_connection_timeout(30);
  8760. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8761. EXPECT_NE(session, nullptr);
  8762. return SSLVerifierResponse::NoDecisionMade;
  8763. });
  8764. auto res = cli.Get("/test");
  8765. EXPECT_FALSE(res);
  8766. }
  8767. TEST(SSLClientServerTest, ClientCAListFromPem) {
  8768. // Test SSL server using PemMemory constructor with client CA certificates
  8769. // Read PEM files
  8770. std::string server_cert_pem, server_key_pem, client_ca_pem;
  8771. read_file(SERVER_CERT_FILE, server_cert_pem);
  8772. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8773. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8774. // Create SSLServer with PemMemory constructor including client CA
  8775. SSLServer::PemMemory server_pem = {
  8776. server_cert_pem.c_str(),
  8777. server_cert_pem.size(),
  8778. server_key_pem.c_str(),
  8779. server_key_pem.size(),
  8780. client_ca_pem.c_str(),
  8781. client_ca_pem.size(),
  8782. nullptr // no password for server key
  8783. };
  8784. SSLServer svr(server_pem);
  8785. ASSERT_TRUE(svr.is_valid());
  8786. // No SSL error should be recorded for valid setup
  8787. EXPECT_EQ(0, svr.ssl_last_error());
  8788. // Set up server endpoints
  8789. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  8790. res.set_content("ok", "text/plain");
  8791. });
  8792. // Start server in a thread
  8793. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  8794. svr.wait_until_ready();
  8795. // Connect with client certificate (using constructor with paths)
  8796. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8797. cli.enable_server_certificate_verification(false);
  8798. auto res = cli.Get("/test-pem-ca");
  8799. ASSERT_TRUE(res);
  8800. EXPECT_EQ(200, res->status);
  8801. EXPECT_EQ("ok", res->body);
  8802. svr.stop();
  8803. server_thread.join();
  8804. }
  8805. #endif
  8806. #ifdef _WIN32
  8807. TEST(CleanupTest, WSACleanup) {
  8808. int ret = WSACleanup();
  8809. ASSERT_EQ(0, ret);
  8810. }
  8811. #endif
  8812. #ifndef CPPHTTPLIB_SSL_ENABLED
  8813. TEST(NoSSLSupport, SimpleInterface) {
  8814. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  8815. }
  8816. #endif
  8817. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8818. TEST(InvalidScheme, SimpleInterface) {
  8819. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  8820. }
  8821. #endif
  8822. TEST(NoScheme, SimpleInterface) {
  8823. Client cli("yahoo.com:80");
  8824. ASSERT_TRUE(cli.is_valid());
  8825. }
  8826. TEST(SendAPI, SimpleInterface_Online) {
  8827. Client cli("http://yahoo.com");
  8828. Request req;
  8829. req.method = "GET";
  8830. req.path = "/";
  8831. auto res = cli.send(req);
  8832. ASSERT_TRUE(res);
  8833. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8834. }
  8835. TEST(SendAPI, WithParamsInRequest) {
  8836. Server svr;
  8837. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  8838. EXPECT_TRUE(req.has_param("test"));
  8839. EXPECT_EQ("test_value", req.get_param_value("test"));
  8840. });
  8841. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  8842. auto se = detail::scope_exit([&] {
  8843. svr.stop();
  8844. t.join();
  8845. ASSERT_FALSE(svr.is_running());
  8846. });
  8847. svr.wait_until_ready();
  8848. Client cli(HOST, PORT);
  8849. {
  8850. Request req;
  8851. req.method = "GET";
  8852. req.path = "/";
  8853. req.params.emplace("test", "test_value");
  8854. auto res = cli.send(req);
  8855. ASSERT_TRUE(res);
  8856. }
  8857. {
  8858. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  8859. ASSERT_TRUE(res);
  8860. }
  8861. }
  8862. TEST(ClientImplMethods, GetSocketTest) {
  8863. httplib::Server svr;
  8864. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  8865. res.status = StatusCode::OK_200;
  8866. });
  8867. auto port = svr.bind_to_any_port("127.0.0.1");
  8868. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  8869. auto se = detail::scope_exit([&] {
  8870. svr.stop();
  8871. thread.join();
  8872. ASSERT_FALSE(svr.is_running());
  8873. });
  8874. svr.wait_until_ready();
  8875. {
  8876. httplib::Client cli("127.0.0.1", port);
  8877. cli.set_keep_alive(true);
  8878. // Use the behavior of cpp-httplib of opening the connection
  8879. // only when the first request happens. If that changes,
  8880. // this test would be obsolete.
  8881. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  8882. // This also implicitly tests the server. But other tests would fail much
  8883. // earlier than this one to be considered.
  8884. auto res = cli.Get("/");
  8885. ASSERT_TRUE(res);
  8886. EXPECT_EQ(StatusCode::OK_200, res->status);
  8887. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  8888. }
  8889. }
  8890. // Disabled due to out-of-memory problem on GitHub Actions
  8891. #ifdef _WIN64
  8892. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  8893. // allocate content size larger than 2GB in memory
  8894. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  8895. char *content = (char *)malloc(content_size);
  8896. ASSERT_TRUE(content);
  8897. Server svr;
  8898. svr.Get("/foo",
  8899. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  8900. res.set_content(content, content_size, "application/octet-stream");
  8901. });
  8902. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8903. auto se = detail::scope_exit([&] {
  8904. svr.stop();
  8905. listen_thread.join();
  8906. if (content) free(content);
  8907. ASSERT_FALSE(svr.is_running());
  8908. });
  8909. svr.wait_until_ready();
  8910. Client cli(HOST, PORT);
  8911. auto res = cli.Get("/foo");
  8912. ASSERT_TRUE(res);
  8913. EXPECT_EQ(StatusCode::OK_200, res->status);
  8914. EXPECT_EQ(content_size, res->body.length());
  8915. }
  8916. #endif
  8917. #ifdef CPPHTTPLIB_SSL_ENABLED
  8918. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  8919. Client cli("http://yahoo.com");
  8920. auto res = cli.Get("/");
  8921. ASSERT_TRUE(res);
  8922. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8923. cli.set_follow_location(true);
  8924. res = cli.Get("/");
  8925. ASSERT_TRUE(res);
  8926. EXPECT_EQ(StatusCode::OK_200, res->status);
  8927. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8928. }
  8929. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  8930. Client cli("https://yahoo.com");
  8931. auto res = cli.Get("/");
  8932. ASSERT_TRUE(res);
  8933. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8934. cli.set_follow_location(true);
  8935. res = cli.Get("/");
  8936. ASSERT_TRUE(res);
  8937. EXPECT_EQ(StatusCode::OK_200, res->status);
  8938. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8939. }
  8940. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  8941. Client cli("https://yahoo.com");
  8942. auto res = cli.Get("/");
  8943. ASSERT_TRUE(res);
  8944. ASSERT_FALSE(!res);
  8945. ASSERT_TRUE(res);
  8946. ASSERT_FALSE(res == nullptr);
  8947. ASSERT_TRUE(res != nullptr);
  8948. EXPECT_EQ(Error::Success, res.error());
  8949. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  8950. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  8951. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8952. cli.set_follow_location(true);
  8953. res = cli.Get("/");
  8954. ASSERT_TRUE(res);
  8955. EXPECT_EQ(Error::Success, res.error());
  8956. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  8957. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  8958. EXPECT_EQ(StatusCode::OK_200, res->status);
  8959. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8960. }
  8961. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8962. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  8963. Client cli("https://cdnjs.cloudflare.com");
  8964. auto res =
  8965. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  8966. ASSERT_TRUE(res);
  8967. EXPECT_EQ(StatusCode::OK_200, res->status);
  8968. EXPECT_EQ(287630U, res->body.size());
  8969. EXPECT_EQ("application/javascript; charset=utf-8",
  8970. res->get_header_value("Content-Type"));
  8971. }
  8972. #endif
  8973. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  8974. #undef REDIR_HOST // Silence compiler warning
  8975. #define REDIR_HOST "https://httpbingo.org"
  8976. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  8977. Client cli(REDIR_HOST);
  8978. cli.set_follow_location(true);
  8979. auto res =
  8980. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  8981. ASSERT_TRUE(res);
  8982. EXPECT_EQ(StatusCode::OK_200, res->status);
  8983. }
  8984. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  8985. Client cli(REDIR_HOST);
  8986. cli.set_follow_location(true);
  8987. Params params;
  8988. params.emplace("url", "http://example.com");
  8989. params.emplace("status_code", "302");
  8990. auto res = cli.Get(REDIR_PATH, params, Headers{});
  8991. ASSERT_TRUE(res);
  8992. EXPECT_EQ(StatusCode::OK_200, res->status);
  8993. }
  8994. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  8995. Client cli(REDIR_HOST);
  8996. cli.set_follow_location(true);
  8997. Params params;
  8998. params.emplace("url", "http://example.com");
  8999. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9000. ASSERT_TRUE(res);
  9001. EXPECT_EQ(StatusCode::OK_200, res->status);
  9002. }
  9003. TEST(HttpToHttpsRedirectTest, CertFile) {
  9004. auto ssl_port = PORT + 1;
  9005. Server svr;
  9006. ASSERT_TRUE(svr.is_valid());
  9007. svr.Get("/index", [&](const Request &, Response &res) {
  9008. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9009. "/index");
  9010. svr.stop();
  9011. });
  9012. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9013. ASSERT_TRUE(ssl_svr.is_valid());
  9014. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9015. res.set_content("test", "text/plain");
  9016. ssl_svr.stop();
  9017. });
  9018. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9019. thread t2 =
  9020. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9021. auto se = detail::scope_exit([&] {
  9022. t2.join();
  9023. t.join();
  9024. ASSERT_FALSE(svr.is_running());
  9025. });
  9026. svr.wait_until_ready();
  9027. ssl_svr.wait_until_ready();
  9028. Client cli("127.0.0.1", PORT);
  9029. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9030. cli.enable_server_certificate_verification(true);
  9031. cli.set_follow_location(true);
  9032. cli.set_connection_timeout(30);
  9033. auto res = cli.Get("/index");
  9034. ASSERT_TRUE(res);
  9035. ASSERT_EQ(StatusCode::OK_200, res->status);
  9036. }
  9037. TEST(SSLClientRedirectTest, CertFile) {
  9038. auto ssl_port = PORT + 1;
  9039. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9040. ASSERT_TRUE(ssl_svr1.is_valid());
  9041. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9042. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9043. "/index");
  9044. ssl_svr1.stop();
  9045. });
  9046. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9047. ASSERT_TRUE(ssl_svr2.is_valid());
  9048. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9049. res.set_content("test", "text/plain");
  9050. ssl_svr2.stop();
  9051. });
  9052. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9053. thread t2 =
  9054. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9055. auto se = detail::scope_exit([&] {
  9056. t2.join();
  9057. t.join();
  9058. ASSERT_FALSE(ssl_svr1.is_running());
  9059. });
  9060. ssl_svr1.wait_until_ready();
  9061. ssl_svr2.wait_until_ready();
  9062. SSLClient cli("127.0.0.1", PORT);
  9063. std::string cert;
  9064. read_file(SERVER_CERT2_FILE, cert);
  9065. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9066. cli.enable_server_certificate_verification(true);
  9067. cli.set_follow_location(true);
  9068. cli.set_connection_timeout(30);
  9069. auto res = cli.Get("/index");
  9070. ASSERT_TRUE(res);
  9071. ASSERT_EQ(StatusCode::OK_200, res->status);
  9072. }
  9073. #endif
  9074. #ifdef CPPHTTPLIB_SSL_ENABLED
  9075. // Test that set_ca_cert_store() skips system certs (consistent with
  9076. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9077. // should be trusted - system certs should NOT be loaded.
  9078. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9079. // Load a specific cert that is NOT a system CA cert
  9080. std::string cert;
  9081. read_file(SERVER_CERT2_FILE, cert);
  9082. SSLClient cli("google.com");
  9083. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9084. cli.enable_server_certificate_verification(true);
  9085. // This should FAIL because:
  9086. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9087. // 2. System certs should NOT be loaded when custom store is set
  9088. // If system certs WERE loaded, this would succeed
  9089. auto res = cli.Get("/");
  9090. ASSERT_FALSE(res);
  9091. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9092. }
  9093. TEST(MultipartFormDataTest, LargeData) {
  9094. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9095. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9096. const ContentReader &content_reader) {
  9097. if (req.is_multipart_form_data()) {
  9098. std::vector<FormData> items;
  9099. content_reader(
  9100. [&](const FormData &file) {
  9101. items.push_back(file);
  9102. return true;
  9103. },
  9104. [&](const char *data, size_t data_length) {
  9105. items.back().content.append(data, data_length);
  9106. return true;
  9107. });
  9108. EXPECT_TRUE(std::string(items[0].name) == "document");
  9109. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9110. EXPECT_TRUE(items[0].filename == "2MB_data");
  9111. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9112. EXPECT_TRUE(items[1].name == "hello");
  9113. EXPECT_TRUE(items[1].content == "world");
  9114. EXPECT_TRUE(items[1].filename == "");
  9115. EXPECT_TRUE(items[1].content_type == "");
  9116. } else {
  9117. std::string body;
  9118. content_reader([&](const char *data, size_t data_length) {
  9119. body.append(data, data_length);
  9120. return true;
  9121. });
  9122. }
  9123. });
  9124. auto port = svr.bind_to_any_port(HOST);
  9125. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9126. auto se = detail::scope_exit([&] {
  9127. svr.stop();
  9128. t.join();
  9129. ASSERT_FALSE(svr.is_running());
  9130. });
  9131. svr.wait_until_ready();
  9132. {
  9133. std::string data(1024 * 1024 * 2, '.');
  9134. std::stringstream buffer;
  9135. buffer << data;
  9136. SSLClient cli(HOST, port);
  9137. cli.enable_server_certificate_verification(false);
  9138. UploadFormDataItems items{
  9139. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9140. {"hello", "world", "", ""},
  9141. };
  9142. auto res = cli.Post("/post", items);
  9143. ASSERT_TRUE(res);
  9144. ASSERT_EQ(StatusCode::OK_200, res->status);
  9145. }
  9146. }
  9147. TEST(MultipartFormDataTest, DataProviderItems) {
  9148. std::random_device seed_gen;
  9149. std::mt19937 random(seed_gen());
  9150. std::string rand1;
  9151. rand1.resize(1000);
  9152. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9153. std::string rand2;
  9154. rand2.resize(3000);
  9155. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9156. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9157. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9158. const ContentReader &content_reader) {
  9159. ASSERT_FALSE(req.is_multipart_form_data());
  9160. std::string body;
  9161. content_reader([&](const char *data, size_t data_length) {
  9162. body.append(data, data_length);
  9163. return true;
  9164. });
  9165. EXPECT_EQ(body, "");
  9166. });
  9167. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9168. const ContentReader &content_reader) {
  9169. ASSERT_TRUE(req.is_multipart_form_data());
  9170. std::vector<FormData> items;
  9171. content_reader(
  9172. [&](const FormData &file) {
  9173. items.push_back(file);
  9174. return true;
  9175. },
  9176. [&](const char *data, size_t data_length) {
  9177. items.back().content.append(data, data_length);
  9178. return true;
  9179. });
  9180. ASSERT_TRUE(items.size() == 2);
  9181. EXPECT_EQ(std::string(items[0].name), "name1");
  9182. EXPECT_EQ(items[0].content, "Testing123");
  9183. EXPECT_EQ(items[0].filename, "filename1");
  9184. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9185. EXPECT_EQ(items[1].name, "name2");
  9186. EXPECT_EQ(items[1].content, "Testing456");
  9187. EXPECT_EQ(items[1].filename, "");
  9188. EXPECT_EQ(items[1].content_type, "");
  9189. });
  9190. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9191. const ContentReader &content_reader) {
  9192. ASSERT_TRUE(req.is_multipart_form_data());
  9193. std::vector<FormData> items;
  9194. content_reader(
  9195. [&](const FormData &file) {
  9196. items.push_back(file);
  9197. return true;
  9198. },
  9199. [&](const char *data, size_t data_length) {
  9200. items.back().content.append(data, data_length);
  9201. return true;
  9202. });
  9203. ASSERT_TRUE(items.size() == 2);
  9204. EXPECT_EQ(items[0].name, "name3");
  9205. EXPECT_EQ(items[0].content, rand1);
  9206. EXPECT_EQ(items[0].filename, "filename3");
  9207. EXPECT_EQ(items[0].content_type, "");
  9208. EXPECT_EQ(items[1].name, "name4");
  9209. EXPECT_EQ(items[1].content, rand2);
  9210. EXPECT_EQ(items[1].filename, "filename4");
  9211. EXPECT_EQ(items[1].content_type, "");
  9212. });
  9213. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9214. const ContentReader &content_reader) {
  9215. ASSERT_TRUE(req.is_multipart_form_data());
  9216. std::vector<FormData> items;
  9217. content_reader(
  9218. [&](const FormData &file) {
  9219. items.push_back(file);
  9220. return true;
  9221. },
  9222. [&](const char *data, size_t data_length) {
  9223. items.back().content.append(data, data_length);
  9224. return true;
  9225. });
  9226. ASSERT_TRUE(items.size() == 4);
  9227. EXPECT_EQ(std::string(items[0].name), "name1");
  9228. EXPECT_EQ(items[0].content, "Testing123");
  9229. EXPECT_EQ(items[0].filename, "filename1");
  9230. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9231. EXPECT_EQ(items[1].name, "name2");
  9232. EXPECT_EQ(items[1].content, "Testing456");
  9233. EXPECT_EQ(items[1].filename, "");
  9234. EXPECT_EQ(items[1].content_type, "");
  9235. EXPECT_EQ(items[2].name, "name3");
  9236. EXPECT_EQ(items[2].content, rand1);
  9237. EXPECT_EQ(items[2].filename, "filename3");
  9238. EXPECT_EQ(items[2].content_type, "");
  9239. EXPECT_EQ(items[3].name, "name4");
  9240. EXPECT_EQ(items[3].content, rand2);
  9241. EXPECT_EQ(items[3].filename, "filename4");
  9242. EXPECT_EQ(items[3].content_type, "");
  9243. });
  9244. auto port = svr.bind_to_any_port("localhost");
  9245. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9246. auto se = detail::scope_exit([&] {
  9247. svr.stop();
  9248. t.join();
  9249. ASSERT_FALSE(svr.is_running());
  9250. });
  9251. svr.wait_until_ready();
  9252. {
  9253. SSLClient cli("localhost", port);
  9254. cli.enable_server_certificate_verification(false);
  9255. UploadFormDataItems items{
  9256. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9257. {"name2", "Testing456", "", ""}, // not a file
  9258. };
  9259. {
  9260. auto res = cli.Post("/post-none", {}, {}, {});
  9261. ASSERT_TRUE(res);
  9262. ASSERT_EQ(StatusCode::OK_200, res->status);
  9263. }
  9264. FormDataProviderItems providers;
  9265. {
  9266. auto res =
  9267. cli.Post("/post-items", {}, items, providers); // empty providers
  9268. ASSERT_TRUE(res);
  9269. ASSERT_EQ(StatusCode::OK_200, res->status);
  9270. }
  9271. providers.push_back({"name3",
  9272. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9273. // test the offset is given correctly at each step
  9274. if (!offset)
  9275. sink.os.write(rand1.data(), 30);
  9276. else if (offset == 30)
  9277. sink.os.write(rand1.data() + 30, 300);
  9278. else if (offset == 330)
  9279. sink.os.write(rand1.data() + 330, 670);
  9280. else if (offset == rand1.size())
  9281. sink.done();
  9282. return true;
  9283. },
  9284. "filename3",
  9285. {}});
  9286. providers.push_back({"name4",
  9287. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9288. // test the offset is given correctly at each step
  9289. if (!offset)
  9290. sink.os.write(rand2.data(), 2000);
  9291. else if (offset == 2000)
  9292. sink.os.write(rand2.data() + 2000, 1);
  9293. else if (offset == 2001)
  9294. sink.os.write(rand2.data() + 2001, 999);
  9295. else if (offset == rand2.size())
  9296. sink.done();
  9297. return true;
  9298. },
  9299. "filename4",
  9300. {}});
  9301. {
  9302. auto res = cli.Post("/post-providers", {}, {}, providers);
  9303. ASSERT_TRUE(res);
  9304. ASSERT_EQ(StatusCode::OK_200, res->status);
  9305. }
  9306. {
  9307. auto res = cli.Post("/post-both", {}, items, providers);
  9308. ASSERT_TRUE(res);
  9309. ASSERT_EQ(StatusCode::OK_200, res->status);
  9310. }
  9311. }
  9312. }
  9313. TEST(MultipartFormDataTest, BadHeader) {
  9314. Server svr;
  9315. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9316. res.set_content("ok", "text/plain");
  9317. });
  9318. thread t = thread([&] { svr.listen(HOST, PORT); });
  9319. auto se = detail::scope_exit([&] {
  9320. svr.stop();
  9321. t.join();
  9322. ASSERT_FALSE(svr.is_running());
  9323. });
  9324. svr.wait_until_ready();
  9325. const std::string body =
  9326. "This is the preamble. It is to be ignored, though it\r\n"
  9327. "is a handy place for composition agents to include an\r\n"
  9328. "explanatory note to non-MIME conformant readers.\r\n"
  9329. "\r\n"
  9330. "\r\n"
  9331. "--simple boundary\r\n"
  9332. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9333. ": BAD...\r\n"
  9334. "\r\n"
  9335. "value1\r\n"
  9336. "--simple boundary\r\n"
  9337. "Content-Disposition: form-data; name=\"field2\"; "
  9338. "filename=\"example.txt\"\r\n"
  9339. "\r\n"
  9340. "value2\r\n"
  9341. "--simple boundary--\r\n"
  9342. "This is the epilogue. It is also to be ignored.\r\n";
  9343. std::string content_type =
  9344. R"(multipart/form-data; boundary="simple boundary")";
  9345. Client cli(HOST, PORT);
  9346. auto res = cli.Post("/post", body, content_type.c_str());
  9347. ASSERT_TRUE(res);
  9348. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9349. }
  9350. TEST(MultipartFormDataTest, WithPreamble) {
  9351. Server svr;
  9352. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9353. res.set_content("ok", "text/plain");
  9354. });
  9355. thread t = thread([&] { svr.listen(HOST, PORT); });
  9356. auto se = detail::scope_exit([&] {
  9357. svr.stop();
  9358. t.join();
  9359. ASSERT_FALSE(svr.is_running());
  9360. });
  9361. svr.wait_until_ready();
  9362. const std::string body =
  9363. "This is the preamble. It is to be ignored, though it\r\n"
  9364. "is a handy place for composition agents to include an\r\n"
  9365. "explanatory note to non-MIME conformant readers.\r\n"
  9366. "\r\n"
  9367. "\r\n"
  9368. "--simple boundary\r\n"
  9369. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9370. "\r\n"
  9371. "value1\r\n"
  9372. "--simple boundary\r\n"
  9373. "Content-Disposition: form-data; name=\"field2\"; "
  9374. "filename=\"example.txt\"\r\n"
  9375. "\r\n"
  9376. "value2\r\n"
  9377. "--simple boundary--\r\n"
  9378. "This is the epilogue. It is also to be ignored.\r\n";
  9379. std::string content_type =
  9380. R"(multipart/form-data; boundary="simple boundary")";
  9381. Client cli(HOST, PORT);
  9382. auto res = cli.Post("/post", body, content_type.c_str());
  9383. ASSERT_TRUE(res);
  9384. EXPECT_EQ(StatusCode::OK_200, res->status);
  9385. }
  9386. TEST(MultipartFormDataTest, PostCustomBoundary) {
  9387. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9388. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  9389. const ContentReader &content_reader) {
  9390. if (req.is_multipart_form_data()) {
  9391. std::vector<FormData> items;
  9392. content_reader(
  9393. [&](const FormData &file) {
  9394. items.push_back(file);
  9395. return true;
  9396. },
  9397. [&](const char *data, size_t data_length) {
  9398. items.back().content.append(data, data_length);
  9399. return true;
  9400. });
  9401. EXPECT_TRUE(std::string(items[0].name) == "document");
  9402. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9403. EXPECT_TRUE(items[0].filename == "2MB_data");
  9404. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9405. EXPECT_TRUE(items[1].name == "hello");
  9406. EXPECT_TRUE(items[1].content == "world");
  9407. EXPECT_TRUE(items[1].filename == "");
  9408. EXPECT_TRUE(items[1].content_type == "");
  9409. } else {
  9410. std::string body;
  9411. content_reader([&](const char *data, size_t data_length) {
  9412. body.append(data, data_length);
  9413. return true;
  9414. });
  9415. }
  9416. });
  9417. auto port = svr.bind_to_any_port("localhost");
  9418. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9419. auto se = detail::scope_exit([&] {
  9420. svr.stop();
  9421. t.join();
  9422. ASSERT_FALSE(svr.is_running());
  9423. });
  9424. svr.wait_until_ready();
  9425. {
  9426. std::string data(1024 * 1024 * 2, '.');
  9427. std::stringstream buffer;
  9428. buffer << data;
  9429. SSLClient cli("localhost", port);
  9430. cli.enable_server_certificate_verification(false);
  9431. UploadFormDataItems items{
  9432. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9433. {"hello", "world", "", ""},
  9434. };
  9435. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9436. ASSERT_TRUE(res);
  9437. ASSERT_EQ(StatusCode::OK_200, res->status);
  9438. }
  9439. }
  9440. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9441. std::string data(1024 * 1024 * 2, '&');
  9442. std::stringstream buffer;
  9443. buffer << data;
  9444. Client cli("https://localhost:8080");
  9445. UploadFormDataItems items{
  9446. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9447. {"hello", "world", "", ""},
  9448. };
  9449. for (const char &c : " \t\r\n") {
  9450. auto res =
  9451. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9452. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9453. ASSERT_FALSE(res);
  9454. }
  9455. }
  9456. TEST(MultipartFormDataTest, PutFormData) {
  9457. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9458. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9459. const ContentReader &content_reader) {
  9460. if (req.is_multipart_form_data()) {
  9461. std::vector<FormData> items;
  9462. content_reader(
  9463. [&](const FormData &file) {
  9464. items.push_back(file);
  9465. return true;
  9466. },
  9467. [&](const char *data, size_t data_length) {
  9468. items.back().content.append(data, data_length);
  9469. return true;
  9470. });
  9471. EXPECT_TRUE(std::string(items[0].name) == "document");
  9472. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9473. EXPECT_TRUE(items[0].filename == "2MB_data");
  9474. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9475. EXPECT_TRUE(items[1].name == "hello");
  9476. EXPECT_TRUE(items[1].content == "world");
  9477. EXPECT_TRUE(items[1].filename == "");
  9478. EXPECT_TRUE(items[1].content_type == "");
  9479. } else {
  9480. std::string body;
  9481. content_reader([&](const char *data, size_t data_length) {
  9482. body.append(data, data_length);
  9483. return true;
  9484. });
  9485. }
  9486. });
  9487. auto port = svr.bind_to_any_port("localhost");
  9488. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9489. auto se = detail::scope_exit([&] {
  9490. svr.stop();
  9491. t.join();
  9492. ASSERT_FALSE(svr.is_running());
  9493. });
  9494. svr.wait_until_ready();
  9495. {
  9496. std::string data(1024 * 1024 * 2, '&');
  9497. std::stringstream buffer;
  9498. buffer << data;
  9499. SSLClient cli("localhost", port);
  9500. cli.enable_server_certificate_verification(false);
  9501. UploadFormDataItems items{
  9502. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9503. {"hello", "world", "", ""},
  9504. };
  9505. auto res = cli.Put("/put", items);
  9506. ASSERT_TRUE(res);
  9507. ASSERT_EQ(StatusCode::OK_200, res->status);
  9508. }
  9509. }
  9510. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  9511. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9512. svr.Put("/put_customboundary",
  9513. [&](const Request &req, const Response & /*res*/,
  9514. const ContentReader &content_reader) {
  9515. if (req.is_multipart_form_data()) {
  9516. std::vector<FormData> items;
  9517. content_reader(
  9518. [&](const FormData &file) {
  9519. items.push_back(file);
  9520. return true;
  9521. },
  9522. [&](const char *data, size_t data_length) {
  9523. items.back().content.append(data, data_length);
  9524. return true;
  9525. });
  9526. EXPECT_TRUE(std::string(items[0].name) == "document");
  9527. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9528. EXPECT_TRUE(items[0].filename == "2MB_data");
  9529. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9530. EXPECT_TRUE(items[1].name == "hello");
  9531. EXPECT_TRUE(items[1].content == "world");
  9532. EXPECT_TRUE(items[1].filename == "");
  9533. EXPECT_TRUE(items[1].content_type == "");
  9534. } else {
  9535. std::string body;
  9536. content_reader([&](const char *data, size_t data_length) {
  9537. body.append(data, data_length);
  9538. return true;
  9539. });
  9540. }
  9541. });
  9542. auto port = svr.bind_to_any_port("localhost");
  9543. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9544. auto se = detail::scope_exit([&] {
  9545. svr.stop();
  9546. t.join();
  9547. ASSERT_FALSE(svr.is_running());
  9548. });
  9549. svr.wait_until_ready();
  9550. {
  9551. std::string data(1024 * 1024 * 2, '&');
  9552. std::stringstream buffer;
  9553. buffer << data;
  9554. SSLClient cli("localhost", port);
  9555. cli.enable_server_certificate_verification(false);
  9556. UploadFormDataItems items{
  9557. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9558. {"hello", "world", "", ""},
  9559. };
  9560. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  9561. ASSERT_TRUE(res);
  9562. ASSERT_EQ(StatusCode::OK_200, res->status);
  9563. }
  9564. }
  9565. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  9566. std::string data(1024 * 1024 * 2, '&');
  9567. std::stringstream buffer;
  9568. buffer << data;
  9569. Client cli("https://localhost:8080");
  9570. cli.enable_server_certificate_verification(false);
  9571. UploadFormDataItems items{
  9572. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9573. {"hello", "world", "", ""},
  9574. };
  9575. for (const char &c : " \t\r\n") {
  9576. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  9577. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9578. ASSERT_FALSE(res);
  9579. }
  9580. }
  9581. TEST(MultipartFormDataTest, AlternateFilename) {
  9582. auto handled = false;
  9583. Server svr;
  9584. svr.Post("/test", [&](const Request &req, Response &res) {
  9585. ASSERT_EQ(2u, req.form.files.size());
  9586. ASSERT_EQ(1u, req.form.fields.size());
  9587. // Test files
  9588. const auto &file1 = req.form.get_file("file1");
  9589. ASSERT_EQ("file1", file1.name);
  9590. ASSERT_EQ("A.txt", file1.filename);
  9591. ASSERT_EQ("text/plain", file1.content_type);
  9592. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  9593. const auto &file2 = req.form.get_file("file2");
  9594. ASSERT_EQ("file2", file2.name);
  9595. ASSERT_EQ("a.html", file2.filename);
  9596. ASSERT_EQ("text/html", file2.content_type);
  9597. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  9598. file2.content);
  9599. // Test text field
  9600. const auto &text = req.form.get_field("text");
  9601. ASSERT_EQ("text default", text);
  9602. res.set_content("ok", "text/plain");
  9603. handled = true;
  9604. });
  9605. thread t = thread([&] { svr.listen(HOST, PORT); });
  9606. auto se = detail::scope_exit([&] {
  9607. svr.stop();
  9608. t.join();
  9609. ASSERT_FALSE(svr.is_running());
  9610. ASSERT_TRUE(handled);
  9611. });
  9612. svr.wait_until_ready();
  9613. auto req = "POST /test HTTP/1.1\r\n"
  9614. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9615. "Content-Length: 399\r\n"
  9616. "\r\n"
  9617. "----------\r\n"
  9618. "Content-Disposition: form-data; name=\"text\"\r\n"
  9619. "\r\n"
  9620. "text default\r\n"
  9621. "----------\r\n"
  9622. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  9623. "filename=\"a.txt\"; name=\"file1\"\r\n"
  9624. "Content-Type: text/plain\r\n"
  9625. "\r\n"
  9626. "Content of a.txt.\r\n"
  9627. "\r\n"
  9628. "----------\r\n"
  9629. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  9630. "\"a.html\"\r\n"
  9631. "Content-Type: text/html\r\n"
  9632. "\r\n"
  9633. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  9634. "\r\n"
  9635. "------------\r\n";
  9636. ASSERT_TRUE(send_request(1, req));
  9637. }
  9638. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  9639. auto handled = false;
  9640. Server svr;
  9641. svr.Post("/test", [&](const Request &req, Response &) {
  9642. ASSERT_EQ(2u, req.form.fields.size());
  9643. const auto &text1 = req.form.get_field("text1");
  9644. ASSERT_EQ("text1", text1);
  9645. const auto &text2 = req.form.get_field("text2");
  9646. ASSERT_EQ("text2", text2);
  9647. handled = true;
  9648. });
  9649. thread t = thread([&] { svr.listen(HOST, PORT); });
  9650. auto se = detail::scope_exit([&] {
  9651. svr.stop();
  9652. t.join();
  9653. ASSERT_FALSE(svr.is_running());
  9654. ASSERT_TRUE(handled);
  9655. });
  9656. svr.wait_until_ready();
  9657. auto req = "POST /test HTTP/1.1\r\n"
  9658. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9659. "Content-Length: 146\r\n"
  9660. "\r\n----------\r\n"
  9661. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9662. "\r\n"
  9663. "text1"
  9664. "\r\n----------\r\n"
  9665. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9666. "\r\n"
  9667. "text2"
  9668. "\r\n------------";
  9669. std::string response;
  9670. ASSERT_TRUE(send_request(1, req, &response));
  9671. ASSERT_EQ("200", response.substr(9, 3));
  9672. }
  9673. TEST(MultipartFormDataTest, ContentLength) {
  9674. auto handled = false;
  9675. Server svr;
  9676. svr.Post("/test", [&](const Request &req, Response &) {
  9677. ASSERT_EQ(2u, req.form.fields.size());
  9678. const auto &text1 = req.form.get_field("text1");
  9679. ASSERT_EQ("text1", text1);
  9680. const auto &text2 = req.form.get_field("text2");
  9681. ASSERT_EQ("text2", text2);
  9682. handled = true;
  9683. });
  9684. thread t = thread([&] { svr.listen(HOST, PORT); });
  9685. auto se = detail::scope_exit([&] {
  9686. svr.stop();
  9687. t.join();
  9688. ASSERT_FALSE(svr.is_running());
  9689. ASSERT_TRUE(handled);
  9690. });
  9691. svr.wait_until_ready();
  9692. auto req = "POST /test HTTP/1.1\r\n"
  9693. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9694. "Content-Length: 167\r\n"
  9695. "\r\n----------\r\n"
  9696. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9697. "Content-Length: 5\r\n"
  9698. "\r\n"
  9699. "text1"
  9700. "\r\n----------\r\n"
  9701. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9702. "\r\n"
  9703. "text2"
  9704. "\r\n------------\r\n";
  9705. std::string response;
  9706. ASSERT_TRUE(send_request(1, req, &response));
  9707. ASSERT_EQ("200", response.substr(9, 3));
  9708. }
  9709. TEST(MultipartFormDataTest, AccessPartHeaders) {
  9710. auto handled = false;
  9711. Server svr;
  9712. svr.Post("/test", [&](const Request &req, Response &) {
  9713. ASSERT_EQ(2u, req.form.fields.size());
  9714. const auto &text1 = req.form.get_field("text1");
  9715. ASSERT_EQ("text1", text1);
  9716. // TODO: Add header access for text fields if needed
  9717. const auto &text2 = req.form.get_field("text2");
  9718. ASSERT_EQ("text2", text2);
  9719. // TODO: Header access for text fields needs to be implemented
  9720. // auto &headers = it->second.headers;
  9721. // ASSERT_EQ(3U, headers.size());
  9722. // auto custom_header = headers.find("x-whatever");
  9723. // ASSERT_TRUE(custom_header != headers.end());
  9724. // ASSERT_NE("customvalue", custom_header->second);
  9725. // ASSERT_EQ("CustomValue", custom_header->second);
  9726. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  9727. handled = true;
  9728. });
  9729. thread t = thread([&] { svr.listen(HOST, PORT); });
  9730. auto se = detail::scope_exit([&] {
  9731. svr.stop();
  9732. t.join();
  9733. ASSERT_FALSE(svr.is_running());
  9734. ASSERT_TRUE(handled);
  9735. });
  9736. svr.wait_until_ready();
  9737. auto req = "POST /test HTTP/1.1\r\n"
  9738. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9739. "Content-Length: 232\r\n"
  9740. "\r\n----------\r\n"
  9741. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9742. "Content-Length: 5\r\n"
  9743. "X-Test: 1\r\n"
  9744. "\r\n"
  9745. "text1"
  9746. "\r\n----------\r\n"
  9747. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9748. "Content-Type: text/plain\r\n"
  9749. "X-Whatever: CustomValue\r\n"
  9750. "\r\n"
  9751. "text2"
  9752. "\r\n------------\r\n"
  9753. "That should be disregarded. Not even read";
  9754. std::string response;
  9755. ASSERT_TRUE(send_request(1, req, &response));
  9756. ASSERT_EQ("200", response.substr(9, 3));
  9757. }
  9758. TEST(MultipartFormDataTest, LargeHeader) {
  9759. auto handled = false;
  9760. Server svr;
  9761. svr.Post("/test", [&](const Request &req, Response &) {
  9762. ASSERT_EQ(1u, req.form.fields.size());
  9763. const auto &text = req.form.get_field("name1");
  9764. ASSERT_EQ("text1", text);
  9765. handled = true;
  9766. });
  9767. thread t = thread([&] { svr.listen(HOST, PORT); });
  9768. auto se = detail::scope_exit([&] {
  9769. svr.stop();
  9770. t.join();
  9771. ASSERT_FALSE(svr.is_running());
  9772. ASSERT_TRUE(handled);
  9773. });
  9774. svr.wait_until_ready();
  9775. auto boundary = std::string("cpp-httplib-multipart-data");
  9776. std::string content = "--" + boundary +
  9777. "\r\n"
  9778. "Content-Disposition: form-data; name=\"name1\"\r\n"
  9779. "\r\n"
  9780. "text1\r\n"
  9781. "--" +
  9782. boundary + "--\r\n";
  9783. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  9784. "Content-Type: multipart/form-data;boundary=" +
  9785. boundary +
  9786. "\r\n"
  9787. "Content-Length: " +
  9788. std::to_string(content.size()) +
  9789. "\r\n"
  9790. "Dummy-Header: ";
  9791. std::string header_suffix = "\r\n"
  9792. "\r\n";
  9793. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  9794. size_t header_dummy_size =
  9795. read_buff_size -
  9796. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  9797. auto header_dummy = std::string(header_dummy_size, '@');
  9798. auto req = header_prefix + header_dummy + header_suffix + content;
  9799. std::string response;
  9800. ASSERT_TRUE(send_request(1, req, &response));
  9801. ASSERT_EQ("200", response.substr(9, 3));
  9802. }
  9803. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  9804. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  9805. // (not chunked Transfer-Encoding) after the streaming refactor.
  9806. auto handled = false;
  9807. Server svr;
  9808. svr.Post("/upload", [&](const Request &req, Response &res) {
  9809. auto cl_it = req.headers.find("Content-Length");
  9810. EXPECT_TRUE(cl_it != req.headers.end());
  9811. auto te_it = req.headers.find("Transfer-Encoding");
  9812. EXPECT_TRUE(te_it == req.headers.end());
  9813. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  9814. res.set_content("ok", "text/plain");
  9815. handled = true;
  9816. });
  9817. auto port = svr.bind_to_any_port(HOST);
  9818. auto t = thread([&] { svr.listen_after_bind(); });
  9819. auto se = detail::scope_exit([&] {
  9820. svr.stop();
  9821. t.join();
  9822. ASSERT_FALSE(svr.is_running());
  9823. ASSERT_TRUE(handled);
  9824. });
  9825. svr.wait_until_ready();
  9826. UploadFormDataItems items = {
  9827. {"field1", "hello", "", "text/plain"},
  9828. {"file1", "world", "test.txt", "application/octet-stream"},
  9829. };
  9830. Client cli(HOST, port);
  9831. auto res = cli.Post("/upload", {}, items);
  9832. ASSERT_TRUE(res);
  9833. EXPECT_EQ(StatusCode::OK_200, res->status);
  9834. }
  9835. TEST(MultipartFormDataTest, MakeFileProvider) {
  9836. // Verify make_file_provider sends a file's contents correctly.
  9837. const std::string file_content(4096, 'Z');
  9838. const std::string tmp_path = "/tmp/httplib_test_make_file_provider.bin";
  9839. {
  9840. std::ofstream ofs(tmp_path, std::ios::binary);
  9841. ofs.write(file_content.data(),
  9842. static_cast<std::streamsize>(file_content.size()));
  9843. }
  9844. auto handled = false;
  9845. Server svr;
  9846. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  9847. const ContentReader &content_reader) {
  9848. ASSERT_TRUE(req.is_multipart_form_data());
  9849. std::vector<FormData> items;
  9850. content_reader(
  9851. [&](const FormData &file) {
  9852. items.push_back(file);
  9853. return true;
  9854. },
  9855. [&](const char *data, size_t data_length) {
  9856. items.back().content.append(data, data_length);
  9857. return true;
  9858. });
  9859. ASSERT_EQ(1u, items.size());
  9860. EXPECT_EQ("myfile", items[0].name);
  9861. EXPECT_EQ("data.bin", items[0].filename);
  9862. EXPECT_EQ("application/octet-stream", items[0].content_type);
  9863. EXPECT_EQ(file_content, items[0].content);
  9864. handled = true;
  9865. });
  9866. auto port = svr.bind_to_any_port(HOST);
  9867. auto t = thread([&] { svr.listen_after_bind(); });
  9868. auto se = detail::scope_exit([&] {
  9869. svr.stop();
  9870. t.join();
  9871. ASSERT_FALSE(svr.is_running());
  9872. ASSERT_TRUE(handled);
  9873. std::remove(tmp_path.c_str());
  9874. });
  9875. svr.wait_until_ready();
  9876. FormDataProviderItems providers;
  9877. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  9878. "application/octet-stream"));
  9879. Client cli(HOST, port);
  9880. auto res = cli.Post("/upload", {}, {}, providers);
  9881. ASSERT_TRUE(res);
  9882. EXPECT_EQ(StatusCode::OK_200, res->status);
  9883. }
  9884. TEST(MakeFileBodyTest, Basic) {
  9885. const std::string file_content(4096, 'Z');
  9886. const std::string tmp_path = "/tmp/httplib_test_make_file_body.bin";
  9887. {
  9888. std::ofstream ofs(tmp_path, std::ios::binary);
  9889. ofs.write(file_content.data(),
  9890. static_cast<std::streamsize>(file_content.size()));
  9891. }
  9892. auto handled = false;
  9893. Server svr;
  9894. svr.Post("/upload", [&](const Request &req, Response &res) {
  9895. EXPECT_EQ(file_content, req.body);
  9896. handled = true;
  9897. res.status = StatusCode::OK_200;
  9898. });
  9899. auto port = svr.bind_to_any_port(HOST);
  9900. auto t = thread([&] { svr.listen_after_bind(); });
  9901. auto se = detail::scope_exit([&] {
  9902. svr.stop();
  9903. t.join();
  9904. ASSERT_FALSE(svr.is_running());
  9905. ASSERT_TRUE(handled);
  9906. std::remove(tmp_path.c_str());
  9907. });
  9908. svr.wait_until_ready();
  9909. auto fb = make_file_body(tmp_path);
  9910. ASSERT_GT(fb.first, 0u);
  9911. Client cli(HOST, port);
  9912. auto res =
  9913. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  9914. ASSERT_TRUE(res);
  9915. EXPECT_EQ(StatusCode::OK_200, res->status);
  9916. }
  9917. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  9918. static constexpr unsigned int number_of_tasks{1000000};
  9919. std::atomic_uint count{0};
  9920. std::unique_ptr<TaskQueue> task_queue{
  9921. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  9922. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  9923. auto queued = task_queue->enqueue(
  9924. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  9925. EXPECT_TRUE(queued);
  9926. }
  9927. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  9928. task_queue->shutdown();
  9929. #else
  9930. EXPECT_NO_THROW(task_queue->shutdown());
  9931. #endif
  9932. EXPECT_EQ(number_of_tasks, count.load());
  9933. }
  9934. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  9935. static constexpr unsigned int number_of_tasks{1000000};
  9936. static constexpr unsigned int qlimit{2};
  9937. unsigned int queued_count{0};
  9938. std::atomic_uint count{0};
  9939. std::unique_ptr<TaskQueue> task_queue{
  9940. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  9941. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  9942. if (task_queue->enqueue(
  9943. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  9944. queued_count++;
  9945. }
  9946. }
  9947. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  9948. task_queue->shutdown();
  9949. #else
  9950. EXPECT_NO_THROW(task_queue->shutdown());
  9951. #endif
  9952. EXPECT_EQ(queued_count, count.load());
  9953. EXPECT_TRUE(queued_count <= number_of_tasks);
  9954. EXPECT_TRUE(queued_count >= qlimit);
  9955. }
  9956. TEST(TaskQueueTest, MaxQueuedRequests) {
  9957. static constexpr unsigned int qlimit{3};
  9958. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  9959. std::condition_variable sem_cv;
  9960. std::mutex sem_mtx;
  9961. int credits = 0;
  9962. bool queued;
  9963. /* Fill up the queue with tasks that will block until we give them credits to
  9964. * complete. */
  9965. for (unsigned int n = 0; n <= qlimit;) {
  9966. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  9967. std::unique_lock<std::mutex> lock(sem_mtx);
  9968. while (credits <= 0) {
  9969. sem_cv.wait(lock);
  9970. }
  9971. /* Consume the credit and signal the test code if they are all gone. */
  9972. if (--credits == 0) { sem_cv.notify_one(); }
  9973. });
  9974. if (n < qlimit) {
  9975. /* The first qlimit enqueues must succeed. */
  9976. EXPECT_TRUE(queued);
  9977. } else {
  9978. /* The last one will succeed only when the worker thread
  9979. * starts and dequeues the first blocking task. Although
  9980. * not necessary for the correctness of this test, we sleep for
  9981. * a short while to avoid busy waiting. */
  9982. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  9983. }
  9984. if (queued) { n++; }
  9985. }
  9986. /* Further enqueues must fail since the queue is full. */
  9987. for (auto i = 0; i < 4; i++) {
  9988. queued = task_queue->enqueue([] {});
  9989. EXPECT_FALSE(queued);
  9990. }
  9991. /* Give the credits to allow the previous tasks to complete. */
  9992. {
  9993. std::unique_lock<std::mutex> lock(sem_mtx);
  9994. credits += qlimit + 1;
  9995. }
  9996. sem_cv.notify_all();
  9997. /* Wait for all the credits to be consumed. */
  9998. {
  9999. std::unique_lock<std::mutex> lock(sem_mtx);
  10000. while (credits > 0) {
  10001. sem_cv.wait(lock);
  10002. }
  10003. }
  10004. /* Check that we are able again to enqueue at least qlimit tasks. */
  10005. for (unsigned int i = 0; i < qlimit; i++) {
  10006. queued = task_queue->enqueue([] {});
  10007. EXPECT_TRUE(queued);
  10008. }
  10009. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10010. task_queue->shutdown();
  10011. #else
  10012. EXPECT_NO_THROW(task_queue->shutdown());
  10013. #endif
  10014. }
  10015. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  10016. Server svr;
  10017. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10018. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  10019. });
  10020. svr.Get("/hello", [](const Request &req, Response &res) {
  10021. res.set_content(req.get_param_value("key"), "text/plain");
  10022. });
  10023. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10024. auto se = detail::scope_exit([&] {
  10025. svr.stop();
  10026. thread.join();
  10027. ASSERT_FALSE(svr.is_running());
  10028. });
  10029. svr.wait_until_ready();
  10030. {
  10031. Client cli(HOST, PORT);
  10032. cli.set_follow_location(true);
  10033. auto res = cli.Get("/");
  10034. ASSERT_TRUE(res);
  10035. EXPECT_EQ(StatusCode::OK_200, res->status);
  10036. EXPECT_EQ("val&key2=val2", res->body);
  10037. }
  10038. }
  10039. #endif
  10040. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  10041. Server svr;
  10042. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10043. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  10044. });
  10045. svr.Get("/hello", [](const Request &req, Response &res) {
  10046. res.set_content(req.get_param_value("key"), "text/plain");
  10047. });
  10048. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10049. auto se = detail::scope_exit([&] {
  10050. svr.stop();
  10051. thread.join();
  10052. ASSERT_FALSE(svr.is_running());
  10053. });
  10054. svr.wait_until_ready();
  10055. {
  10056. Client cli(HOST, PORT);
  10057. cli.set_follow_location(true);
  10058. auto res = cli.Get("/");
  10059. ASSERT_TRUE(res);
  10060. EXPECT_EQ(StatusCode::OK_200, res->status);
  10061. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  10062. }
  10063. }
  10064. #ifdef CPPHTTPLIB_SSL_ENABLED
  10065. TEST(RedirectTest, Issue2185_Online) {
  10066. SSLClient client("github.com");
  10067. client.set_follow_location(true);
  10068. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  10069. "Coollab-Windows.zip");
  10070. ASSERT_TRUE(res);
  10071. EXPECT_EQ(StatusCode::OK_200, res->status);
  10072. EXPECT_EQ(9920427U, res->body.size());
  10073. }
  10074. #endif
  10075. TEST(VulnerabilityTest, CRLFInjection) {
  10076. Server svr;
  10077. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  10078. res.set_content("Hello 1", "text/plain");
  10079. });
  10080. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  10081. res.set_content("Hello 2", "text/plain");
  10082. });
  10083. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  10084. res.set_content("Hello 3", "text/plain");
  10085. });
  10086. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  10087. res.set_content("Hello 4", "text/plain");
  10088. });
  10089. svr.set_logger([](const Request &req, const Response & /*res*/) {
  10090. for (const auto &x : req.headers) {
  10091. auto key = x.first;
  10092. EXPECT_STRNE("evil", key.c_str());
  10093. }
  10094. });
  10095. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10096. auto se = detail::scope_exit([&] {
  10097. svr.stop();
  10098. thread.join();
  10099. ASSERT_FALSE(svr.is_running());
  10100. });
  10101. svr.wait_until_ready();
  10102. {
  10103. Client cli(HOST, PORT);
  10104. cli.Post("/test1", "A=B",
  10105. "application/x-www-form-urlencoded\r\nevil: hello1");
  10106. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  10107. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  10108. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  10109. }
  10110. }
  10111. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  10112. auto server_thread = std::thread([] {
  10113. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10114. default_socket_options(srv);
  10115. sockaddr_in addr{};
  10116. addr.sin_family = AF_INET;
  10117. addr.sin_port = htons(PORT + 1);
  10118. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10119. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10120. ::listen(srv, 1);
  10121. sockaddr_in cli_addr{};
  10122. socklen_t cli_len = sizeof(cli_addr);
  10123. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10124. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  10125. std::string buf_all;
  10126. char buf[2048];
  10127. ssize_t n;
  10128. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  10129. buf_all.append(buf, static_cast<size_t>(n));
  10130. size_t pos;
  10131. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  10132. auto request_block = buf_all.substr(0, pos + 4); // include separator
  10133. auto e = request_block.find("\r\n");
  10134. if (e != std::string::npos) {
  10135. auto request_line = request_block.substr(0, e);
  10136. std::string msg =
  10137. "CRLF injection detected in request line: '" + request_line + "'";
  10138. EXPECT_FALSE(true) << msg;
  10139. }
  10140. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  10141. ::send(cli,
  10142. #ifdef _WIN32
  10143. static_cast<const char *>(resp.c_str()),
  10144. static_cast<int>(resp.size()),
  10145. #else
  10146. resp.c_str(), resp.size(),
  10147. #endif
  10148. 0);
  10149. buf_all.erase(0, pos + 4);
  10150. }
  10151. }
  10152. detail::close_socket(cli);
  10153. detail::close_socket(srv);
  10154. });
  10155. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10156. auto cli = Client("127.0.0.1", PORT + 1);
  10157. auto headers = Headers{
  10158. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  10159. {"Connection", "keep-alive"}};
  10160. auto res = cli.Get("/hi", headers);
  10161. EXPECT_FALSE(res);
  10162. EXPECT_EQ(Error::InvalidHeaders, res.error());
  10163. server_thread.join();
  10164. }
  10165. TEST(PathParamsTest, StaticMatch) {
  10166. const auto pattern = "/users/all";
  10167. detail::PathParamsMatcher matcher(pattern);
  10168. Request request;
  10169. request.path = "/users/all";
  10170. ASSERT_TRUE(matcher.match(request));
  10171. std::unordered_map<std::string, std::string> expected_params = {};
  10172. EXPECT_EQ(request.path_params, expected_params);
  10173. }
  10174. TEST(PathParamsTest, StaticMismatch) {
  10175. const auto pattern = "/users/all";
  10176. detail::PathParamsMatcher matcher(pattern);
  10177. Request request;
  10178. request.path = "/users/1";
  10179. ASSERT_FALSE(matcher.match(request));
  10180. }
  10181. TEST(PathParamsTest, SingleParamInTheMiddle) {
  10182. const auto pattern = "/users/:id/subscriptions";
  10183. detail::PathParamsMatcher matcher(pattern);
  10184. Request request;
  10185. request.path = "/users/42/subscriptions";
  10186. ASSERT_TRUE(matcher.match(request));
  10187. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10188. EXPECT_EQ(request.path_params, expected_params);
  10189. }
  10190. TEST(PathParamsTest, SingleParamInTheEnd) {
  10191. const auto pattern = "/users/:id";
  10192. detail::PathParamsMatcher matcher(pattern);
  10193. Request request;
  10194. request.path = "/users/24";
  10195. ASSERT_TRUE(matcher.match(request));
  10196. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  10197. EXPECT_EQ(request.path_params, expected_params);
  10198. }
  10199. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  10200. const auto pattern = "/users/:id/";
  10201. detail::PathParamsMatcher matcher(pattern);
  10202. Request request;
  10203. request.path = "/users/42/";
  10204. ASSERT_TRUE(matcher.match(request));
  10205. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10206. EXPECT_EQ(request.path_params, expected_params);
  10207. }
  10208. TEST(PathParamsTest, EmptyParam) {
  10209. const auto pattern = "/users/:id/";
  10210. detail::PathParamsMatcher matcher(pattern);
  10211. Request request;
  10212. request.path = "/users//";
  10213. ASSERT_TRUE(matcher.match(request));
  10214. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10215. EXPECT_EQ(request.path_params, expected_params);
  10216. }
  10217. TEST(PathParamsTest, FragmentMismatch) {
  10218. const auto pattern = "/users/:id/";
  10219. detail::PathParamsMatcher matcher(pattern);
  10220. Request request;
  10221. request.path = "/admins/24/";
  10222. ASSERT_FALSE(matcher.match(request));
  10223. }
  10224. TEST(PathParamsTest, ExtraFragments) {
  10225. const auto pattern = "/users/:id";
  10226. detail::PathParamsMatcher matcher(pattern);
  10227. Request request;
  10228. request.path = "/users/42/subscriptions";
  10229. ASSERT_FALSE(matcher.match(request));
  10230. }
  10231. TEST(PathParamsTest, MissingTrailingParam) {
  10232. const auto pattern = "/users/:id";
  10233. detail::PathParamsMatcher matcher(pattern);
  10234. Request request;
  10235. request.path = "/users";
  10236. ASSERT_FALSE(matcher.match(request));
  10237. }
  10238. TEST(PathParamsTest, MissingParamInTheMiddle) {
  10239. const auto pattern = "/users/:id/subscriptions";
  10240. detail::PathParamsMatcher matcher(pattern);
  10241. Request request;
  10242. request.path = "/users/subscriptions";
  10243. ASSERT_FALSE(matcher.match(request));
  10244. }
  10245. TEST(PathParamsTest, MultipleParams) {
  10246. const auto pattern = "/users/:userid/subscriptions/:subid";
  10247. detail::PathParamsMatcher matcher(pattern);
  10248. Request request;
  10249. request.path = "/users/42/subscriptions/2";
  10250. ASSERT_TRUE(matcher.match(request));
  10251. std::unordered_map<std::string, std::string> expected_params = {
  10252. {"userid", "42"}, {"subid", "2"}};
  10253. EXPECT_EQ(request.path_params, expected_params);
  10254. }
  10255. TEST(PathParamsTest, SequenceOfParams) {
  10256. const auto pattern = "/values/:x/:y/:z";
  10257. detail::PathParamsMatcher matcher(pattern);
  10258. Request request;
  10259. request.path = "/values/1/2/3";
  10260. ASSERT_TRUE(matcher.match(request));
  10261. std::unordered_map<std::string, std::string> expected_params = {
  10262. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  10263. EXPECT_EQ(request.path_params, expected_params);
  10264. }
  10265. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  10266. const auto pattern = "/prefix:suffix";
  10267. detail::PathParamsMatcher matcher(pattern);
  10268. Request request;
  10269. request.path = "/prefix:suffix";
  10270. ASSERT_TRUE(matcher.match(request));
  10271. const std::unordered_map<std::string, std::string> expected_params = {};
  10272. EXPECT_EQ(request.path_params, expected_params);
  10273. }
  10274. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  10275. // If ipv6 regex working, regex match codepath is taken.
  10276. // else port will default to 80 in Client impl
  10277. int clientImplMagicPort = 80;
  10278. int port = 4321;
  10279. // above ports must be different to avoid false negative
  10280. EXPECT_NE(clientImplMagicPort, port);
  10281. std::string ipV6TestURL = "http://[ff06::c3]";
  10282. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  10283. CLIENT_PRIVATE_KEY_FILE);
  10284. EXPECT_EQ(cli.port(), port);
  10285. }
  10286. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  10287. auto file_path = "./www/dir/index.html";
  10288. auto dir_path = "./www/dir";
  10289. detail::FileStat stat_file(file_path);
  10290. EXPECT_TRUE(stat_file.is_file());
  10291. EXPECT_FALSE(stat_file.is_dir());
  10292. detail::FileStat stat_dir(dir_path);
  10293. EXPECT_FALSE(stat_dir.is_file());
  10294. EXPECT_TRUE(stat_dir.is_dir());
  10295. }
  10296. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  10297. // IPv4 with default HTTP port (80)
  10298. EXPECT_EQ("example.com",
  10299. detail::make_host_and_port_string("example.com", 80, false));
  10300. // IPv4 with default HTTPS port (443)
  10301. EXPECT_EQ("example.com",
  10302. detail::make_host_and_port_string("example.com", 443, true));
  10303. // IPv4 with non-default HTTP port
  10304. EXPECT_EQ("example.com:8080",
  10305. detail::make_host_and_port_string("example.com", 8080, false));
  10306. // IPv4 with non-default HTTPS port
  10307. EXPECT_EQ("example.com:8443",
  10308. detail::make_host_and_port_string("example.com", 8443, true));
  10309. // IPv6 with default HTTP port (80)
  10310. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  10311. // IPv6 with default HTTPS port (443)
  10312. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  10313. // IPv6 with non-default HTTP port
  10314. EXPECT_EQ("[::1]:8080",
  10315. detail::make_host_and_port_string("::1", 8080, false));
  10316. // IPv6 with non-default HTTPS port
  10317. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  10318. // IPv6 full address with default port
  10319. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  10320. detail::make_host_and_port_string(
  10321. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  10322. // IPv6 full address with non-default port
  10323. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  10324. detail::make_host_and_port_string(
  10325. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  10326. // IPv6 localhost with non-default port
  10327. EXPECT_EQ("[::1]:3000",
  10328. detail::make_host_and_port_string("::1", 3000, false));
  10329. // IPv6 with zone ID (link-local address) with default port
  10330. EXPECT_EQ("[fe80::1%eth0]",
  10331. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  10332. // IPv6 with zone ID (link-local address) with non-default port
  10333. EXPECT_EQ("[fe80::1%eth0]:8080",
  10334. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  10335. // Edge case: Port 443 with is_ssl=false (should add port)
  10336. EXPECT_EQ("example.com:443",
  10337. detail::make_host_and_port_string("example.com", 443, false));
  10338. // Edge case: Port 80 with is_ssl=true (should add port)
  10339. EXPECT_EQ("example.com:80",
  10340. detail::make_host_and_port_string("example.com", 80, true));
  10341. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  10342. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  10343. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  10344. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  10345. // Security fix: Already bracketed IPv6 should not get double brackets
  10346. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  10347. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  10348. EXPECT_EQ("[::1]:8080",
  10349. detail::make_host_and_port_string("[::1]", 8080, false));
  10350. EXPECT_EQ("[2001:db8::1]:8080",
  10351. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  10352. EXPECT_EQ("[fe80::1%eth0]",
  10353. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  10354. EXPECT_EQ("[fe80::1%eth0]:8080",
  10355. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  10356. // Edge case: Empty host (should return as-is)
  10357. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  10358. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  10359. // This is a known limitation but shouldn't crash
  10360. EXPECT_EQ("[host:name]",
  10361. detail::make_host_and_port_string("host:name", 80, false));
  10362. // Port number edge cases (no validation, but should not crash)
  10363. EXPECT_EQ("example.com:0",
  10364. detail::make_host_and_port_string("example.com", 0, false));
  10365. EXPECT_EQ("example.com:-1",
  10366. detail::make_host_and_port_string("example.com", -1, false));
  10367. EXPECT_EQ("example.com:65535",
  10368. detail::make_host_and_port_string("example.com", 65535, false));
  10369. EXPECT_EQ("example.com:65536",
  10370. detail::make_host_and_port_string("example.com", 65536, false));
  10371. }
  10372. #ifdef CPPHTTPLIB_SSL_ENABLED
  10373. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  10374. httplib::SSLClient cli("roblox.com", 443);
  10375. cli.set_follow_location(true);
  10376. auto res = cli.Get("/");
  10377. ASSERT_TRUE(res);
  10378. EXPECT_EQ(StatusCode::OK_200, res->status);
  10379. }
  10380. #endif
  10381. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  10382. Server svr;
  10383. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10384. EXPECT_EQ(res.status, 400);
  10385. });
  10386. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10387. auto se = detail::scope_exit([&] {
  10388. svr.stop();
  10389. thread.join();
  10390. ASSERT_FALSE(svr.is_running());
  10391. });
  10392. svr.wait_until_ready();
  10393. Client cli(HOST, PORT);
  10394. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  10395. }
  10396. TEST(InvalidHeaderCharsTest, is_field_name) {
  10397. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  10398. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  10399. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  10400. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  10401. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  10402. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  10403. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  10404. EXPECT_FALSE(detail::fields::is_field_name(""));
  10405. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  10406. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  10407. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  10408. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  10409. }
  10410. TEST(InvalidHeaderCharsTest, is_field_value) {
  10411. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  10412. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  10413. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  10414. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  10415. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  10416. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  10417. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  10418. EXPECT_TRUE(detail::fields::is_field_value(""));
  10419. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  10420. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  10421. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  10422. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  10423. EXPECT_TRUE(detail::fields::is_field_value("0"));
  10424. }
  10425. TEST(InvalidHeaderCharsTest, OnServer) {
  10426. Server svr;
  10427. svr.Get("/test_name", [&](const Request &req, Response &res) {
  10428. std::string header = "Not Set";
  10429. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10430. res.set_header(header, "value");
  10431. res.set_content("Page Content Page Content", "text/plain");
  10432. });
  10433. svr.Get("/test_value", [&](const Request &req, Response &res) {
  10434. std::string header = "Not Set";
  10435. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10436. res.set_header("X-Test", header);
  10437. res.set_content("Page Content Page Content", "text/plain");
  10438. });
  10439. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10440. auto se = detail::scope_exit([&] {
  10441. svr.stop();
  10442. thread.join();
  10443. ASSERT_FALSE(svr.is_running());
  10444. });
  10445. svr.wait_until_ready();
  10446. Client cli(HOST, PORT);
  10447. {
  10448. auto res = cli.Get(
  10449. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10450. ASSERT_TRUE(res);
  10451. EXPECT_EQ("Page Content Page Content", res->body);
  10452. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10453. }
  10454. {
  10455. auto res = cli.Get(
  10456. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10457. ASSERT_TRUE(res);
  10458. EXPECT_EQ("Page Content Page Content", res->body);
  10459. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10460. }
  10461. }
  10462. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  10463. auto handled = false;
  10464. Server svr;
  10465. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10466. thread t = thread([&] { svr.listen(HOST, PORT); });
  10467. auto se = detail::scope_exit([&] {
  10468. svr.stop();
  10469. t.join();
  10470. ASSERT_FALSE(svr.is_running());
  10471. ASSERT_FALSE(handled);
  10472. });
  10473. svr.wait_until_ready();
  10474. auto req = "POST /test HTTP/1.1\r\n"
  10475. "Content-Length: x\r\n"
  10476. "\r\n";
  10477. std::string response;
  10478. ASSERT_TRUE(send_request(1, req, &response));
  10479. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10480. response.substr(0, response.find("\r\n")));
  10481. }
  10482. #ifndef _WIN32
  10483. TEST(Expect100ContinueTest, ServerClosesConnection) {
  10484. static constexpr char reject[] = "Unauthorized";
  10485. static constexpr char accept[] = "Upload accepted";
  10486. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  10487. Server svr;
  10488. svr.set_expect_100_continue_handler(
  10489. [](const Request & /*req*/, Response &res) {
  10490. res.status = StatusCode::Unauthorized_401;
  10491. res.set_content(reject, "text/plain");
  10492. return res.status;
  10493. });
  10494. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  10495. res.set_content(accept, "text/plain");
  10496. });
  10497. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10498. auto se = detail::scope_exit([&] {
  10499. svr.stop();
  10500. thread.join();
  10501. ASSERT_FALSE(svr.is_running());
  10502. });
  10503. svr.wait_until_ready();
  10504. {
  10505. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  10506. curl_easy_init(), &curl_easy_cleanup};
  10507. ASSERT_NE(curl, nullptr);
  10508. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  10509. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  10510. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  10511. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  10512. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  10513. &curl_slist_free_all};
  10514. ASSERT_NE(list, nullptr);
  10515. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  10516. struct read_data {
  10517. size_t read_size;
  10518. size_t total_size;
  10519. } data = {0, total_size};
  10520. using read_callback_t =
  10521. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10522. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  10523. void *userdata) -> size_t {
  10524. read_data *data = (read_data *)userdata;
  10525. if (!userdata || data->read_size >= data->total_size) { return 0; }
  10526. std::fill_n(ptr, size * nmemb, 'A');
  10527. data->read_size += size * nmemb;
  10528. return size * nmemb;
  10529. };
  10530. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  10531. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  10532. std::vector<char> buffer;
  10533. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  10534. using write_callback_t =
  10535. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10536. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  10537. void *userdata) -> size_t {
  10538. std::vector<char> *buffer = (std::vector<char> *)userdata;
  10539. buffer->reserve(buffer->size() + size * nmemb + 1);
  10540. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  10541. return size * nmemb;
  10542. };
  10543. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  10544. {
  10545. const auto res = curl_easy_perform(curl.get());
  10546. ASSERT_EQ(res, CURLE_OK);
  10547. }
  10548. {
  10549. auto response_code = long{};
  10550. const auto res =
  10551. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  10552. ASSERT_EQ(res, CURLE_OK);
  10553. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  10554. }
  10555. {
  10556. auto dl = curl_off_t{};
  10557. const auto res =
  10558. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  10559. ASSERT_EQ(res, CURLE_OK);
  10560. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  10561. }
  10562. {
  10563. buffer.push_back('\0');
  10564. ASSERT_STRCASEEQ(buffer.data(), reject);
  10565. }
  10566. }
  10567. }
  10568. #endif
  10569. template <typename S, typename C>
  10570. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  10571. svr.Get("/stream", [&](const Request &, Response &res) {
  10572. auto data = new std::string("01234567890123456789");
  10573. res.set_content_provider(
  10574. data->size(), "text/plain",
  10575. [&, data](size_t offset, size_t length, DataSink &sink) {
  10576. const size_t DATA_CHUNK_SIZE = 4;
  10577. const auto &d = *data;
  10578. std::this_thread::sleep_for(std::chrono::seconds(1));
  10579. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  10580. return true;
  10581. },
  10582. [data](bool success) {
  10583. EXPECT_FALSE(success);
  10584. delete data;
  10585. });
  10586. });
  10587. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  10588. auto i = new size_t(0);
  10589. res.set_content_provider(
  10590. "text/plain",
  10591. [i](size_t, DataSink &sink) {
  10592. if (*i < 5) {
  10593. std::this_thread::sleep_for(std::chrono::seconds(1));
  10594. sink.write("abcd", 4);
  10595. (*i)++;
  10596. } else {
  10597. sink.done();
  10598. }
  10599. return true;
  10600. },
  10601. [i](bool success) {
  10602. EXPECT_FALSE(success);
  10603. delete i;
  10604. });
  10605. });
  10606. svr.Get("/chunked", [&](const Request &, Response &res) {
  10607. auto i = new size_t(0);
  10608. res.set_chunked_content_provider(
  10609. "text/plain",
  10610. [i](size_t, DataSink &sink) {
  10611. if (*i < 5) {
  10612. std::this_thread::sleep_for(std::chrono::seconds(1));
  10613. sink.os << "abcd";
  10614. (*i)++;
  10615. } else {
  10616. sink.done();
  10617. }
  10618. return true;
  10619. },
  10620. [i](bool success) {
  10621. EXPECT_FALSE(success);
  10622. delete i;
  10623. });
  10624. });
  10625. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10626. auto se = detail::scope_exit([&] {
  10627. svr.stop();
  10628. listen_thread.join();
  10629. ASSERT_FALSE(svr.is_running());
  10630. });
  10631. svr.wait_until_ready();
  10632. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  10633. {
  10634. auto start = std::chrono::steady_clock::now();
  10635. auto res = cli.Get("/stream");
  10636. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10637. std::chrono::steady_clock::now() - start)
  10638. .count();
  10639. ASSERT_FALSE(res);
  10640. EXPECT_EQ(Error::Read, res.error());
  10641. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10642. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10643. }
  10644. {
  10645. auto start = std::chrono::steady_clock::now();
  10646. auto res = cli.Get("/stream_without_length");
  10647. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10648. std::chrono::steady_clock::now() - start)
  10649. .count();
  10650. ASSERT_FALSE(res);
  10651. EXPECT_EQ(Error::Read, res.error());
  10652. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10653. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10654. }
  10655. {
  10656. auto start = std::chrono::steady_clock::now();
  10657. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  10658. EXPECT_EQ("abcd", string(data, data_length));
  10659. return true;
  10660. });
  10661. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10662. std::chrono::steady_clock::now() - start)
  10663. .count();
  10664. ASSERT_FALSE(res);
  10665. EXPECT_EQ(Error::Read, res.error());
  10666. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10667. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10668. }
  10669. }
  10670. TEST(MaxTimeoutTest, ContentStream) {
  10671. time_t timeout = 2000;
  10672. time_t threshold = 200;
  10673. Server svr;
  10674. Client cli("localhost", PORT);
  10675. max_timeout_test(svr, cli, timeout, threshold);
  10676. }
  10677. #ifdef CPPHTTPLIB_SSL_ENABLED
  10678. TEST(MaxTimeoutTest, ContentStreamSSL) {
  10679. time_t timeout = 2000;
  10680. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  10681. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10682. SSLClient cli("localhost", PORT);
  10683. cli.enable_server_certificate_verification(false);
  10684. max_timeout_test(svr, cli, timeout, threshold);
  10685. }
  10686. #endif
  10687. class EventDispatcher {
  10688. public:
  10689. EventDispatcher() {}
  10690. bool wait_event(DataSink *sink) {
  10691. unique_lock<mutex> lk(m_);
  10692. int id = id_;
  10693. // Wait with timeout to prevent hanging if client disconnects
  10694. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  10695. [&] { return cid_ == id; })) {
  10696. return false; // Timeout occurred
  10697. }
  10698. sink->write(message_.data(), message_.size());
  10699. return true;
  10700. }
  10701. void send_event(const string &message) {
  10702. lock_guard<mutex> lk(m_);
  10703. cid_ = id_++;
  10704. message_ = message;
  10705. cv_.notify_all();
  10706. }
  10707. private:
  10708. mutex m_;
  10709. condition_variable cv_;
  10710. atomic_int id_{0};
  10711. atomic_int cid_{-1};
  10712. string message_;
  10713. };
  10714. TEST(ClientInThreadTest, Issue2068) {
  10715. EventDispatcher ed;
  10716. Server svr;
  10717. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  10718. res.set_chunked_content_provider("text/event-stream",
  10719. [&](size_t /*offset*/, DataSink &sink) {
  10720. return ed.wait_event(&sink);
  10721. });
  10722. });
  10723. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10724. svr.wait_until_ready();
  10725. thread event_thread([&] {
  10726. int id = 0;
  10727. while (svr.is_running()) {
  10728. this_thread::sleep_for(chrono::milliseconds(500));
  10729. std::stringstream ss;
  10730. ss << "data: " << id << "\n\n";
  10731. ed.send_event(ss.str());
  10732. id++;
  10733. }
  10734. });
  10735. auto se = detail::scope_exit([&] {
  10736. svr.stop();
  10737. listen_thread.join();
  10738. event_thread.join();
  10739. ASSERT_FALSE(svr.is_running());
  10740. });
  10741. {
  10742. auto client = detail::make_unique<Client>(HOST, PORT);
  10743. client->set_read_timeout(std::chrono::minutes(10));
  10744. std::atomic<bool> stop{false};
  10745. std::thread t([&] {
  10746. client->Get("/event1",
  10747. [&](const char *, size_t) -> bool { return !stop; });
  10748. });
  10749. std::this_thread::sleep_for(std::chrono::seconds(2));
  10750. stop = true;
  10751. client->stop();
  10752. t.join();
  10753. // Reset client after thread has finished
  10754. client.reset();
  10755. }
  10756. }
  10757. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  10758. Server svr;
  10759. svr.Get("/", [](const Request &req, Response &res) {
  10760. EXPECT_EQ(2U, req.trailers.size());
  10761. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  10762. // Denied
  10763. EXPECT_FALSE(req.has_trailer("Content-Length"));
  10764. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  10765. // Accepted
  10766. EXPECT_TRUE(req.has_trailer("X-Hello"));
  10767. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  10768. EXPECT_TRUE(req.has_trailer("X-World"));
  10769. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  10770. res.set_content("ok", "text/plain");
  10771. });
  10772. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10773. auto se = detail::scope_exit([&] {
  10774. svr.stop();
  10775. t.join();
  10776. ASSERT_FALSE(svr.is_running());
  10777. });
  10778. svr.wait_until_ready();
  10779. const std::string req = "GET / HTTP/1.1\r\n"
  10780. "Transfer-Encoding: chunked\r\n"
  10781. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  10782. "\r\n"
  10783. "0\r\n"
  10784. "Content-Length: 10\r\n"
  10785. "Host: internal.local\r\n"
  10786. "Content-Type: malicious/content\r\n"
  10787. "Cookie: any\r\n"
  10788. "Set-Cookie: any\r\n"
  10789. "X-Forwarded-For: attacker.com\r\n"
  10790. "X-Real-Ip: 1.1.1.1\r\n"
  10791. "X-Hello: hello\r\n"
  10792. "X-World: world\r\n"
  10793. "\r\n";
  10794. std::string res;
  10795. ASSERT_TRUE(send_request(1, req, &res));
  10796. }
  10797. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  10798. Server svr;
  10799. std::string observed_remote_addr;
  10800. std::string observed_xff;
  10801. svr.Get("/ip", [&](const Request &req, Response &res) {
  10802. observed_remote_addr = req.remote_addr;
  10803. observed_xff = req.get_header_value("X-Forwarded-For");
  10804. res.set_content("ok", "text/plain");
  10805. });
  10806. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10807. auto se = detail::scope_exit([&] {
  10808. svr.stop();
  10809. t.join();
  10810. ASSERT_FALSE(svr.is_running());
  10811. });
  10812. svr.wait_until_ready();
  10813. Client cli(HOST, PORT);
  10814. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  10815. ASSERT_TRUE(res);
  10816. EXPECT_EQ(StatusCode::OK_200, res->status);
  10817. EXPECT_EQ(observed_xff, "203.0.113.66");
  10818. EXPECT_TRUE(observed_remote_addr == "::1" ||
  10819. observed_remote_addr == "127.0.0.1");
  10820. }
  10821. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  10822. Server svr;
  10823. svr.set_trusted_proxies({"203.0.113.66"});
  10824. std::string observed_remote_addr;
  10825. std::string observed_xff;
  10826. svr.Get("/ip", [&](const Request &req, Response &res) {
  10827. observed_remote_addr = req.remote_addr;
  10828. observed_xff = req.get_header_value("X-Forwarded-For");
  10829. res.set_content("ok", "text/plain");
  10830. });
  10831. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10832. auto se = detail::scope_exit([&] {
  10833. svr.stop();
  10834. t.join();
  10835. ASSERT_FALSE(svr.is_running());
  10836. });
  10837. svr.wait_until_ready();
  10838. Client cli(HOST, PORT);
  10839. auto res = cli.Get("/ip");
  10840. ASSERT_TRUE(res);
  10841. EXPECT_EQ(StatusCode::OK_200, res->status);
  10842. EXPECT_EQ(observed_xff, "");
  10843. EXPECT_TRUE(observed_remote_addr == "::1" ||
  10844. observed_remote_addr == "127.0.0.1");
  10845. }
  10846. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  10847. Server svr;
  10848. svr.set_trusted_proxies({"203.0.113.66"});
  10849. std::string observed_remote_addr;
  10850. std::string observed_xff;
  10851. svr.Get("/ip", [&](const Request &req, Response &res) {
  10852. observed_remote_addr = req.remote_addr;
  10853. observed_xff = req.get_header_value("X-Forwarded-For");
  10854. res.set_content("ok", "text/plain");
  10855. });
  10856. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10857. auto se = detail::scope_exit([&] {
  10858. svr.stop();
  10859. t.join();
  10860. ASSERT_FALSE(svr.is_running());
  10861. });
  10862. svr.wait_until_ready();
  10863. Client cli(HOST, PORT);
  10864. auto res =
  10865. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  10866. ASSERT_TRUE(res);
  10867. EXPECT_EQ(StatusCode::OK_200, res->status);
  10868. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  10869. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10870. }
  10871. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  10872. Server svr;
  10873. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  10874. std::string observed_remote_addr;
  10875. std::string observed_xff;
  10876. svr.Get("/ip", [&](const Request &req, Response &res) {
  10877. observed_remote_addr = req.remote_addr;
  10878. observed_xff = req.get_header_value("X-Forwarded-For");
  10879. res.set_content("ok", "text/plain");
  10880. });
  10881. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10882. auto se = detail::scope_exit([&] {
  10883. svr.stop();
  10884. t.join();
  10885. ASSERT_FALSE(svr.is_running());
  10886. });
  10887. svr.wait_until_ready();
  10888. Client cli(HOST, PORT);
  10889. auto res = cli.Get(
  10890. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  10891. ASSERT_TRUE(res);
  10892. EXPECT_EQ(StatusCode::OK_200, res->status);
  10893. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  10894. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10895. }
  10896. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  10897. Server svr;
  10898. svr.set_trusted_proxies({"192.0.2.45"});
  10899. std::string observed_remote_addr;
  10900. std::string observed_xff;
  10901. svr.Get("/ip", [&](const Request &req, Response &res) {
  10902. observed_remote_addr = req.remote_addr;
  10903. observed_xff = req.get_header_value("X-Forwarded-For");
  10904. res.set_content("ok", "text/plain");
  10905. });
  10906. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10907. auto se = detail::scope_exit([&] {
  10908. svr.stop();
  10909. t.join();
  10910. ASSERT_FALSE(svr.is_running());
  10911. });
  10912. svr.wait_until_ready();
  10913. Client cli(HOST, PORT);
  10914. auto res =
  10915. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  10916. ASSERT_TRUE(res);
  10917. EXPECT_EQ(StatusCode::OK_200, res->status);
  10918. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  10919. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10920. }
  10921. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  10922. Server svr;
  10923. svr.set_trusted_proxies({"192.0.2.45"});
  10924. std::string observed_remote_addr;
  10925. std::string observed_xff;
  10926. svr.Get("/ip", [&](const Request &req, Response &res) {
  10927. observed_remote_addr = req.remote_addr;
  10928. observed_xff = req.get_header_value("X-Forwarded-For");
  10929. res.set_content("ok", "text/plain");
  10930. });
  10931. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10932. auto se = detail::scope_exit([&] {
  10933. svr.stop();
  10934. t.join();
  10935. ASSERT_FALSE(svr.is_running());
  10936. });
  10937. svr.wait_until_ready();
  10938. Client cli(HOST, PORT);
  10939. auto res = cli.Get(
  10940. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  10941. ASSERT_TRUE(res);
  10942. EXPECT_EQ(StatusCode::OK_200, res->status);
  10943. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  10944. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  10945. }
  10946. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  10947. Server svr;
  10948. svr.set_trusted_proxies({"192.0.2.45"});
  10949. std::string observed_remote_addr;
  10950. std::string observed_xff;
  10951. svr.Get("/ip", [&](const Request &req, Response &res) {
  10952. observed_remote_addr = req.remote_addr;
  10953. observed_xff = req.get_header_value("X-Forwarded-For");
  10954. res.set_content("ok", "text/plain");
  10955. });
  10956. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10957. auto se = detail::scope_exit([&] {
  10958. svr.stop();
  10959. t.join();
  10960. ASSERT_FALSE(svr.is_running());
  10961. });
  10962. svr.wait_until_ready();
  10963. std::string raw_req =
  10964. "GET /ip HTTP/1.1\r\n"
  10965. "Host: localhost\r\n"
  10966. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  10967. "Connection: close\r\n"
  10968. "\r\n";
  10969. std::string out;
  10970. ASSERT_TRUE(send_request(5, raw_req, &out));
  10971. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10972. // Header parser trims surrounding whitespace of the header value
  10973. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  10974. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  10975. }
  10976. #ifndef _WIN32
  10977. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  10978. Server svr;
  10979. svr.Post("/post", [&](const Request &req, Response &res) {
  10980. res.set_content(req.body, "text/plain");
  10981. });
  10982. svr.Put("/put", [&](const Request &req, Response &res) {
  10983. res.set_content(req.body, "text/plain");
  10984. });
  10985. svr.Patch("/patch", [&](const Request &req, Response &res) {
  10986. res.set_content(req.body, "text/plain");
  10987. });
  10988. svr.Delete("/delete", [&](const Request &req, Response &res) {
  10989. res.set_content(req.body, "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. });
  10997. svr.wait_until_ready();
  10998. std::string resp;
  10999. // POST without Content-Length
  11000. ASSERT_TRUE(send_request(5,
  11001. "POST /post HTTP/1.1\r\n"
  11002. "Host: localhost\r\n"
  11003. "Connection: close\r\n"
  11004. "\r\n",
  11005. &resp));
  11006. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11007. // PUT without Content-Length
  11008. resp.clear();
  11009. ASSERT_TRUE(send_request(5,
  11010. "PUT /put HTTP/1.1\r\n"
  11011. "Host: localhost\r\n"
  11012. "Connection: close\r\n"
  11013. "\r\n",
  11014. &resp));
  11015. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11016. // PATCH without Content-Length
  11017. resp.clear();
  11018. ASSERT_TRUE(send_request(5,
  11019. "PATCH /patch HTTP/1.1\r\n"
  11020. "Host: localhost\r\n"
  11021. "Connection: close\r\n"
  11022. "\r\n",
  11023. &resp));
  11024. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11025. // DELETE without Content-Length
  11026. resp.clear();
  11027. ASSERT_TRUE(send_request(5,
  11028. "DELETE /delete HTTP/1.1\r\n"
  11029. "Host: localhost\r\n"
  11030. "Connection: close\r\n"
  11031. "\r\n",
  11032. &resp));
  11033. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11034. }
  11035. #endif
  11036. //==============================================================================
  11037. // open_stream() Tests
  11038. //==============================================================================
  11039. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  11040. std::string result;
  11041. char buf[8192];
  11042. ssize_t n;
  11043. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11044. result.append(buf, static_cast<size_t>(n));
  11045. }
  11046. return result;
  11047. }
  11048. // Mock stream for unit tests
  11049. class MockStream : public Stream {
  11050. public:
  11051. std::string data;
  11052. size_t pos = 0;
  11053. ssize_t error_after = -1; // -1 = no error
  11054. explicit MockStream(const std::string &d, ssize_t err = -1)
  11055. : data(d), error_after(err) {}
  11056. bool is_readable() const override { return true; }
  11057. bool wait_readable() const override { return true; }
  11058. bool wait_writable() const override { return true; }
  11059. ssize_t read(char *ptr, size_t size) override {
  11060. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  11061. if (pos >= data.size()) return 0;
  11062. size_t limit =
  11063. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  11064. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  11065. std::memcpy(ptr, data.data() + pos, to_read);
  11066. pos += to_read;
  11067. return static_cast<ssize_t>(to_read);
  11068. }
  11069. ssize_t write(const char *, size_t) override { return -1; }
  11070. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  11071. ip = "127.0.0.1";
  11072. port = 0;
  11073. }
  11074. void get_local_ip_and_port(std::string &ip, int &port) const override {
  11075. ip = "127.0.0.1";
  11076. port = 0;
  11077. }
  11078. socket_t socket() const override { return INVALID_SOCKET; }
  11079. time_t duration() const override { return 0; }
  11080. };
  11081. TEST(StreamHandleTest, Basic) {
  11082. ClientImpl::StreamHandle handle;
  11083. EXPECT_FALSE(handle.is_valid());
  11084. handle.response = detail::make_unique<Response>();
  11085. handle.error = Error::Connection;
  11086. EXPECT_FALSE(handle.is_valid());
  11087. handle.error = Error::Success;
  11088. EXPECT_TRUE(handle.is_valid());
  11089. }
  11090. TEST(BodyReaderTest, Basic) {
  11091. MockStream stream("Hello, World!");
  11092. detail::BodyReader reader;
  11093. reader.stream = &stream;
  11094. reader.content_length = 13;
  11095. char buf[32];
  11096. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  11097. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  11098. EXPECT_TRUE(reader.eof);
  11099. }
  11100. TEST(BodyReaderTest, NoStream) {
  11101. detail::BodyReader reader;
  11102. char buf[32];
  11103. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11104. EXPECT_EQ(Error::Connection, reader.last_error);
  11105. }
  11106. TEST(BodyReaderTest, Error) {
  11107. MockStream stream("Hello, World!", 5);
  11108. detail::BodyReader reader;
  11109. reader.stream = &stream;
  11110. reader.content_length = 13;
  11111. char buf[32];
  11112. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  11113. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11114. EXPECT_EQ(Error::Read, reader.last_error);
  11115. }
  11116. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  11117. // Mock-based StreamHandle tests relying on private internals are removed.
  11118. class OpenStreamTest : public ::testing::Test {
  11119. protected:
  11120. void SetUp() override {
  11121. svr_.Get("/hello", [](const Request &, Response &res) {
  11122. res.set_content("Hello World!", "text/plain");
  11123. });
  11124. svr_.Get("/large", [](const Request &, Response &res) {
  11125. res.set_content(std::string(10000, 'X'), "text/plain");
  11126. });
  11127. svr_.Get("/chunked", [](const Request &, Response &res) {
  11128. res.set_chunked_content_provider("text/plain",
  11129. [](size_t offset, DataSink &sink) {
  11130. if (offset < 15) {
  11131. sink.write("chunk", 5);
  11132. return true;
  11133. }
  11134. sink.done();
  11135. return true;
  11136. });
  11137. });
  11138. svr_.Get("/compressible", [](const Request &, Response &res) {
  11139. res.set_chunked_content_provider("text/plain", [](size_t offset,
  11140. DataSink &sink) {
  11141. if (offset < 100 * 1024) {
  11142. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  11143. sink.write(chunk.data(), chunk.size());
  11144. return true;
  11145. }
  11146. sink.done();
  11147. return true;
  11148. });
  11149. });
  11150. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  11151. [](const Request & /*req*/, Response &res) {
  11152. auto i = new int(0);
  11153. res.set_header("Trailer", "Content-Length, X-Allowed");
  11154. res.set_chunked_content_provider(
  11155. "text/plain",
  11156. [i](size_t /*offset*/, DataSink &sink) {
  11157. switch (*i) {
  11158. case 0: sink.os << "123"; break;
  11159. case 1: sink.os << "456"; break;
  11160. case 2: sink.os << "789"; break;
  11161. case 3: {
  11162. sink.done_with_trailer(
  11163. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  11164. } break;
  11165. }
  11166. (*i)++;
  11167. return true;
  11168. },
  11169. [i](bool success) {
  11170. EXPECT_TRUE(success);
  11171. delete i;
  11172. });
  11173. });
  11174. // Echo headers endpoint for header-related tests
  11175. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  11176. std::string body;
  11177. for (const auto &h : req.headers) {
  11178. body.append(h.first);
  11179. body.push_back(':');
  11180. body.append(h.second);
  11181. body.push_back('\n');
  11182. }
  11183. res.set_content(body, "text/plain");
  11184. });
  11185. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  11186. std::string body;
  11187. for (const auto &h : req.headers) {
  11188. body.append(h.first);
  11189. body.push_back(':');
  11190. body.append(h.second);
  11191. body.push_back('\n');
  11192. }
  11193. res.set_content(body, "text/plain");
  11194. });
  11195. port_ = svr_.bind_to_any_port("127.0.0.1");
  11196. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11197. svr_.wait_until_ready();
  11198. }
  11199. void TearDown() override {
  11200. svr_.stop();
  11201. if (thread_.joinable()) thread_.join();
  11202. }
  11203. Server svr_;
  11204. std::thread thread_;
  11205. int port_ = 0;
  11206. };
  11207. TEST_F(OpenStreamTest, Basic) {
  11208. Client cli("127.0.0.1", port_);
  11209. auto handle = cli.open_stream("GET", "/hello");
  11210. EXPECT_TRUE(handle.is_valid());
  11211. EXPECT_EQ("Hello World!", read_all(handle));
  11212. }
  11213. TEST_F(OpenStreamTest, SmallBuffer) {
  11214. Client cli("127.0.0.1", port_);
  11215. auto handle = cli.open_stream("GET", "/hello");
  11216. std::string result;
  11217. char buf[4];
  11218. ssize_t n;
  11219. while ((n = handle.read(buf, sizeof(buf))) > 0)
  11220. result.append(buf, static_cast<size_t>(n));
  11221. EXPECT_EQ("Hello World!", result);
  11222. }
  11223. TEST_F(OpenStreamTest, DefaultHeaders) {
  11224. Client cli("127.0.0.1", port_);
  11225. // open_stream GET should include Host, User-Agent and Accept-Encoding
  11226. {
  11227. auto handle = cli.open_stream("GET", "/echo-headers");
  11228. ASSERT_TRUE(handle.is_valid());
  11229. auto body = read_all(handle);
  11230. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  11231. std::string::npos);
  11232. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  11233. std::string::npos);
  11234. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  11235. }
  11236. // open_stream POST with body and no explicit content_type should NOT add
  11237. // text/plain Content-Type (behavior differs from non-streaming path), but
  11238. // should include Content-Length
  11239. {
  11240. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  11241. ASSERT_TRUE(handle.is_valid());
  11242. auto body = read_all(handle);
  11243. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  11244. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  11245. }
  11246. // open_stream POST with explicit Content-Type should preserve it
  11247. {
  11248. auto handle = cli.open_stream("POST", "/echo-headers", {},
  11249. {{"Content-Type", "application/custom"}},
  11250. "{}", "application/custom");
  11251. ASSERT_TRUE(handle.is_valid());
  11252. auto body = read_all(handle);
  11253. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  11254. }
  11255. // User-specified User-Agent must not be overwritten for stream API
  11256. {
  11257. auto handle = cli.open_stream("GET", "/echo-headers", {},
  11258. {{"User-Agent", "MyAgent/1.2"}});
  11259. ASSERT_TRUE(handle.is_valid());
  11260. auto body = read_all(handle);
  11261. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  11262. }
  11263. }
  11264. TEST_F(OpenStreamTest, Large) {
  11265. Client cli("127.0.0.1", port_);
  11266. auto handle = cli.open_stream("GET", "/large");
  11267. EXPECT_EQ(10000u, read_all(handle).size());
  11268. }
  11269. TEST_F(OpenStreamTest, ConnectionError) {
  11270. Client cli("127.0.0.1", 9999);
  11271. auto handle = cli.open_stream("GET", "/hello");
  11272. EXPECT_FALSE(handle.is_valid());
  11273. }
  11274. TEST_F(OpenStreamTest, Chunked) {
  11275. Client cli("127.0.0.1", port_);
  11276. auto handle = cli.open_stream("GET", "/chunked");
  11277. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11278. "Transfer-Encoding") == "chunked");
  11279. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  11280. }
  11281. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  11282. Client cli("127.0.0.1", port_);
  11283. auto handle =
  11284. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  11285. ASSERT_TRUE(handle.is_valid());
  11286. // Consume body to allow trailers to be received/parsed
  11287. auto body = read_all(handle);
  11288. // Explicitly parse trailers (ensure trailers are available for assertion)
  11289. handle.parse_trailers_if_needed();
  11290. EXPECT_EQ(std::string("123456789"), body);
  11291. // The response should include a Trailer header declaring both names
  11292. ASSERT_TRUE(handle.response);
  11293. EXPECT_TRUE(handle.response->has_header("Trailer"));
  11294. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  11295. handle.response->get_header_value("Trailer"));
  11296. // Prohibited trailer must not be present
  11297. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  11298. // Allowed trailer should be present
  11299. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  11300. EXPECT_EQ(std::string("yes"),
  11301. handle.response->get_trailer_value("X-Allowed"));
  11302. // Verify trailers are NOT present as regular headers
  11303. EXPECT_EQ(std::string(""),
  11304. handle.response->get_header_value("Content-Length"));
  11305. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  11306. }
  11307. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11308. TEST_F(OpenStreamTest, Gzip) {
  11309. Client cli("127.0.0.1", port_);
  11310. auto handle = cli.open_stream("GET", "/compressible", {},
  11311. {{"Accept-Encoding", "gzip"}});
  11312. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  11313. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11314. }
  11315. #endif
  11316. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11317. TEST_F(OpenStreamTest, Brotli) {
  11318. Client cli("127.0.0.1", port_);
  11319. auto handle =
  11320. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  11321. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  11322. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11323. }
  11324. #endif
  11325. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11326. TEST_F(OpenStreamTest, Zstd) {
  11327. Client cli("127.0.0.1", port_);
  11328. auto handle = cli.open_stream("GET", "/compressible", {},
  11329. {{"Accept-Encoding", "zstd"}});
  11330. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  11331. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11332. }
  11333. #endif
  11334. #ifdef CPPHTTPLIB_SSL_ENABLED
  11335. class SSLOpenStreamTest : public ::testing::Test {
  11336. protected:
  11337. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  11338. void SetUp() override {
  11339. svr_.Get("/hello", [](const Request &, Response &res) {
  11340. res.set_content("Hello SSL World!", "text/plain");
  11341. });
  11342. svr_.Get("/chunked", [](const Request &, Response &res) {
  11343. res.set_chunked_content_provider("text/plain",
  11344. [](size_t offset, DataSink &sink) {
  11345. if (offset < 15) {
  11346. sink.write("chunk", 5);
  11347. return true;
  11348. }
  11349. sink.done();
  11350. return true;
  11351. });
  11352. });
  11353. svr_.Post("/echo", [](const Request &req, Response &res) {
  11354. res.set_content(req.body, req.get_header_value("Content-Type"));
  11355. });
  11356. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  11357. std::string body = req.body;
  11358. res.set_chunked_content_provider(
  11359. "text/plain", [body](size_t offset, DataSink &sink) {
  11360. if (offset < body.size()) {
  11361. sink.write(body.data() + offset, body.size() - offset);
  11362. }
  11363. sink.done();
  11364. return true;
  11365. });
  11366. });
  11367. port_ = svr_.bind_to_any_port("127.0.0.1");
  11368. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11369. svr_.wait_until_ready();
  11370. }
  11371. void TearDown() override {
  11372. svr_.stop();
  11373. if (thread_.joinable()) thread_.join();
  11374. }
  11375. SSLServer svr_;
  11376. std::thread thread_;
  11377. int port_ = 0;
  11378. };
  11379. TEST_F(SSLOpenStreamTest, Basic) {
  11380. SSLClient cli("127.0.0.1", port_);
  11381. cli.enable_server_certificate_verification(false);
  11382. auto handle = cli.open_stream("GET", "/hello");
  11383. ASSERT_TRUE(handle.is_valid());
  11384. EXPECT_EQ("Hello SSL World!", read_all(handle));
  11385. }
  11386. TEST_F(SSLOpenStreamTest, Chunked) {
  11387. SSLClient cli("127.0.0.1", port_);
  11388. cli.enable_server_certificate_verification(false);
  11389. auto handle = cli.open_stream("GET", "/chunked");
  11390. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11391. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11392. "Transfer-Encoding") == "chunked");
  11393. auto body = read_all(handle);
  11394. EXPECT_EQ("chunkchunkchunk", body);
  11395. }
  11396. TEST_F(SSLOpenStreamTest, Post) {
  11397. SSLClient cli("127.0.0.1", port_);
  11398. cli.enable_server_certificate_verification(false);
  11399. auto handle =
  11400. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  11401. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11402. EXPECT_EQ(200, handle.response->status);
  11403. auto body = read_all(handle);
  11404. EXPECT_EQ("Hello SSL POST", body);
  11405. }
  11406. TEST_F(SSLOpenStreamTest, PostChunked) {
  11407. SSLClient cli("127.0.0.1", port_);
  11408. cli.enable_server_certificate_verification(false);
  11409. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  11410. "Chunked SSL Data", "text/plain");
  11411. ASSERT_TRUE(handle.is_valid());
  11412. EXPECT_EQ(200, handle.response->status);
  11413. auto body = read_all(handle);
  11414. EXPECT_EQ("Chunked SSL Data", body);
  11415. }
  11416. #endif // CPPHTTPLIB_SSL_ENABLED
  11417. //==============================================================================
  11418. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  11419. // results for various scenarios.
  11420. //==============================================================================
  11421. TEST(ParityTest, GetVsOpenStream) {
  11422. Server svr;
  11423. const std::string path = "/parity";
  11424. const std::string content = "Parity test content: hello world";
  11425. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11426. res.set_content(content, "text/plain");
  11427. });
  11428. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11429. auto se = detail::scope_exit([&] {
  11430. svr.stop();
  11431. t.join();
  11432. ASSERT_FALSE(svr.is_running());
  11433. });
  11434. svr.wait_until_ready();
  11435. Client cli(HOST, PORT);
  11436. // Non-stream path
  11437. auto r1 = cli.Get(path);
  11438. ASSERT_TRUE(r1);
  11439. EXPECT_EQ(StatusCode::OK_200, r1->status);
  11440. // Stream path
  11441. auto h = cli.open_stream("GET", path);
  11442. ASSERT_TRUE(h.is_valid());
  11443. EXPECT_EQ(r1->body, read_all(h));
  11444. }
  11445. // Helper to compress data with provided compressor type T
  11446. template <typename Compressor>
  11447. static std::string compress_payload_for_parity(const std::string &in) {
  11448. std::string out;
  11449. Compressor compressor;
  11450. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  11451. [&](const char *data, size_t n) {
  11452. out.append(data, n);
  11453. return true;
  11454. });
  11455. EXPECT_TRUE(ok);
  11456. return out;
  11457. }
  11458. // Helper function for compression parity tests
  11459. template <typename Compressor>
  11460. static void test_compression_parity(const std::string &original,
  11461. const std::string &path,
  11462. const std::string &encoding) {
  11463. const std::string compressed =
  11464. compress_payload_for_parity<Compressor>(original);
  11465. Server svr;
  11466. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11467. res.set_content(compressed, "application/octet-stream");
  11468. res.set_header("Content-Encoding", encoding);
  11469. });
  11470. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  11471. auto se = detail::scope_exit([&] {
  11472. svr.stop();
  11473. t.join();
  11474. ASSERT_FALSE(svr.is_running());
  11475. });
  11476. svr.wait_until_ready();
  11477. Client cli(HOST, PORT);
  11478. // Non-streaming
  11479. {
  11480. auto res = cli.Get(path);
  11481. ASSERT_TRUE(res);
  11482. EXPECT_EQ(StatusCode::OK_200, res->status);
  11483. EXPECT_EQ(original, res->body);
  11484. }
  11485. // Streaming
  11486. {
  11487. auto h = cli.open_stream("GET", path);
  11488. ASSERT_TRUE(h.is_valid());
  11489. EXPECT_EQ(original, read_all(h));
  11490. }
  11491. }
  11492. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11493. TEST(ParityTest, Gzip) {
  11494. test_compression_parity<detail::gzip_compressor>(
  11495. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  11496. }
  11497. #endif
  11498. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11499. TEST(ParityTest, Brotli) {
  11500. test_compression_parity<detail::brotli_compressor>(
  11501. "Hello, brotli parity test payload", "/parity-br", "br");
  11502. }
  11503. #endif
  11504. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11505. TEST(ParityTest, Zstd) {
  11506. test_compression_parity<detail::zstd_compressor>(
  11507. "Zstandard parity test payload", "/parity-zstd", "zstd");
  11508. }
  11509. #endif
  11510. //==============================================================================
  11511. // New Stream API Tests
  11512. //==============================================================================
  11513. inline std::string read_body(httplib::stream::Result &result) {
  11514. std::string body;
  11515. while (result.next()) {
  11516. body.append(result.data(), result.size());
  11517. }
  11518. return body;
  11519. }
  11520. TEST(ClientConnectionTest, Basic) {
  11521. httplib::ClientConnection conn;
  11522. EXPECT_FALSE(conn.is_open());
  11523. conn.sock = 1;
  11524. EXPECT_TRUE(conn.is_open());
  11525. httplib::ClientConnection conn2(std::move(conn));
  11526. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  11527. conn2.sock = INVALID_SOCKET;
  11528. }
  11529. // Unified test server for all stream::* tests
  11530. class StreamApiTest : public ::testing::Test {
  11531. protected:
  11532. void SetUp() override {
  11533. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11534. res.set_content("Hello World!", "text/plain");
  11535. });
  11536. svr_.Get("/echo-params",
  11537. [](const httplib::Request &req, httplib::Response &res) {
  11538. std::string r;
  11539. for (const auto &p : req.params) {
  11540. if (!r.empty()) r += "&";
  11541. r += p.first + "=" + p.second;
  11542. }
  11543. res.set_content(r, "text/plain");
  11544. });
  11545. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11546. res.set_content(req.body, req.get_header_value("Content-Type"));
  11547. });
  11548. svr_.Post("/echo-headers",
  11549. [](const httplib::Request &req, httplib::Response &res) {
  11550. std::string r;
  11551. for (const auto &h : req.headers)
  11552. r += h.first + ": " + h.second + "\n";
  11553. res.set_content(r, "text/plain");
  11554. });
  11555. svr_.Post("/echo-params",
  11556. [](const httplib::Request &req, httplib::Response &res) {
  11557. std::string r = "params:";
  11558. for (const auto &p : req.params)
  11559. r += p.first + "=" + p.second + ";";
  11560. res.set_content(r + " body:" + req.body, "text/plain");
  11561. });
  11562. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  11563. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  11564. });
  11565. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11566. res.set_content("PUT:" + req.body, "text/plain");
  11567. });
  11568. svr_.Patch("/echo",
  11569. [](const httplib::Request &req, httplib::Response &res) {
  11570. res.set_content("PATCH:" + req.body, "text/plain");
  11571. });
  11572. svr_.Delete(
  11573. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  11574. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  11575. "text/plain");
  11576. });
  11577. svr_.Get("/head-test",
  11578. [](const httplib::Request &, httplib::Response &res) {
  11579. res.set_content("body for HEAD", "text/plain");
  11580. });
  11581. svr_.Options("/options",
  11582. [](const httplib::Request &, httplib::Response &res) {
  11583. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  11584. });
  11585. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  11586. svr_.wait_until_ready();
  11587. }
  11588. void TearDown() override {
  11589. svr_.stop();
  11590. if (thread_.joinable()) thread_.join();
  11591. }
  11592. httplib::Server svr_;
  11593. std::thread thread_;
  11594. };
  11595. // stream::Get tests
  11596. TEST_F(StreamApiTest, GetBasic) {
  11597. httplib::Client cli(HOST, PORT);
  11598. auto result = httplib::stream::Get(cli, "/hello");
  11599. ASSERT_TRUE(result.is_valid());
  11600. EXPECT_EQ(200, result.status());
  11601. EXPECT_EQ("Hello World!", read_body(result));
  11602. }
  11603. TEST_F(StreamApiTest, GetWithParams) {
  11604. httplib::Client cli(HOST, PORT);
  11605. httplib::Params params{{"foo", "bar"}};
  11606. auto result = httplib::stream::Get(cli, "/echo-params", params);
  11607. ASSERT_TRUE(result.is_valid());
  11608. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  11609. }
  11610. TEST_F(StreamApiTest, GetConnectionError) {
  11611. httplib::Client cli(HOST, 9999);
  11612. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  11613. }
  11614. TEST_F(StreamApiTest, Get404) {
  11615. httplib::Client cli(HOST, PORT);
  11616. auto result = httplib::stream::Get(cli, "/nonexistent");
  11617. EXPECT_TRUE(result.is_valid());
  11618. EXPECT_EQ(404, result.status());
  11619. }
  11620. // stream::Post tests
  11621. TEST_F(StreamApiTest, PostBasic) {
  11622. httplib::Client cli(HOST, PORT);
  11623. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  11624. "application/json");
  11625. ASSERT_TRUE(result.is_valid());
  11626. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  11627. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  11628. }
  11629. TEST_F(StreamApiTest, PostWithHeaders) {
  11630. httplib::Client cli(HOST, PORT);
  11631. httplib::Headers headers{{"X-Custom", "value"}};
  11632. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  11633. "text/plain");
  11634. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  11635. }
  11636. TEST_F(StreamApiTest, PostWithParams) {
  11637. httplib::Client cli(HOST, PORT);
  11638. httplib::Params params{{"k", "v"}};
  11639. auto result =
  11640. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  11641. auto body = read_body(result);
  11642. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  11643. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  11644. }
  11645. TEST_F(StreamApiTest, PostLarge) {
  11646. httplib::Client cli(HOST, PORT);
  11647. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  11648. size_t total = 0;
  11649. while (result.next()) {
  11650. total += result.size();
  11651. }
  11652. EXPECT_EQ(100u * 1024u, total);
  11653. }
  11654. // stream::Put/Patch tests
  11655. TEST_F(StreamApiTest, PutAndPatch) {
  11656. httplib::Client cli(HOST, PORT);
  11657. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  11658. EXPECT_EQ("PUT:test", read_body(put));
  11659. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  11660. EXPECT_EQ("PATCH:test", read_body(patch));
  11661. }
  11662. // stream::Delete tests
  11663. TEST_F(StreamApiTest, Delete) {
  11664. httplib::Client cli(HOST, PORT);
  11665. auto del1 = httplib::stream::Delete(cli, "/resource");
  11666. EXPECT_EQ("Deleted", read_body(del1));
  11667. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  11668. EXPECT_EQ("Deleted:data", read_body(del2));
  11669. }
  11670. // stream::Head/Options tests
  11671. TEST_F(StreamApiTest, HeadAndOptions) {
  11672. httplib::Client cli(HOST, PORT);
  11673. auto head = httplib::stream::Head(cli, "/head-test");
  11674. EXPECT_TRUE(head.is_valid());
  11675. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  11676. auto opts = httplib::stream::Options(cli, "/options");
  11677. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  11678. }
  11679. // SSL stream::* tests
  11680. #ifdef CPPHTTPLIB_SSL_ENABLED
  11681. class SSLStreamApiTest : public ::testing::Test {
  11682. protected:
  11683. void SetUp() override {
  11684. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11685. res.set_content("Hello SSL!", "text/plain");
  11686. });
  11687. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11688. res.set_content(req.body, "text/plain");
  11689. });
  11690. port_ = svr_.bind_to_any_port("127.0.0.1");
  11691. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11692. svr_.wait_until_ready();
  11693. }
  11694. void TearDown() override {
  11695. svr_.stop();
  11696. if (thread_.joinable()) thread_.join();
  11697. }
  11698. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  11699. std::thread thread_;
  11700. int port_ = 0;
  11701. };
  11702. TEST_F(SSLStreamApiTest, GetAndPost) {
  11703. httplib::SSLClient cli("127.0.0.1", port_);
  11704. cli.enable_server_certificate_verification(false);
  11705. auto get = httplib::stream::Get(cli, "/hello");
  11706. EXPECT_EQ("Hello SSL!", read_body(get));
  11707. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  11708. EXPECT_EQ("test", read_body(post));
  11709. }
  11710. #endif
  11711. // Tests for Error::Timeout and Error::ConnectionClosed error types
  11712. // These errors are set in SocketStream/SSLSocketStream and propagated through
  11713. // BodyReader
  11714. TEST(ErrorHandlingTest, StreamReadTimeout) {
  11715. // Test that read timeout during streaming is detected
  11716. // Use a large content-length response where server delays mid-stream
  11717. Server svr;
  11718. svr.Get("/slow-stream", [](const Request &, Response &res) {
  11719. // Send a large response with delay in the middle
  11720. res.set_content_provider(
  11721. 1000, // content_length
  11722. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  11723. if (offset < 100) {
  11724. // Send first 100 bytes immediately
  11725. std::string data(100, 'A');
  11726. sink.write(data.c_str(), data.size());
  11727. return true;
  11728. }
  11729. // Then delay longer than client timeout
  11730. std::this_thread::sleep_for(std::chrono::seconds(3));
  11731. std::string data(900, 'B');
  11732. sink.write(data.c_str(), data.size());
  11733. return true;
  11734. });
  11735. });
  11736. auto port = 8091;
  11737. std::thread t([&]() { svr.listen("localhost", port); });
  11738. svr.wait_until_ready();
  11739. Client cli("localhost", port);
  11740. cli.set_read_timeout(1, 0); // 1 second timeout
  11741. auto handle = cli.open_stream("GET", "/slow-stream");
  11742. ASSERT_TRUE(handle.is_valid());
  11743. char buf[256];
  11744. ssize_t total = 0;
  11745. ssize_t n;
  11746. bool got_error = false;
  11747. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11748. total += n;
  11749. }
  11750. if (n < 0) {
  11751. got_error = true;
  11752. // Should be timeout or read error
  11753. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  11754. handle.get_read_error() == Error::Read)
  11755. << "Actual error: " << to_string(handle.get_read_error());
  11756. }
  11757. // Either we got an error, or we got less data than expected
  11758. EXPECT_TRUE(got_error || total < 1000)
  11759. << "Expected timeout but got all " << total << " bytes";
  11760. svr.stop();
  11761. t.join();
  11762. }
  11763. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  11764. // Test connection closed detection via BodyReader
  11765. Server svr;
  11766. std::atomic<bool> close_now{false};
  11767. svr.Get("/will-close", [&](const Request &, Response &res) {
  11768. res.set_content_provider(
  11769. 10000, // Large content_length that we won't fully send
  11770. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  11771. if (offset < 100) {
  11772. std::string data(100, 'X');
  11773. sink.write(data.c_str(), data.size());
  11774. return true;
  11775. }
  11776. // Wait for signal then abort
  11777. while (!close_now) {
  11778. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11779. }
  11780. return false; // Abort - server will close connection
  11781. });
  11782. });
  11783. auto port = 8092;
  11784. std::thread t([&]() { svr.listen("localhost", port); });
  11785. svr.wait_until_ready();
  11786. Client cli("localhost", port);
  11787. auto handle = cli.open_stream("GET", "/will-close");
  11788. ASSERT_TRUE(handle.is_valid());
  11789. char buf[256];
  11790. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  11791. EXPECT_GT(n, 0) << "First read should succeed";
  11792. // Signal server to close
  11793. close_now = true;
  11794. // Keep reading until error or EOF
  11795. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11796. // Keep reading
  11797. }
  11798. // Should get an error since content_length wasn't satisfied
  11799. if (n < 0) {
  11800. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  11801. handle.get_read_error() == Error::Read)
  11802. << "Actual error: " << to_string(handle.get_read_error());
  11803. }
  11804. svr.stop();
  11805. t.join();
  11806. }
  11807. #ifdef CPPHTTPLIB_SSL_ENABLED
  11808. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  11809. // Test that read timeout during SSL streaming is detected
  11810. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11811. svr.Get("/slow-stream", [](const Request &, Response &res) {
  11812. res.set_content_provider(
  11813. 1000, "text/plain",
  11814. [](size_t offset, size_t /*length*/, DataSink &sink) {
  11815. if (offset < 100) {
  11816. std::string data(100, 'A');
  11817. sink.write(data.c_str(), data.size());
  11818. return true;
  11819. }
  11820. std::this_thread::sleep_for(std::chrono::seconds(3));
  11821. std::string data(900, 'B');
  11822. sink.write(data.c_str(), data.size());
  11823. return true;
  11824. });
  11825. });
  11826. auto port = 8093;
  11827. std::thread t([&]() { svr.listen("localhost", port); });
  11828. svr.wait_until_ready();
  11829. SSLClient cli("localhost", port);
  11830. cli.enable_server_certificate_verification(false);
  11831. cli.set_read_timeout(1, 0); // 1 second timeout
  11832. auto handle = cli.open_stream("GET", "/slow-stream");
  11833. ASSERT_TRUE(handle.is_valid());
  11834. char buf[256];
  11835. ssize_t total = 0;
  11836. ssize_t n;
  11837. bool got_error = false;
  11838. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11839. total += n;
  11840. }
  11841. if (n < 0) {
  11842. got_error = true;
  11843. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  11844. handle.get_read_error() == Error::Read)
  11845. << "Actual error: " << to_string(handle.get_read_error());
  11846. }
  11847. EXPECT_TRUE(got_error || total < 1000)
  11848. << "Expected timeout but got all " << total << " bytes";
  11849. svr.stop();
  11850. t.join();
  11851. }
  11852. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  11853. // Test SSL connection closed detection
  11854. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11855. std::atomic<bool> close_now{false};
  11856. svr.Get("/will-close", [&](const Request &, Response &res) {
  11857. res.set_content_provider(
  11858. 10000, "text/plain",
  11859. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  11860. if (offset < 100) {
  11861. std::string data(100, 'X');
  11862. sink.write(data.c_str(), data.size());
  11863. return true;
  11864. }
  11865. while (!close_now) {
  11866. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11867. }
  11868. return false;
  11869. });
  11870. });
  11871. auto port = 8094;
  11872. std::thread t([&]() { svr.listen("localhost", port); });
  11873. svr.wait_until_ready();
  11874. SSLClient cli("localhost", port);
  11875. cli.enable_server_certificate_verification(false);
  11876. auto handle = cli.open_stream("GET", "/will-close");
  11877. ASSERT_TRUE(handle.is_valid());
  11878. char buf[256];
  11879. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  11880. EXPECT_GT(n, 0);
  11881. // Signal server to close
  11882. close_now = true;
  11883. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11884. // Keep reading
  11885. }
  11886. if (n < 0) {
  11887. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  11888. handle.get_read_error() == Error::Read)
  11889. << "Actual error: " << to_string(handle.get_read_error());
  11890. }
  11891. svr.stop();
  11892. t.join();
  11893. }
  11894. #endif
  11895. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  11896. using namespace httplib;
  11897. // Create a test file
  11898. const char *fname = "etag_testfile.txt";
  11899. const char *content = "etag-content";
  11900. {
  11901. std::ofstream ofs(fname);
  11902. ofs << content;
  11903. ASSERT_TRUE(ofs.good());
  11904. }
  11905. Server svr;
  11906. svr.set_mount_point("/static", ".");
  11907. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  11908. svr.wait_until_ready();
  11909. Client cli(HOST, PORT);
  11910. // First request: should get 200 with ETag header
  11911. auto res1 = cli.Get("/static/etag_testfile.txt");
  11912. ASSERT_TRUE(res1);
  11913. ASSERT_EQ(200, res1->status);
  11914. ASSERT_TRUE(res1->has_header("ETag"));
  11915. std::string etag = res1->get_header_value("ETag");
  11916. EXPECT_FALSE(etag.empty());
  11917. // Verify ETag format: W/"hex-hex"
  11918. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  11919. EXPECT_EQ('W', etag[0]);
  11920. EXPECT_EQ('/', etag[1]);
  11921. EXPECT_EQ('"', etag[2]);
  11922. EXPECT_EQ('"', etag.back());
  11923. // Exact match: expect 304 Not Modified
  11924. Headers h2 = {{"If-None-Match", etag}};
  11925. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  11926. ASSERT_TRUE(res2);
  11927. EXPECT_EQ(304, res2->status);
  11928. // Wildcard match: expect 304 Not Modified
  11929. Headers h3 = {{"If-None-Match", "*"}};
  11930. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  11931. ASSERT_TRUE(res3);
  11932. EXPECT_EQ(304, res3->status);
  11933. // Non-matching ETag: expect 200
  11934. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  11935. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  11936. ASSERT_TRUE(res4);
  11937. EXPECT_EQ(200, res4->status);
  11938. // Multiple ETags with one matching: expect 304
  11939. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  11940. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  11941. ASSERT_TRUE(res5);
  11942. EXPECT_EQ(304, res5->status);
  11943. svr.stop();
  11944. t.join();
  11945. std::remove(fname);
  11946. }
  11947. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  11948. using namespace httplib;
  11949. Server svr;
  11950. svr.set_mount_point("/static", ".");
  11951. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11952. svr.wait_until_ready();
  11953. Client cli(HOST, PORT);
  11954. // Send If-None-Match: * to a non-existent file
  11955. Headers h = {{"If-None-Match", "*"}};
  11956. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  11957. ASSERT_TRUE(res);
  11958. EXPECT_EQ(404, res->status);
  11959. svr.stop();
  11960. t.join();
  11961. }
  11962. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  11963. using namespace httplib;
  11964. // Create a test file
  11965. const char *fname = "etag_boundary_testfile.txt";
  11966. const char *content = "boundary-test";
  11967. {
  11968. std::ofstream ofs(fname);
  11969. ofs << content;
  11970. ASSERT_TRUE(ofs.good());
  11971. }
  11972. Server svr;
  11973. svr.set_mount_point("/static", ".");
  11974. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  11975. svr.wait_until_ready();
  11976. Client cli(HOST, PORT);
  11977. // Get the actual ETag
  11978. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  11979. ASSERT_TRUE(res1);
  11980. ASSERT_EQ(200, res1->status);
  11981. ASSERT_TRUE(res1->has_header("ETag"));
  11982. std::string etag = res1->get_header_value("ETag");
  11983. // Test 1: Very long ETag value (longer than actual ETag)
  11984. // Should NOT match and return 200 (not trigger out-of-bounds read)
  11985. Headers h1 = {{"If-None-Match", "W/"
  11986. "\"very-long-etag-value-that-is-much-longer-"
  11987. "than-the-actual-etag-value\""}};
  11988. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  11989. ASSERT_TRUE(res2);
  11990. EXPECT_EQ(200, res2->status); // Should not match
  11991. // Test 2: Long string followed by wildcard
  11992. // Should match on "*" and return 304 (without out-of-bounds read on the long
  11993. // string)
  11994. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  11995. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  11996. ASSERT_TRUE(res3);
  11997. EXPECT_EQ(304, res3->status); // Should match on "*"
  11998. // Test 3: Wildcard followed by long string
  11999. // Should match on "*" immediately and return 304
  12000. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  12001. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  12002. ASSERT_TRUE(res4);
  12003. EXPECT_EQ(304, res4->status); // Should match on "*"
  12004. // Test 4: Multiple long non-matching values
  12005. // Should NOT match and return 200 (test that all comparisons are safe)
  12006. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  12007. "W/\"second-long-non-matching-value\", "
  12008. "W/\"third-long-non-matching-value\""}};
  12009. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  12010. ASSERT_TRUE(res5);
  12011. EXPECT_EQ(200, res5->status); // Should not match
  12012. // Test 5: Single character that is not "*" (edge case)
  12013. Headers h5 = {{"If-None-Match", "X"}};
  12014. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  12015. ASSERT_TRUE(res6);
  12016. EXPECT_EQ(200, res6->status); // Should not match
  12017. svr.stop();
  12018. t.join();
  12019. std::remove(fname);
  12020. }
  12021. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  12022. using namespace httplib;
  12023. // Create a test file
  12024. const char *fname = "ims_testfile.txt";
  12025. const char *content = "if-modified-since-test";
  12026. {
  12027. std::ofstream ofs(fname);
  12028. ofs << content;
  12029. ASSERT_TRUE(ofs.good());
  12030. }
  12031. Server svr;
  12032. svr.set_mount_point("/static", ".");
  12033. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12034. svr.wait_until_ready();
  12035. Client cli(HOST, PORT);
  12036. // First request: should get 200 with Last-Modified header
  12037. auto res1 = cli.Get("/static/ims_testfile.txt");
  12038. ASSERT_TRUE(res1);
  12039. ASSERT_EQ(200, res1->status);
  12040. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12041. std::string last_modified = res1->get_header_value("Last-Modified");
  12042. EXPECT_FALSE(last_modified.empty());
  12043. // If-Modified-Since with same time: expect 304
  12044. Headers h2 = {{"If-Modified-Since", last_modified}};
  12045. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  12046. ASSERT_TRUE(res2);
  12047. EXPECT_EQ(304, res2->status);
  12048. // If-Modified-Since with future time: expect 304
  12049. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12050. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  12051. ASSERT_TRUE(res3);
  12052. EXPECT_EQ(304, res3->status);
  12053. // If-Modified-Since with past time: expect 200
  12054. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12055. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  12056. ASSERT_TRUE(res4);
  12057. EXPECT_EQ(200, res4->status);
  12058. // If-None-Match takes precedence over If-Modified-Since
  12059. // (send matching ETag with old If-Modified-Since -> should still be 304)
  12060. ASSERT_TRUE(res1->has_header("ETag"));
  12061. std::string etag = res1->get_header_value("ETag");
  12062. Headers h5 = {{"If-None-Match", etag},
  12063. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12064. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  12065. ASSERT_TRUE(res5);
  12066. EXPECT_EQ(304, res5->status);
  12067. svr.stop();
  12068. t.join();
  12069. std::remove(fname);
  12070. }
  12071. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  12072. using namespace httplib;
  12073. Server svr;
  12074. // Endpoint that returns compressible content
  12075. svr.Get("/compressible", [](const Request &, Response &res) {
  12076. // Return a large enough body to trigger compression
  12077. std::string body(1000, 'a');
  12078. res.set_content(body, "text/plain");
  12079. });
  12080. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12081. svr.wait_until_ready();
  12082. Client cli(HOST, PORT);
  12083. // Request with gzip support: should get Vary header when compressed
  12084. cli.set_compress(true);
  12085. auto res1 = cli.Get("/compressible");
  12086. ASSERT_TRUE(res1);
  12087. EXPECT_EQ(200, res1->status);
  12088. // If Content-Encoding is set, Vary should also be set
  12089. if (res1->has_header("Content-Encoding")) {
  12090. EXPECT_TRUE(res1->has_header("Vary"));
  12091. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  12092. }
  12093. // Request without Accept-Encoding header: should not have compression
  12094. Headers h_no_compress;
  12095. auto res2 = cli.Get("/compressible", h_no_compress);
  12096. ASSERT_TRUE(res2);
  12097. EXPECT_EQ(200, res2->status);
  12098. // Verify Vary header is present when compression is applied
  12099. // (the exact behavior depends on server configuration)
  12100. svr.stop();
  12101. t.join();
  12102. }
  12103. TEST(ETagTest, IfRangeWithETag) {
  12104. using namespace httplib;
  12105. // Create a test file with known content
  12106. const char *fname = "if_range_testfile.txt";
  12107. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  12108. {
  12109. std::ofstream ofs(fname);
  12110. ofs << content;
  12111. ASSERT_TRUE(ofs.good());
  12112. }
  12113. Server svr;
  12114. svr.set_mount_point("/static", ".");
  12115. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12116. svr.wait_until_ready();
  12117. Client cli(HOST, PORT);
  12118. // First request: get ETag
  12119. auto res1 = cli.Get("/static/if_range_testfile.txt");
  12120. ASSERT_TRUE(res1);
  12121. ASSERT_EQ(200, res1->status);
  12122. ASSERT_TRUE(res1->has_header("ETag"));
  12123. std::string etag = res1->get_header_value("ETag");
  12124. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  12125. // Since our server generates weak ETags (W/"..."), If-Range with our
  12126. // ETag should NOT result in partial content - it should return full content.
  12127. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  12128. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  12129. ASSERT_TRUE(res2);
  12130. // Weak ETag in If-Range -> full content (200), not partial (206)
  12131. EXPECT_EQ(200, res2->status);
  12132. EXPECT_EQ(content, res2->body);
  12133. EXPECT_FALSE(res2->has_header("Content-Range"));
  12134. // Range request with non-matching If-Range (ETag): should get 200 (full
  12135. // content)
  12136. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  12137. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  12138. ASSERT_TRUE(res3);
  12139. EXPECT_EQ(200, res3->status);
  12140. EXPECT_EQ(content, res3->body);
  12141. EXPECT_FALSE(res3->has_header("Content-Range"));
  12142. // Range request with strong ETag (hypothetical - our server doesn't generate
  12143. // strong ETags, but if client sends a strong ETag that doesn't match, it
  12144. // should return full content)
  12145. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  12146. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  12147. ASSERT_TRUE(res4);
  12148. EXPECT_EQ(200, res4->status);
  12149. EXPECT_EQ(content, res4->body);
  12150. EXPECT_FALSE(res4->has_header("Content-Range"));
  12151. svr.stop();
  12152. t.join();
  12153. std::remove(fname);
  12154. }
  12155. TEST(ETagTest, IfRangeWithDate) {
  12156. using namespace httplib;
  12157. // Create a test file
  12158. const char *fname = "if_range_date_testfile.txt";
  12159. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  12160. {
  12161. std::ofstream ofs(fname);
  12162. ofs << content;
  12163. ASSERT_TRUE(ofs.good());
  12164. }
  12165. Server svr;
  12166. svr.set_mount_point("/static", ".");
  12167. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12168. svr.wait_until_ready();
  12169. Client cli(HOST, PORT);
  12170. // First request: get Last-Modified
  12171. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  12172. ASSERT_TRUE(res1);
  12173. ASSERT_EQ(200, res1->status);
  12174. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12175. std::string last_modified = res1->get_header_value("Last-Modified");
  12176. // Range request with matching If-Range (date): should get 206
  12177. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  12178. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  12179. ASSERT_TRUE(res2);
  12180. EXPECT_EQ(206, res2->status);
  12181. EXPECT_EQ("FGHIJ", res2->body);
  12182. // Range request with old If-Range date: should get 200 (full content)
  12183. Headers h3 = {{"Range", "bytes=5-9"},
  12184. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12185. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  12186. ASSERT_TRUE(res3);
  12187. EXPECT_EQ(200, res3->status);
  12188. EXPECT_EQ(content, res3->body);
  12189. // Range request with future If-Range date: should get 206
  12190. Headers h4 = {{"Range", "bytes=0-4"},
  12191. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12192. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  12193. ASSERT_TRUE(res4);
  12194. EXPECT_EQ(206, res4->status);
  12195. EXPECT_EQ("ABCDE", res4->body);
  12196. svr.stop();
  12197. t.join();
  12198. std::remove(fname);
  12199. }
  12200. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  12201. using namespace httplib;
  12202. const char *fname = "etag_malformed.txt";
  12203. const char *content = "malformed-etag";
  12204. {
  12205. std::ofstream ofs(fname);
  12206. ofs << content;
  12207. ASSERT_TRUE(ofs.good());
  12208. }
  12209. Server svr;
  12210. svr.set_mount_point("/static", ".");
  12211. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12212. svr.wait_until_ready();
  12213. Client cli(HOST, PORT);
  12214. // baseline: should get 200 and an ETag
  12215. auto res1 = cli.Get("/static/etag_malformed.txt");
  12216. ASSERT_TRUE(res1);
  12217. ASSERT_EQ(200, res1->status);
  12218. ASSERT_TRUE(res1->has_header("ETag"));
  12219. // Malformed ETag value (missing quotes) should be treated as non-matching
  12220. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  12221. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  12222. ASSERT_TRUE(res_bad);
  12223. EXPECT_EQ(200, res_bad->status);
  12224. // Whitespace-only header value should be considered invalid / non-matching
  12225. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  12226. "Host: localhost\r\n"
  12227. "If-None-Match: \r\n"
  12228. "Connection: close\r\n"
  12229. "\r\n";
  12230. std::string out;
  12231. ASSERT_TRUE(send_request(5, raw_req, &out));
  12232. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12233. svr.stop();
  12234. t.join();
  12235. std::remove(fname);
  12236. }
  12237. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  12238. using namespace httplib;
  12239. const char *fname = "ims_invalid_format.txt";
  12240. const char *content = "ims-bad-format";
  12241. {
  12242. std::ofstream ofs(fname);
  12243. ofs << content;
  12244. ASSERT_TRUE(ofs.good());
  12245. }
  12246. Server svr;
  12247. svr.set_mount_point("/static", ".");
  12248. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12249. svr.wait_until_ready();
  12250. Client cli(HOST, PORT);
  12251. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  12252. ASSERT_TRUE(res1);
  12253. ASSERT_EQ(200, res1->status);
  12254. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12255. // If-Modified-Since with invalid format should not result in 304
  12256. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  12257. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  12258. ASSERT_TRUE(res_bad);
  12259. EXPECT_EQ(200, res_bad->status);
  12260. // If-Range with invalid date format should be treated as mismatch -> full
  12261. // content (200)
  12262. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  12263. {"If-Range", "invalid-date"}};
  12264. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  12265. ASSERT_TRUE(res_ifrange);
  12266. EXPECT_EQ(200, res_ifrange->status);
  12267. svr.stop();
  12268. t.join();
  12269. std::remove(fname);
  12270. }
  12271. TEST(ETagTest, IfRangeWithMalformedETag) {
  12272. using namespace httplib;
  12273. const char *fname = "ifrange_malformed.txt";
  12274. const std::string content = "0123456789";
  12275. {
  12276. std::ofstream ofs(fname);
  12277. ofs << content;
  12278. ASSERT_TRUE(ofs.good());
  12279. }
  12280. Server svr;
  12281. svr.set_mount_point("/static", ".");
  12282. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12283. svr.wait_until_ready();
  12284. Client cli(HOST, PORT);
  12285. // First request: get ETag
  12286. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  12287. ASSERT_TRUE(res1);
  12288. ASSERT_EQ(200, res1->status);
  12289. ASSERT_TRUE(res1->has_header("ETag"));
  12290. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  12291. // full content (200)
  12292. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  12293. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  12294. ASSERT_TRUE(res2);
  12295. EXPECT_EQ(200, res2->status);
  12296. EXPECT_EQ(content, res2->body);
  12297. svr.stop();
  12298. t.join();
  12299. std::remove(fname);
  12300. }
  12301. TEST(ETagTest, ExtremeLargeDateValues) {
  12302. using namespace httplib;
  12303. const char *fname = "ims_extreme_date.txt";
  12304. const char *content = "ims-extreme-date";
  12305. {
  12306. std::ofstream ofs(fname);
  12307. ofs << content;
  12308. ASSERT_TRUE(ofs.good());
  12309. }
  12310. Server svr;
  12311. svr.set_mount_point("/static", ".");
  12312. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12313. svr.wait_until_ready();
  12314. Client cli(HOST, PORT);
  12315. auto res1 = cli.Get(std::string("/static/") + fname);
  12316. ASSERT_TRUE(res1);
  12317. ASSERT_EQ(200, res1->status);
  12318. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12319. // Extremely large year that may overflow date parsing routines.
  12320. Headers h_large_date = {
  12321. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12322. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  12323. ASSERT_TRUE(res_bad);
  12324. // Expect server to treat this as invalid/mismatch and return full content
  12325. EXPECT_EQ(200, res_bad->status);
  12326. // If-Range with extremely large date should be treated as mismatch -> full
  12327. // content (200)
  12328. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  12329. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12330. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  12331. ASSERT_TRUE(res_ifrange);
  12332. EXPECT_EQ(200, res_ifrange->status);
  12333. svr.stop();
  12334. t.join();
  12335. std::remove(fname);
  12336. }
  12337. TEST(ETagTest, NegativeFileModificationTime) {
  12338. using namespace httplib;
  12339. const char *fname = "ims_negative_mtime.txt";
  12340. const std::string content = "negative-mtime";
  12341. {
  12342. std::ofstream ofs(fname);
  12343. ofs << content;
  12344. ASSERT_TRUE(ofs.good());
  12345. }
  12346. // Try to set file mtime to a negative value. This may fail on some
  12347. // platforms/filesystems; if it fails, the test will still verify server
  12348. // behaves safely by performing a regular conditional request.
  12349. #if defined(__APPLE__) || defined(__linux__)
  12350. bool set_negative = false;
  12351. do {
  12352. struct timeval times[2];
  12353. // access time: now
  12354. times[0].tv_sec = time(nullptr);
  12355. times[0].tv_usec = 0;
  12356. // modification time: negative (e.g., -1)
  12357. times[1].tv_sec = -1;
  12358. times[1].tv_usec = 0;
  12359. if (utimes(fname, times) == 0) { set_negative = true; }
  12360. } while (0);
  12361. #else
  12362. bool set_negative = false;
  12363. #endif
  12364. Server svr;
  12365. svr.set_mount_point("/static", ".");
  12366. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12367. svr.wait_until_ready();
  12368. Client cli(HOST, PORT);
  12369. auto res1 = cli.Get(std::string("/static/") + fname);
  12370. ASSERT_TRUE(res1);
  12371. ASSERT_EQ(200, res1->status);
  12372. bool has_last_modified = res1->has_header("Last-Modified");
  12373. std::string last_modified;
  12374. if (has_last_modified) {
  12375. last_modified = res1->get_header_value("Last-Modified");
  12376. }
  12377. if (set_negative) {
  12378. // If we successfully set a negative mtime, ensure server returns a
  12379. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  12380. // with an old date and ensure server handles it without crash.
  12381. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  12382. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  12383. ASSERT_TRUE(res2);
  12384. // Behavior may vary; at minimum ensure server responds (200 or 304).
  12385. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  12386. } else {
  12387. // Could not set negative mtime on this platform; fall back to verifying
  12388. // that normal invalid/malformed dates are treated safely (non-304).
  12389. Headers h_bad_date = {
  12390. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12391. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  12392. ASSERT_TRUE(res_bad);
  12393. EXPECT_EQ(200, res_bad->status);
  12394. }
  12395. svr.stop();
  12396. t.join();
  12397. std::remove(fname);
  12398. }
  12399. //==============================================================================
  12400. // SSE Parsing Tests
  12401. //==============================================================================
  12402. class SSEParsingTest : public ::testing::Test {
  12403. protected:
  12404. // Test helper that mimics SSE parsing behavior
  12405. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  12406. int &retry_ms) {
  12407. // Blank line signals end of event
  12408. if (line.empty() || line == "\r") { return true; }
  12409. // Lines starting with ':' are comments (ignored)
  12410. if (!line.empty() && line[0] == ':') { return false; }
  12411. // Find the colon separator
  12412. auto colon_pos = line.find(':');
  12413. if (colon_pos == std::string::npos) {
  12414. // Line with no colon is treated as field name with empty value
  12415. return false;
  12416. }
  12417. std::string field = line.substr(0, colon_pos);
  12418. std::string value;
  12419. // Value starts after colon, skip optional single space
  12420. if (colon_pos + 1 < line.size()) {
  12421. size_t value_start = colon_pos + 1;
  12422. if (line[value_start] == ' ') { value_start++; }
  12423. value = line.substr(value_start);
  12424. // Remove trailing \r if present
  12425. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  12426. }
  12427. // Handle known fields
  12428. if (field == "event") {
  12429. msg.event = value;
  12430. } else if (field == "data") {
  12431. // Multiple data lines are concatenated with newlines
  12432. if (!msg.data.empty()) { msg.data += "\n"; }
  12433. msg.data += value;
  12434. } else if (field == "id") {
  12435. // Empty id is valid (clears the last event ID)
  12436. msg.id = value;
  12437. } else if (field == "retry") {
  12438. // Parse retry interval in milliseconds
  12439. {
  12440. int v = 0;
  12441. auto res =
  12442. detail::from_chars(value.data(), value.data() + value.size(), v);
  12443. if (res.ec == std::errc{}) { retry_ms = v; }
  12444. }
  12445. }
  12446. // Unknown fields are ignored per SSE spec
  12447. return false;
  12448. }
  12449. };
  12450. // Test: Single-line data
  12451. TEST_F(SSEParsingTest, SingleLineData) {
  12452. sse::SSEMessage msg;
  12453. int retry_ms = 3000;
  12454. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  12455. EXPECT_EQ(msg.data, "hello");
  12456. EXPECT_EQ(msg.event, "message");
  12457. // Blank line ends event
  12458. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12459. }
  12460. // Test: Multi-line data
  12461. TEST_F(SSEParsingTest, MultiLineData) {
  12462. sse::SSEMessage msg;
  12463. int retry_ms = 3000;
  12464. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  12465. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  12466. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  12467. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  12468. }
  12469. // Test: Custom event types
  12470. TEST_F(SSEParsingTest, CustomEventType) {
  12471. sse::SSEMessage msg;
  12472. int retry_ms = 3000;
  12473. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  12474. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  12475. EXPECT_EQ(msg.event, "update");
  12476. EXPECT_EQ(msg.data, "payload");
  12477. }
  12478. // Test: Event ID handling
  12479. TEST_F(SSEParsingTest, EventIdHandling) {
  12480. sse::SSEMessage msg;
  12481. int retry_ms = 3000;
  12482. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  12483. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  12484. EXPECT_EQ(msg.id, "12345");
  12485. }
  12486. // Test: Empty event ID (clears last event ID)
  12487. TEST_F(SSEParsingTest, EmptyEventId) {
  12488. sse::SSEMessage msg;
  12489. msg.id = "previous";
  12490. int retry_ms = 3000;
  12491. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  12492. EXPECT_EQ(msg.id, "");
  12493. }
  12494. // Test: Retry field parsing
  12495. TEST_F(SSEParsingTest, RetryFieldParsing) {
  12496. sse::SSEMessage msg;
  12497. int retry_ms = 3000;
  12498. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  12499. EXPECT_EQ(retry_ms, 5000);
  12500. }
  12501. // Test: Invalid retry value
  12502. TEST_F(SSEParsingTest, InvalidRetryValue) {
  12503. sse::SSEMessage msg;
  12504. int retry_ms = 3000;
  12505. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  12506. EXPECT_EQ(retry_ms, 3000); // Unchanged
  12507. }
  12508. // Test: Comments (lines starting with :)
  12509. TEST_F(SSEParsingTest, CommentsIgnored) {
  12510. sse::SSEMessage msg;
  12511. int retry_ms = 3000;
  12512. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  12513. EXPECT_EQ(msg.data, "");
  12514. EXPECT_EQ(msg.event, "message");
  12515. }
  12516. // Test: Colon in value
  12517. TEST_F(SSEParsingTest, ColonInValue) {
  12518. sse::SSEMessage msg;
  12519. int retry_ms = 3000;
  12520. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  12521. EXPECT_EQ(msg.data, "hello:world:test");
  12522. }
  12523. // Test: Line with no colon (field name only)
  12524. TEST_F(SSEParsingTest, FieldNameOnly) {
  12525. sse::SSEMessage msg;
  12526. int retry_ms = 3000;
  12527. // According to SSE spec, this is treated as field name with empty value
  12528. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  12529. // Since we don't recognize "data" without colon, data should be empty
  12530. EXPECT_EQ(msg.data, "");
  12531. }
  12532. // Test: Trailing \r handling
  12533. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  12534. sse::SSEMessage msg;
  12535. int retry_ms = 3000;
  12536. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  12537. EXPECT_EQ(msg.data, "hello");
  12538. }
  12539. // Test: Unknown fields ignored
  12540. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  12541. sse::SSEMessage msg;
  12542. int retry_ms = 3000;
  12543. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  12544. EXPECT_EQ(msg.data, "");
  12545. EXPECT_EQ(msg.event, "message");
  12546. }
  12547. // Test: Space after colon is optional
  12548. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  12549. sse::SSEMessage msg1, msg2;
  12550. int retry_ms = 3000;
  12551. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  12552. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  12553. EXPECT_EQ(msg1.data, "hello");
  12554. EXPECT_EQ(msg2.data, "hello");
  12555. }
  12556. // Test: SSEMessage clear
  12557. TEST_F(SSEParsingTest, MessageClear) {
  12558. sse::SSEMessage msg;
  12559. msg.event = "custom";
  12560. msg.data = "some data";
  12561. msg.id = "123";
  12562. msg.clear();
  12563. EXPECT_EQ(msg.event, "message");
  12564. EXPECT_EQ(msg.data, "");
  12565. EXPECT_EQ(msg.id, "");
  12566. }
  12567. // Test: Complete event parsing
  12568. TEST_F(SSEParsingTest, CompleteEventParsing) {
  12569. sse::SSEMessage msg;
  12570. int retry_ms = 3000;
  12571. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  12572. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  12573. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  12574. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  12575. // Blank line ends event
  12576. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12577. EXPECT_EQ(msg.event, "notification");
  12578. EXPECT_EQ(msg.id, "evt-42");
  12579. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  12580. EXPECT_EQ(retry_ms, 1000);
  12581. }
  12582. //==============================================================================
  12583. // Integration Tests with Server
  12584. //==============================================================================
  12585. class SSEIntegrationTest : public ::testing::Test {
  12586. protected:
  12587. void SetUp() override {
  12588. stop_server_.store(false);
  12589. events_.clear();
  12590. server_ = httplib::detail::make_unique<Server>();
  12591. setup_server();
  12592. start_server();
  12593. }
  12594. void TearDown() override {
  12595. stop_server_.store(true);
  12596. event_cv_.notify_all();
  12597. server_->stop();
  12598. if (server_thread_.joinable()) { server_thread_.join(); }
  12599. }
  12600. void setup_server() {
  12601. // Simple SSE endpoint
  12602. server_->Get("/events", [this](const Request &req, Response &res) {
  12603. auto last_id = req.get_header_value("Last-Event-ID");
  12604. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  12605. res.set_chunked_content_provider(
  12606. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  12607. std::unique_lock<std::mutex> lock(event_mutex_);
  12608. if (event_cv_.wait_for(
  12609. lock, std::chrono::milliseconds(200), [this] {
  12610. return !events_.empty() || stop_server_.load();
  12611. })) {
  12612. if (stop_server_.load()) { return false; }
  12613. if (!events_.empty()) {
  12614. std::string event = events_.front();
  12615. events_.erase(events_.begin());
  12616. sink.write(event.data(), event.size());
  12617. return true;
  12618. }
  12619. }
  12620. return !stop_server_.load();
  12621. });
  12622. });
  12623. // Endpoint that returns error
  12624. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  12625. res.status = 500;
  12626. res.set_content("Internal Server Error", "text/plain");
  12627. });
  12628. // Endpoint for custom event types
  12629. server_->Get("/custom-events", [](const Request &, Response &res) {
  12630. res.set_chunked_content_provider(
  12631. "text/event-stream", [](size_t offset, DataSink &sink) {
  12632. if (offset == 0) {
  12633. std::string event = "event: update\ndata: updated\n\n"
  12634. "event: delete\ndata: deleted\n\n";
  12635. sink.write(event.data(), event.size());
  12636. }
  12637. return false; // End stream after sending
  12638. });
  12639. });
  12640. }
  12641. void start_server() {
  12642. port_ = server_->bind_to_any_port(HOST);
  12643. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  12644. // Wait for server to start
  12645. while (!server_->is_running()) {
  12646. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12647. }
  12648. }
  12649. int get_port() const { return port_; }
  12650. void send_event(const std::string &event) {
  12651. std::lock_guard<std::mutex> lock(event_mutex_);
  12652. events_.push_back(event);
  12653. event_cv_.notify_all();
  12654. }
  12655. std::unique_ptr<Server> server_;
  12656. std::thread server_thread_;
  12657. std::mutex event_mutex_;
  12658. std::condition_variable event_cv_;
  12659. std::vector<std::string> events_;
  12660. std::atomic<bool> stop_server_{false};
  12661. std::string last_received_event_id_;
  12662. int port_ = 0;
  12663. };
  12664. // Test: Successful connection and on_open callback
  12665. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  12666. // Add a simple endpoint that sends one event and closes
  12667. server_->Get("/simple-event", [](const Request &, Response &res) {
  12668. res.set_chunked_content_provider(
  12669. "text/event-stream", [](size_t offset, DataSink &sink) {
  12670. if (offset == 0) {
  12671. std::string event = "data: hello\n\n";
  12672. sink.write(event.data(), event.size());
  12673. }
  12674. return false; // Close stream after sending
  12675. });
  12676. });
  12677. Client client("localhost", get_port());
  12678. sse::SSEClient sse(client, "/simple-event");
  12679. std::atomic<bool> open_called{false};
  12680. std::atomic<bool> message_received{false};
  12681. sse.on_open([&open_called]() { open_called.store(true); });
  12682. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  12683. if (msg.data == "hello") { message_received.store(true); }
  12684. });
  12685. sse.set_reconnect_interval(100);
  12686. sse.set_max_reconnect_attempts(1);
  12687. // Start async
  12688. sse.start_async();
  12689. // Wait for message to be processed
  12690. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12691. sse.stop();
  12692. EXPECT_TRUE(open_called.load());
  12693. EXPECT_TRUE(message_received.load());
  12694. }
  12695. // Test: on_message callback
  12696. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  12697. // Endpoint that sends multiple events then closes
  12698. server_->Get("/multi-event", [](const Request &, Response &res) {
  12699. res.set_chunked_content_provider(
  12700. "text/event-stream", [](size_t offset, DataSink &sink) {
  12701. if (offset == 0) {
  12702. std::string events = "data: message1\n\ndata: message2\n\n";
  12703. sink.write(events.data(), events.size());
  12704. }
  12705. return false;
  12706. });
  12707. });
  12708. Client client("localhost", get_port());
  12709. sse::SSEClient sse(client, "/multi-event");
  12710. std::vector<std::string> received_messages;
  12711. std::mutex messages_mutex;
  12712. sse.on_message([&](const sse::SSEMessage &msg) {
  12713. std::lock_guard<std::mutex> lock(messages_mutex);
  12714. received_messages.push_back(msg.data);
  12715. });
  12716. sse.set_reconnect_interval(100);
  12717. sse.set_max_reconnect_attempts(1);
  12718. sse.start_async();
  12719. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12720. sse.stop();
  12721. std::lock_guard<std::mutex> lock(messages_mutex);
  12722. EXPECT_GE(received_messages.size(), 2u);
  12723. if (received_messages.size() >= 2) {
  12724. EXPECT_EQ(received_messages[0], "message1");
  12725. EXPECT_EQ(received_messages[1], "message2");
  12726. }
  12727. }
  12728. // Test: on_event for specific types
  12729. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  12730. Client client("localhost", get_port());
  12731. sse::SSEClient sse(client, "/custom-events");
  12732. std::atomic<bool> update_received{false};
  12733. std::atomic<bool> delete_received{false};
  12734. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  12735. if (msg.data == "updated") { update_received.store(true); }
  12736. });
  12737. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  12738. if (msg.data == "deleted") { delete_received.store(true); }
  12739. });
  12740. sse.set_max_reconnect_attempts(1);
  12741. sse.start_async();
  12742. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  12743. sse.stop();
  12744. EXPECT_TRUE(update_received.load());
  12745. EXPECT_TRUE(delete_received.load());
  12746. }
  12747. // Test: on_error callback on connection failure
  12748. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  12749. // Connect to a non-existent port
  12750. Client client("localhost", 59999);
  12751. sse::SSEClient sse(client, "/events");
  12752. std::atomic<bool> error_called{false};
  12753. Error received_error = Error::Success;
  12754. sse.on_error([&](Error err) {
  12755. error_called.store(true);
  12756. received_error = err;
  12757. });
  12758. sse.set_reconnect_interval(50);
  12759. sse.set_max_reconnect_attempts(1);
  12760. sse.start_async();
  12761. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12762. sse.stop();
  12763. EXPECT_TRUE(error_called.load());
  12764. EXPECT_NE(received_error, Error::Success);
  12765. }
  12766. // Test: Last-Event-ID header sent on reconnect
  12767. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  12768. // Endpoint that sends event with ID
  12769. server_->Get("/event-with-id", [](const Request &, Response &res) {
  12770. res.set_chunked_content_provider(
  12771. "text/event-stream", [](size_t offset, DataSink &sink) {
  12772. if (offset == 0) {
  12773. std::string event = "id: evt-123\ndata: test\n\n";
  12774. sink.write(event.data(), event.size());
  12775. }
  12776. return false;
  12777. });
  12778. });
  12779. Client client("localhost", get_port());
  12780. sse::SSEClient sse(client, "/event-with-id");
  12781. std::atomic<bool> id_received{false};
  12782. sse.on_message([&](const sse::SSEMessage &msg) {
  12783. if (!msg.id.empty()) { id_received.store(true); }
  12784. });
  12785. sse.set_reconnect_interval(100);
  12786. sse.set_max_reconnect_attempts(1);
  12787. sse.start_async();
  12788. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12789. sse.stop();
  12790. EXPECT_TRUE(id_received.load());
  12791. EXPECT_EQ(sse.last_event_id(), "evt-123");
  12792. }
  12793. // Test: Manual stop
  12794. TEST_F(SSEIntegrationTest, ManualStop) {
  12795. // Endpoint that sends one event and stays open briefly
  12796. std::atomic<bool> handler_running{true};
  12797. server_->Get("/stay-open", [&handler_running](const Request &,
  12798. Response &res) {
  12799. res.set_chunked_content_provider(
  12800. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  12801. if (offset == 0) {
  12802. std::string event = "data: connected\n\n";
  12803. sink.write(event.data(), event.size());
  12804. }
  12805. // Keep connection open while handler_running is true
  12806. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  12807. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  12808. }
  12809. return false;
  12810. });
  12811. });
  12812. Client client("localhost", get_port());
  12813. sse::SSEClient sse(client, "/stay-open");
  12814. std::atomic<bool> connected{false};
  12815. sse.on_open([&connected]() { connected.store(true); });
  12816. sse.set_reconnect_interval(100);
  12817. sse.set_max_reconnect_attempts(1);
  12818. sse.start_async();
  12819. // Wait for connection to establish
  12820. for (int i = 0; i < 20 && !connected.load(); ++i) {
  12821. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  12822. }
  12823. EXPECT_TRUE(connected.load());
  12824. EXPECT_TRUE(sse.is_connected());
  12825. // Signal handler to stop
  12826. handler_running.store(false);
  12827. // Stop SSE client
  12828. sse.stop();
  12829. EXPECT_FALSE(sse.is_connected());
  12830. }
  12831. // Test: SSEClient with custom headers
  12832. TEST_F(SSEIntegrationTest, CustomHeaders) {
  12833. // Setup a server endpoint that checks for custom header
  12834. std::atomic<bool> header_received{false};
  12835. server_->Get("/header-check", [&](const Request &req, Response &res) {
  12836. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  12837. header_received.store(true);
  12838. }
  12839. res.set_chunked_content_provider("text/event-stream",
  12840. [](size_t, DataSink &) { return false; });
  12841. });
  12842. Client client("localhost", get_port());
  12843. Headers headers = {{"X-Custom-Header", "custom-value"}};
  12844. sse::SSEClient sse(client, "/header-check", headers);
  12845. sse.set_max_reconnect_attempts(1);
  12846. sse.start_async();
  12847. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12848. sse.stop();
  12849. EXPECT_TRUE(header_received.load());
  12850. }
  12851. // Test: Reconnect interval configuration
  12852. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  12853. Client client("localhost", get_port());
  12854. sse::SSEClient sse(client, "/events");
  12855. auto &result = sse.set_reconnect_interval(500);
  12856. // Builder pattern should return reference to self
  12857. EXPECT_EQ(&result, &sse);
  12858. }
  12859. // Test: Max reconnect attempts
  12860. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  12861. // Connect to non-existent port to force reconnects
  12862. Client client("localhost", 59998);
  12863. sse::SSEClient sse(client, "/events");
  12864. std::atomic<int> error_count{0};
  12865. sse.on_error([&](Error) { error_count.fetch_add(1); });
  12866. sse.set_reconnect_interval(50);
  12867. sse.set_max_reconnect_attempts(2);
  12868. auto start = std::chrono::steady_clock::now();
  12869. sse.start(); // Blocking call
  12870. auto end = std::chrono::steady_clock::now();
  12871. // Should have stopped after 2 failed attempts
  12872. EXPECT_GE(error_count.load(), 2);
  12873. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  12874. auto duration =
  12875. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  12876. #ifdef _WIN32
  12877. // Windows is much slower for socket connection failures
  12878. EXPECT_LT(duration.count(), 7000);
  12879. #else
  12880. EXPECT_LT(duration.count(), 1000);
  12881. #endif
  12882. }
  12883. // Test: Multi-line data in integration
  12884. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  12885. // Endpoint with multi-line data
  12886. server_->Get("/multiline-data", [](const Request &, Response &res) {
  12887. res.set_chunked_content_provider(
  12888. "text/event-stream", [](size_t offset, DataSink &sink) {
  12889. if (offset == 0) {
  12890. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  12891. sink.write(event.data(), event.size());
  12892. }
  12893. return false;
  12894. });
  12895. });
  12896. Client client("localhost", get_port());
  12897. sse::SSEClient sse(client, "/multiline-data");
  12898. std::string received_data;
  12899. std::mutex data_mutex;
  12900. sse.on_message([&](const sse::SSEMessage &msg) {
  12901. std::lock_guard<std::mutex> lock(data_mutex);
  12902. received_data = msg.data;
  12903. });
  12904. sse.set_reconnect_interval(100);
  12905. sse.set_max_reconnect_attempts(1);
  12906. sse.start_async();
  12907. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12908. sse.stop();
  12909. std::lock_guard<std::mutex> lock(data_mutex);
  12910. EXPECT_EQ(received_data, "line1\nline2\nline3");
  12911. }
  12912. // Test: Auto-reconnect after server disconnection
  12913. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  12914. std::atomic<int> connection_count{0};
  12915. std::atomic<int> message_count{0};
  12916. // Endpoint that sends one event and closes, forcing reconnect
  12917. server_->Get("/reconnect-test",
  12918. [&connection_count](const Request &, Response &res) {
  12919. connection_count.fetch_add(1);
  12920. res.set_chunked_content_provider(
  12921. "text/event-stream", [](size_t offset, DataSink &sink) {
  12922. if (offset == 0) {
  12923. std::string event = "data: hello\n\n";
  12924. sink.write(event.data(), event.size());
  12925. }
  12926. return false; // Close connection after sending
  12927. });
  12928. });
  12929. Client client("localhost", get_port());
  12930. sse::SSEClient sse(client, "/reconnect-test");
  12931. sse.on_message([&message_count](const sse::SSEMessage &) {
  12932. message_count.fetch_add(1);
  12933. });
  12934. sse.set_reconnect_interval(100);
  12935. sse.set_max_reconnect_attempts(3);
  12936. sse.start_async();
  12937. // Wait long enough for multiple reconnects
  12938. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  12939. sse.stop();
  12940. // Should have connected multiple times (initial + reconnects)
  12941. EXPECT_GE(connection_count.load(), 2);
  12942. // Should have received messages from multiple connections
  12943. EXPECT_GE(message_count.load(), 2);
  12944. }
  12945. // Test: Last-Event-ID sent on reconnect
  12946. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  12947. std::atomic<int> connection_count{0};
  12948. std::vector<std::string> received_last_event_ids;
  12949. std::mutex id_mutex;
  12950. // Endpoint that checks Last-Event-ID header and sends event with ID
  12951. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  12952. int conn = connection_count.fetch_add(1);
  12953. // Capture the Last-Event-ID header from each connection
  12954. {
  12955. std::lock_guard<std::mutex> lock(id_mutex);
  12956. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  12957. }
  12958. res.set_chunked_content_provider(
  12959. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  12960. if (offset == 0) {
  12961. std::string event =
  12962. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  12963. sink.write(event.data(), event.size());
  12964. }
  12965. return false;
  12966. });
  12967. });
  12968. Client client("localhost", get_port());
  12969. sse::SSEClient sse(client, "/reconnect-with-id");
  12970. sse.set_reconnect_interval(100);
  12971. sse.set_max_reconnect_attempts(3);
  12972. sse.start_async();
  12973. // Wait for at least 2 connections
  12974. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12975. sse.stop();
  12976. // Verify behavior
  12977. std::lock_guard<std::mutex> lock(id_mutex);
  12978. EXPECT_GE(received_last_event_ids.size(), 2u);
  12979. // First connection should have no Last-Event-ID
  12980. if (!received_last_event_ids.empty()) {
  12981. EXPECT_EQ(received_last_event_ids[0], "");
  12982. }
  12983. // Second connection should have Last-Event-ID from first connection
  12984. if (received_last_event_ids.size() >= 2) {
  12985. EXPECT_EQ(received_last_event_ids[1], "event-0");
  12986. }
  12987. }
  12988. TEST(Issue2318Test, EmptyHostString) {
  12989. {
  12990. httplib::Client cli_empty("", PORT);
  12991. auto res = cli_empty.Get("/");
  12992. ASSERT_FALSE(res);
  12993. EXPECT_EQ(httplib::Error::Connection, res.error());
  12994. }
  12995. {
  12996. httplib::Client cli(" ", PORT);
  12997. auto res = cli.Get("/");
  12998. ASSERT_FALSE(res);
  12999. EXPECT_EQ(httplib::Error::Connection, res.error());
  13000. }
  13001. }
  13002. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13003. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  13004. Server svr;
  13005. // Set a small payload limit (1KB)
  13006. svr.set_payload_max_length(1024);
  13007. svr.Post("/test", [&](const Request &req, Response &res) {
  13008. res.set_content("Body size: " + std::to_string(req.body.size()),
  13009. "text/plain");
  13010. });
  13011. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13012. auto se = detail::scope_exit([&] {
  13013. svr.stop();
  13014. listen_thread.join();
  13015. });
  13016. svr.wait_until_ready();
  13017. // Create data that compresses well but exceeds limit when decompressed
  13018. // 8KB of repeated null bytes compresses to a very small size
  13019. std::string original_data(8 * 1024, '\0');
  13020. // Compress the data using gzip
  13021. std::string compressed_data;
  13022. detail::gzip_compressor compressor;
  13023. compressor.compress(original_data.data(), original_data.size(), true,
  13024. [&](const char *data, size_t size) {
  13025. compressed_data.append(data, size);
  13026. return true;
  13027. });
  13028. // Verify compression worked (compressed should be much smaller)
  13029. ASSERT_LT(compressed_data.size(), original_data.size());
  13030. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  13031. // Send compressed data with Content-Encoding: gzip
  13032. Client cli(HOST, PORT);
  13033. Headers headers = {{"Content-Encoding", "gzip"}};
  13034. auto res =
  13035. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  13036. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  13037. ASSERT_TRUE(res);
  13038. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13039. }
  13040. #endif
  13041. // ============================================================================
  13042. // OpenSSL-Specific Tests
  13043. // ============================================================================
  13044. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13045. X509 *readCertificate(const std::string &strFileName) {
  13046. std::ifstream inStream(strFileName);
  13047. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  13048. std::istreambuf_iterator<char>());
  13049. if (strCertPEM.empty()) return (nullptr);
  13050. BIO *pbCert = BIO_new(BIO_s_mem());
  13051. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  13052. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  13053. BIO_free(pbCert);
  13054. return (pCert);
  13055. }
  13056. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  13057. std::ifstream inStream(strFileName);
  13058. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  13059. std::istreambuf_iterator<char>());
  13060. if (strPrivateKeyPEM.empty()) return (nullptr);
  13061. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  13062. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  13063. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  13064. BIO_free(pbPrivKey);
  13065. return (pPrivateKey);
  13066. }
  13067. TEST(BindServerTest, UpdateCerts) {
  13068. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13069. int port = svr.bind_to_any_port("0.0.0.0");
  13070. ASSERT_TRUE(svr.is_valid());
  13071. ASSERT_TRUE(port > 0);
  13072. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13073. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13074. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13075. ASSERT_TRUE(cert != nullptr);
  13076. ASSERT_TRUE(ca_cert != nullptr);
  13077. ASSERT_TRUE(key != nullptr);
  13078. X509_STORE *cert_store = X509_STORE_new();
  13079. X509_STORE_add_cert(cert_store, ca_cert);
  13080. // svr.update_certs(cert, key, cert_store); // deprecated
  13081. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13082. CLIENT_CA_CERT_FILE);
  13083. ASSERT_TRUE(svr.is_valid());
  13084. svr.stop();
  13085. X509_STORE_free(cert_store);
  13086. X509_free(cert);
  13087. X509_free(ca_cert);
  13088. EVP_PKEY_free(key);
  13089. }
  13090. // Test that SSLServer(X509*, EVP_PKEY*, X509_STORE*) constructor sets
  13091. // client CA list correctly for TLS handshake
  13092. TEST(SSLClientServerTest, X509ConstructorSetsClientCAList) {
  13093. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13094. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13095. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13096. ASSERT_TRUE(cert != nullptr);
  13097. ASSERT_TRUE(ca_cert != nullptr);
  13098. ASSERT_TRUE(key != nullptr);
  13099. X509_STORE *cert_store = X509_STORE_new();
  13100. X509_STORE_add_cert(cert_store, ca_cert);
  13101. // Use X509-based constructor (deprecated but should still work correctly)
  13102. #pragma GCC diagnostic push
  13103. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  13104. SSLServer svr(cert, key, cert_store);
  13105. #pragma GCC diagnostic pop
  13106. ASSERT_TRUE(svr.is_valid());
  13107. // Verify that client CA list is set in SSL_CTX
  13108. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13109. ASSERT_TRUE(ssl_ctx != nullptr);
  13110. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13111. ASSERT_TRUE(ca_list != nullptr);
  13112. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13113. X509_free(cert);
  13114. X509_free(ca_cert);
  13115. EVP_PKEY_free(key);
  13116. }
  13117. // Test that update_certs() updates client CA list correctly
  13118. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  13119. // Start with file-based constructor
  13120. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13121. ASSERT_TRUE(svr.is_valid());
  13122. // Initially no client CA list should be set
  13123. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13124. ASSERT_TRUE(ssl_ctx != nullptr);
  13125. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  13126. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  13127. EXPECT_EQ(0, count_before);
  13128. // Now update with client CA (PEM string)
  13129. std::string cert_pem, key_pem, ca_pem;
  13130. read_file(SERVER_CERT_FILE, cert_pem);
  13131. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13132. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13133. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  13134. ASSERT_TRUE(svr.is_valid());
  13135. // Now client CA list should be set
  13136. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  13137. ASSERT_TRUE(ca_list_after != nullptr);
  13138. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  13139. }
  13140. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  13141. // Test that the file-path SSLServer constructor properly sets the client CA
  13142. // list that is sent to clients during the TLS handshake (CertificateRequest)
  13143. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13144. ASSERT_TRUE(svr.is_valid());
  13145. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13146. ASSERT_TRUE(ssl_ctx != nullptr);
  13147. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13148. ASSERT_TRUE(ca_list != nullptr);
  13149. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13150. }
  13151. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  13152. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  13153. // prepare large data
  13154. std::random_device seed_gen;
  13155. std::mt19937 random(seed_gen());
  13156. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  13157. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  13158. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  13159. // server
  13160. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13161. ASSERT_TRUE(svr.is_valid());
  13162. svr.Post("/binary", [&](const Request &req, Response &res) {
  13163. EXPECT_EQ(large_size_byte, req.body.size());
  13164. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  13165. res.set_content(req.body, "application/octet-stream");
  13166. });
  13167. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  13168. auto se = detail::scope_exit([&] {
  13169. svr.stop();
  13170. listen_thread.join();
  13171. ASSERT_FALSE(svr.is_running());
  13172. });
  13173. svr.wait_until_ready();
  13174. // client POST
  13175. SSLClient cli("localhost", PORT);
  13176. cli.enable_server_certificate_verification(false);
  13177. cli.set_read_timeout(std::chrono::seconds(100));
  13178. cli.set_write_timeout(std::chrono::seconds(100));
  13179. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  13180. large_size_byte, "application/octet-stream");
  13181. // compare
  13182. EXPECT_EQ(StatusCode::OK_200, res->status);
  13183. EXPECT_EQ(large_size_byte, res->body.size());
  13184. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  13185. }
  13186. #endif
  13187. // ============================================================================
  13188. // MbedTLS-Specific Tests
  13189. // ============================================================================
  13190. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  13191. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  13192. using namespace httplib::tls;
  13193. // Track if callback was invoked
  13194. bool callback_invoked = false;
  13195. // The callback receives void* ctx which is actually MbedTlsContext*
  13196. // We can access the mbedtls_ssl_config via the context
  13197. auto setup_callback = [&callback_invoked](void *ctx) {
  13198. callback_invoked = true;
  13199. // Cast to MbedTlsContext* to access the ssl config
  13200. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  13201. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  13202. // Use static variables to hold certificate data (simplified for test)
  13203. static mbedtls_x509_crt own_cert;
  13204. static mbedtls_pk_context own_key;
  13205. static mbedtls_x509_crt ca_chain;
  13206. static bool initialized = false;
  13207. if (!initialized) {
  13208. mbedtls_x509_crt_init(&own_cert);
  13209. mbedtls_pk_init(&own_key);
  13210. mbedtls_x509_crt_init(&ca_chain);
  13211. // Load server certificate
  13212. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  13213. return false;
  13214. }
  13215. // Load server private key
  13216. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  13217. #if MBEDTLS_VERSION_MAJOR >= 3
  13218. ,
  13219. mbedtls_ctr_drbg_random, nullptr
  13220. #endif
  13221. ) != 0) {
  13222. return false;
  13223. }
  13224. // Load CA chain for client verification
  13225. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  13226. return false;
  13227. }
  13228. initialized = true;
  13229. }
  13230. // Configure the SSL config
  13231. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  13232. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  13233. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  13234. // Set minimum TLS version using mbedTLS native API
  13235. #if MBEDTLS_VERSION_MAJOR >= 3
  13236. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  13237. #else
  13238. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  13239. MBEDTLS_SSL_MINOR_VERSION_3);
  13240. #endif
  13241. return true;
  13242. };
  13243. SSLServer svr(setup_callback);
  13244. ASSERT_TRUE(svr.is_valid());
  13245. ASSERT_TRUE(callback_invoked);
  13246. svr.Get("/test", [&](const Request &req, Response &res) {
  13247. res.set_content("test", "text/plain");
  13248. auto cert = req.peer_cert();
  13249. ASSERT_TRUE(static_cast<bool>(cert));
  13250. auto common_name = cert.subject_cn();
  13251. EXPECT_EQ("Common Name", common_name);
  13252. });
  13253. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13254. auto se = detail::scope_exit([&] {
  13255. svr.stop();
  13256. t.join();
  13257. ASSERT_FALSE(svr.is_running());
  13258. });
  13259. svr.wait_until_ready();
  13260. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13261. cli.enable_server_certificate_verification(false);
  13262. cli.set_connection_timeout(30);
  13263. auto res = cli.Get("/test");
  13264. ASSERT_TRUE(res);
  13265. ASSERT_EQ(StatusCode::OK_200, res->status);
  13266. }
  13267. #endif
  13268. // WebSocket Tests
  13269. TEST(WebSocketTest, RSVBitsMustBeZero) {
  13270. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  13271. // defining the meaning of these bits has been negotiated.
  13272. auto make_frame = [](uint8_t first_byte) {
  13273. std::string frame;
  13274. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  13275. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  13276. frame += "Hello";
  13277. return frame;
  13278. };
  13279. // RSV1 set (0x40)
  13280. {
  13281. detail::BufferStream strm;
  13282. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  13283. ws::Opcode opcode;
  13284. std::string payload;
  13285. bool fin;
  13286. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13287. false, 1024));
  13288. }
  13289. // RSV2 set (0x20)
  13290. {
  13291. detail::BufferStream strm;
  13292. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  13293. ws::Opcode opcode;
  13294. std::string payload;
  13295. bool fin;
  13296. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13297. false, 1024));
  13298. }
  13299. // RSV3 set (0x10)
  13300. {
  13301. detail::BufferStream strm;
  13302. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  13303. ws::Opcode opcode;
  13304. std::string payload;
  13305. bool fin;
  13306. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13307. false, 1024));
  13308. }
  13309. // No RSV bits set - should succeed
  13310. {
  13311. detail::BufferStream strm;
  13312. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  13313. ws::Opcode opcode;
  13314. std::string payload;
  13315. bool fin;
  13316. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13317. false, 1024));
  13318. EXPECT_EQ(ws::Opcode::Text, opcode);
  13319. EXPECT_EQ("Hello", payload);
  13320. EXPECT_TRUE(fin);
  13321. }
  13322. }
  13323. TEST(WebSocketTest, ControlFrameValidation) {
  13324. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  13325. // payload length <= 125.
  13326. // Ping with FIN=0 - must be rejected
  13327. {
  13328. detail::BufferStream strm;
  13329. std::string frame;
  13330. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  13331. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13332. strm.write(frame.data(), frame.size());
  13333. ws::Opcode opcode;
  13334. std::string payload;
  13335. bool fin;
  13336. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13337. false, 1024));
  13338. }
  13339. // Close with FIN=0 - must be rejected
  13340. {
  13341. detail::BufferStream strm;
  13342. std::string frame;
  13343. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  13344. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13345. strm.write(frame.data(), frame.size());
  13346. ws::Opcode opcode;
  13347. std::string payload;
  13348. bool fin;
  13349. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13350. false, 1024));
  13351. }
  13352. // Ping with payload_len=126 (extended length) - must be rejected
  13353. {
  13354. detail::BufferStream strm;
  13355. std::string frame;
  13356. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13357. frame += static_cast<char>(126); // payload_len=126 (>125)
  13358. frame += static_cast<char>(0x00); // extended length high byte
  13359. frame += static_cast<char>(126); // extended length low byte
  13360. frame += std::string(126, 'x');
  13361. strm.write(frame.data(), frame.size());
  13362. ws::Opcode opcode;
  13363. std::string payload;
  13364. bool fin;
  13365. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13366. false, 1024));
  13367. }
  13368. // Ping with FIN=1 and payload_len=125 - should succeed
  13369. {
  13370. detail::BufferStream strm;
  13371. std::string frame;
  13372. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13373. frame += static_cast<char>(125); // payload_len=125
  13374. frame += std::string(125, 'x');
  13375. strm.write(frame.data(), frame.size());
  13376. ws::Opcode opcode;
  13377. std::string payload;
  13378. bool fin;
  13379. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13380. false, 1024));
  13381. EXPECT_EQ(ws::Opcode::Ping, opcode);
  13382. EXPECT_EQ(125u, payload.size());
  13383. EXPECT_TRUE(fin);
  13384. }
  13385. }
  13386. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  13387. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  13388. // length MUST be 0.
  13389. // MSB set - must be rejected
  13390. {
  13391. detail::BufferStream strm;
  13392. std::string frame;
  13393. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13394. frame += static_cast<char>(127); // 64-bit extended length
  13395. frame += static_cast<char>(0x80); // MSB set (invalid)
  13396. frame += std::string(7, '\0'); // remaining 7 bytes of length
  13397. strm.write(frame.data(), frame.size());
  13398. ws::Opcode opcode;
  13399. std::string payload;
  13400. bool fin;
  13401. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13402. false, 1024));
  13403. }
  13404. // MSB clear - should pass length parsing (will be rejected by max_len,
  13405. // but that's a different check; use a small length to verify)
  13406. {
  13407. detail::BufferStream strm;
  13408. std::string frame;
  13409. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13410. frame += static_cast<char>(127); // 64-bit extended length
  13411. frame += std::string(7, '\0'); // high bytes = 0
  13412. frame += static_cast<char>(0x03); // length = 3
  13413. frame += "abc";
  13414. strm.write(frame.data(), frame.size());
  13415. ws::Opcode opcode;
  13416. std::string payload;
  13417. bool fin;
  13418. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13419. false, 1024));
  13420. EXPECT_EQ(ws::Opcode::Text, opcode);
  13421. EXPECT_EQ("abc", payload);
  13422. }
  13423. }
  13424. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  13425. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  13426. // Valid UTF-8
  13427. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  13428. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  13429. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  13430. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  13431. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  13432. // Invalid UTF-8
  13433. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  13434. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  13435. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  13436. EXPECT_FALSE(
  13437. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  13438. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  13439. }
  13440. TEST(WebSocketTest, ConnectAndDisconnect) {
  13441. Server svr;
  13442. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  13443. std::string msg;
  13444. while (ws.read(msg)) {}
  13445. });
  13446. auto port = svr.bind_to_any_port(HOST);
  13447. std::thread t([&]() { svr.listen_after_bind(); });
  13448. svr.wait_until_ready();
  13449. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  13450. ASSERT_TRUE(client.connect());
  13451. EXPECT_TRUE(client.is_open());
  13452. client.close();
  13453. EXPECT_FALSE(client.is_open());
  13454. svr.stop();
  13455. t.join();
  13456. }
  13457. TEST(WebSocketTest, ValidURL) {
  13458. ws::WebSocketClient ws1("ws://localhost:8080/path");
  13459. EXPECT_TRUE(ws1.is_valid());
  13460. ws::WebSocketClient ws2("ws://example.com/path");
  13461. EXPECT_TRUE(ws2.is_valid());
  13462. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  13463. EXPECT_TRUE(ws3.is_valid());
  13464. #ifdef CPPHTTPLIB_SSL_ENABLED
  13465. ws::WebSocketClient wss1("wss://example.com/path");
  13466. EXPECT_TRUE(wss1.is_valid());
  13467. ws::WebSocketClient wss2("wss://example.com:443/path");
  13468. EXPECT_TRUE(wss2.is_valid());
  13469. #endif
  13470. }
  13471. TEST(WebSocketTest, InvalidURL) {
  13472. // No scheme
  13473. ws::WebSocketClient ws1("localhost:8080/path");
  13474. EXPECT_FALSE(ws1.is_valid());
  13475. // No path
  13476. ws::WebSocketClient ws2("ws://localhost:8080");
  13477. EXPECT_FALSE(ws2.is_valid());
  13478. // Empty string
  13479. ws::WebSocketClient ws3("");
  13480. EXPECT_FALSE(ws3.is_valid());
  13481. // Missing host
  13482. ws::WebSocketClient ws4("ws://:8080/path");
  13483. EXPECT_FALSE(ws4.is_valid());
  13484. }
  13485. TEST(WebSocketTest, UnsupportedScheme) {
  13486. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13487. ws::WebSocketClient ws1("http://localhost:8080/path");
  13488. EXPECT_FALSE(ws1.is_valid());
  13489. ws::WebSocketClient ws2("https://localhost:8080/path");
  13490. EXPECT_FALSE(ws2.is_valid());
  13491. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  13492. EXPECT_FALSE(ws3.is_valid());
  13493. #else
  13494. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  13495. std::invalid_argument);
  13496. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  13497. std::invalid_argument);
  13498. #endif
  13499. }
  13500. TEST(WebSocketTest, ConnectWhenInvalid) {
  13501. ws::WebSocketClient ws("not a valid url");
  13502. EXPECT_FALSE(ws.is_valid());
  13503. EXPECT_FALSE(ws.connect());
  13504. }
  13505. TEST(WebSocketTest, DefaultPort) {
  13506. ws::WebSocketClient ws1("ws://example.com/path");
  13507. EXPECT_TRUE(ws1.is_valid());
  13508. // ws:// defaults to port 80 (verified by successful parse)
  13509. #ifdef CPPHTTPLIB_SSL_ENABLED
  13510. ws::WebSocketClient ws2("wss://example.com/path");
  13511. EXPECT_TRUE(ws2.is_valid());
  13512. // wss:// defaults to port 443 (verified by successful parse)
  13513. #endif
  13514. }
  13515. TEST(WebSocketTest, IPv6LiteralAddress) {
  13516. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  13517. EXPECT_TRUE(ws1.is_valid());
  13518. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  13519. EXPECT_TRUE(ws2.is_valid());
  13520. }
  13521. TEST(WebSocketTest, ComplexPath) {
  13522. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  13523. EXPECT_TRUE(ws1.is_valid());
  13524. ws::WebSocketClient ws2("ws://localhost:8080/");
  13525. EXPECT_TRUE(ws2.is_valid());
  13526. }
  13527. class WebSocketIntegrationTest : public ::testing::Test {
  13528. protected:
  13529. void SetUp() override {
  13530. server_ = httplib::detail::make_unique<Server>();
  13531. setup_server();
  13532. start_server();
  13533. }
  13534. void TearDown() override {
  13535. server_->stop();
  13536. if (server_thread_.joinable()) { server_thread_.join(); }
  13537. }
  13538. void setup_server() {
  13539. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  13540. std::string msg;
  13541. ws::ReadResult ret;
  13542. while ((ret = ws.read(msg))) {
  13543. if (ret == ws::Binary) {
  13544. ws.send(msg.data(), msg.size());
  13545. } else {
  13546. ws.send(msg);
  13547. }
  13548. }
  13549. });
  13550. server_->WebSocket("/ws-echo-string",
  13551. [](const Request &, ws::WebSocket &ws) {
  13552. std::string msg;
  13553. while (ws.read(msg)) {
  13554. ws.send("echo: " + msg);
  13555. }
  13556. });
  13557. server_->WebSocket(
  13558. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  13559. // Echo back request metadata
  13560. ws.send("path:" + req.path);
  13561. ws.send("header:" + req.get_header_value("X-Test-Header"));
  13562. std::string msg;
  13563. while (ws.read(msg)) {}
  13564. });
  13565. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  13566. std::string msg;
  13567. ws.read(msg); // wait for a message
  13568. ws.close();
  13569. });
  13570. server_->WebSocket("/ws-close-status",
  13571. [](const Request &, ws::WebSocket &ws) {
  13572. std::string msg;
  13573. ws.read(msg); // wait for a message
  13574. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  13575. });
  13576. server_->WebSocket(
  13577. "/ws-subprotocol",
  13578. [](const Request &, ws::WebSocket &ws) {
  13579. std::string msg;
  13580. while (ws.read(msg)) {
  13581. ws.send(msg);
  13582. }
  13583. },
  13584. [](const std::vector<std::string> &protocols) -> std::string {
  13585. for (const auto &p : protocols) {
  13586. if (p == "graphql-ws") { return p; }
  13587. }
  13588. return "";
  13589. });
  13590. }
  13591. void start_server() {
  13592. port_ = server_->bind_to_any_port(HOST);
  13593. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13594. server_->wait_until_ready();
  13595. }
  13596. std::unique_ptr<Server> server_;
  13597. std::thread server_thread_;
  13598. int port_ = 0;
  13599. };
  13600. TEST_F(WebSocketIntegrationTest, TextEcho) {
  13601. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13602. "/ws-echo");
  13603. ASSERT_TRUE(client.connect());
  13604. ASSERT_TRUE(client.is_open());
  13605. ASSERT_TRUE(client.send("Hello WebSocket"));
  13606. std::string msg;
  13607. EXPECT_EQ(ws::Text, client.read(msg));
  13608. EXPECT_EQ("Hello WebSocket", msg);
  13609. client.close();
  13610. }
  13611. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  13612. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13613. "/ws-echo");
  13614. ASSERT_TRUE(client.connect());
  13615. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  13616. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  13617. std::string msg;
  13618. EXPECT_EQ(ws::Binary, client.read(msg));
  13619. EXPECT_EQ(binary_data, msg);
  13620. client.close();
  13621. }
  13622. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  13623. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13624. "/ws-echo");
  13625. ASSERT_TRUE(client.connect());
  13626. for (int i = 0; i < 10; i++) {
  13627. auto text = "message " + std::to_string(i);
  13628. ASSERT_TRUE(client.send(text));
  13629. std::string msg;
  13630. ASSERT_TRUE(client.read(msg));
  13631. EXPECT_EQ(text, msg);
  13632. }
  13633. client.close();
  13634. }
  13635. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  13636. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13637. "/ws-close");
  13638. ASSERT_TRUE(client.connect());
  13639. // Send a message to trigger the server to close
  13640. ASSERT_TRUE(client.send("trigger close"));
  13641. // The server will close, so read should return false
  13642. std::string msg;
  13643. EXPECT_FALSE(client.read(msg));
  13644. EXPECT_FALSE(client.is_open());
  13645. }
  13646. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  13647. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13648. "/ws-echo");
  13649. ASSERT_TRUE(client.connect());
  13650. // 128KB message
  13651. std::string large_data(128 * 1024, 'X');
  13652. ASSERT_TRUE(client.send(large_data));
  13653. std::string msg;
  13654. ASSERT_TRUE(client.read(msg));
  13655. EXPECT_EQ(large_data, msg);
  13656. client.close();
  13657. }
  13658. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  13659. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13660. "/ws-echo");
  13661. ASSERT_TRUE(client.connect());
  13662. const int num_threads = 4;
  13663. std::vector<std::thread> threads;
  13664. std::atomic<int> send_count{0};
  13665. for (int t = 0; t < num_threads; t++) {
  13666. threads.emplace_back([&client, &send_count, t]() {
  13667. for (int i = 0; i < 5; i++) {
  13668. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  13669. if (client.send(text)) { send_count++; }
  13670. }
  13671. });
  13672. }
  13673. for (auto &th : threads) {
  13674. th.join();
  13675. }
  13676. int received = 0;
  13677. std::string msg;
  13678. while (received < send_count.load()) {
  13679. if (!client.read(msg)) { break; }
  13680. received++;
  13681. }
  13682. EXPECT_EQ(send_count.load(), received);
  13683. client.close();
  13684. }
  13685. TEST_F(WebSocketIntegrationTest, ReadString) {
  13686. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13687. "/ws-echo-string");
  13688. ASSERT_TRUE(client.connect());
  13689. ASSERT_TRUE(client.send("hello"));
  13690. std::string msg;
  13691. ASSERT_TRUE(client.read(msg));
  13692. EXPECT_EQ("echo: hello", msg);
  13693. ASSERT_TRUE(client.send("world"));
  13694. ASSERT_TRUE(client.read(msg));
  13695. EXPECT_EQ("echo: world", msg);
  13696. client.close();
  13697. }
  13698. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  13699. Headers headers = {{"X-Test-Header", "test-value"}};
  13700. ws::WebSocketClient client(
  13701. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  13702. ASSERT_TRUE(client.connect());
  13703. std::string msg;
  13704. ASSERT_TRUE(client.read(msg));
  13705. EXPECT_EQ("path:/ws-request-info", msg);
  13706. ASSERT_TRUE(client.read(msg));
  13707. EXPECT_EQ("header:test-value", msg);
  13708. client.close();
  13709. }
  13710. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  13711. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13712. "/ws-echo");
  13713. client.set_read_timeout(1, 0); // 1 second
  13714. ASSERT_TRUE(client.connect());
  13715. // Don't send anything — server echo handler waits for a message,
  13716. // so read() should time out and return false.
  13717. std::string msg;
  13718. EXPECT_FALSE(client.read(msg));
  13719. }
  13720. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  13721. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13722. "/ws-echo");
  13723. client.set_read_timeout(5, 0);
  13724. ASSERT_TRUE(client.connect());
  13725. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  13726. // The server should reject it and close the connection.
  13727. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  13728. client.send(oversized);
  13729. // The server's read() should have failed due to payload limit,
  13730. // so our read() should return false (connection closed).
  13731. std::string msg;
  13732. EXPECT_FALSE(client.read(msg));
  13733. }
  13734. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  13735. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13736. "/ws-echo");
  13737. client.set_read_timeout(10, 0);
  13738. ASSERT_TRUE(client.connect());
  13739. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  13740. // This should succeed.
  13741. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  13742. ASSERT_TRUE(client.send(at_limit));
  13743. std::string msg;
  13744. ASSERT_TRUE(client.read(msg));
  13745. EXPECT_EQ(at_limit.size(), msg.size());
  13746. client.close();
  13747. }
  13748. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  13749. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13750. "/nonexistent");
  13751. EXPECT_FALSE(client.connect());
  13752. EXPECT_FALSE(client.is_open());
  13753. }
  13754. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  13755. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13756. "/ws-echo");
  13757. ASSERT_TRUE(client.connect());
  13758. ASSERT_TRUE(client.send(""));
  13759. std::string msg;
  13760. EXPECT_EQ(ws::Text, client.read(msg));
  13761. EXPECT_EQ("", msg);
  13762. client.close();
  13763. }
  13764. TEST_F(WebSocketIntegrationTest, Reconnect) {
  13765. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13766. "/ws-echo");
  13767. // First connection
  13768. ASSERT_TRUE(client.connect());
  13769. ASSERT_TRUE(client.send("first"));
  13770. std::string msg;
  13771. ASSERT_TRUE(client.read(msg));
  13772. EXPECT_EQ("first", msg);
  13773. client.close();
  13774. EXPECT_FALSE(client.is_open());
  13775. // Reconnect using the same client object
  13776. ASSERT_TRUE(client.connect());
  13777. ASSERT_TRUE(client.is_open());
  13778. ASSERT_TRUE(client.send("second"));
  13779. ASSERT_TRUE(client.read(msg));
  13780. EXPECT_EQ("second", msg);
  13781. client.close();
  13782. }
  13783. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  13784. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13785. "/ws-close-status");
  13786. ASSERT_TRUE(client.connect());
  13787. // Trigger the server to close with GoingAway status
  13788. ASSERT_TRUE(client.send("trigger"));
  13789. // read() should return false after receiving the close frame
  13790. std::string msg;
  13791. EXPECT_FALSE(client.read(msg));
  13792. EXPECT_FALSE(client.is_open());
  13793. }
  13794. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  13795. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13796. "/ws-echo");
  13797. ASSERT_TRUE(client.connect());
  13798. client.close(ws::CloseStatus::GoingAway, "client leaving");
  13799. EXPECT_FALSE(client.is_open());
  13800. }
  13801. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  13802. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  13803. ws::WebSocketClient client(
  13804. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  13805. ASSERT_TRUE(client.connect());
  13806. // Server should have selected graphql-ws
  13807. EXPECT_EQ("graphql-ws", client.subprotocol());
  13808. client.close();
  13809. }
  13810. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  13811. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  13812. ws::WebSocketClient client(
  13813. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  13814. ASSERT_TRUE(client.connect());
  13815. // Server should not have selected any subprotocol
  13816. EXPECT_TRUE(client.subprotocol().empty());
  13817. client.close();
  13818. }
  13819. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  13820. // Connect without requesting any subprotocol
  13821. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13822. "/ws-subprotocol");
  13823. ASSERT_TRUE(client.connect());
  13824. EXPECT_TRUE(client.subprotocol().empty());
  13825. client.close();
  13826. }
  13827. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  13828. Server svr;
  13829. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  13830. if (!req.has_header("Authorization")) {
  13831. res.status = StatusCode::Unauthorized_401;
  13832. res.set_content("Unauthorized", "text/plain");
  13833. return Server::HandlerResponse::Handled;
  13834. }
  13835. return Server::HandlerResponse::Unhandled;
  13836. });
  13837. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  13838. std::string msg;
  13839. while (ws.read(msg)) {
  13840. ws.send(msg);
  13841. }
  13842. });
  13843. auto port = svr.bind_to_any_port("localhost");
  13844. std::thread t([&]() { svr.listen_after_bind(); });
  13845. svr.wait_until_ready();
  13846. // Without Authorization header - should be rejected before upgrade
  13847. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  13848. EXPECT_FALSE(client1.connect());
  13849. // With Authorization header - should succeed
  13850. Headers headers = {{"Authorization", "Bearer token123"}};
  13851. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  13852. headers);
  13853. ASSERT_TRUE(client2.connect());
  13854. ASSERT_TRUE(client2.send("hello"));
  13855. std::string msg;
  13856. ASSERT_TRUE(client2.read(msg));
  13857. EXPECT_EQ("hello", msg);
  13858. client2.close();
  13859. svr.stop();
  13860. t.join();
  13861. }
  13862. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13863. class WebSocketSSLIntegrationTest : public ::testing::Test {
  13864. protected:
  13865. void SetUp() override {
  13866. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  13867. SERVER_PRIVATE_KEY_FILE);
  13868. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  13869. std::string msg;
  13870. ws::ReadResult ret;
  13871. while ((ret = ws.read(msg))) {
  13872. if (ret == ws::Binary) {
  13873. ws.send(msg.data(), msg.size());
  13874. } else {
  13875. ws.send(msg);
  13876. }
  13877. }
  13878. });
  13879. port_ = server_->bind_to_any_port(HOST);
  13880. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13881. server_->wait_until_ready();
  13882. }
  13883. void TearDown() override {
  13884. server_->stop();
  13885. if (server_thread_.joinable()) { server_thread_.join(); }
  13886. }
  13887. std::unique_ptr<SSLServer> server_;
  13888. std::thread server_thread_;
  13889. int port_ = 0;
  13890. };
  13891. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  13892. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  13893. "/ws-echo");
  13894. client.enable_server_certificate_verification(false);
  13895. ASSERT_TRUE(client.connect());
  13896. ASSERT_TRUE(client.is_open());
  13897. ASSERT_TRUE(client.send("Hello WSS"));
  13898. std::string msg;
  13899. EXPECT_EQ(ws::Text, client.read(msg));
  13900. EXPECT_EQ("Hello WSS", msg);
  13901. client.close();
  13902. }
  13903. #endif