test.cc 523 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065
  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(SanitizeFilenameTest, VariousPatterns) {
  344. // Path traversal
  345. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  346. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  347. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  348. // Normal and edge cases
  349. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  350. EXPECT_EQ("filename.txt",
  351. httplib::sanitize_filename("/path/to/filename.txt"));
  352. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  353. EXPECT_EQ("", httplib::sanitize_filename(".."));
  354. EXPECT_EQ("", httplib::sanitize_filename(""));
  355. // Null bytes stripped
  356. EXPECT_EQ("safe.txt",
  357. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  358. // Whitespace-only rejected
  359. EXPECT_EQ("", httplib::sanitize_filename(" "));
  360. }
  361. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  362. string unescapedCharacters = "-_.!~*'()";
  363. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  364. }
  365. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  366. string reservedCharacters = ";,/?:@&=+$";
  367. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  368. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  369. }
  370. TEST(ClientQueryOrder, PreserveOrder) {
  371. // This test reproduces Issue #2259: client may reorder query parameters
  372. // when sending a GET request. The expected behavior is that the client
  373. // preserves the original query string order when the caller supplied it
  374. // as part of the path.
  375. Server svr;
  376. svr.Get("/", [&](const Request &req, Response &res) {
  377. // Echo back the raw target so the test can assert ordering
  378. res.set_content(req.target, "text/plain");
  379. });
  380. std::thread t{[&] { svr.listen(HOST, PORT); }};
  381. auto se = detail::scope_exit([&] {
  382. svr.stop();
  383. t.join();
  384. ASSERT_FALSE(svr.is_running());
  385. });
  386. svr.wait_until_ready();
  387. Client cli(HOST, PORT);
  388. ASSERT_TRUE(cli.is_valid());
  389. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  390. auto res = cli.Get(original);
  391. ASSERT_TRUE(res);
  392. // Expect the echoed target to exactly match the original path (order
  393. // preserved)
  394. EXPECT_EQ(res->body, original);
  395. }
  396. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  397. string chineseCharacters = U8("中国語");
  398. string russianCharacters = U8("дом");
  399. string brazilianCharacters = U8("óculos");
  400. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  401. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  402. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  403. "%D0%B4%D0%BE%D0%BC");
  404. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  405. }
  406. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  407. string unescapedCharacters = "-_.!~*'()";
  408. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  409. }
  410. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  411. string reservedCharacters = ";,/?:@&=+$";
  412. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  413. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  414. }
  415. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  416. string chineseCharacters = U8("中国語");
  417. string russianCharacters = U8("дом");
  418. string brazilianCharacters = U8("óculos");
  419. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  420. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  421. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  422. "%D0%B4%D0%BE%D0%BC");
  423. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  424. }
  425. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  426. // Issue #2082 use case: encoding path component with ampersand
  427. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  428. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  429. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  430. }
  431. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  432. string unescapedCharacters = "-_.!~*'()";
  433. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  434. }
  435. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  436. string reservedCharacters = ";,/?:@&=+$#";
  437. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  438. }
  439. TEST(EncodeUriTest, TestUTF8Characters) {
  440. string chineseCharacters = U8("中国語");
  441. string russianCharacters = U8("дом");
  442. string brazilianCharacters = U8("óculos");
  443. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  444. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  445. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  446. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  447. }
  448. TEST(EncodeUriTest, TestCompleteUri) {
  449. string uri =
  450. "https://example.com/path/to/resource?query=value&param=test#fragment";
  451. EXPECT_EQ(
  452. httplib::encode_uri(uri),
  453. "https://example.com/path/to/resource?query=value&param=test#fragment");
  454. }
  455. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  456. string uri =
  457. "https://example.com/path with spaces/file name.html?q=hello world";
  458. EXPECT_EQ(httplib::encode_uri(uri),
  459. "https://example.com/path%20with%20spaces/"
  460. "file%20name.html?q=hello%20world");
  461. }
  462. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  463. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  464. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  465. }
  466. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  467. string unescapedCharacters = "-_.!~*'()";
  468. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  469. }
  470. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  471. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  472. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  473. string encodedBrazilian = "%C3%B3culos";
  474. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  475. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  476. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  477. }
  478. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  479. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  480. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  481. "Piri Tommy Villiers - on & on");
  482. }
  483. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  484. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  485. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  486. }
  487. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  488. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  489. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  490. }
  491. TEST(DecodeUriTest, TestUTF8Characters) {
  492. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  493. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  494. string encodedBrazilian = "%C3%B3culos";
  495. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  496. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  497. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  498. }
  499. TEST(DecodeUriTest, TestCompleteUri) {
  500. string encodedUri = "https://example.com/path%20with%20spaces/"
  501. "file%20name.html?q=hello%20world";
  502. EXPECT_EQ(
  503. httplib::decode_uri(encodedUri),
  504. "https://example.com/path with spaces/file name.html?q=hello world");
  505. }
  506. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  507. string original =
  508. "https://example.com/path with spaces/file name.html?q=hello world";
  509. string encoded = httplib::encode_uri(original);
  510. string decoded = httplib::decode_uri(encoded);
  511. EXPECT_EQ(decoded, original);
  512. }
  513. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  514. string original = "Piri Tommy Villiers - on & on";
  515. string encoded = httplib::encode_uri_component(original);
  516. string decoded = httplib::decode_uri_component(encoded);
  517. EXPECT_EQ(decoded, original);
  518. }
  519. TEST(TrimTests, TrimStringTests) {
  520. EXPECT_EQ("abc", detail::trim_copy("abc"));
  521. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  522. EXPECT_TRUE(detail::trim_copy("").empty());
  523. }
  524. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  525. // Simple case without quality values
  526. std::vector<std::string> result1;
  527. EXPECT_TRUE(detail::parse_accept_header(
  528. "text/html,application/json,text/plain", result1));
  529. EXPECT_EQ(result1.size(), 3U);
  530. EXPECT_EQ(result1[0], "text/html");
  531. EXPECT_EQ(result1[1], "application/json");
  532. EXPECT_EQ(result1[2], "text/plain");
  533. // With quality values
  534. std::vector<std::string> result2;
  535. EXPECT_TRUE(detail::parse_accept_header(
  536. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  537. EXPECT_EQ(result2.size(), 3U);
  538. EXPECT_EQ(result2[0], "application/json"); // highest q value
  539. EXPECT_EQ(result2[1], "text/html");
  540. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  541. }
  542. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  543. // Mixed with and without quality values
  544. std::vector<std::string> result;
  545. EXPECT_TRUE(detail::parse_accept_header(
  546. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  547. EXPECT_EQ(result.size(), 3U);
  548. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  549. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  550. EXPECT_EQ(result[2], "application/json"); // q=0.5
  551. }
  552. TEST(ParseAcceptHeaderTest, EdgeCases) {
  553. // Empty header
  554. std::vector<std::string> empty_result;
  555. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  556. EXPECT_TRUE(empty_result.empty());
  557. // Single type
  558. std::vector<std::string> single_result;
  559. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  560. EXPECT_EQ(single_result.size(), 1U);
  561. EXPECT_EQ(single_result[0], "application/json");
  562. // Wildcard types
  563. std::vector<std::string> wildcard_result;
  564. EXPECT_TRUE(detail::parse_accept_header(
  565. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  566. EXPECT_EQ(wildcard_result.size(), 3U);
  567. EXPECT_EQ(wildcard_result[0], "application/json");
  568. EXPECT_EQ(wildcard_result[1], "text/*");
  569. EXPECT_EQ(wildcard_result[2], "*/*");
  570. }
  571. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  572. // Common browser Accept header
  573. std::vector<std::string> browser_result;
  574. EXPECT_TRUE(
  575. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  576. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  577. browser_result));
  578. EXPECT_EQ(browser_result.size(), 6U);
  579. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  580. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  581. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  582. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  583. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  584. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  585. // API client header
  586. std::vector<std::string> api_result;
  587. EXPECT_TRUE(detail::parse_accept_header(
  588. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  589. api_result));
  590. EXPECT_EQ(api_result.size(), 3U);
  591. EXPECT_EQ(api_result[0], "application/json");
  592. EXPECT_EQ(api_result[1], "application/xml");
  593. EXPECT_EQ(api_result[2], "text/plain");
  594. }
  595. TEST(ParseAcceptHeaderTest, SpecialCases) {
  596. // Quality value with 3 decimal places
  597. std::vector<std::string> decimal_result;
  598. EXPECT_TRUE(detail::parse_accept_header(
  599. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  600. EXPECT_EQ(decimal_result.size(), 2U);
  601. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  602. EXPECT_EQ(decimal_result[1], "text/html");
  603. // Zero quality (should still be included but with lowest priority)
  604. std::vector<std::string> zero_q_result;
  605. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  606. zero_q_result));
  607. EXPECT_EQ(zero_q_result.size(), 2U);
  608. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  609. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  610. // No spaces around commas
  611. std::vector<std::string> no_space_result;
  612. EXPECT_TRUE(detail::parse_accept_header(
  613. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  614. no_space_result));
  615. EXPECT_EQ(no_space_result.size(), 3U);
  616. EXPECT_EQ(no_space_result[0], "text/html");
  617. EXPECT_EQ(no_space_result[1], "application/json");
  618. EXPECT_EQ(no_space_result[2], "text/plain");
  619. }
  620. TEST(ParseAcceptHeaderTest, InvalidCases) {
  621. std::vector<std::string> result;
  622. // Invalid quality value (> 1.0)
  623. EXPECT_FALSE(
  624. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  625. // Invalid quality value (< 0.0)
  626. EXPECT_FALSE(
  627. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  628. // Invalid quality value (not a number)
  629. EXPECT_FALSE(detail::parse_accept_header(
  630. "text/html;q=invalid,application/json", result));
  631. // Empty quality value
  632. EXPECT_FALSE(
  633. detail::parse_accept_header("text/html;q=,application/json", result));
  634. // Invalid media type format (no slash and not wildcard)
  635. EXPECT_FALSE(
  636. detail::parse_accept_header("invalidtype,application/json", result));
  637. // Empty media type
  638. result.clear();
  639. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  640. // Only commas
  641. result.clear();
  642. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  643. // Valid cases should still work
  644. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  645. EXPECT_EQ(result.size(), 1U);
  646. EXPECT_EQ(result[0], "*/*");
  647. EXPECT_TRUE(detail::parse_accept_header("*", result));
  648. EXPECT_EQ(result.size(), 1U);
  649. EXPECT_EQ(result[0], "*");
  650. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  651. EXPECT_EQ(result.size(), 1U);
  652. EXPECT_EQ(result[0], "text/*");
  653. }
  654. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  655. Server svr;
  656. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  657. EXPECT_EQ(req.accept_content_types.size(), 3U);
  658. EXPECT_EQ(req.accept_content_types[0], "application/json");
  659. EXPECT_EQ(req.accept_content_types[1], "text/html");
  660. EXPECT_EQ(req.accept_content_types[2], "*/*");
  661. res.set_content("ok", "text/plain");
  662. });
  663. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  664. EXPECT_TRUE(false);
  665. res.set_content("bad request", "text/plain");
  666. });
  667. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  668. auto se = detail::scope_exit([&] {
  669. svr.stop();
  670. listen_thread.join();
  671. ASSERT_FALSE(svr.is_running());
  672. });
  673. svr.wait_until_ready();
  674. Client cli("localhost", PORT);
  675. {
  676. auto res =
  677. cli.Get("/accept_ok",
  678. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  679. ASSERT_TRUE(res);
  680. EXPECT_EQ(StatusCode::OK_200, res->status);
  681. }
  682. {
  683. auto res = cli.Get("/accept_bad_request",
  684. {{"Accept", "text/html;q=abc,application/json"}});
  685. ASSERT_TRUE(res);
  686. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  687. }
  688. }
  689. TEST(DivideTest, DivideStringTests) {
  690. auto divide = [](const std::string &str, char d) {
  691. std::string lhs;
  692. std::string rhs;
  693. detail::divide(str, d,
  694. [&](const char *lhs_data, std::size_t lhs_size,
  695. const char *rhs_data, std::size_t rhs_size) {
  696. lhs.assign(lhs_data, lhs_size);
  697. rhs.assign(rhs_data, rhs_size);
  698. });
  699. return std::make_pair(std::move(lhs), std::move(rhs));
  700. };
  701. {
  702. const auto res = divide("", '=');
  703. EXPECT_EQ(res.first, "");
  704. EXPECT_EQ(res.second, "");
  705. }
  706. {
  707. const auto res = divide("=", '=');
  708. EXPECT_EQ(res.first, "");
  709. EXPECT_EQ(res.second, "");
  710. }
  711. {
  712. const auto res = divide(" ", '=');
  713. EXPECT_EQ(res.first, " ");
  714. EXPECT_EQ(res.second, "");
  715. }
  716. {
  717. const auto res = divide("a", '=');
  718. EXPECT_EQ(res.first, "a");
  719. EXPECT_EQ(res.second, "");
  720. }
  721. {
  722. const auto res = divide("a=", '=');
  723. EXPECT_EQ(res.first, "a");
  724. EXPECT_EQ(res.second, "");
  725. }
  726. {
  727. const auto res = divide("=b", '=');
  728. EXPECT_EQ(res.first, "");
  729. EXPECT_EQ(res.second, "b");
  730. }
  731. {
  732. const auto res = divide("a=b", '=');
  733. EXPECT_EQ(res.first, "a");
  734. EXPECT_EQ(res.second, "b");
  735. }
  736. {
  737. const auto res = divide("a=b=", '=');
  738. EXPECT_EQ(res.first, "a");
  739. EXPECT_EQ(res.second, "b=");
  740. }
  741. {
  742. const auto res = divide("a=b=c", '=');
  743. EXPECT_EQ(res.first, "a");
  744. EXPECT_EQ(res.second, "b=c");
  745. }
  746. }
  747. TEST(SplitTest, ParseQueryString) {
  748. string s = "key1=val1&key2=val2&key3=val3";
  749. Params dic;
  750. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  751. [&](const char *b, const char *e) {
  752. string key, val;
  753. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  754. if (key.empty()) {
  755. key.assign(b2, e2);
  756. } else {
  757. val.assign(b2, e2);
  758. }
  759. });
  760. dic.emplace(key, val);
  761. });
  762. EXPECT_EQ("val1", dic.find("key1")->second);
  763. EXPECT_EQ("val2", dic.find("key2")->second);
  764. EXPECT_EQ("val3", dic.find("key3")->second);
  765. }
  766. TEST(SplitTest, ParseInvalidQueryTests) {
  767. {
  768. string s = " ";
  769. Params dict;
  770. detail::parse_query_text(s, dict);
  771. EXPECT_TRUE(dict.empty());
  772. }
  773. {
  774. string s = " = =";
  775. Params dict;
  776. detail::parse_query_text(s, dict);
  777. EXPECT_TRUE(dict.empty());
  778. }
  779. }
  780. TEST(ParseQueryTest, ParseQueryString) {
  781. {
  782. std::string s = "key1=val1&key2=val2&key3=val3";
  783. Params dic;
  784. detail::parse_query_text(s, dic);
  785. EXPECT_EQ("val1", dic.find("key1")->second);
  786. EXPECT_EQ("val2", dic.find("key2")->second);
  787. EXPECT_EQ("val3", dic.find("key3")->second);
  788. }
  789. {
  790. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  791. Params dic;
  792. detail::parse_query_text(s, dic);
  793. EXPECT_EQ("", dic.find("key1")->second);
  794. EXPECT_EQ("val1", dic.find("key2")->second);
  795. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  796. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  797. }
  798. }
  799. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  800. Params dic;
  801. EXPECT_EQ(detail::params_to_query_str(dic), "");
  802. dic.emplace("key1", "val1");
  803. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  804. dic.emplace("key2", "val2");
  805. dic.emplace("key3", "val3");
  806. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  807. }
  808. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  809. string content_type = "multipart/form-data; boundary=something";
  810. string boundary;
  811. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  812. EXPECT_TRUE(ret);
  813. EXPECT_EQ(boundary, "something");
  814. }
  815. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  816. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  817. string boundary;
  818. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  819. EXPECT_TRUE(ret);
  820. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  821. }
  822. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  823. string content_type =
  824. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  825. string boundary;
  826. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  827. EXPECT_TRUE(ret);
  828. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  829. }
  830. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  831. string content_type =
  832. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  833. string boundary;
  834. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  835. EXPECT_TRUE(ret);
  836. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  837. }
  838. TEST(GetHeaderValueTest, DefaultValue) {
  839. Headers headers = {{"Dummy", "Dummy"}};
  840. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  841. EXPECT_STREQ("text/plain", val);
  842. }
  843. TEST(GetHeaderValueTest, DefaultValueInt) {
  844. Headers headers = {{"Dummy", "Dummy"}};
  845. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  846. EXPECT_EQ(100ull, val);
  847. }
  848. TEST(GetHeaderValueTest, RegularValue) {
  849. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  850. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  851. EXPECT_STREQ("text/html", val);
  852. }
  853. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  854. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  855. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  856. EXPECT_STREQ("text/html", val);
  857. }
  858. TEST(GetHeaderValueTest, SetContent) {
  859. Response res;
  860. res.set_content("html", "text/html");
  861. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  862. res.set_content("text", "text/plain");
  863. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  864. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  865. }
  866. TEST(GetHeaderValueTest, RegularValueInt) {
  867. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  868. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  869. EXPECT_EQ(100ull, val);
  870. }
  871. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  872. Headers headers = {{"Content-Length", "x"}};
  873. auto is_invalid_value = false;
  874. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  875. is_invalid_value);
  876. EXPECT_EQ(0ull, val);
  877. EXPECT_TRUE(is_invalid_value);
  878. }
  879. TEST(GetHeaderValueTest, Range) {
  880. {
  881. Headers headers = {make_range_header({{1, -1}})};
  882. auto val = detail::get_header_value(headers, "Range", 0, 0);
  883. EXPECT_STREQ("bytes=1-", val);
  884. }
  885. {
  886. Headers headers = {make_range_header({{-1, 1}})};
  887. auto val = detail::get_header_value(headers, "Range", 0, 0);
  888. EXPECT_STREQ("bytes=-1", val);
  889. }
  890. {
  891. Headers headers = {make_range_header({{1, 10}})};
  892. auto val = detail::get_header_value(headers, "Range", 0, 0);
  893. EXPECT_STREQ("bytes=1-10", val);
  894. }
  895. {
  896. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  897. auto val = detail::get_header_value(headers, "Range", 0, 0);
  898. EXPECT_STREQ("bytes=1-10, 100-", val);
  899. }
  900. {
  901. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  902. auto val = detail::get_header_value(headers, "Range", 0, 0);
  903. EXPECT_STREQ("bytes=1-10, 100-200", val);
  904. }
  905. {
  906. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  907. auto val = detail::get_header_value(headers, "Range", 0, 0);
  908. EXPECT_STREQ("bytes=0-0, -1", val);
  909. }
  910. }
  911. TEST(ParseHeaderValueTest, Range) {
  912. {
  913. Ranges ranges;
  914. auto ret = detail::parse_range_header("bytes=1-", ranges);
  915. EXPECT_TRUE(ret);
  916. EXPECT_EQ(1u, ranges.size());
  917. EXPECT_EQ(1u, ranges[0].first);
  918. EXPECT_EQ(-1, ranges[0].second);
  919. }
  920. {
  921. Ranges ranges;
  922. auto ret = detail::parse_range_header("bytes=-1", ranges);
  923. EXPECT_TRUE(ret);
  924. EXPECT_EQ(1u, ranges.size());
  925. EXPECT_EQ(-1, ranges[0].first);
  926. EXPECT_EQ(1u, ranges[0].second);
  927. }
  928. {
  929. Ranges ranges;
  930. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  931. EXPECT_TRUE(ret);
  932. EXPECT_EQ(1u, ranges.size());
  933. EXPECT_EQ(1u, ranges[0].first);
  934. EXPECT_EQ(10u, ranges[0].second);
  935. }
  936. {
  937. Ranges ranges;
  938. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  939. EXPECT_FALSE(ret);
  940. }
  941. {
  942. Ranges ranges;
  943. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  944. EXPECT_TRUE(ret);
  945. EXPECT_EQ(2u, ranges.size());
  946. EXPECT_EQ(1u, ranges[0].first);
  947. EXPECT_EQ(10u, ranges[0].second);
  948. EXPECT_EQ(100u, ranges[1].first);
  949. EXPECT_EQ(-1, ranges[1].second);
  950. }
  951. {
  952. Ranges ranges;
  953. auto ret =
  954. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  955. EXPECT_TRUE(ret);
  956. EXPECT_EQ(3u, ranges.size());
  957. EXPECT_EQ(1u, ranges[0].first);
  958. EXPECT_EQ(10u, ranges[0].second);
  959. EXPECT_EQ(100u, ranges[1].first);
  960. EXPECT_EQ(200u, ranges[1].second);
  961. EXPECT_EQ(300u, ranges[2].first);
  962. EXPECT_EQ(400u, ranges[2].second);
  963. }
  964. {
  965. Ranges ranges;
  966. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  967. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  968. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  969. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  970. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  971. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  972. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  973. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  974. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  975. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  976. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  977. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  978. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  979. EXPECT_TRUE(ranges.empty());
  980. }
  981. }
  982. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  983. Request req;
  984. req.set_header("Accept-Encoding", "gzip");
  985. Response res;
  986. res.set_header("Content-Type", "text/plain");
  987. auto ret = detail::encoding_type(req, res);
  988. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  989. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  990. #else
  991. EXPECT_TRUE(ret == detail::EncodingType::None);
  992. #endif
  993. }
  994. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  995. Request req;
  996. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  997. Response res;
  998. res.set_header("Content-Type", "text/plain");
  999. auto ret = detail::encoding_type(req, res);
  1000. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1001. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1002. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1003. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1004. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1005. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1006. #else
  1007. EXPECT_TRUE(ret == detail::EncodingType::None);
  1008. #endif
  1009. }
  1010. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1011. Request req;
  1012. req.set_header("Accept-Encoding",
  1013. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1014. Response res;
  1015. res.set_header("Content-Type", "text/plain");
  1016. auto ret = detail::encoding_type(req, res);
  1017. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1018. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1019. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1020. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1021. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1022. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1023. #else
  1024. EXPECT_TRUE(ret == detail::EncodingType::None);
  1025. #endif
  1026. }
  1027. TEST(BufferStreamTest, read) {
  1028. detail::BufferStream strm1;
  1029. Stream &strm = strm1;
  1030. EXPECT_EQ(5, strm.write("hello"));
  1031. char buf[512];
  1032. EXPECT_EQ(2, strm.read(buf, 2));
  1033. EXPECT_EQ('h', buf[0]);
  1034. EXPECT_EQ('e', buf[1]);
  1035. EXPECT_EQ(2, strm.read(buf, 2));
  1036. EXPECT_EQ('l', buf[0]);
  1037. EXPECT_EQ('l', buf[1]);
  1038. EXPECT_EQ(1, strm.read(buf, 1));
  1039. EXPECT_EQ('o', buf[0]);
  1040. EXPECT_EQ(0, strm.read(buf, 1));
  1041. }
  1042. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1043. auto host = "www.httpwatch.com";
  1044. auto ip = hosted_at(host);
  1045. EXPECT_EQ("23.96.13.243", ip);
  1046. std::vector<std::string> addrs;
  1047. hosted_at(host, addrs);
  1048. EXPECT_EQ(1u, addrs.size());
  1049. }
  1050. #if 0 // It depends on each test environment...
  1051. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1052. auto host = "www.youtube.com";
  1053. std::vector<std::string> addrs;
  1054. hosted_at(host, addrs);
  1055. EXPECT_EQ(20u, addrs.size());
  1056. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1057. EXPECT_TRUE(it != addrs.end());
  1058. }
  1059. #endif
  1060. class ChunkedEncodingTest : public ::testing::Test {
  1061. protected:
  1062. ChunkedEncodingTest()
  1063. : cli_(HOST, PORT)
  1064. #ifdef CPPHTTPLIB_SSL_ENABLED
  1065. ,
  1066. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1067. #endif
  1068. {
  1069. cli_.set_connection_timeout(2);
  1070. #ifdef CPPHTTPLIB_SSL_ENABLED
  1071. cli_.enable_server_certificate_verification(false);
  1072. #endif
  1073. }
  1074. virtual void SetUp() {
  1075. read_file("./image.jpg", image_data_);
  1076. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1077. res.set_content("Hello World!", "text/plain");
  1078. });
  1079. svr_.Get(
  1080. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1081. res.set_chunked_content_provider(
  1082. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1083. size_t remaining = image_data_.size() - offset;
  1084. if (remaining == 0) {
  1085. sink.done();
  1086. } else {
  1087. constexpr size_t CHUNK_SIZE = 1024;
  1088. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1089. sink.write(&image_data_[offset], send_size);
  1090. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1091. }
  1092. return true;
  1093. });
  1094. });
  1095. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1096. svr_.wait_until_ready();
  1097. }
  1098. virtual void TearDown() {
  1099. svr_.stop();
  1100. if (!request_threads_.empty()) {
  1101. std::this_thread::sleep_for(std::chrono::seconds(1));
  1102. for (auto &t : request_threads_) {
  1103. t.join();
  1104. }
  1105. }
  1106. t_.join();
  1107. }
  1108. #ifdef CPPHTTPLIB_SSL_ENABLED
  1109. SSLClient cli_;
  1110. SSLServer svr_;
  1111. #else
  1112. Client cli_;
  1113. Server svr_;
  1114. #endif
  1115. thread t_;
  1116. std::vector<thread> request_threads_;
  1117. std::string image_data_;
  1118. };
  1119. TEST_F(ChunkedEncodingTest, NormalGet) {
  1120. auto res = cli_.Get("/chunked");
  1121. ASSERT_TRUE(res);
  1122. std::string out;
  1123. read_file("./image.jpg", out);
  1124. EXPECT_EQ(StatusCode::OK_200, res->status);
  1125. EXPECT_EQ(out, res->body);
  1126. }
  1127. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1128. std::string body;
  1129. auto res = cli_.Get("/chunked", [&](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_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1140. std::string body;
  1141. auto res = cli_.Get(
  1142. "/chunked",
  1143. [&](const Response &response) {
  1144. EXPECT_EQ(StatusCode::OK_200, response.status);
  1145. return true;
  1146. },
  1147. [&](const char *data, size_t data_length) {
  1148. body.append(data, data_length);
  1149. return true;
  1150. });
  1151. ASSERT_TRUE(res);
  1152. std::string out;
  1153. read_file("./image.jpg", out);
  1154. EXPECT_EQ(StatusCode::OK_200, res->status);
  1155. EXPECT_EQ(out, body);
  1156. }
  1157. TEST(RangeTest, FromHTTPBin_Online) {
  1158. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1159. auto host = "httpcan.org";
  1160. auto path = std::string{"/range/32"};
  1161. #else
  1162. auto host = "nghttp2.org";
  1163. auto path = std::string{"/httpbin/range/32"};
  1164. #endif
  1165. #ifdef CPPHTTPLIB_SSL_ENABLED
  1166. auto port = 443;
  1167. SSLClient cli(host, port);
  1168. #else
  1169. auto port = 80;
  1170. Client cli(host, port);
  1171. #endif
  1172. cli.set_connection_timeout(5);
  1173. {
  1174. auto res = cli.Get(path);
  1175. ASSERT_TRUE(res);
  1176. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1177. EXPECT_EQ(StatusCode::OK_200, res->status);
  1178. }
  1179. {
  1180. Headers headers = {make_range_header({{1, -1}})};
  1181. auto res = cli.Get(path, headers);
  1182. ASSERT_TRUE(res);
  1183. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1184. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1185. }
  1186. {
  1187. Headers headers = {make_range_header({{1, 10}})};
  1188. auto res = cli.Get(path, headers);
  1189. ASSERT_TRUE(res);
  1190. EXPECT_EQ("bcdefghijk", res->body);
  1191. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1192. }
  1193. {
  1194. Headers headers = {make_range_header({{0, 31}})};
  1195. auto res = cli.Get(path, headers);
  1196. ASSERT_TRUE(res);
  1197. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1198. EXPECT_EQ(StatusCode::OK_200, res->status);
  1199. }
  1200. {
  1201. Headers headers = {make_range_header({{0, -1}})};
  1202. auto res = cli.Get(path, headers);
  1203. ASSERT_TRUE(res);
  1204. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1205. EXPECT_EQ(StatusCode::OK_200, res->status);
  1206. }
  1207. {
  1208. Headers headers = {make_range_header({{0, 32}})};
  1209. auto res = cli.Get(path, headers);
  1210. ASSERT_TRUE(res);
  1211. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1212. }
  1213. }
  1214. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1215. auto host = "unresolvableaddress.local";
  1216. auto path = std::string{"/"};
  1217. #ifdef CPPHTTPLIB_SSL_ENABLED
  1218. auto port = 443;
  1219. SSLClient cli(host, port);
  1220. #else
  1221. auto port = 80;
  1222. Client cli(host, port);
  1223. #endif
  1224. cli.set_connection_timeout(1);
  1225. {
  1226. auto res = cli.Get(path);
  1227. ASSERT_FALSE(res);
  1228. }
  1229. std::this_thread::sleep_for(std::chrono::seconds(8));
  1230. }
  1231. TEST(ConnectionErrorTest, InvalidHost) {
  1232. auto host = "-abcde.com";
  1233. #ifdef CPPHTTPLIB_SSL_ENABLED
  1234. auto port = 443;
  1235. SSLClient cli(host, port);
  1236. #else
  1237. auto port = 80;
  1238. Client cli(host, port);
  1239. #endif
  1240. cli.set_connection_timeout(std::chrono::seconds(2));
  1241. auto res = cli.Get("/");
  1242. ASSERT_TRUE(!res);
  1243. EXPECT_EQ(Error::Connection, res.error());
  1244. }
  1245. TEST(ConnectionErrorTest, InvalidHost2) {
  1246. auto host = "httpcan.org/";
  1247. #ifdef CPPHTTPLIB_SSL_ENABLED
  1248. SSLClient cli(host);
  1249. #else
  1250. Client cli(host);
  1251. #endif
  1252. cli.set_connection_timeout(std::chrono::seconds(2));
  1253. auto res = cli.Get("/");
  1254. ASSERT_TRUE(!res);
  1255. EXPECT_EQ(Error::Connection, res.error());
  1256. }
  1257. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1258. auto host = "httpcan.org/";
  1259. #ifdef CPPHTTPLIB_SSL_ENABLED
  1260. SSLClient cli(host);
  1261. #else
  1262. Client cli(host);
  1263. #endif
  1264. cli.set_connection_timeout(std::chrono::seconds(2));
  1265. auto res = cli.Get("/");
  1266. ASSERT_TRUE(!res);
  1267. stringstream s;
  1268. s << "error code: " << res.error();
  1269. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1270. }
  1271. TEST(ConnectionErrorTest, InvalidPort) {
  1272. auto host = "localhost";
  1273. auto port = 44380;
  1274. #ifdef CPPHTTPLIB_SSL_ENABLED
  1275. SSLClient cli(host, port);
  1276. #else
  1277. Client cli(host, port);
  1278. #endif
  1279. cli.set_connection_timeout(std::chrono::seconds(2));
  1280. auto res = cli.Get("/");
  1281. ASSERT_TRUE(!res);
  1282. EXPECT_TRUE(Error::Connection == res.error() ||
  1283. Error::ConnectionTimeout == res.error());
  1284. }
  1285. TEST(ConnectionErrorTest, Timeout_Online) {
  1286. auto host = "google.com";
  1287. #ifdef CPPHTTPLIB_SSL_ENABLED
  1288. auto port = 44380;
  1289. SSLClient cli(host, port);
  1290. #else
  1291. auto port = 8080;
  1292. Client cli(host, port);
  1293. #endif
  1294. cli.set_connection_timeout(std::chrono::seconds(2));
  1295. // only probe one address type so that the error reason
  1296. // correlates to the timed-out IPv4, not the unsupported
  1297. // IPv6 connection attempt
  1298. cli.set_address_family(AF_INET);
  1299. auto res = cli.Get("/");
  1300. ASSERT_TRUE(!res);
  1301. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1302. }
  1303. TEST(CancelTest, NoCancel_Online) {
  1304. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1305. auto host = "httpcan.org";
  1306. auto path = std::string{"/range/32"};
  1307. #else
  1308. auto host = "nghttp2.org";
  1309. auto path = std::string{"/httpbin/range/32"};
  1310. #endif
  1311. #ifdef CPPHTTPLIB_SSL_ENABLED
  1312. auto port = 443;
  1313. SSLClient cli(host, port);
  1314. #else
  1315. auto port = 80;
  1316. Client cli(host, port);
  1317. #endif
  1318. cli.set_connection_timeout(std::chrono::seconds(5));
  1319. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1320. ASSERT_TRUE(res);
  1321. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1322. EXPECT_EQ(StatusCode::OK_200, res->status);
  1323. }
  1324. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1325. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1326. auto host = "httpcan.org";
  1327. auto path = std::string{"/range/32"};
  1328. #else
  1329. auto host = "nghttp2.org";
  1330. auto path = std::string{"/httpbin/range/32"};
  1331. #endif
  1332. #ifdef CPPHTTPLIB_SSL_ENABLED
  1333. auto port = 443;
  1334. SSLClient cli(host, port);
  1335. #else
  1336. auto port = 80;
  1337. Client cli(host, port);
  1338. #endif
  1339. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1340. cli.set_connection_timeout(std::chrono::seconds(5));
  1341. ASSERT_TRUE(!res);
  1342. EXPECT_EQ(Error::Canceled, res.error());
  1343. }
  1344. TEST(CancelTest, WithCancelLargePayload_Online) {
  1345. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1346. auto host = "httpcan.org";
  1347. auto path = std::string{"/range/65536"};
  1348. #else
  1349. auto host = "nghttp2.org";
  1350. auto path = std::string{"/httpbin/range/65536"};
  1351. #endif
  1352. #ifdef CPPHTTPLIB_SSL_ENABLED
  1353. auto port = 443;
  1354. SSLClient cli(host, port);
  1355. #else
  1356. auto port = 80;
  1357. Client cli(host, port);
  1358. #endif
  1359. cli.set_connection_timeout(std::chrono::seconds(5));
  1360. uint32_t count = 0;
  1361. auto res =
  1362. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1363. ASSERT_TRUE(!res);
  1364. EXPECT_EQ(Error::Canceled, res.error());
  1365. }
  1366. TEST(CancelTest, NoCancelPost) {
  1367. Server svr;
  1368. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1369. res.set_content("Hello World!", "text/plain");
  1370. });
  1371. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1372. auto se = detail::scope_exit([&] {
  1373. svr.stop();
  1374. thread.join();
  1375. ASSERT_FALSE(svr.is_running());
  1376. });
  1377. svr.wait_until_ready();
  1378. Client cli(HOST, PORT);
  1379. cli.set_connection_timeout(std::chrono::seconds(5));
  1380. auto res =
  1381. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1382. "application/json", [](uint64_t, uint64_t) { return true; });
  1383. ASSERT_TRUE(res);
  1384. EXPECT_EQ("Hello World!", res->body);
  1385. EXPECT_EQ(StatusCode::OK_200, res->status);
  1386. }
  1387. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1388. Server svr;
  1389. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1390. res.set_content("Hello World!", "text/plain");
  1391. });
  1392. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1393. auto se = detail::scope_exit([&] {
  1394. svr.stop();
  1395. thread.join();
  1396. ASSERT_FALSE(svr.is_running());
  1397. });
  1398. svr.wait_until_ready();
  1399. Client cli(HOST, PORT);
  1400. cli.set_connection_timeout(std::chrono::seconds(5));
  1401. auto res =
  1402. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1403. "application/json", [](uint64_t, uint64_t) { return false; });
  1404. ASSERT_TRUE(!res);
  1405. EXPECT_EQ(Error::Canceled, res.error());
  1406. }
  1407. TEST(CancelTest, WithCancelLargePayloadPost) {
  1408. Server svr;
  1409. svr.set_payload_max_length(200 * 1024 * 1024);
  1410. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1411. res.set_content(LARGE_DATA, "text/plain");
  1412. });
  1413. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1414. auto se = detail::scope_exit([&] {
  1415. svr.stop();
  1416. thread.join();
  1417. ASSERT_FALSE(svr.is_running());
  1418. });
  1419. svr.wait_until_ready();
  1420. Client cli(HOST, PORT);
  1421. cli.set_payload_max_length(200 * 1024 * 1024);
  1422. cli.set_connection_timeout(std::chrono::seconds(5));
  1423. auto res =
  1424. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1425. "application/json", [](uint64_t, uint64_t) { return false; });
  1426. ASSERT_TRUE(!res);
  1427. EXPECT_EQ(Error::Canceled, res.error());
  1428. }
  1429. TEST(CancelTest, NoCancelPut) {
  1430. Server svr;
  1431. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1432. res.set_content("Hello World!", "text/plain");
  1433. });
  1434. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1435. auto se = detail::scope_exit([&] {
  1436. svr.stop();
  1437. thread.join();
  1438. ASSERT_FALSE(svr.is_running());
  1439. });
  1440. svr.wait_until_ready();
  1441. Client cli(HOST, PORT);
  1442. cli.set_connection_timeout(std::chrono::seconds(5));
  1443. auto res =
  1444. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1445. "application/json", [](uint64_t, uint64_t) { return true; });
  1446. ASSERT_TRUE(res);
  1447. EXPECT_EQ("Hello World!", res->body);
  1448. EXPECT_EQ(StatusCode::OK_200, res->status);
  1449. }
  1450. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1451. Server svr;
  1452. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1453. res.set_content("Hello World!", "text/plain");
  1454. });
  1455. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1456. auto se = detail::scope_exit([&] {
  1457. svr.stop();
  1458. thread.join();
  1459. ASSERT_FALSE(svr.is_running());
  1460. });
  1461. svr.wait_until_ready();
  1462. Client cli(HOST, PORT);
  1463. cli.set_connection_timeout(std::chrono::seconds(5));
  1464. auto res =
  1465. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1466. "application/json", [](uint64_t, uint64_t) { return false; });
  1467. ASSERT_TRUE(!res);
  1468. EXPECT_EQ(Error::Canceled, res.error());
  1469. }
  1470. TEST(CancelTest, WithCancelLargePayloadPut) {
  1471. Server svr;
  1472. svr.set_payload_max_length(200 * 1024 * 1024);
  1473. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1474. res.set_content(LARGE_DATA, "text/plain");
  1475. });
  1476. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1477. auto se = detail::scope_exit([&] {
  1478. svr.stop();
  1479. thread.join();
  1480. ASSERT_FALSE(svr.is_running());
  1481. });
  1482. svr.wait_until_ready();
  1483. Client cli(HOST, PORT);
  1484. cli.set_payload_max_length(200 * 1024 * 1024);
  1485. cli.set_connection_timeout(std::chrono::seconds(5));
  1486. auto res =
  1487. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1488. "application/json", [](uint64_t, uint64_t) { return false; });
  1489. ASSERT_TRUE(!res);
  1490. EXPECT_EQ(Error::Canceled, res.error());
  1491. }
  1492. TEST(CancelTest, NoCancelPatch) {
  1493. Server svr;
  1494. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1495. res.set_content("Hello World!", "text/plain");
  1496. });
  1497. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1498. auto se = detail::scope_exit([&] {
  1499. svr.stop();
  1500. thread.join();
  1501. ASSERT_FALSE(svr.is_running());
  1502. });
  1503. svr.wait_until_ready();
  1504. Client cli(HOST, PORT);
  1505. cli.set_connection_timeout(std::chrono::seconds(5));
  1506. auto res =
  1507. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1508. "application/json", [](uint64_t, uint64_t) { return true; });
  1509. ASSERT_TRUE(res);
  1510. EXPECT_EQ("Hello World!", res->body);
  1511. EXPECT_EQ(StatusCode::OK_200, res->status);
  1512. }
  1513. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1514. Server svr;
  1515. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1516. res.set_content("Hello World!", "text/plain");
  1517. });
  1518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1519. auto se = detail::scope_exit([&] {
  1520. svr.stop();
  1521. thread.join();
  1522. ASSERT_FALSE(svr.is_running());
  1523. });
  1524. svr.wait_until_ready();
  1525. Client cli(HOST, PORT);
  1526. cli.set_connection_timeout(std::chrono::seconds(5));
  1527. auto res =
  1528. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1529. "application/json", [](uint64_t, uint64_t) { return false; });
  1530. ASSERT_TRUE(!res);
  1531. EXPECT_EQ(Error::Canceled, res.error());
  1532. }
  1533. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1534. Server svr;
  1535. svr.set_payload_max_length(200 * 1024 * 1024);
  1536. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1537. res.set_content(LARGE_DATA, "text/plain");
  1538. });
  1539. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1540. auto se = detail::scope_exit([&] {
  1541. svr.stop();
  1542. thread.join();
  1543. ASSERT_FALSE(svr.is_running());
  1544. });
  1545. svr.wait_until_ready();
  1546. Client cli(HOST, PORT);
  1547. cli.set_payload_max_length(200 * 1024 * 1024);
  1548. cli.set_connection_timeout(std::chrono::seconds(5));
  1549. auto res =
  1550. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1551. "application/json", [](uint64_t, uint64_t) { return false; });
  1552. ASSERT_TRUE(!res);
  1553. EXPECT_EQ(Error::Canceled, res.error());
  1554. }
  1555. TEST(CancelTest, NoCancelDelete) {
  1556. Server svr;
  1557. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1558. res.set_content("Hello World!", "text/plain");
  1559. });
  1560. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1561. auto se = detail::scope_exit([&] {
  1562. svr.stop();
  1563. thread.join();
  1564. ASSERT_FALSE(svr.is_running());
  1565. });
  1566. svr.wait_until_ready();
  1567. Client cli(HOST, PORT);
  1568. cli.set_connection_timeout(std::chrono::seconds(5));
  1569. auto res =
  1570. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1571. "application/json", [](uint64_t, uint64_t) { return true; });
  1572. ASSERT_TRUE(res);
  1573. EXPECT_EQ("Hello World!", res->body);
  1574. EXPECT_EQ(StatusCode::OK_200, res->status);
  1575. }
  1576. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1577. Server svr;
  1578. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1579. res.set_content("Hello World!", "text/plain");
  1580. });
  1581. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1582. auto se = detail::scope_exit([&] {
  1583. svr.stop();
  1584. thread.join();
  1585. ASSERT_FALSE(svr.is_running());
  1586. });
  1587. svr.wait_until_ready();
  1588. Client cli(HOST, PORT);
  1589. cli.set_connection_timeout(std::chrono::seconds(5));
  1590. auto res =
  1591. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1592. "application/json", [](uint64_t, uint64_t) { return false; });
  1593. ASSERT_TRUE(!res);
  1594. EXPECT_EQ(Error::Canceled, res.error());
  1595. }
  1596. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1597. Server svr;
  1598. svr.set_payload_max_length(200 * 1024 * 1024);
  1599. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1600. res.set_content(LARGE_DATA, "text/plain");
  1601. });
  1602. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1603. auto se = detail::scope_exit([&] {
  1604. svr.stop();
  1605. thread.join();
  1606. ASSERT_FALSE(svr.is_running());
  1607. });
  1608. svr.wait_until_ready();
  1609. Client cli(HOST, PORT);
  1610. cli.set_payload_max_length(200 * 1024 * 1024);
  1611. cli.set_connection_timeout(std::chrono::seconds(5));
  1612. auto res =
  1613. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1614. "application/json", [](uint64_t, uint64_t) { return false; });
  1615. ASSERT_TRUE(!res);
  1616. EXPECT_EQ(Error::Canceled, res.error());
  1617. }
  1618. static std::string remove_whitespace(const std::string &input) {
  1619. std::string output;
  1620. output.reserve(input.size());
  1621. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1622. [](unsigned char c) { return !std::isspace(c); });
  1623. return output;
  1624. }
  1625. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1626. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1627. auto host = "httpcan.org";
  1628. auto path = std::string{"/basic-auth/hello/world"};
  1629. #else
  1630. auto host = "nghttp2.org";
  1631. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1632. #endif
  1633. #ifdef CPPHTTPLIB_SSL_ENABLED
  1634. auto port = 443;
  1635. SSLClient cli(host, port);
  1636. #else
  1637. auto port = 80;
  1638. Client cli(host, port);
  1639. #endif
  1640. {
  1641. auto res = cli.Get(path);
  1642. ASSERT_TRUE(res);
  1643. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1644. }
  1645. {
  1646. auto res =
  1647. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1648. ASSERT_TRUE(res);
  1649. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1650. remove_whitespace(res->body));
  1651. EXPECT_EQ(StatusCode::OK_200, res->status);
  1652. }
  1653. {
  1654. cli.set_basic_auth("hello", "world");
  1655. auto res = cli.Get(path);
  1656. ASSERT_TRUE(res);
  1657. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1658. remove_whitespace(res->body));
  1659. EXPECT_EQ(StatusCode::OK_200, res->status);
  1660. }
  1661. {
  1662. cli.set_basic_auth("hello", "bad");
  1663. auto res = cli.Get(path);
  1664. ASSERT_TRUE(res);
  1665. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1666. }
  1667. {
  1668. cli.set_basic_auth("bad", "world");
  1669. auto res = cli.Get(path);
  1670. ASSERT_TRUE(res);
  1671. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1672. }
  1673. }
  1674. #ifdef CPPHTTPLIB_SSL_ENABLED
  1675. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1676. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1677. auto host = "httpcan.org";
  1678. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1679. auto paths = std::vector<std::string>{
  1680. "/digest-auth/auth/hello/world/MD5",
  1681. "/digest-auth/auth/hello/world/SHA-256",
  1682. "/digest-auth/auth/hello/world/SHA-512",
  1683. };
  1684. #else
  1685. auto host = "nghttp2.org";
  1686. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1687. auto paths = std::vector<std::string>{
  1688. "/httpbin/digest-auth/auth/hello/world/MD5",
  1689. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1690. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1691. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1692. };
  1693. #endif
  1694. auto port = 443;
  1695. SSLClient cli(host, port);
  1696. {
  1697. auto res = cli.Get(unauth_path);
  1698. ASSERT_TRUE(res);
  1699. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1700. }
  1701. {
  1702. cli.set_digest_auth("hello", "world");
  1703. for (const auto &path : paths) {
  1704. auto res = cli.Get(path.c_str());
  1705. ASSERT_TRUE(res);
  1706. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1707. std::string algo(path.substr(path.rfind('/') + 1));
  1708. EXPECT_EQ(
  1709. remove_whitespace("{\"algorithm\":\"" + algo +
  1710. "\",\"authenticated\":true,\"user\":\"hello\"}\n"),
  1711. remove_whitespace(res->body));
  1712. #else
  1713. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1714. remove_whitespace(res->body));
  1715. #endif
  1716. EXPECT_EQ(StatusCode::OK_200, res->status);
  1717. }
  1718. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1719. cli.set_digest_auth("hello", "bad");
  1720. for (const auto &path : paths) {
  1721. auto res = cli.Get(path.c_str());
  1722. ASSERT_TRUE(res);
  1723. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1724. }
  1725. #endif
  1726. }
  1727. }
  1728. #endif
  1729. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1730. auto host = "google.com";
  1731. auto another_host = "example.com";
  1732. auto wrong_ip = "0.0.0.0";
  1733. #ifdef CPPHTTPLIB_SSL_ENABLED
  1734. SSLClient cli(host);
  1735. #else
  1736. Client cli(host);
  1737. #endif
  1738. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1739. auto res = cli.Get("/");
  1740. ASSERT_TRUE(res);
  1741. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1742. }
  1743. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1744. auto host = "google.com";
  1745. auto wrong_ip = "0.0.0.0";
  1746. #ifdef CPPHTTPLIB_SSL_ENABLED
  1747. SSLClient cli(host);
  1748. #else
  1749. Client cli(host);
  1750. #endif
  1751. cli.set_hostname_addr_map({{host, wrong_ip}});
  1752. auto res = cli.Get("/");
  1753. ASSERT_TRUE(!res);
  1754. EXPECT_EQ(Error::Connection, res.error());
  1755. }
  1756. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1757. auto host = "nghttp2.org";
  1758. #ifdef CPPHTTPLIB_SSL_ENABLED
  1759. SSLClient cli(host);
  1760. #else
  1761. Client cli(host);
  1762. #endif
  1763. cli.set_follow_location(true);
  1764. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1765. ASSERT_TRUE(res);
  1766. EXPECT_EQ(StatusCode::OK_200, res->status);
  1767. }
  1768. TEST(RedirectTest, Redirect_Online) {
  1769. auto host = "nghttp2.org";
  1770. #ifdef CPPHTTPLIB_SSL_ENABLED
  1771. SSLClient cli(host);
  1772. #else
  1773. Client cli(host);
  1774. #endif
  1775. cli.set_follow_location(true);
  1776. auto res = cli.Get("/httpbin/redirect/3");
  1777. ASSERT_TRUE(res);
  1778. EXPECT_EQ(StatusCode::OK_200, res->status);
  1779. }
  1780. TEST(RelativeRedirectTest, Redirect_Online) {
  1781. auto host = "nghttp2.org";
  1782. #ifdef CPPHTTPLIB_SSL_ENABLED
  1783. SSLClient cli(host);
  1784. #else
  1785. Client cli(host);
  1786. #endif
  1787. cli.set_follow_location(true);
  1788. auto res = cli.Get("/httpbin/relative-redirect/3");
  1789. ASSERT_TRUE(res);
  1790. EXPECT_EQ(StatusCode::OK_200, res->status);
  1791. }
  1792. TEST(TooManyRedirectTest, Redirect_Online) {
  1793. auto host = "nghttp2.org";
  1794. #ifdef CPPHTTPLIB_SSL_ENABLED
  1795. SSLClient cli(host);
  1796. #else
  1797. Client cli(host);
  1798. #endif
  1799. cli.set_follow_location(true);
  1800. auto res = cli.Get("/httpbin/redirect/21");
  1801. ASSERT_TRUE(!res);
  1802. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1803. }
  1804. #ifdef CPPHTTPLIB_SSL_ENABLED
  1805. TEST(YahooRedirectTest, Redirect_Online) {
  1806. Client cli("yahoo.com");
  1807. auto res = cli.Get("/");
  1808. ASSERT_TRUE(res);
  1809. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1810. cli.set_follow_location(true);
  1811. res = cli.Get("/");
  1812. ASSERT_TRUE(res);
  1813. EXPECT_EQ(StatusCode::OK_200, res->status);
  1814. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1815. }
  1816. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1817. #define REDIR_HOST "httpbingo.org"
  1818. #define REDIR_PATH "/redirect-to"
  1819. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1820. SSLClient cli(REDIR_HOST);
  1821. cli.set_follow_location(true);
  1822. auto res =
  1823. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1824. ASSERT_TRUE(res);
  1825. EXPECT_EQ(StatusCode::OK_200, res->status);
  1826. }
  1827. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1828. SSLClient cli(REDIR_HOST);
  1829. cli.set_follow_location(true);
  1830. Params params;
  1831. params.emplace("url", "http://example.com");
  1832. params.emplace("status_code", "302");
  1833. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1834. ASSERT_TRUE(res);
  1835. EXPECT_EQ(StatusCode::OK_200, res->status);
  1836. }
  1837. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1838. SSLClient cli(REDIR_HOST);
  1839. cli.set_follow_location(true);
  1840. Params params;
  1841. params.emplace("url", "http://example.com");
  1842. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1843. ASSERT_TRUE(res);
  1844. EXPECT_EQ(StatusCode::OK_200, res->status);
  1845. }
  1846. TEST(UrlWithSpace, Redirect_Online) {
  1847. SSLClient cli("edge.forgecdn.net");
  1848. cli.set_follow_location(true);
  1849. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1850. ASSERT_TRUE(res);
  1851. EXPECT_EQ(StatusCode::OK_200, res->status);
  1852. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1853. }
  1854. #endif
  1855. #if !defined(_WIN32) && !defined(_WIN64)
  1856. TEST(ReceiveSignals, Signal) {
  1857. auto setupSignalHandlers = []() {
  1858. struct sigaction act;
  1859. sigemptyset(&act.sa_mask);
  1860. act.sa_flags = SA_SIGINFO;
  1861. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1862. switch (sig) {
  1863. case SIGINT:
  1864. default: break;
  1865. }
  1866. };
  1867. ::sigaction(SIGINT, &act, nullptr);
  1868. };
  1869. Server svr;
  1870. int port = 0;
  1871. auto thread = std::thread([&]() {
  1872. setupSignalHandlers();
  1873. port = svr.bind_to_any_port(HOST);
  1874. svr.listen_after_bind();
  1875. });
  1876. auto se = detail::scope_exit([&] {
  1877. svr.stop();
  1878. thread.join();
  1879. ASSERT_FALSE(svr.is_running());
  1880. });
  1881. svr.wait_until_ready();
  1882. ASSERT_TRUE(svr.is_running());
  1883. pthread_kill(thread.native_handle(), SIGINT);
  1884. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1885. ASSERT_TRUE(svr.is_running());
  1886. }
  1887. #endif
  1888. TEST(RedirectToDifferentPort, Redirect) {
  1889. Server svr1;
  1890. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1891. res.set_content("Hello World!", "text/plain");
  1892. });
  1893. int svr1_port = 0;
  1894. auto thread1 = std::thread([&]() {
  1895. svr1_port = svr1.bind_to_any_port(HOST);
  1896. svr1.listen_after_bind();
  1897. });
  1898. Server svr2;
  1899. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1900. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1901. });
  1902. int svr2_port = 0;
  1903. auto thread2 = std::thread([&]() {
  1904. svr2_port = svr2.bind_to_any_port(HOST);
  1905. svr2.listen_after_bind();
  1906. });
  1907. auto se = detail::scope_exit([&] {
  1908. svr2.stop();
  1909. thread2.join();
  1910. svr1.stop();
  1911. thread1.join();
  1912. ASSERT_FALSE(svr2.is_running());
  1913. ASSERT_FALSE(svr1.is_running());
  1914. });
  1915. svr1.wait_until_ready();
  1916. svr2.wait_until_ready();
  1917. Client cli("localhost", svr2_port);
  1918. cli.set_follow_location(true);
  1919. auto res = cli.Get("/2");
  1920. ASSERT_TRUE(res);
  1921. EXPECT_EQ(StatusCode::OK_200, res->status);
  1922. EXPECT_EQ("Hello World!", res->body);
  1923. }
  1924. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  1925. Server svr;
  1926. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  1927. // Port number that overflows int — should not crash
  1928. res.set_redirect("http://localhost:99999999999999999999/target");
  1929. });
  1930. auto port = svr.bind_to_any_port(HOST);
  1931. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  1932. auto se = detail::scope_exit([&] {
  1933. svr.stop();
  1934. thread.join();
  1935. ASSERT_FALSE(svr.is_running());
  1936. });
  1937. svr.wait_until_ready();
  1938. Client cli(HOST, port);
  1939. cli.set_follow_location(true);
  1940. auto res = cli.Get("/redir");
  1941. // Should fail gracefully, not crash (no valid response due to bad port)
  1942. EXPECT_FALSE(res);
  1943. }
  1944. TEST(RedirectFromPageWithContent, Redirect) {
  1945. Server svr;
  1946. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1947. res.set_content("___", "text/plain");
  1948. res.set_redirect("/2");
  1949. });
  1950. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1951. res.set_content("Hello World!", "text/plain");
  1952. });
  1953. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1954. auto se = detail::scope_exit([&] {
  1955. svr.stop();
  1956. th.join();
  1957. ASSERT_FALSE(svr.is_running());
  1958. });
  1959. svr.wait_until_ready();
  1960. {
  1961. Client cli("localhost", PORT);
  1962. cli.set_follow_location(true);
  1963. std::string body;
  1964. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1965. body.append(data, data_length);
  1966. return true;
  1967. });
  1968. ASSERT_TRUE(res);
  1969. EXPECT_EQ(StatusCode::OK_200, res->status);
  1970. EXPECT_EQ("Hello World!", body);
  1971. }
  1972. {
  1973. Client cli("localhost", PORT);
  1974. std::string body;
  1975. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1976. body.append(data, data_length);
  1977. return true;
  1978. });
  1979. ASSERT_TRUE(res);
  1980. EXPECT_EQ(StatusCode::Found_302, res->status);
  1981. EXPECT_EQ("___", body);
  1982. }
  1983. }
  1984. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1985. Server svr;
  1986. auto port_str = std::to_string(PORT);
  1987. auto redirect_url = "http://[::1]:" + port_str + "/2";
  1988. auto expected_host = "[::1]:" + port_str;
  1989. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1990. res.set_content("___", "text/plain");
  1991. // res.set_redirect("/2");
  1992. res.set_redirect(redirect_url);
  1993. });
  1994. svr.Get("/2", [&](const Request &req, Response &res) {
  1995. auto host_header = req.headers.find("Host");
  1996. ASSERT_TRUE(host_header != req.headers.end());
  1997. EXPECT_EQ(expected_host, host_header->second);
  1998. res.set_content("Hello World!", "text/plain");
  1999. });
  2000. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2001. auto se = detail::scope_exit([&] {
  2002. svr.stop();
  2003. th.join();
  2004. ASSERT_FALSE(svr.is_running());
  2005. });
  2006. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2007. // actually starts anything, so the condition !svr.is_running() will
  2008. // always remain true, and the loop never stops.
  2009. // This basically counts how many milliseconds have passed since the
  2010. // call to svr.listen(), and if after 5 seconds nothing started yet
  2011. // aborts the test.
  2012. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2013. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2014. ASSERT_LT(milliseconds, 5000U);
  2015. }
  2016. {
  2017. Client cli("::1", PORT);
  2018. cli.set_follow_location(true);
  2019. std::string body;
  2020. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2021. body.append(data, data_length);
  2022. return true;
  2023. });
  2024. ASSERT_TRUE(res);
  2025. EXPECT_EQ(StatusCode::OK_200, res->status);
  2026. EXPECT_EQ("Hello World!", body);
  2027. }
  2028. {
  2029. Client cli("::1", PORT);
  2030. std::string body;
  2031. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2032. body.append(data, data_length);
  2033. return true;
  2034. });
  2035. ASSERT_TRUE(res);
  2036. EXPECT_EQ(StatusCode::Found_302, res->status);
  2037. EXPECT_EQ("___", body);
  2038. }
  2039. }
  2040. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2041. Server svr;
  2042. svr.Get("/foo", [](const Request &req, Response &res) {
  2043. auto a = req.params.find("a");
  2044. if (a != req.params.end()) {
  2045. res.set_content((*a).second, "text/plain");
  2046. res.status = StatusCode::OK_200;
  2047. } else {
  2048. res.status = StatusCode::BadRequest_400;
  2049. }
  2050. });
  2051. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2052. auto se = detail::scope_exit([&] {
  2053. svr.stop();
  2054. thread.join();
  2055. ASSERT_FALSE(svr.is_running());
  2056. });
  2057. svr.wait_until_ready();
  2058. {
  2059. Client cli(HOST, PORT);
  2060. cli.set_path_encode(false);
  2061. auto res = cli.Get("/foo?a=explicitly+encoded");
  2062. ASSERT_TRUE(res);
  2063. EXPECT_EQ(StatusCode::OK_200, res->status);
  2064. // This expects it back with a space, as the `+` won't have been
  2065. // url-encoded, and server-side the params get decoded turning `+`
  2066. // into spaces.
  2067. EXPECT_EQ("explicitly encoded", res->body);
  2068. }
  2069. }
  2070. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2071. Server svr;
  2072. svr.Get("/", [](const Request &req, Response &) {
  2073. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2074. });
  2075. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2076. auto se = detail::scope_exit([&] {
  2077. svr.stop();
  2078. thread.join();
  2079. ASSERT_FALSE(svr.is_running());
  2080. });
  2081. svr.wait_until_ready();
  2082. {
  2083. Client cli(HOST, PORT);
  2084. cli.set_path_encode(false);
  2085. auto res = cli.Get("/?something=%0A");
  2086. ASSERT_TRUE(res);
  2087. EXPECT_EQ(StatusCode::OK_200, res->status);
  2088. }
  2089. }
  2090. TEST(BindServerTest, DISABLED_BindDualStack) {
  2091. Server svr;
  2092. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2093. res.set_content("Hello World!", "text/plain");
  2094. });
  2095. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2096. auto se = detail::scope_exit([&] {
  2097. svr.stop();
  2098. thread.join();
  2099. ASSERT_FALSE(svr.is_running());
  2100. });
  2101. svr.wait_until_ready();
  2102. {
  2103. Client cli("127.0.0.1", PORT);
  2104. auto res = cli.Get("/1");
  2105. ASSERT_TRUE(res);
  2106. EXPECT_EQ(StatusCode::OK_200, res->status);
  2107. EXPECT_EQ("Hello World!", res->body);
  2108. }
  2109. {
  2110. Client cli("::1", PORT);
  2111. auto res = cli.Get("/1");
  2112. ASSERT_TRUE(res);
  2113. EXPECT_EQ(StatusCode::OK_200, res->status);
  2114. EXPECT_EQ("Hello World!", res->body);
  2115. }
  2116. }
  2117. TEST(BindServerTest, BindAndListenSeparately) {
  2118. Server svr;
  2119. int port = svr.bind_to_any_port("0.0.0.0");
  2120. ASSERT_TRUE(svr.is_valid());
  2121. ASSERT_TRUE(port > 0);
  2122. svr.stop();
  2123. }
  2124. #ifdef CPPHTTPLIB_SSL_ENABLED
  2125. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2126. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2127. CLIENT_CA_CERT_DIR);
  2128. int port = svr.bind_to_any_port("0.0.0.0");
  2129. ASSERT_TRUE(svr.is_valid());
  2130. ASSERT_TRUE(port > 0);
  2131. svr.stop();
  2132. }
  2133. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2134. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2135. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2136. int port = svr.bind_to_any_port("0.0.0.0");
  2137. ASSERT_TRUE(svr.is_valid());
  2138. ASSERT_TRUE(port > 0);
  2139. svr.stop();
  2140. }
  2141. TEST(BindServerTest, UpdateCertsPem) {
  2142. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2143. int port = svr.bind_to_any_port("0.0.0.0");
  2144. ASSERT_TRUE(svr.is_valid());
  2145. ASSERT_TRUE(port > 0);
  2146. // Read PEM files
  2147. std::string cert_pem, key_pem, ca_pem;
  2148. read_file(SERVER_CERT_FILE, cert_pem);
  2149. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2150. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2151. // Update server certificates using PEM API
  2152. ASSERT_TRUE(
  2153. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2154. ASSERT_TRUE(svr.is_valid());
  2155. svr.stop();
  2156. }
  2157. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2158. // Start server with client CA (enables client auth)
  2159. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2160. ASSERT_TRUE(svr.is_valid());
  2161. bool handler_called = false;
  2162. svr.Get("/test", [&](const Request &req, Response &res) {
  2163. handler_called = true;
  2164. // Verify client certificate is present
  2165. auto cert = req.peer_cert();
  2166. EXPECT_TRUE(static_cast<bool>(cert));
  2167. res.set_content("ok", "text/plain");
  2168. });
  2169. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2170. auto se = detail::scope_exit([&] {
  2171. svr.stop();
  2172. t.join();
  2173. ASSERT_FALSE(svr.is_running());
  2174. });
  2175. svr.wait_until_ready();
  2176. // Read PEM files
  2177. std::string cert_pem, key_pem, ca_pem;
  2178. read_file(SERVER_CERT_FILE, cert_pem);
  2179. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2180. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2181. // Update server certificates and client CA using PEM API while server running
  2182. ASSERT_TRUE(
  2183. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2184. // Connect with client certificate
  2185. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2186. cli.enable_server_certificate_verification(false);
  2187. cli.set_connection_timeout(30);
  2188. auto res = cli.Get("/test");
  2189. ASSERT_TRUE(res);
  2190. ASSERT_EQ(StatusCode::OK_200, res->status);
  2191. ASSERT_TRUE(handler_called);
  2192. EXPECT_EQ("ok", res->body);
  2193. }
  2194. #endif
  2195. TEST(ErrorHandlerTest, ContentLength) {
  2196. Server svr;
  2197. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2198. res.status = StatusCode::OK_200;
  2199. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2200. "text/html"); // <= Content-Length still 13
  2201. });
  2202. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2203. res.set_content("Hello World!\n", "text/plain");
  2204. res.status = 524;
  2205. });
  2206. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2207. auto se = detail::scope_exit([&] {
  2208. svr.stop();
  2209. thread.join();
  2210. ASSERT_FALSE(svr.is_running());
  2211. });
  2212. svr.wait_until_ready();
  2213. {
  2214. Client cli(HOST, PORT);
  2215. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2216. ASSERT_TRUE(res);
  2217. EXPECT_EQ(StatusCode::OK_200, res->status);
  2218. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2219. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2220. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2221. }
  2222. }
  2223. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2224. TEST(ExceptionTest, WithoutExceptionHandler) {
  2225. Server svr;
  2226. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2227. throw std::runtime_error("exception...");
  2228. });
  2229. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2230. throw std::runtime_error("exception\r\n...");
  2231. });
  2232. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2233. auto se = detail::scope_exit([&] {
  2234. svr.stop();
  2235. listen_thread.join();
  2236. ASSERT_FALSE(svr.is_running());
  2237. });
  2238. svr.wait_until_ready();
  2239. Client cli("localhost", PORT);
  2240. {
  2241. auto res = cli.Get("/exception");
  2242. ASSERT_TRUE(res);
  2243. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2244. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2245. }
  2246. {
  2247. auto res = cli.Get("/unknown");
  2248. ASSERT_TRUE(res);
  2249. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2250. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2251. }
  2252. }
  2253. TEST(ExceptionTest, WithExceptionHandler) {
  2254. Server svr;
  2255. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2256. std::exception_ptr ep) {
  2257. EXPECT_FALSE(ep == nullptr);
  2258. try {
  2259. std::rethrow_exception(ep);
  2260. } catch (std::exception &e) {
  2261. EXPECT_EQ("abc", std::string(e.what()));
  2262. } catch (...) {}
  2263. res.status = StatusCode::InternalServerError_500;
  2264. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2265. "text/html"); // <= Content-Length still 13 at this point
  2266. });
  2267. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2268. res.set_content("Hello World!\n", "text/plain");
  2269. throw std::runtime_error("abc");
  2270. });
  2271. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2272. auto se = detail::scope_exit([&] {
  2273. svr.stop();
  2274. thread.join();
  2275. ASSERT_FALSE(svr.is_running());
  2276. });
  2277. svr.wait_until_ready();
  2278. for (size_t i = 0; i < 10; i++) {
  2279. Client cli(HOST, PORT);
  2280. for (size_t j = 0; j < 100; j++) {
  2281. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2282. ASSERT_TRUE(res);
  2283. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2284. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2285. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2286. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2287. }
  2288. cli.set_keep_alive(true);
  2289. for (size_t j = 0; j < 100; j++) {
  2290. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2291. ASSERT_TRUE(res);
  2292. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2293. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2294. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2295. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2296. }
  2297. }
  2298. }
  2299. TEST(ExceptionTest, AndErrorHandler) {
  2300. Server svr;
  2301. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2302. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2303. });
  2304. svr.set_exception_handler(
  2305. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2306. EXPECT_FALSE(ep == nullptr);
  2307. try {
  2308. std::rethrow_exception(ep);
  2309. } catch (std::exception &e) {
  2310. res.set_content(e.what(), "text/html");
  2311. } catch (...) {}
  2312. res.status = StatusCode::InternalServerError_500;
  2313. });
  2314. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2315. throw std::runtime_error("EXCEPTION");
  2316. });
  2317. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2318. res.set_content("ERROR", "text/html");
  2319. res.status = StatusCode::InternalServerError_500;
  2320. });
  2321. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2322. auto se = detail::scope_exit([&] {
  2323. svr.stop();
  2324. thread.join();
  2325. ASSERT_FALSE(svr.is_running());
  2326. });
  2327. svr.wait_until_ready();
  2328. Client cli(HOST, PORT);
  2329. {
  2330. auto res = cli.Get("/exception");
  2331. ASSERT_TRUE(res);
  2332. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2333. EXPECT_EQ("EXCEPTION", res->body);
  2334. }
  2335. {
  2336. auto res = cli.Get("/error");
  2337. ASSERT_TRUE(res);
  2338. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2339. EXPECT_EQ("ERROR", res->body);
  2340. }
  2341. {
  2342. auto res = cli.Get("/invalid");
  2343. ASSERT_TRUE(res);
  2344. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2345. EXPECT_EQ("NOT_FOUND", res->body);
  2346. }
  2347. }
  2348. #endif
  2349. TEST(NoContentTest, ContentLength) {
  2350. Server svr;
  2351. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2352. res.status = StatusCode::NoContent_204;
  2353. });
  2354. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2355. auto se = detail::scope_exit([&] {
  2356. svr.stop();
  2357. thread.join();
  2358. ASSERT_FALSE(svr.is_running());
  2359. });
  2360. svr.wait_until_ready();
  2361. {
  2362. Client cli(HOST, PORT);
  2363. auto res = cli.Get("/hi");
  2364. ASSERT_TRUE(res);
  2365. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2366. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2367. }
  2368. }
  2369. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2370. #ifdef CPPHTTPLIB_SSL_ENABLED
  2371. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2372. ASSERT_TRUE(svr.is_valid());
  2373. #else
  2374. Server svr;
  2375. #endif
  2376. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2377. if (req.path == "/routing_handler") {
  2378. res.set_header("PRE_ROUTING", "on");
  2379. res.set_content("Routing Handler", "text/plain");
  2380. return httplib::Server::HandlerResponse::Handled;
  2381. }
  2382. return httplib::Server::HandlerResponse::Unhandled;
  2383. });
  2384. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2385. res.set_content("Error", "text/html");
  2386. });
  2387. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2388. if (req.path == "/routing_handler") {
  2389. res.set_header("POST_ROUTING", "on");
  2390. }
  2391. });
  2392. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2393. res.set_content("Hello World!\n", "text/plain");
  2394. });
  2395. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2396. auto se = detail::scope_exit([&] {
  2397. svr.stop();
  2398. thread.join();
  2399. ASSERT_FALSE(svr.is_running());
  2400. });
  2401. svr.wait_until_ready();
  2402. {
  2403. #ifdef CPPHTTPLIB_SSL_ENABLED
  2404. SSLClient cli(HOST, PORT);
  2405. cli.enable_server_certificate_verification(false);
  2406. #else
  2407. Client cli(HOST, PORT);
  2408. #endif
  2409. auto res = cli.Get("/routing_handler");
  2410. ASSERT_TRUE(res);
  2411. EXPECT_EQ(StatusCode::OK_200, res->status);
  2412. EXPECT_EQ("Routing Handler", res->body);
  2413. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2414. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2415. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2416. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2417. }
  2418. {
  2419. #ifdef CPPHTTPLIB_SSL_ENABLED
  2420. SSLClient cli(HOST, PORT);
  2421. cli.enable_server_certificate_verification(false);
  2422. #else
  2423. Client cli(HOST, PORT);
  2424. #endif
  2425. auto res = cli.Get("/hi");
  2426. ASSERT_TRUE(res);
  2427. EXPECT_EQ(StatusCode::OK_200, res->status);
  2428. EXPECT_EQ("Hello World!\n", res->body);
  2429. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2430. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2431. }
  2432. {
  2433. #ifdef CPPHTTPLIB_SSL_ENABLED
  2434. SSLClient cli(HOST, PORT);
  2435. cli.enable_server_certificate_verification(false);
  2436. #else
  2437. Client cli(HOST, PORT);
  2438. #endif
  2439. auto res = cli.Get("/aaa");
  2440. ASSERT_TRUE(res);
  2441. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2442. EXPECT_EQ("Error", res->body);
  2443. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2444. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2445. }
  2446. }
  2447. TEST(RequestHandlerTest, PreRequestHandler) {
  2448. auto route_path = "/user/:user";
  2449. Server svr;
  2450. svr.Get("/hi", [](const Request &, Response &res) {
  2451. res.set_content("hi", "text/plain");
  2452. });
  2453. svr.Get(route_path, [](const Request &req, Response &res) {
  2454. res.set_content(req.path_params.at("user"), "text/plain");
  2455. });
  2456. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2457. if (req.matched_route == route_path) {
  2458. auto user = req.path_params.at("user");
  2459. if (user != "john") {
  2460. res.status = StatusCode::Forbidden_403;
  2461. res.set_content("error", "text/html");
  2462. return Server::HandlerResponse::Handled;
  2463. }
  2464. }
  2465. return Server::HandlerResponse::Unhandled;
  2466. });
  2467. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2468. auto se = detail::scope_exit([&] {
  2469. svr.stop();
  2470. thread.join();
  2471. ASSERT_FALSE(svr.is_running());
  2472. });
  2473. svr.wait_until_ready();
  2474. Client cli(HOST, PORT);
  2475. {
  2476. auto res = cli.Get("/hi");
  2477. ASSERT_TRUE(res);
  2478. EXPECT_EQ(StatusCode::OK_200, res->status);
  2479. EXPECT_EQ("hi", res->body);
  2480. }
  2481. {
  2482. auto res = cli.Get("/user/john");
  2483. ASSERT_TRUE(res);
  2484. EXPECT_EQ(StatusCode::OK_200, res->status);
  2485. EXPECT_EQ("john", res->body);
  2486. }
  2487. {
  2488. auto res = cli.Get("/user/invalid-user");
  2489. ASSERT_TRUE(res);
  2490. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2491. EXPECT_EQ("error", res->body);
  2492. }
  2493. }
  2494. TEST(AnyTest, BasicOperations) {
  2495. // Default construction
  2496. httplib::any a;
  2497. EXPECT_FALSE(a.has_value());
  2498. // Value construction and any_cast (pointer form, noexcept)
  2499. httplib::any b(42);
  2500. EXPECT_TRUE(b.has_value());
  2501. auto *p = httplib::any_cast<int>(&b);
  2502. ASSERT_NE(nullptr, p);
  2503. EXPECT_EQ(42, *p);
  2504. // Type mismatch → nullptr
  2505. auto *q = httplib::any_cast<std::string>(&b);
  2506. EXPECT_EQ(nullptr, q);
  2507. // any_cast (value form) succeeds
  2508. EXPECT_EQ(42, httplib::any_cast<int>(b));
  2509. // any_cast (value form) throws on type mismatch
  2510. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2511. EXPECT_THROW(httplib::any_cast<std::string>(b), httplib::bad_any_cast);
  2512. #endif
  2513. // Copy
  2514. httplib::any c = b;
  2515. EXPECT_EQ(42, httplib::any_cast<int>(c));
  2516. // Move
  2517. httplib::any d = std::move(c);
  2518. EXPECT_EQ(42, httplib::any_cast<int>(d));
  2519. // Assignment with different type
  2520. b = std::string("hello");
  2521. EXPECT_EQ("hello", httplib::any_cast<std::string>(b));
  2522. // Reset
  2523. b.reset();
  2524. EXPECT_FALSE(b.has_value());
  2525. }
  2526. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2527. struct AuthCtx {
  2528. std::string user_id;
  2529. };
  2530. Server svr;
  2531. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2532. res.user_data["auth"] = AuthCtx{"alice"};
  2533. return Server::HandlerResponse::Unhandled;
  2534. });
  2535. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2536. auto *ctx = httplib::any_cast<AuthCtx>(&res.user_data["auth"]);
  2537. ASSERT_NE(nullptr, ctx);
  2538. res.set_content("Hello " + ctx->user_id, "text/plain");
  2539. });
  2540. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2541. auto se = detail::scope_exit([&] {
  2542. svr.stop();
  2543. thread.join();
  2544. ASSERT_FALSE(svr.is_running());
  2545. });
  2546. svr.wait_until_ready();
  2547. Client cli(HOST, PORT);
  2548. auto res = cli.Get("/me");
  2549. ASSERT_TRUE(res);
  2550. EXPECT_EQ(StatusCode::OK_200, res->status);
  2551. EXPECT_EQ("Hello alice", res->body);
  2552. }
  2553. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2554. struct RoleCtx {
  2555. std::string role;
  2556. };
  2557. Server svr;
  2558. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2559. res.user_data["role"] = RoleCtx{"admin"};
  2560. return Server::HandlerResponse::Unhandled;
  2561. });
  2562. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2563. auto *ctx = httplib::any_cast<RoleCtx>(&res.user_data["role"]);
  2564. ASSERT_NE(nullptr, ctx);
  2565. res.set_content(ctx->role, "text/plain");
  2566. });
  2567. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2568. auto se = detail::scope_exit([&] {
  2569. svr.stop();
  2570. thread.join();
  2571. ASSERT_FALSE(svr.is_running());
  2572. });
  2573. svr.wait_until_ready();
  2574. Client cli(HOST, PORT);
  2575. auto res = cli.Get("/role");
  2576. ASSERT_TRUE(res);
  2577. EXPECT_EQ(StatusCode::OK_200, res->status);
  2578. EXPECT_EQ("admin", res->body);
  2579. }
  2580. TEST(InvalidFormatTest, StatusCode) {
  2581. Server svr;
  2582. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2583. res.set_content("Hello World!\n", "text/plain");
  2584. res.status = 9999; // Status should be a three-digit code...
  2585. });
  2586. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2587. auto se = detail::scope_exit([&] {
  2588. svr.stop();
  2589. thread.join();
  2590. ASSERT_FALSE(svr.is_running());
  2591. });
  2592. svr.wait_until_ready();
  2593. {
  2594. Client cli(HOST, PORT);
  2595. auto res = cli.Get("/hi");
  2596. ASSERT_FALSE(res);
  2597. }
  2598. }
  2599. TEST(URLFragmentTest, WithFragment) {
  2600. Server svr;
  2601. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2602. EXPECT_TRUE(req.target == "/hi");
  2603. });
  2604. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2605. auto se = detail::scope_exit([&] {
  2606. svr.stop();
  2607. thread.join();
  2608. ASSERT_FALSE(svr.is_running());
  2609. });
  2610. svr.wait_until_ready();
  2611. {
  2612. Client cli(HOST, PORT);
  2613. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2614. EXPECT_TRUE(res);
  2615. EXPECT_EQ(StatusCode::OK_200, res->status);
  2616. res = cli.Get("/hi%23key1=val1=key2=val2");
  2617. EXPECT_TRUE(res);
  2618. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2619. }
  2620. }
  2621. TEST(HeaderWriter, SetHeaderWriter) {
  2622. Server svr;
  2623. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2624. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2625. return detail::write_headers(strm, hdrs);
  2626. });
  2627. svr.Get("/hi", [](const Request &req, Response &res) {
  2628. auto it = req.headers.find("CustomClientHeader");
  2629. EXPECT_TRUE(it != req.headers.end());
  2630. EXPECT_EQ(it->second, "CustomClientValue");
  2631. res.set_content("Hello World!\n", "text/plain");
  2632. });
  2633. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2634. auto se = detail::scope_exit([&] {
  2635. svr.stop();
  2636. thread.join();
  2637. ASSERT_FALSE(svr.is_running());
  2638. });
  2639. svr.wait_until_ready();
  2640. {
  2641. Client cli(HOST, PORT);
  2642. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2643. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2644. return detail::write_headers(strm, hdrs);
  2645. });
  2646. auto res = cli.Get("/hi");
  2647. EXPECT_TRUE(res);
  2648. EXPECT_EQ(StatusCode::OK_200, res->status);
  2649. auto it = res->headers.find("CustomServerHeader");
  2650. EXPECT_TRUE(it != res->headers.end());
  2651. EXPECT_EQ(it->second, "CustomServerValue");
  2652. }
  2653. }
  2654. class ServerTest : public ::testing::Test {
  2655. protected:
  2656. ServerTest()
  2657. : cli_(HOST, PORT)
  2658. #ifdef CPPHTTPLIB_SSL_ENABLED
  2659. ,
  2660. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2661. #endif
  2662. {
  2663. #ifdef CPPHTTPLIB_SSL_ENABLED
  2664. cli_.enable_server_certificate_verification(false);
  2665. #endif
  2666. // Allow LARGE_DATA (100MB) responses
  2667. cli_.set_payload_max_length(200 * 1024 * 1024);
  2668. }
  2669. virtual void SetUp() {
  2670. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2671. svr_.set_payload_max_length(200 * 1024 * 1024);
  2672. svr_.set_mount_point("/", "./www");
  2673. svr_.set_mount_point("/mount", "./www2");
  2674. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2675. svr_.Get("/hi",
  2676. [&](const Request & /*req*/, Response &res) {
  2677. res.set_content("Hello World!", "text/plain");
  2678. })
  2679. .Get("/file_content",
  2680. [&](const Request & /*req*/, Response &res) {
  2681. res.set_file_content("./www/dir/test.html");
  2682. })
  2683. .Get("/file_content_with_content_type",
  2684. [&](const Request & /*req*/, Response &res) {
  2685. res.set_file_content("./www/file", "text/plain");
  2686. })
  2687. .Get("/invalid_file_content",
  2688. [&](const Request & /*req*/, Response &res) {
  2689. res.set_file_content("./www/dir/invalid_file_path");
  2690. })
  2691. .Get("/http_response_splitting",
  2692. [&](const Request & /*req*/, Response &res) {
  2693. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2694. EXPECT_EQ(0U, res.headers.size());
  2695. EXPECT_FALSE(res.has_header("a"));
  2696. res.set_header("a", "1\nSet-Cookie: a=1");
  2697. EXPECT_EQ(0U, res.headers.size());
  2698. EXPECT_FALSE(res.has_header("a"));
  2699. res.set_header("a", "1\rSet-Cookie: a=1");
  2700. EXPECT_EQ(0U, res.headers.size());
  2701. EXPECT_FALSE(res.has_header("a"));
  2702. res.set_header("a\r\nb", "0");
  2703. EXPECT_EQ(0U, res.headers.size());
  2704. EXPECT_FALSE(res.has_header("a"));
  2705. res.set_header("a\rb", "0");
  2706. EXPECT_EQ(0U, res.headers.size());
  2707. EXPECT_FALSE(res.has_header("a"));
  2708. res.set_header("a\nb", "0");
  2709. EXPECT_EQ(0U, res.headers.size());
  2710. EXPECT_FALSE(res.has_header("a"));
  2711. res.set_redirect("1\r\nSet-Cookie: a=1");
  2712. EXPECT_EQ(0U, res.headers.size());
  2713. EXPECT_FALSE(res.has_header("Location"));
  2714. })
  2715. .Get("/slow",
  2716. [&](const Request & /*req*/, Response &res) {
  2717. std::this_thread::sleep_for(std::chrono::seconds(2));
  2718. res.set_content("slow", "text/plain");
  2719. })
  2720. #if 0
  2721. .Post("/slowpost",
  2722. [&](const Request & /*req*/, Response &res) {
  2723. std::this_thread::sleep_for(std::chrono::seconds(2));
  2724. res.set_content("slow", "text/plain");
  2725. })
  2726. #endif
  2727. .Get("/remote_addr",
  2728. [&](const Request &req, Response &res) {
  2729. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2730. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2731. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2732. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2733. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2734. #endif
  2735. res.set_content(req.remote_addr, "text/plain");
  2736. })
  2737. .Get("/local_addr",
  2738. [&](const Request &req, Response &res) {
  2739. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2740. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2741. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2742. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2743. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2744. #endif
  2745. auto local_addr = req.local_addr;
  2746. auto local_port = std::to_string(req.local_port);
  2747. res.set_content(local_addr.append(":").append(local_port),
  2748. "text/plain");
  2749. })
  2750. .Get("/endwith%",
  2751. [&](const Request & /*req*/, Response &res) {
  2752. res.set_content("Hello World!", "text/plain");
  2753. })
  2754. .Get("/a\\+\\+b",
  2755. [&](const Request &req, Response &res) {
  2756. ASSERT_TRUE(req.has_param("a +b"));
  2757. auto val = req.get_param_value("a +b");
  2758. res.set_content(val, "text/plain");
  2759. })
  2760. .Get("/", [&](const Request & /*req*/,
  2761. Response &res) { res.set_redirect("/hi"); })
  2762. .Post("/1",
  2763. [](const Request & /*req*/, Response &res) {
  2764. res.set_redirect("/2", StatusCode::SeeOther_303);
  2765. })
  2766. .Get("/2",
  2767. [](const Request & /*req*/, Response &res) {
  2768. res.set_content("redirected.", "text/plain");
  2769. res.status = StatusCode::OK_200;
  2770. })
  2771. .Post("/person",
  2772. [&](const Request &req, Response &res) {
  2773. if (req.has_param("name") && req.has_param("note")) {
  2774. persons_[req.get_param_value("name")] =
  2775. req.get_param_value("note");
  2776. } else {
  2777. res.status = StatusCode::BadRequest_400;
  2778. }
  2779. })
  2780. .Put("/person",
  2781. [&](const Request &req, Response &res) {
  2782. if (req.has_param("name") && req.has_param("note")) {
  2783. persons_[req.get_param_value("name")] =
  2784. req.get_param_value("note");
  2785. } else {
  2786. res.status = StatusCode::BadRequest_400;
  2787. }
  2788. })
  2789. .Get("/person/(.*)",
  2790. [&](const Request &req, Response &res) {
  2791. string name = req.matches[1];
  2792. if (persons_.find(name) != persons_.end()) {
  2793. auto note = persons_[name];
  2794. res.set_content(note, "text/plain");
  2795. } else {
  2796. res.status = StatusCode::NotFound_404;
  2797. }
  2798. })
  2799. .Delete("/person",
  2800. [&](const Request &req, Response &res) {
  2801. if (req.has_param("name")) {
  2802. string name = req.get_param_value("name");
  2803. if (persons_.find(name) != persons_.end()) {
  2804. persons_.erase(name);
  2805. res.set_content("DELETED", "text/plain");
  2806. } else {
  2807. res.status = StatusCode::NotFound_404;
  2808. }
  2809. } else {
  2810. res.status = StatusCode::BadRequest_400;
  2811. }
  2812. })
  2813. .Post("/x-www-form-urlencoded-json",
  2814. [&](const Request &req, Response &res) {
  2815. auto json = req.get_param_value("json");
  2816. ASSERT_EQ(JSON_DATA, json);
  2817. res.set_content(json, "appliation/json");
  2818. res.status = StatusCode::OK_200;
  2819. })
  2820. .Get("/streamed-chunked",
  2821. [&](const Request & /*req*/, Response &res) {
  2822. res.set_chunked_content_provider(
  2823. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2824. sink.os << "123";
  2825. sink.os << "456";
  2826. sink.os << "789";
  2827. sink.done();
  2828. return true;
  2829. });
  2830. })
  2831. .Get("/streamed-chunked-with-prohibited-trailer",
  2832. [&](const Request & /*req*/, Response &res) {
  2833. auto i = new int(0);
  2834. // Declare both a prohibited trailer (Content-Length) and an
  2835. // allowed one
  2836. res.set_header("Trailer", "Content-Length, X-Allowed");
  2837. res.set_chunked_content_provider(
  2838. "text/plain",
  2839. [i](size_t /*offset*/, DataSink &sink) {
  2840. switch (*i) {
  2841. case 0: sink.os << "123"; break;
  2842. case 1: sink.os << "456"; break;
  2843. case 2: sink.os << "789"; break;
  2844. case 3: {
  2845. sink.done_with_trailer(
  2846. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2847. } break;
  2848. }
  2849. (*i)++;
  2850. return true;
  2851. },
  2852. [i](bool success) {
  2853. EXPECT_TRUE(success);
  2854. delete i;
  2855. });
  2856. })
  2857. .Get("/streamed-chunked2",
  2858. [&](const Request & /*req*/, Response &res) {
  2859. auto i = new int(0);
  2860. res.set_chunked_content_provider(
  2861. "text/plain",
  2862. [i](size_t /*offset*/, DataSink &sink) {
  2863. switch (*i) {
  2864. case 0: sink.os << "123"; break;
  2865. case 1: sink.os << "456"; break;
  2866. case 2: sink.os << "789"; break;
  2867. case 3: sink.done(); break;
  2868. }
  2869. (*i)++;
  2870. return true;
  2871. },
  2872. [i](bool success) {
  2873. EXPECT_TRUE(success);
  2874. delete i;
  2875. });
  2876. })
  2877. .Get("/streamed-chunked-with-trailer",
  2878. [&](const Request & /*req*/, Response &res) {
  2879. auto i = new int(0);
  2880. res.set_header("Trailer", "Dummy1, Dummy2");
  2881. res.set_chunked_content_provider(
  2882. "text/plain",
  2883. [i](size_t /*offset*/, DataSink &sink) {
  2884. switch (*i) {
  2885. case 0: sink.os << "123"; break;
  2886. case 1: sink.os << "456"; break;
  2887. case 2: sink.os << "789"; break;
  2888. case 3: {
  2889. sink.done_with_trailer(
  2890. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2891. } break;
  2892. }
  2893. (*i)++;
  2894. return true;
  2895. },
  2896. [i](bool success) {
  2897. EXPECT_TRUE(success);
  2898. delete i;
  2899. });
  2900. })
  2901. .Get("/streamed",
  2902. [&](const Request & /*req*/, Response &res) {
  2903. res.set_content_provider(
  2904. 6, "text/plain",
  2905. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2906. sink.os << (offset < 3 ? "a" : "b");
  2907. return true;
  2908. });
  2909. })
  2910. .Get("/streamed-with-range",
  2911. [&](const Request &req, Response &res) {
  2912. auto data = new std::string("abcdefg");
  2913. res.set_content_provider(
  2914. data->size(), "text/plain",
  2915. [data](size_t offset, size_t length, DataSink &sink) {
  2916. size_t DATA_CHUNK_SIZE = 4;
  2917. const auto &d = *data;
  2918. auto out_len =
  2919. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2920. auto ret =
  2921. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2922. EXPECT_TRUE(ret);
  2923. return true;
  2924. },
  2925. [data, &req](bool success) {
  2926. EXPECT_EQ(success, !req.has_param("error"));
  2927. delete data;
  2928. });
  2929. })
  2930. .Get("/streamed-cancel",
  2931. [&](const Request & /*req*/, Response &res) {
  2932. res.set_content_provider(
  2933. size_t(-1), "text/plain",
  2934. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2935. sink.os << "data_chunk";
  2936. return true;
  2937. });
  2938. })
  2939. .Get("/regex-with-delimiter",
  2940. [&](const Request &req, Response & /*res*/) {
  2941. ASSERT_TRUE(req.has_param("key"));
  2942. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2943. })
  2944. .Get("/with-range",
  2945. [&](const Request & /*req*/, Response &res) {
  2946. res.set_content("abcdefg", "text/plain");
  2947. })
  2948. .Get("/test-start-time",
  2949. [&](const Request &req, Response & /*res*/) {
  2950. EXPECT_NE(req.start_time_,
  2951. std::chrono::steady_clock::time_point::min());
  2952. })
  2953. .Get("/with-range-customized-response",
  2954. [&](const Request & /*req*/, Response &res) {
  2955. res.status = StatusCode::BadRequest_400;
  2956. res.set_content(JSON_DATA, "application/json");
  2957. })
  2958. .Post("/chunked",
  2959. [&](const Request &req, Response & /*res*/) {
  2960. EXPECT_EQ(req.body, "dechunked post body");
  2961. })
  2962. .Post("/large-chunked",
  2963. [&](const Request &req, Response & /*res*/) {
  2964. std::string expected(6 * 30 * 1024u, 'a');
  2965. EXPECT_EQ(req.body, expected);
  2966. })
  2967. .Post("/multipart",
  2968. [&](const Request &req, Response & /*res*/) {
  2969. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2970. req.form.get_field_count("text2") +
  2971. req.form.get_field_count("file3") +
  2972. req.form.get_field_count("file4"));
  2973. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2974. req.form.get_file_count("file2"));
  2975. ASSERT_TRUE(!req.form.has_file("???"));
  2976. ASSERT_TRUE(!req.form.has_field("???"));
  2977. ASSERT_TRUE(req.body.empty());
  2978. {
  2979. const auto &text = req.form.get_field("text1");
  2980. EXPECT_EQ("text default", text);
  2981. }
  2982. {
  2983. const auto &text = req.form.get_field("text2");
  2984. EXPECT_EQ("aωb", text);
  2985. }
  2986. {
  2987. const auto &file = req.form.get_file("file1");
  2988. EXPECT_EQ("hello.txt", file.filename);
  2989. EXPECT_EQ("text/plain", file.content_type);
  2990. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2991. }
  2992. {
  2993. const auto &file = req.form.get_file("file2");
  2994. EXPECT_EQ("world.json", file.filename);
  2995. EXPECT_EQ("application/json", file.content_type);
  2996. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2997. }
  2998. {
  2999. const auto &text = req.form.get_field("file3");
  3000. EXPECT_EQ(0u, text.size());
  3001. }
  3002. {
  3003. const auto &text = req.form.get_field("file4");
  3004. EXPECT_EQ(0u, text.size());
  3005. }
  3006. })
  3007. .Post("/multipart/multi_file_values",
  3008. [&](const Request &req, Response & /*res*/) {
  3009. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3010. req.form.get_field_count("multi_text1"));
  3011. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3012. ASSERT_TRUE(!req.form.has_file("???"));
  3013. ASSERT_TRUE(!req.form.has_field("???"));
  3014. ASSERT_TRUE(req.body.empty());
  3015. {
  3016. const auto &text = req.form.get_field("text");
  3017. EXPECT_EQ("default text", text);
  3018. }
  3019. {
  3020. const auto &text1_values = req.form.get_fields("multi_text1");
  3021. EXPECT_EQ(2u, text1_values.size());
  3022. EXPECT_EQ("aaaaa", text1_values[0]);
  3023. EXPECT_EQ("bbbbb", text1_values[1]);
  3024. }
  3025. {
  3026. const auto &file1_values = req.form.get_files("multi_file1");
  3027. EXPECT_EQ(2u, file1_values.size());
  3028. auto file1 = file1_values[0];
  3029. EXPECT_EQ(file1.filename, "hello.txt");
  3030. EXPECT_EQ(file1.content_type, "text/plain");
  3031. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3032. auto file2 = file1_values[1];
  3033. EXPECT_EQ(file2.filename, "world.json");
  3034. EXPECT_EQ(file2.content_type, "application/json");
  3035. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3036. }
  3037. })
  3038. .Post("/empty",
  3039. [&](const Request &req, Response &res) {
  3040. EXPECT_EQ(req.body, "");
  3041. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3042. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3043. res.set_content("empty", "text/plain");
  3044. })
  3045. .Post("/empty-no-content-type",
  3046. [&](const Request &req, Response &res) {
  3047. EXPECT_EQ(req.body, "");
  3048. EXPECT_FALSE(req.has_header("Content-Type"));
  3049. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3050. res.set_content("empty-no-content-type", "text/plain");
  3051. })
  3052. .Post("/path-only",
  3053. [&](const Request &req, Response &res) {
  3054. EXPECT_EQ(req.body, "");
  3055. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3056. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3057. res.set_content("path-only", "text/plain");
  3058. })
  3059. .Post("/path-headers-only",
  3060. [&](const Request &req, Response &res) {
  3061. EXPECT_EQ(req.body, "");
  3062. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3063. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3064. EXPECT_EQ("world", req.get_header_value("hello"));
  3065. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3066. res.set_content("path-headers-only", "text/plain");
  3067. })
  3068. .Post("/post-large",
  3069. [&](const Request &req, Response &res) {
  3070. EXPECT_EQ(req.body, LARGE_DATA);
  3071. res.set_content(req.body, "text/plain");
  3072. })
  3073. .Post("/post-loopback",
  3074. [&](const Request &, Response &res,
  3075. ContentReader const &content_reader) {
  3076. std::string body;
  3077. content_reader([&](const char *data, size_t data_length) {
  3078. body.append(data, data_length);
  3079. return true;
  3080. });
  3081. res.set_content(body, "text/plain");
  3082. })
  3083. .Put("/put-loopback",
  3084. [&](const Request &, Response &res,
  3085. ContentReader const &content_reader) {
  3086. std::string body;
  3087. content_reader([&](const char *data, size_t data_length) {
  3088. body.append(data, data_length);
  3089. return true;
  3090. });
  3091. res.set_content(body, "text/plain");
  3092. })
  3093. .Patch("/patch-loopback",
  3094. [&](const Request &, Response &res,
  3095. ContentReader const &content_reader) {
  3096. std::string body;
  3097. content_reader([&](const char *data, size_t data_length) {
  3098. body.append(data, data_length);
  3099. return true;
  3100. });
  3101. res.set_content(body, "text/plain");
  3102. })
  3103. .Put("/empty-no-content-type",
  3104. [&](const Request &req, Response &res) {
  3105. EXPECT_EQ(req.body, "");
  3106. EXPECT_FALSE(req.has_header("Content-Type"));
  3107. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3108. res.set_content("empty-no-content-type", "text/plain");
  3109. })
  3110. .Put("/put",
  3111. [&](const Request &req, Response &res) {
  3112. EXPECT_EQ(req.body, "PUT");
  3113. res.set_content(req.body, "text/plain");
  3114. })
  3115. .Put("/put-large",
  3116. [&](const Request &req, Response &res) {
  3117. EXPECT_EQ(req.body, LARGE_DATA);
  3118. res.set_content(req.body, "text/plain");
  3119. })
  3120. .Patch("/patch",
  3121. [&](const Request &req, Response &res) {
  3122. EXPECT_EQ(req.body, "PATCH");
  3123. res.set_content(req.body, "text/plain");
  3124. })
  3125. .Delete("/delete",
  3126. [&](const Request & /*req*/, Response &res) {
  3127. res.set_content("DELETE", "text/plain");
  3128. })
  3129. .Delete("/delete-body",
  3130. [&](const Request &req, Response &res) {
  3131. EXPECT_EQ(req.body, "content");
  3132. res.set_content(req.body, "text/plain");
  3133. })
  3134. .Options(R"(\*)",
  3135. [&](const Request & /*req*/, Response &res) {
  3136. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3137. })
  3138. .Get("/request-target",
  3139. [&](const Request &req, Response & /*res*/) {
  3140. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3141. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3142. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3143. })
  3144. .Get("/long-query-value",
  3145. [&](const Request &req, Response & /*res*/) {
  3146. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3147. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3148. })
  3149. .Get("/too-long-query-value",
  3150. [&](const Request &req, Response & /*res*/) {
  3151. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3152. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3153. })
  3154. .Get("/array-param",
  3155. [&](const Request &req, Response & /*res*/) {
  3156. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3157. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3158. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3159. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3160. })
  3161. .Post("/validate-no-multiple-headers",
  3162. [&](const Request &req, Response & /*res*/) {
  3163. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3164. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3165. })
  3166. .Post("/content_receiver",
  3167. [&](const Request &req, Response &res,
  3168. const ContentReader &content_reader) {
  3169. if (req.is_multipart_form_data()) {
  3170. std::vector<FormData> items;
  3171. content_reader(
  3172. [&](const FormData &file) {
  3173. items.push_back(file);
  3174. return true;
  3175. },
  3176. [&](const char *data, size_t data_length) {
  3177. items.back().content.append(data, data_length);
  3178. return true;
  3179. });
  3180. EXPECT_EQ(5u, items.size());
  3181. {
  3182. const auto &file = get_file_value(items, "text1");
  3183. EXPECT_TRUE(file.filename.empty());
  3184. EXPECT_EQ("text default", file.content);
  3185. }
  3186. {
  3187. const auto &file = get_file_value(items, "text2");
  3188. EXPECT_TRUE(file.filename.empty());
  3189. EXPECT_EQ("aωb", file.content);
  3190. }
  3191. {
  3192. const auto &file = get_file_value(items, "file1");
  3193. EXPECT_EQ("hello.txt", file.filename);
  3194. EXPECT_EQ("text/plain", file.content_type);
  3195. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3196. }
  3197. {
  3198. const auto &file = get_file_value(items, "file2");
  3199. EXPECT_EQ("world.json", file.filename);
  3200. EXPECT_EQ("application/json", file.content_type);
  3201. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3202. }
  3203. {
  3204. const auto &file = get_file_value(items, "file3");
  3205. EXPECT_TRUE(file.filename.empty());
  3206. EXPECT_EQ("application/octet-stream", file.content_type);
  3207. EXPECT_EQ(0u, file.content.size());
  3208. }
  3209. } else {
  3210. std::string body;
  3211. content_reader([&](const char *data, size_t data_length) {
  3212. EXPECT_EQ(7U, data_length);
  3213. body.append(data, data_length);
  3214. return true;
  3215. });
  3216. EXPECT_EQ(body, "content");
  3217. res.set_content(body, "text/plain");
  3218. }
  3219. })
  3220. .Put("/content_receiver",
  3221. [&](const Request & /*req*/, Response &res,
  3222. const ContentReader &content_reader) {
  3223. std::string body;
  3224. content_reader([&](const char *data, size_t data_length) {
  3225. body.append(data, data_length);
  3226. return true;
  3227. });
  3228. EXPECT_EQ(body, "content");
  3229. res.set_content(body, "text/plain");
  3230. })
  3231. .Patch("/content_receiver",
  3232. [&](const Request & /*req*/, Response &res,
  3233. const ContentReader &content_reader) {
  3234. std::string body;
  3235. content_reader([&](const char *data, size_t data_length) {
  3236. body.append(data, data_length);
  3237. return true;
  3238. });
  3239. EXPECT_EQ(body, "content");
  3240. res.set_content(body, "text/plain");
  3241. })
  3242. .Post("/query-string-and-body",
  3243. [&](const Request &req, Response & /*res*/) {
  3244. ASSERT_TRUE(req.has_param("key"));
  3245. EXPECT_EQ(req.get_param_value("key"), "value");
  3246. EXPECT_EQ(req.body, "content");
  3247. })
  3248. .Get("/last-request",
  3249. [&](const Request &req, Response & /*res*/) {
  3250. EXPECT_EQ("close", req.get_header_value("Connection"));
  3251. })
  3252. .Get(R"(/redirect/(\d+))",
  3253. [&](const Request &req, Response &res) {
  3254. auto num = std::stoi(req.matches[1]) + 1;
  3255. std::string url = "/redirect/" + std::to_string(num);
  3256. res.set_redirect(url);
  3257. })
  3258. .Post("/binary",
  3259. [&](const Request &req, Response &res) {
  3260. EXPECT_EQ(4U, req.body.size());
  3261. EXPECT_EQ("application/octet-stream",
  3262. req.get_header_value("Content-Type"));
  3263. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3264. res.set_content(req.body, "application/octet-stream");
  3265. })
  3266. .Put("/binary",
  3267. [&](const Request &req, Response &res) {
  3268. EXPECT_EQ(4U, req.body.size());
  3269. EXPECT_EQ("application/octet-stream",
  3270. req.get_header_value("Content-Type"));
  3271. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3272. res.set_content(req.body, "application/octet-stream");
  3273. })
  3274. .Patch("/binary",
  3275. [&](const Request &req, Response &res) {
  3276. EXPECT_EQ(4U, req.body.size());
  3277. EXPECT_EQ("application/octet-stream",
  3278. req.get_header_value("Content-Type"));
  3279. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3280. res.set_content(req.body, "application/octet-stream");
  3281. })
  3282. .Delete("/binary",
  3283. [&](const Request &req, Response &res) {
  3284. EXPECT_EQ(4U, req.body.size());
  3285. EXPECT_EQ("application/octet-stream",
  3286. req.get_header_value("Content-Type"));
  3287. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3288. res.set_content(req.body, "application/octet-stream");
  3289. })
  3290. .Get("/issue1772",
  3291. [&](const Request & /*req*/, Response &res) {
  3292. res.status = 401;
  3293. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3294. })
  3295. .Delete("/issue609",
  3296. [](const httplib::Request &, httplib::Response &res,
  3297. const httplib::ContentReader &) {
  3298. res.set_content("ok", "text/plain");
  3299. })
  3300. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3301. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3302. .Get("/compress",
  3303. [&](const Request & /*req*/, Response &res) {
  3304. res.set_content(
  3305. "12345678901234567890123456789012345678901234567890123456789"
  3306. "01234567890123456789012345678901234567890",
  3307. "text/plain");
  3308. })
  3309. .Get("/compress-with-charset",
  3310. [&](const Request & /*req*/, Response &res) {
  3311. res.set_content(
  3312. "12345678901234567890123456789012345678901234567890123456789"
  3313. "01234567890123456789012345678901234567890",
  3314. "application/json; charset=utf-8");
  3315. })
  3316. .Get("/nocompress",
  3317. [&](const Request & /*req*/, Response &res) {
  3318. res.set_content(
  3319. "12345678901234567890123456789012345678901234567890123456789"
  3320. "01234567890123456789012345678901234567890",
  3321. "application/octet-stream");
  3322. })
  3323. .Post("/compress-multipart",
  3324. [&](const Request &req, Response & /*res*/) {
  3325. EXPECT_EQ(2u, req.form.fields.size());
  3326. ASSERT_TRUE(!req.form.has_field("???"));
  3327. {
  3328. const auto &text = req.form.get_field("key1");
  3329. EXPECT_EQ("test", text);
  3330. }
  3331. {
  3332. const auto &text = req.form.get_field("key2");
  3333. EXPECT_EQ("--abcdefg123", text);
  3334. }
  3335. })
  3336. #endif
  3337. ;
  3338. persons_["john"] = "programmer";
  3339. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3340. svr_.wait_until_ready();
  3341. }
  3342. virtual void TearDown() {
  3343. svr_.stop();
  3344. if (!request_threads_.empty()) {
  3345. std::this_thread::sleep_for(std::chrono::seconds(1));
  3346. for (auto &t : request_threads_) {
  3347. t.join();
  3348. }
  3349. }
  3350. t_.join();
  3351. }
  3352. map<string, string> persons_;
  3353. #ifdef CPPHTTPLIB_SSL_ENABLED
  3354. SSLClient cli_;
  3355. SSLServer svr_;
  3356. #else
  3357. Client cli_;
  3358. Server svr_;
  3359. #endif
  3360. thread t_;
  3361. std::vector<thread> request_threads_;
  3362. };
  3363. TEST_F(ServerTest, GetMethod200) {
  3364. auto res = cli_.Get("/hi");
  3365. ASSERT_TRUE(res);
  3366. EXPECT_EQ("HTTP/1.1", res->version);
  3367. EXPECT_EQ(StatusCode::OK_200, res->status);
  3368. EXPECT_EQ("OK", res->reason);
  3369. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3370. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3371. EXPECT_EQ("Hello World!", res->body);
  3372. }
  3373. TEST_F(ServerTest, GetEmptyFile) {
  3374. auto res = cli_.Get("/empty_file");
  3375. ASSERT_TRUE(res);
  3376. EXPECT_EQ(StatusCode::OK_200, res->status);
  3377. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3378. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3379. EXPECT_EQ("", res->body);
  3380. }
  3381. TEST_F(ServerTest, GetFileContent) {
  3382. auto res = cli_.Get("/file_content");
  3383. ASSERT_TRUE(res);
  3384. EXPECT_EQ(StatusCode::OK_200, res->status);
  3385. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3386. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3387. EXPECT_EQ("test.html", res->body);
  3388. }
  3389. TEST_F(ServerTest, GetFileContentWithRange) {
  3390. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3391. ASSERT_TRUE(res);
  3392. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3393. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3394. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3395. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3396. EXPECT_EQ("est", res->body);
  3397. }
  3398. TEST_F(ServerTest, GetFileContentWithContentType) {
  3399. auto res = cli_.Get("/file_content_with_content_type");
  3400. ASSERT_TRUE(res);
  3401. EXPECT_EQ(StatusCode::OK_200, res->status);
  3402. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3403. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3404. EXPECT_EQ("file\n", res->body);
  3405. }
  3406. TEST_F(ServerTest, GetInvalidFileContent) {
  3407. auto res = cli_.Get("/invalid_file_content");
  3408. ASSERT_TRUE(res);
  3409. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3410. }
  3411. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3412. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3413. ASSERT_TRUE(res);
  3414. EXPECT_EQ("HTTP/1.1", res->version);
  3415. EXPECT_EQ(StatusCode::OK_200, res->status);
  3416. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3417. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3418. EXPECT_EQ("Hello World!", res->body);
  3419. }
  3420. TEST_F(ServerTest, GetMethod302) {
  3421. auto res = cli_.Get("/");
  3422. ASSERT_TRUE(res);
  3423. EXPECT_EQ(StatusCode::Found_302, res->status);
  3424. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3425. }
  3426. TEST_F(ServerTest, GetMethod302Redirect) {
  3427. cli_.set_follow_location(true);
  3428. auto res = cli_.Get("/");
  3429. ASSERT_TRUE(res);
  3430. EXPECT_EQ(StatusCode::OK_200, res->status);
  3431. EXPECT_EQ("Hello World!", res->body);
  3432. EXPECT_EQ("/hi", res->location);
  3433. }
  3434. TEST_F(ServerTest, GetMethod404) {
  3435. auto res = cli_.Get("/invalid");
  3436. ASSERT_TRUE(res);
  3437. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3438. }
  3439. TEST_F(ServerTest, HeadMethod200) {
  3440. auto res = cli_.Head("/hi");
  3441. ASSERT_TRUE(res);
  3442. EXPECT_EQ(StatusCode::OK_200, res->status);
  3443. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3444. EXPECT_TRUE(res->body.empty());
  3445. }
  3446. TEST_F(ServerTest, HeadMethod200Static) {
  3447. auto res = cli_.Head("/mount/dir/index.html");
  3448. ASSERT_TRUE(res);
  3449. EXPECT_EQ(StatusCode::OK_200, res->status);
  3450. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3451. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3452. EXPECT_TRUE(res->body.empty());
  3453. }
  3454. TEST_F(ServerTest, HeadMethod404) {
  3455. auto res = cli_.Head("/invalid");
  3456. ASSERT_TRUE(res);
  3457. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3458. EXPECT_TRUE(res->body.empty());
  3459. }
  3460. TEST_F(ServerTest, GetMethodPersonJohn) {
  3461. auto res = cli_.Get("/person/john");
  3462. ASSERT_TRUE(res);
  3463. EXPECT_EQ(StatusCode::OK_200, res->status);
  3464. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3465. EXPECT_EQ("programmer", res->body);
  3466. }
  3467. TEST_F(ServerTest, PostMethod1) {
  3468. auto res = cli_.Get("/person/john1");
  3469. ASSERT_TRUE(res);
  3470. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3471. res = cli_.Post("/person", "name=john1&note=coder",
  3472. "application/x-www-form-urlencoded");
  3473. ASSERT_TRUE(res);
  3474. ASSERT_EQ(StatusCode::OK_200, res->status);
  3475. res = cli_.Get("/person/john1");
  3476. ASSERT_TRUE(res);
  3477. ASSERT_EQ(StatusCode::OK_200, res->status);
  3478. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3479. ASSERT_EQ("coder", res->body);
  3480. }
  3481. TEST_F(ServerTest, PostMethod2) {
  3482. auto res = cli_.Get("/person/john2");
  3483. ASSERT_TRUE(res);
  3484. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3485. Params params;
  3486. params.emplace("name", "john2");
  3487. params.emplace("note", "coder");
  3488. res = cli_.Post("/person", params);
  3489. ASSERT_TRUE(res);
  3490. ASSERT_EQ(StatusCode::OK_200, res->status);
  3491. res = cli_.Get("/person/john2");
  3492. ASSERT_TRUE(res);
  3493. ASSERT_EQ(StatusCode::OK_200, res->status);
  3494. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3495. ASSERT_EQ("coder", res->body);
  3496. }
  3497. TEST_F(ServerTest, PutMethod3) {
  3498. auto res = cli_.Get("/person/john3");
  3499. ASSERT_TRUE(res);
  3500. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3501. Params params;
  3502. params.emplace("name", "john3");
  3503. params.emplace("note", "coder");
  3504. res = cli_.Put("/person", params);
  3505. ASSERT_TRUE(res);
  3506. ASSERT_EQ(StatusCode::OK_200, res->status);
  3507. res = cli_.Get("/person/john3");
  3508. ASSERT_TRUE(res);
  3509. ASSERT_EQ(StatusCode::OK_200, res->status);
  3510. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3511. ASSERT_EQ("coder", res->body);
  3512. }
  3513. TEST_F(ServerTest, DeleteMethod1) {
  3514. auto res = cli_.Get("/person/john4");
  3515. ASSERT_TRUE(res);
  3516. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3517. Params params;
  3518. params.emplace("name", "john4");
  3519. params.emplace("note", "coder");
  3520. res = cli_.Post("/person", params);
  3521. ASSERT_TRUE(res);
  3522. ASSERT_EQ(StatusCode::OK_200, res->status);
  3523. res = cli_.Get("/person/john4");
  3524. ASSERT_TRUE(res);
  3525. ASSERT_EQ(StatusCode::OK_200, res->status);
  3526. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3527. ASSERT_EQ("coder", res->body);
  3528. Params delete_params;
  3529. delete_params.emplace("name", "john4");
  3530. res = cli_.Delete("/person", delete_params);
  3531. ASSERT_TRUE(res);
  3532. ASSERT_EQ(StatusCode::OK_200, res->status);
  3533. ASSERT_EQ("DELETED", res->body);
  3534. res = cli_.Get("/person/john4");
  3535. ASSERT_TRUE(res);
  3536. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3537. }
  3538. TEST_F(ServerTest, DeleteMethod2) {
  3539. auto res = cli_.Get("/person/john5");
  3540. ASSERT_TRUE(res);
  3541. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3542. Params params;
  3543. params.emplace("name", "john5");
  3544. params.emplace("note", "developer");
  3545. res = cli_.Post("/person", params);
  3546. ASSERT_TRUE(res);
  3547. ASSERT_EQ(StatusCode::OK_200, res->status);
  3548. res = cli_.Get("/person/john5");
  3549. ASSERT_TRUE(res);
  3550. ASSERT_EQ(StatusCode::OK_200, res->status);
  3551. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3552. ASSERT_EQ("developer", res->body);
  3553. Params delete_params;
  3554. delete_params.emplace("name", "john5");
  3555. Headers headers;
  3556. headers.emplace("Custom-Header", "test-value");
  3557. res = cli_.Delete("/person", headers, delete_params);
  3558. ASSERT_TRUE(res);
  3559. ASSERT_EQ(StatusCode::OK_200, res->status);
  3560. ASSERT_EQ("DELETED", res->body);
  3561. res = cli_.Get("/person/john5");
  3562. ASSERT_TRUE(res);
  3563. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3564. }
  3565. TEST_F(ServerTest, DeleteMethod3) {
  3566. auto res = cli_.Get("/person/john6");
  3567. ASSERT_TRUE(res);
  3568. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3569. Params params;
  3570. params.emplace("name", "john6");
  3571. params.emplace("note", "tester");
  3572. res = cli_.Post("/person", params);
  3573. ASSERT_TRUE(res);
  3574. ASSERT_EQ(StatusCode::OK_200, res->status);
  3575. res = cli_.Get("/person/john6");
  3576. ASSERT_TRUE(res);
  3577. ASSERT_EQ(StatusCode::OK_200, res->status);
  3578. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3579. ASSERT_EQ("tester", res->body);
  3580. Params delete_params;
  3581. delete_params.emplace("name", "john6");
  3582. Headers headers;
  3583. headers.emplace("Custom-Header", "test-value");
  3584. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3585. ASSERT_TRUE(res);
  3586. ASSERT_EQ(StatusCode::OK_200, res->status);
  3587. ASSERT_EQ("DELETED", res->body);
  3588. res = cli_.Get("/person/john6");
  3589. ASSERT_TRUE(res);
  3590. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3591. }
  3592. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3593. Params params;
  3594. params.emplace("json", JSON_DATA);
  3595. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3596. ASSERT_TRUE(res);
  3597. ASSERT_EQ(StatusCode::OK_200, res->status);
  3598. ASSERT_EQ(JSON_DATA, res->body);
  3599. }
  3600. TEST_F(ServerTest, PostEmptyContent) {
  3601. auto res = cli_.Post("/empty", "", "text/plain");
  3602. ASSERT_TRUE(res);
  3603. ASSERT_EQ(StatusCode::OK_200, res->status);
  3604. ASSERT_EQ("empty", res->body);
  3605. }
  3606. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3607. auto res = cli_.Post("/empty-no-content-type");
  3608. ASSERT_TRUE(res);
  3609. ASSERT_EQ(StatusCode::OK_200, res->status);
  3610. ASSERT_EQ("empty-no-content-type", res->body);
  3611. }
  3612. TEST_F(ServerTest, PostPathOnly) {
  3613. auto res = cli_.Post("/path-only");
  3614. ASSERT_TRUE(res);
  3615. ASSERT_EQ(StatusCode::OK_200, res->status);
  3616. ASSERT_EQ("path-only", res->body);
  3617. }
  3618. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3619. auto res = cli_.Post("/path-headers-only",
  3620. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3621. ASSERT_TRUE(res);
  3622. ASSERT_EQ(StatusCode::OK_200, res->status);
  3623. ASSERT_EQ("path-headers-only", res->body);
  3624. }
  3625. TEST_F(ServerTest, PostLarge) {
  3626. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3627. ASSERT_TRUE(res);
  3628. ASSERT_EQ(StatusCode::OK_200, res->status);
  3629. EXPECT_EQ(LARGE_DATA, res->body);
  3630. }
  3631. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3632. auto res = cli_.Put("/empty-no-content-type");
  3633. ASSERT_TRUE(res);
  3634. ASSERT_EQ(StatusCode::OK_200, res->status);
  3635. ASSERT_EQ("empty-no-content-type", res->body);
  3636. }
  3637. TEST_F(ServerTest, GetMethodDir) {
  3638. auto res = cli_.Get("/dir/");
  3639. ASSERT_TRUE(res);
  3640. EXPECT_EQ(StatusCode::OK_200, res->status);
  3641. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3642. auto body = R"(<html>
  3643. <head>
  3644. </head>
  3645. <body>
  3646. <a href="/dir/test.html">Test</a>
  3647. <a href="/hi">hi</a>
  3648. </body>
  3649. </html>
  3650. )";
  3651. EXPECT_EQ(body, res->body);
  3652. }
  3653. TEST_F(ServerTest, GetMethodDirTest) {
  3654. auto res = cli_.Get("/dir/test.html");
  3655. ASSERT_TRUE(res);
  3656. EXPECT_EQ(StatusCode::OK_200, res->status);
  3657. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3658. EXPECT_EQ("test.html", res->body);
  3659. }
  3660. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3661. auto res = cli_.Get("/dir/../dir/test.html");
  3662. ASSERT_TRUE(res);
  3663. EXPECT_EQ(StatusCode::OK_200, res->status);
  3664. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3665. EXPECT_EQ("test.html", res->body);
  3666. }
  3667. TEST_F(ServerTest, GetMethodInvalidPath) {
  3668. auto res = cli_.Get("/dir/../test.html");
  3669. ASSERT_TRUE(res);
  3670. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3671. }
  3672. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3673. auto res = cli_.Get("/../www/dir/test.html");
  3674. ASSERT_TRUE(res);
  3675. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3676. }
  3677. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3678. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3679. ASSERT_TRUE(res);
  3680. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3681. }
  3682. TEST_F(ServerTest, GetMethodDirMountTest) {
  3683. auto res = cli_.Get("/mount/dir/test.html");
  3684. ASSERT_TRUE(res);
  3685. EXPECT_EQ(StatusCode::OK_200, res->status);
  3686. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3687. EXPECT_EQ("test.html", res->body);
  3688. }
  3689. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3690. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3691. ASSERT_TRUE(res);
  3692. EXPECT_EQ(StatusCode::OK_200, res->status);
  3693. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3694. EXPECT_EQ("test.html", res->body);
  3695. }
  3696. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3697. auto res = cli_.Get("/mount/dir/../test.html");
  3698. ASSERT_TRUE(res);
  3699. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3700. }
  3701. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3702. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3703. ASSERT_TRUE(res);
  3704. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3705. }
  3706. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3707. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3708. ASSERT_TRUE(res);
  3709. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3710. }
  3711. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3712. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3713. ASSERT_TRUE(res);
  3714. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3715. }
  3716. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3717. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3718. ASSERT_TRUE(res);
  3719. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3720. }
  3721. TEST_F(ServerTest, PostMethod303) {
  3722. auto res = cli_.Post("/1", "body", "text/plain");
  3723. ASSERT_TRUE(res);
  3724. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3725. EXPECT_EQ("/2", res->get_header_value("Location"));
  3726. }
  3727. TEST_F(ServerTest, PostMethod303Redirect) {
  3728. cli_.set_follow_location(true);
  3729. auto res = cli_.Post("/1", "body", "text/plain");
  3730. ASSERT_TRUE(res);
  3731. EXPECT_EQ(StatusCode::OK_200, res->status);
  3732. EXPECT_EQ("redirected.", res->body);
  3733. EXPECT_EQ("/2", res->location);
  3734. }
  3735. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3736. auto res = cli_.Get("/dir/test.abcde");
  3737. ASSERT_TRUE(res);
  3738. EXPECT_EQ(StatusCode::OK_200, res->status);
  3739. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3740. EXPECT_EQ("abcde", res->body);
  3741. }
  3742. TEST_F(ServerTest, StaticFileRange) {
  3743. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3744. ASSERT_TRUE(res);
  3745. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3746. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3747. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3748. EXPECT_EQ(true, res->has_header("Content-Range"));
  3749. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3750. EXPECT_EQ(std::string("cd"), res->body);
  3751. }
  3752. TEST_F(ServerTest, StaticFileRanges) {
  3753. auto res =
  3754. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3755. ASSERT_TRUE(res);
  3756. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3757. EXPECT_TRUE(
  3758. res->get_header_value("Content-Type")
  3759. .find(
  3760. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3761. 0);
  3762. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3763. }
  3764. TEST_F(ServerTest, StaticFileRangeHead) {
  3765. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3766. ASSERT_TRUE(res);
  3767. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3768. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3769. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3770. EXPECT_EQ(true, res->has_header("Content-Range"));
  3771. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3772. }
  3773. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3774. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3775. ASSERT_TRUE(res);
  3776. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3777. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3778. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3779. EXPECT_EQ(true, res->has_header("Content-Range"));
  3780. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3781. res->get_header_value("Content-Range"));
  3782. EXPECT_EQ("LAST\n", res->body);
  3783. }
  3784. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3785. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3786. ASSERT_TRUE(res);
  3787. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3788. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3789. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3790. EXPECT_EQ(true, res->has_header("Content-Range"));
  3791. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3792. }
  3793. TEST_F(ServerTest, StaticFileBigFile) {
  3794. auto res = cli_.Get("/dir/1MB.txt");
  3795. ASSERT_TRUE(res);
  3796. EXPECT_EQ(StatusCode::OK_200, res->status);
  3797. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3798. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3799. }
  3800. TEST_F(ServerTest, InvalidBaseDirMount) {
  3801. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3802. }
  3803. TEST_F(ServerTest, Binary) {
  3804. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3805. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3806. "application/octet-stream");
  3807. ASSERT_TRUE(res);
  3808. ASSERT_EQ(StatusCode::OK_200, res->status);
  3809. ASSERT_EQ(4U, res->body.size());
  3810. res = cli_.Put("/binary", binary.data(), binary.size(),
  3811. "application/octet-stream");
  3812. ASSERT_TRUE(res);
  3813. ASSERT_EQ(StatusCode::OK_200, res->status);
  3814. ASSERT_EQ(4U, res->body.size());
  3815. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3816. "application/octet-stream");
  3817. ASSERT_TRUE(res);
  3818. ASSERT_EQ(StatusCode::OK_200, res->status);
  3819. ASSERT_EQ(4U, res->body.size());
  3820. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3821. "application/octet-stream");
  3822. ASSERT_TRUE(res);
  3823. ASSERT_EQ(StatusCode::OK_200, res->status);
  3824. ASSERT_EQ(4U, res->body.size());
  3825. }
  3826. TEST_F(ServerTest, BinaryString) {
  3827. auto binary = std::string("\x00\x01\x02\x03", 4);
  3828. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3829. ASSERT_TRUE(res);
  3830. ASSERT_EQ(StatusCode::OK_200, res->status);
  3831. ASSERT_EQ(4U, res->body.size());
  3832. res = cli_.Put("/binary", binary, "application/octet-stream");
  3833. ASSERT_TRUE(res);
  3834. ASSERT_EQ(StatusCode::OK_200, res->status);
  3835. ASSERT_EQ(4U, res->body.size());
  3836. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3837. ASSERT_TRUE(res);
  3838. ASSERT_EQ(StatusCode::OK_200, res->status);
  3839. ASSERT_EQ(4U, res->body.size());
  3840. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3841. ASSERT_TRUE(res);
  3842. ASSERT_EQ(StatusCode::OK_200, res->status);
  3843. ASSERT_EQ(4U, res->body.size());
  3844. }
  3845. TEST_F(ServerTest, EmptyRequest) {
  3846. auto res = cli_.Get("");
  3847. ASSERT_TRUE(!res);
  3848. EXPECT_EQ(Error::Connection, res.error());
  3849. }
  3850. TEST_F(ServerTest, LongRequest) {
  3851. std::string request;
  3852. for (size_t i = 0; i < 545; i++) {
  3853. request += "/TooLongRequest";
  3854. }
  3855. request += "OK";
  3856. auto res = cli_.Get(request.c_str());
  3857. ASSERT_TRUE(res);
  3858. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3859. }
  3860. TEST_F(ServerTest, TooLongRequest) {
  3861. std::string request;
  3862. for (size_t i = 0; i < 546; i++) {
  3863. request += "/TooLongRequest";
  3864. }
  3865. request += "_NG";
  3866. auto start = std::chrono::high_resolution_clock::now();
  3867. cli_.set_keep_alive(true);
  3868. auto res = cli_.Get(request.c_str());
  3869. auto end = std::chrono::high_resolution_clock::now();
  3870. auto elapsed =
  3871. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3872. .count();
  3873. ASSERT_TRUE(res);
  3874. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3875. EXPECT_LE(elapsed, 1000);
  3876. EXPECT_EQ("close", res->get_header_value("Connection"));
  3877. EXPECT_FALSE(cli_.is_socket_open());
  3878. }
  3879. TEST_F(ServerTest, AlmostTooLongRequest) {
  3880. // test for #2046 - URI length check shouldn't include other content on req
  3881. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3882. // leading /, space, HTTP/1.1)
  3883. std::string request =
  3884. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3885. auto res = cli_.Get(request.c_str());
  3886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3887. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3888. }
  3889. TEST_F(ServerTest, LongHeader) {
  3890. Request req;
  3891. req.method = "GET";
  3892. req.path = "/hi";
  3893. std::string host_and_port;
  3894. host_and_port += HOST;
  3895. host_and_port += ":";
  3896. host_and_port += std::to_string(PORT);
  3897. req.headers.emplace("Host", host_and_port.c_str());
  3898. req.headers.emplace("Accept", "*/*");
  3899. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3900. req.headers.emplace(
  3901. "Header-Name",
  3902. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3903. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3904. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3905. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3906. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3907. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3908. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3909. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3910. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3911. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3912. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3913. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3914. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3915. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3916. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3917. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3918. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3919. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3920. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3921. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3922. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3923. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3924. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3925. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3926. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3927. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3928. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3929. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3930. "@@@@@@@@@@@@@@@@");
  3931. auto res = std::make_shared<Response>();
  3932. auto error = Error::Success;
  3933. auto ret = cli_.send(req, *res, error);
  3934. ASSERT_TRUE(ret);
  3935. EXPECT_EQ(StatusCode::OK_200, res->status);
  3936. }
  3937. TEST_F(ServerTest, LongQueryValue) {
  3938. auto start = std::chrono::high_resolution_clock::now();
  3939. cli_.set_keep_alive(true);
  3940. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3941. auto end = std::chrono::high_resolution_clock::now();
  3942. auto elapsed =
  3943. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3944. .count();
  3945. ASSERT_TRUE(res);
  3946. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3947. EXPECT_LE(elapsed, 1000);
  3948. EXPECT_EQ("close", res->get_header_value("Connection"));
  3949. EXPECT_FALSE(cli_.is_socket_open());
  3950. }
  3951. TEST_F(ServerTest, TooLongQueryValue) {
  3952. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3953. ASSERT_FALSE(res);
  3954. EXPECT_EQ(Error::Read, res.error());
  3955. }
  3956. TEST_F(ServerTest, TooLongHeader) {
  3957. Request req;
  3958. req.method = "GET";
  3959. req.path = "/hi";
  3960. std::string host_and_port;
  3961. host_and_port += HOST;
  3962. host_and_port += ":";
  3963. host_and_port += std::to_string(PORT);
  3964. req.headers.emplace("Host", host_and_port.c_str());
  3965. req.headers.emplace("Accept", "*/*");
  3966. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3967. req.headers.emplace(
  3968. "Header-Name",
  3969. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3970. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3971. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3972. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3973. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3974. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3975. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3976. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3977. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3978. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3979. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3980. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3981. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3982. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3983. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3984. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3985. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3986. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3987. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3988. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3989. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3990. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3991. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3992. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3993. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3994. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3995. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3996. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3997. "@@@@@@@@@@@@@@@@@");
  3998. auto res = std::make_shared<Response>();
  3999. auto error = Error::Success;
  4000. auto ret = cli_.send(req, *res, error);
  4001. ASSERT_TRUE(ret);
  4002. EXPECT_EQ(StatusCode::OK_200, res->status);
  4003. }
  4004. TEST_F(ServerTest, HeaderCountAtLimit) {
  4005. // Test with headers just under the 100 limit
  4006. httplib::Headers headers;
  4007. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4008. // This should keep us just under the 100 header limit
  4009. for (int i = 0; i < 95; i++) {
  4010. std::string name = "X-Test-Header-" + std::to_string(i);
  4011. std::string value = "value" + std::to_string(i);
  4012. headers.emplace(name, value);
  4013. }
  4014. // This should work fine as we're under the limit
  4015. auto res = cli_.Get("/hi", headers);
  4016. EXPECT_TRUE(res);
  4017. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4018. }
  4019. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4020. // Test with many headers to exceed the 100 limit
  4021. httplib::Headers headers;
  4022. // Add 150 headers to definitely exceed the 100 limit
  4023. for (int i = 0; i < 150; i++) {
  4024. std::string name = "X-Test-Header-" + std::to_string(i);
  4025. std::string value = "value" + std::to_string(i);
  4026. headers.emplace(name, value);
  4027. }
  4028. // This should fail due to exceeding header count limit
  4029. cli_.set_keep_alive(true);
  4030. auto res = cli_.Get("/hi", headers);
  4031. // The server should respond with 400 Bad Request
  4032. ASSERT_TRUE(res);
  4033. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4034. EXPECT_EQ("close", res->get_header_value("Connection"));
  4035. EXPECT_FALSE(cli_.is_socket_open());
  4036. }
  4037. TEST_F(ServerTest, PercentEncoding) {
  4038. auto res = cli_.Get("/e%6edwith%");
  4039. ASSERT_TRUE(res);
  4040. EXPECT_EQ(StatusCode::OK_200, res->status);
  4041. }
  4042. TEST_F(ServerTest, PercentEncodingUnicode) {
  4043. auto res = cli_.Get("/e%u006edwith%");
  4044. ASSERT_TRUE(res);
  4045. EXPECT_EQ(StatusCode::OK_200, res->status);
  4046. }
  4047. TEST_F(ServerTest, InvalidPercentEncoding) {
  4048. auto res = cli_.Get("/%endwith%");
  4049. ASSERT_TRUE(res);
  4050. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4051. }
  4052. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4053. auto res = cli_.Get("/%uendwith%");
  4054. ASSERT_TRUE(res);
  4055. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4056. }
  4057. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4058. auto res = cli_.Get("/hello?aaa=bbb%");
  4059. ASSERT_TRUE(res);
  4060. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4061. }
  4062. TEST_F(ServerTest, PlusSignEncoding) {
  4063. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4064. ASSERT_TRUE(res);
  4065. EXPECT_EQ(StatusCode::OK_200, res->status);
  4066. EXPECT_EQ("a +b", res->body);
  4067. }
  4068. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4069. // This test simulates a potential DoS attack using many headers
  4070. // to verify our security fix prevents memory exhaustion
  4071. httplib::Headers attack_headers;
  4072. // Attempt to add many headers like an attacker would (200 headers to far
  4073. // exceed limit)
  4074. for (int i = 0; i < 200; i++) {
  4075. std::string name = "X-Attack-Header-" + std::to_string(i);
  4076. std::string value = "attack_payload_" + std::to_string(i);
  4077. attack_headers.emplace(name, value);
  4078. }
  4079. // Try to POST with excessive headers
  4080. cli_.set_keep_alive(true);
  4081. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4082. // Should either fail or return 400 Bad Request due to security limit
  4083. if (res) {
  4084. // If we get a response, it should be 400 Bad Request
  4085. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4086. EXPECT_EQ("close", res->get_header_value("Connection"));
  4087. }
  4088. EXPECT_FALSE(cli_.is_socket_open());
  4089. }
  4090. TEST_F(ServerTest, MultipartFormData) {
  4091. UploadFormDataItems items = {
  4092. {"text1", "text default", "", ""},
  4093. {"text2", "aωb", "", ""},
  4094. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4095. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4096. {"file3", "", "", "application/octet-stream"},
  4097. {"file4", "", "", " application/json tmp-string "}};
  4098. auto res = cli_.Post("/multipart", items);
  4099. ASSERT_TRUE(res);
  4100. EXPECT_EQ(StatusCode::OK_200, res->status);
  4101. }
  4102. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4103. UploadFormDataItems items = {
  4104. {"text", "default text", "", ""},
  4105. {"multi_text1", "aaaaa", "", ""},
  4106. {"multi_text1", "bbbbb", "", ""},
  4107. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4108. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4109. "application/json"},
  4110. };
  4111. auto res = cli_.Post("/multipart/multi_file_values", items);
  4112. ASSERT_TRUE(res);
  4113. EXPECT_EQ(StatusCode::OK_200, res->status);
  4114. }
  4115. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4116. auto res = cli_.Get("/hi");
  4117. ASSERT_TRUE(res);
  4118. EXPECT_EQ(StatusCode::OK_200, res->status);
  4119. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4120. EXPECT_EQ("Hello World!", res->body);
  4121. }
  4122. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4123. Request req;
  4124. req.method = "POST";
  4125. req.path = "/chunked";
  4126. std::string host_and_port;
  4127. host_and_port += HOST;
  4128. host_and_port += ":";
  4129. host_and_port += std::to_string(PORT);
  4130. req.headers.emplace("Host", host_and_port.c_str());
  4131. req.headers.emplace("Accept", "*/*");
  4132. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4133. req.headers.emplace("Content-Type", "text/plain");
  4134. req.headers.emplace("Content-Length", "0");
  4135. req.headers.emplace(
  4136. "Transfer-Encoding",
  4137. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4138. // Client does not chunk, so make a chunked body manually.
  4139. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4140. auto res = std::make_shared<Response>();
  4141. auto error = Error::Success;
  4142. auto ret = cli_.send(req, *res, error);
  4143. ASSERT_TRUE(ret);
  4144. EXPECT_EQ(StatusCode::OK_200, res->status);
  4145. }
  4146. TEST_F(ServerTest, GetStreamed2) {
  4147. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4148. ASSERT_TRUE(res);
  4149. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4150. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4151. EXPECT_EQ(true, res->has_header("Content-Range"));
  4152. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4153. EXPECT_EQ(std::string("ab"), res->body);
  4154. }
  4155. TEST_F(ServerTest, GetStreamed) {
  4156. auto res = cli_.Get("/streamed");
  4157. ASSERT_TRUE(res);
  4158. EXPECT_EQ(StatusCode::OK_200, res->status);
  4159. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4160. EXPECT_EQ(std::string("aaabbb"), res->body);
  4161. }
  4162. TEST_F(ServerTest, GetStreamedWithRange1) {
  4163. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4164. ASSERT_TRUE(res);
  4165. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4166. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4167. EXPECT_EQ(true, res->has_header("Content-Range"));
  4168. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4169. EXPECT_EQ(std::string("def"), res->body);
  4170. }
  4171. TEST_F(ServerTest, GetStreamedWithRange2) {
  4172. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4173. ASSERT_TRUE(res);
  4174. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4175. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4176. EXPECT_EQ(true, res->has_header("Content-Range"));
  4177. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4178. EXPECT_EQ(std::string("bcdefg"), res->body);
  4179. }
  4180. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4181. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4182. ASSERT_TRUE(res);
  4183. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4184. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4185. EXPECT_EQ(true, res->has_header("Content-Range"));
  4186. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4187. EXPECT_EQ(std::string("efg"), res->body);
  4188. }
  4189. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4190. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4191. ASSERT_TRUE(res);
  4192. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4193. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4194. EXPECT_EQ(false, res->has_header("Content-Range"));
  4195. EXPECT_EQ(0U, res->body.size());
  4196. }
  4197. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4198. auto res = cli_.Get("/streamed-with-range",
  4199. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4200. "92233720368547758079223372036854775807"}});
  4201. ASSERT_TRUE(res);
  4202. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4203. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4204. EXPECT_EQ(false, res->has_header("Content-Range"));
  4205. EXPECT_EQ(0U, res->body.size());
  4206. }
  4207. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4208. auto res = cli_.Get(
  4209. "/with-range",
  4210. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4211. {"Accept-Encoding", ""}});
  4212. ASSERT_TRUE(res);
  4213. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4214. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4215. EXPECT_EQ(true, res->has_header("Content-Range"));
  4216. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4217. EXPECT_EQ(std::string("abcdefg"), res->body);
  4218. }
  4219. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4220. auto res = cli_.Get("/with-range", {
  4221. {"Range", "bytes=0-"},
  4222. {"Accept-Encoding", ""},
  4223. });
  4224. ASSERT_TRUE(res);
  4225. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4226. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4227. EXPECT_EQ(true, res->has_header("Content-Range"));
  4228. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4229. EXPECT_EQ(std::string("abcdefg"), res->body);
  4230. }
  4231. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4232. auto res =
  4233. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4234. ASSERT_TRUE(res);
  4235. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4236. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4237. EXPECT_EQ(false, res->has_header("Content-Range"));
  4238. EXPECT_EQ(267U, res->body.size());
  4239. // Check that both range contents are present
  4240. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4241. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4242. // Check that Content-Range headers are present for both ranges
  4243. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4244. std::string::npos);
  4245. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4246. std::string::npos);
  4247. }
  4248. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4249. Ranges ranges;
  4250. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4251. ranges.emplace_back(0, -1);
  4252. }
  4253. auto res =
  4254. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4255. ASSERT_TRUE(res);
  4256. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4257. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4258. EXPECT_EQ(false, res->has_header("Content-Range"));
  4259. EXPECT_EQ(0U, res->body.size());
  4260. }
  4261. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4262. auto res =
  4263. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4264. ASSERT_TRUE(res);
  4265. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4266. EXPECT_EQ(5U, res->body.size());
  4267. // Check that overlapping ranges are coalesced into a single range
  4268. EXPECT_EQ("bcdef", res->body);
  4269. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4270. // Should be single range, not multipart
  4271. EXPECT_TRUE(res->has_header("Content-Range"));
  4272. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4273. }
  4274. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4275. auto res =
  4276. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4277. ASSERT_TRUE(res);
  4278. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4279. EXPECT_EQ(268U, res->body.size());
  4280. // Check that both range contents are present
  4281. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4282. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4283. // Check that Content-Range headers are present for both ranges
  4284. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4285. std::string::npos);
  4286. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4287. std::string::npos);
  4288. }
  4289. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4290. auto res =
  4291. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4292. ASSERT_TRUE(res);
  4293. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4294. EXPECT_EQ(269U, res->body.size());
  4295. // Check that both duplicate range contents are present
  4296. size_t first_abc = res->body.find("abc\r\n");
  4297. EXPECT_TRUE(first_abc != std::string::npos);
  4298. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4299. EXPECT_TRUE(second_abc != std::string::npos);
  4300. // Check that Content-Range headers are present for both ranges
  4301. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4302. EXPECT_TRUE(first_range != std::string::npos);
  4303. size_t second_range =
  4304. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4305. EXPECT_TRUE(second_range != std::string::npos);
  4306. }
  4307. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4308. auto res = cli_.Get("/streamed-with-range?error",
  4309. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4310. ASSERT_TRUE(res);
  4311. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4312. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4313. EXPECT_EQ(false, res->has_header("Content-Range"));
  4314. EXPECT_EQ(0U, res->body.size());
  4315. }
  4316. TEST_F(ServerTest, GetStreamedEndless) {
  4317. uint64_t offset = 0;
  4318. auto res = cli_.Get("/streamed-cancel",
  4319. [&](const char * /*data*/, uint64_t data_length) {
  4320. if (offset < 100) {
  4321. offset += data_length;
  4322. return true;
  4323. }
  4324. return false;
  4325. });
  4326. ASSERT_TRUE(!res);
  4327. EXPECT_EQ(Error::Canceled, res.error());
  4328. }
  4329. TEST_F(ServerTest, ClientStop) {
  4330. std::atomic_size_t count{4};
  4331. std::vector<std::thread> threads;
  4332. for (auto i = count.load(); i != 0; --i) {
  4333. threads.emplace_back([&]() {
  4334. auto res = cli_.Get("/streamed-cancel",
  4335. [&](const char *, uint64_t) { return true; });
  4336. --count;
  4337. ASSERT_TRUE(!res);
  4338. EXPECT_TRUE(res.error() == Error::Canceled ||
  4339. res.error() == Error::Read || res.error() == Error::Write);
  4340. });
  4341. }
  4342. std::this_thread::sleep_for(std::chrono::seconds(2));
  4343. while (count != 0) {
  4344. cli_.stop();
  4345. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4346. }
  4347. for (auto &t : threads) {
  4348. t.join();
  4349. }
  4350. }
  4351. TEST_F(ServerTest, GetWithRange1) {
  4352. auto res = cli_.Get("/with-range", {
  4353. make_range_header({{3, 5}}),
  4354. {"Accept-Encoding", ""},
  4355. });
  4356. ASSERT_TRUE(res);
  4357. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4358. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4359. EXPECT_EQ(true, res->has_header("Content-Range"));
  4360. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4361. EXPECT_EQ(std::string("def"), res->body);
  4362. }
  4363. TEST_F(ServerTest, GetWithRange2) {
  4364. auto res = cli_.Get("/with-range", {
  4365. make_range_header({{1, -1}}),
  4366. {"Accept-Encoding", ""},
  4367. });
  4368. ASSERT_TRUE(res);
  4369. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4370. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4371. EXPECT_EQ(true, res->has_header("Content-Range"));
  4372. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4373. EXPECT_EQ(std::string("bcdefg"), res->body);
  4374. }
  4375. TEST_F(ServerTest, GetWithRange3) {
  4376. auto res = cli_.Get("/with-range", {
  4377. make_range_header({{0, 0}}),
  4378. {"Accept-Encoding", ""},
  4379. });
  4380. ASSERT_TRUE(res);
  4381. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4382. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4383. EXPECT_EQ(true, res->has_header("Content-Range"));
  4384. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4385. EXPECT_EQ(std::string("a"), res->body);
  4386. }
  4387. TEST_F(ServerTest, GetWithRange4) {
  4388. auto res = cli_.Get("/with-range", {
  4389. make_range_header({{-1, 2}}),
  4390. {"Accept-Encoding", ""},
  4391. });
  4392. ASSERT_TRUE(res);
  4393. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4394. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4395. EXPECT_EQ(true, res->has_header("Content-Range"));
  4396. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4397. EXPECT_EQ(std::string("fg"), res->body);
  4398. }
  4399. TEST_F(ServerTest, GetWithRange5) {
  4400. auto res = cli_.Get("/with-range", {
  4401. make_range_header({{0, 5}}),
  4402. {"Accept-Encoding", ""},
  4403. });
  4404. ASSERT_TRUE(res);
  4405. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4406. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4407. EXPECT_EQ(true, res->has_header("Content-Range"));
  4408. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4409. EXPECT_EQ(std::string("abcdef"), res->body);
  4410. }
  4411. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4412. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4413. ASSERT_TRUE(res);
  4414. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4415. }
  4416. TEST_F(ServerTest, GetWithRangeMultipart) {
  4417. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4418. ASSERT_TRUE(res);
  4419. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4420. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4421. EXPECT_EQ(false, res->has_header("Content-Range"));
  4422. EXPECT_EQ(267U, res->body.size());
  4423. }
  4424. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4425. auto res =
  4426. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4427. ASSERT_TRUE(res);
  4428. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4429. }
  4430. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4431. auto res = cli_.Get("/with-range-customized-response",
  4432. {{make_range_header({{1, 2}})}});
  4433. ASSERT_TRUE(res);
  4434. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4435. EXPECT_EQ(true, res->has_header("Content-Length"));
  4436. EXPECT_EQ(false, res->has_header("Content-Range"));
  4437. EXPECT_EQ(JSON_DATA, res->body);
  4438. }
  4439. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4440. auto res = cli_.Get("/with-range-customized-response",
  4441. {{make_range_header({{1, 2}, {4, 5}})}});
  4442. ASSERT_TRUE(res);
  4443. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4444. EXPECT_EQ(true, res->has_header("Content-Length"));
  4445. EXPECT_EQ(false, res->has_header("Content-Range"));
  4446. EXPECT_EQ(JSON_DATA, res->body);
  4447. }
  4448. TEST_F(ServerTest, Issue1772) {
  4449. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4450. ASSERT_TRUE(res);
  4451. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4452. }
  4453. TEST_F(ServerTest, Issue609) {
  4454. auto res = cli_.Delete("/issue609");
  4455. ASSERT_TRUE(res);
  4456. EXPECT_EQ(StatusCode::OK_200, res->status);
  4457. EXPECT_EQ(std::string("ok"), res->body);
  4458. }
  4459. TEST_F(ServerTest, GetStreamedChunked) {
  4460. auto res = cli_.Get("/streamed-chunked");
  4461. ASSERT_TRUE(res);
  4462. EXPECT_EQ(StatusCode::OK_200, res->status);
  4463. EXPECT_EQ(std::string("123456789"), res->body);
  4464. }
  4465. TEST_F(ServerTest, GetStreamedChunked2) {
  4466. auto res = cli_.Get("/streamed-chunked2");
  4467. ASSERT_TRUE(res);
  4468. EXPECT_EQ(StatusCode::OK_200, res->status);
  4469. EXPECT_EQ(std::string("123456789"), res->body);
  4470. }
  4471. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4472. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4473. ASSERT_TRUE(res);
  4474. EXPECT_EQ(StatusCode::OK_200, res->status);
  4475. EXPECT_EQ(std::string("123456789"), res->body);
  4476. EXPECT_TRUE(res->has_header("Trailer"));
  4477. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4478. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4479. // Trailers are now stored separately from headers (security fix)
  4480. EXPECT_EQ(2U, res->trailers.size());
  4481. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4482. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4483. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4484. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4485. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4486. // Verify trailers are NOT in headers (security verification)
  4487. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4488. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4489. }
  4490. TEST_F(ServerTest, LargeChunkedPost) {
  4491. Request req;
  4492. req.method = "POST";
  4493. req.path = "/large-chunked";
  4494. std::string host_and_port;
  4495. host_and_port += HOST;
  4496. host_and_port += ":";
  4497. host_and_port += std::to_string(PORT);
  4498. req.headers.emplace("Host", host_and_port.c_str());
  4499. req.headers.emplace("Accept", "*/*");
  4500. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4501. req.headers.emplace("Content-Type", "text/plain");
  4502. req.headers.emplace("Content-Length", "0");
  4503. req.headers.emplace("Transfer-Encoding", "chunked");
  4504. std::string long_string(30 * 1024u, 'a');
  4505. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4506. // Attempt to make a large enough post to exceed OS buffers, to test that
  4507. // the server handles short reads if the full chunk data isn't available.
  4508. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4509. auto res = std::make_shared<Response>();
  4510. auto error = Error::Success;
  4511. auto ret = cli_.send(req, *res, error);
  4512. ASSERT_TRUE(ret);
  4513. EXPECT_EQ(StatusCode::OK_200, res->status);
  4514. }
  4515. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4516. auto res = cli_.Get("/remote_addr");
  4517. ASSERT_TRUE(res);
  4518. EXPECT_EQ(StatusCode::OK_200, res->status);
  4519. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4520. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4521. }
  4522. TEST_F(ServerTest, GetMethodLocalAddr) {
  4523. auto res = cli_.Get("/local_addr");
  4524. ASSERT_TRUE(res);
  4525. EXPECT_EQ(StatusCode::OK_200, res->status);
  4526. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4527. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4528. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4529. }
  4530. TEST_F(ServerTest, HTTPResponseSplitting) {
  4531. auto res = cli_.Get("/http_response_splitting");
  4532. ASSERT_TRUE(res);
  4533. EXPECT_EQ(StatusCode::OK_200, res->status);
  4534. }
  4535. TEST_F(ServerTest, SlowRequest) {
  4536. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4537. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4538. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4539. }
  4540. #if 0
  4541. TEST_F(ServerTest, SlowPost) {
  4542. char buffer[64 * 1024];
  4543. memset(buffer, 0x42, sizeof(buffer));
  4544. auto res = cli_.Post(
  4545. "/slowpost", 64 * 1024 * 1024,
  4546. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4547. auto ret = sink.write(buffer, sizeof(buffer));
  4548. EXPECT_TRUE(ret);
  4549. return true;
  4550. },
  4551. "text/plain");
  4552. ASSERT_TRUE(res);
  4553. EXPECT_EQ(StatusCode::OK_200, res->status);
  4554. }
  4555. TEST_F(ServerTest, SlowPostFail) {
  4556. char buffer[64 * 1024];
  4557. memset(buffer, 0x42, sizeof(buffer));
  4558. cli_.set_write_timeout(std::chrono::seconds(0));
  4559. auto res = cli_.Post(
  4560. "/slowpost", 64 * 1024 * 1024,
  4561. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4562. sink.write(buffer, sizeof(buffer));
  4563. return true;
  4564. },
  4565. "text/plain");
  4566. ASSERT_TRUE(!res);
  4567. EXPECT_EQ(Error::Write, res.error());
  4568. }
  4569. #endif
  4570. TEST_F(ServerTest, Put) {
  4571. auto res = cli_.Put("/put", "PUT", "text/plain");
  4572. ASSERT_TRUE(res);
  4573. EXPECT_EQ(StatusCode::OK_200, res->status);
  4574. EXPECT_EQ("PUT", res->body);
  4575. }
  4576. TEST_F(ServerTest, PutWithContentProvider) {
  4577. auto res = cli_.Put(
  4578. "/put", 3,
  4579. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4580. sink.os << "PUT";
  4581. return true;
  4582. },
  4583. "text/plain");
  4584. ASSERT_TRUE(res);
  4585. EXPECT_EQ(StatusCode::OK_200, res->status);
  4586. EXPECT_EQ("PUT", res->body);
  4587. }
  4588. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4589. auto res = cli_.Post(
  4590. "/post", 42,
  4591. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4592. return false;
  4593. },
  4594. "text/plain");
  4595. ASSERT_TRUE(!res);
  4596. EXPECT_EQ(Error::Canceled, res.error());
  4597. }
  4598. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4599. auto res = cli_.Put(
  4600. "/put",
  4601. [](size_t /*offset*/, DataSink &sink) {
  4602. sink.os << "PUT";
  4603. sink.done();
  4604. return true;
  4605. },
  4606. "text/plain");
  4607. ASSERT_TRUE(res);
  4608. EXPECT_EQ(StatusCode::OK_200, res->status);
  4609. EXPECT_EQ("PUT", res->body);
  4610. }
  4611. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4612. auto res = cli_.Post(
  4613. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4614. "text/plain");
  4615. ASSERT_TRUE(!res);
  4616. EXPECT_EQ(Error::Canceled, res.error());
  4617. }
  4618. TEST_F(ServerTest, PostLoopBack) {
  4619. std::string body;
  4620. auto res = cli_.Post(
  4621. "/post-loopback", 9,
  4622. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4623. EXPECT_EQ(9u, length);
  4624. sink.write("123", 3);
  4625. sink.write("456", 3);
  4626. sink.write("789", 3);
  4627. return true;
  4628. },
  4629. "text/plain",
  4630. [&body](const char *data, size_t data_length) {
  4631. body.append(data, data_length);
  4632. return true;
  4633. });
  4634. ASSERT_TRUE(res);
  4635. EXPECT_EQ(StatusCode::OK_200, res->status);
  4636. EXPECT_EQ("123456789", body);
  4637. }
  4638. TEST_F(ServerTest, PutLoopBack) {
  4639. std::string body;
  4640. auto res = cli_.Put(
  4641. "/put-loopback", 9,
  4642. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4643. EXPECT_EQ(9u, length);
  4644. sink.write("123", 3);
  4645. sink.write("456", 3);
  4646. sink.write("789", 3);
  4647. return true;
  4648. },
  4649. "text/plain",
  4650. [&body](const char *data, size_t data_length) {
  4651. body.append(data, data_length);
  4652. return true;
  4653. });
  4654. ASSERT_TRUE(res);
  4655. EXPECT_EQ(StatusCode::OK_200, res->status);
  4656. EXPECT_EQ("123456789", body);
  4657. }
  4658. TEST_F(ServerTest, PatchLoopBack) {
  4659. std::string body;
  4660. auto res = cli_.Patch(
  4661. "/patch-loopback", 9,
  4662. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4663. EXPECT_EQ(9u, length);
  4664. sink.write("123", 3);
  4665. sink.write("456", 3);
  4666. sink.write("789", 3);
  4667. return true;
  4668. },
  4669. "text/plain",
  4670. [&body](const char *data, size_t data_length) {
  4671. body.append(data, data_length);
  4672. return true;
  4673. });
  4674. ASSERT_TRUE(res);
  4675. EXPECT_EQ(StatusCode::OK_200, res->status);
  4676. EXPECT_EQ("123456789", body);
  4677. }
  4678. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4679. std::string body;
  4680. auto res = cli_.Post(
  4681. "/post-loopback",
  4682. [](size_t /*offset*/, DataSink &sink) {
  4683. sink.write("123", 3);
  4684. sink.write("456", 3);
  4685. sink.write("789", 3);
  4686. sink.done();
  4687. return true;
  4688. },
  4689. "text/plain",
  4690. [&body](const char *data, size_t data_length) {
  4691. body.append(data, data_length);
  4692. return true;
  4693. });
  4694. ASSERT_TRUE(res);
  4695. EXPECT_EQ(StatusCode::OK_200, res->status);
  4696. EXPECT_EQ("123456789", body);
  4697. }
  4698. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4699. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4700. cli_.set_compress(true);
  4701. auto res = cli_.Put(
  4702. "/put", 3,
  4703. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4704. sink.os << "PUT";
  4705. return true;
  4706. },
  4707. "text/plain");
  4708. ASSERT_TRUE(res);
  4709. EXPECT_EQ(StatusCode::OK_200, res->status);
  4710. EXPECT_EQ("PUT", res->body);
  4711. }
  4712. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4713. cli_.set_compress(true);
  4714. auto res = cli_.Post(
  4715. "/post", 42,
  4716. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4717. return false;
  4718. },
  4719. "text/plain");
  4720. ASSERT_TRUE(!res);
  4721. EXPECT_EQ(Error::Canceled, res.error());
  4722. }
  4723. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4724. cli_.set_compress(true);
  4725. auto res = cli_.Put(
  4726. "/put",
  4727. [](size_t /*offset*/, DataSink &sink) {
  4728. sink.os << "PUT";
  4729. sink.done();
  4730. return true;
  4731. },
  4732. "text/plain");
  4733. ASSERT_TRUE(res);
  4734. EXPECT_EQ(StatusCode::OK_200, res->status);
  4735. EXPECT_EQ("PUT", res->body);
  4736. }
  4737. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4738. cli_.set_compress(true);
  4739. auto res = cli_.Post(
  4740. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4741. "text/plain");
  4742. ASSERT_TRUE(!res);
  4743. EXPECT_EQ(Error::Canceled, res.error());
  4744. }
  4745. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4746. cli_.set_compress(true);
  4747. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4748. ASSERT_TRUE(res);
  4749. EXPECT_EQ(StatusCode::OK_200, res->status);
  4750. EXPECT_EQ(LARGE_DATA, res->body);
  4751. }
  4752. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4753. #ifdef CPPHTTPLIB_SSL_ENABLED
  4754. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4755. Client cli(s.c_str());
  4756. cli.enable_server_certificate_verification(false);
  4757. #else
  4758. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4759. Client cli(s.c_str());
  4760. #endif
  4761. cli.set_compress(true);
  4762. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4763. ASSERT_TRUE(res);
  4764. EXPECT_EQ(StatusCode::OK_200, res->status);
  4765. EXPECT_EQ(LARGE_DATA, res->body);
  4766. // The compressed size should be less than a 10th of the original. May vary
  4767. // depending on the zlib library.
  4768. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4769. static_cast<uint64_t>(10 * 1024 * 1024));
  4770. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4771. }
  4772. TEST_F(ServerTest, PutContentWithDeflate) {
  4773. cli_.set_compress(false);
  4774. Headers headers;
  4775. headers.emplace("Content-Encoding", "deflate");
  4776. // PUT in deflate format:
  4777. auto res = cli_.Put("/put", headers,
  4778. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4779. ASSERT_TRUE(res);
  4780. EXPECT_EQ(StatusCode::OK_200, res->status);
  4781. EXPECT_EQ("PUT", res->body);
  4782. }
  4783. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4784. Headers headers;
  4785. headers.emplace("Accept-Encoding", "gzip, deflate");
  4786. auto res = cli_.Get("/streamed-chunked", headers);
  4787. ASSERT_TRUE(res);
  4788. EXPECT_EQ(StatusCode::OK_200, res->status);
  4789. EXPECT_EQ(std::string("123456789"), res->body);
  4790. }
  4791. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4792. Headers headers;
  4793. headers.emplace("Accept-Encoding", "gzip, deflate");
  4794. auto res = cli_.Get("/streamed-chunked2", headers);
  4795. ASSERT_TRUE(res);
  4796. EXPECT_EQ(StatusCode::OK_200, res->status);
  4797. EXPECT_EQ(std::string("123456789"), res->body);
  4798. }
  4799. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4800. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4801. ASSERT_TRUE(res);
  4802. EXPECT_EQ(StatusCode::OK_200, res->status);
  4803. }
  4804. TEST(GzipDecompressor, ChunkedDecompression) {
  4805. std::string data;
  4806. for (size_t i = 0; i < 32 * 1024; ++i) {
  4807. data.push_back(static_cast<char>('a' + i % 26));
  4808. }
  4809. std::string compressed_data;
  4810. {
  4811. httplib::detail::gzip_compressor compressor;
  4812. bool result = compressor.compress(
  4813. data.data(), data.size(),
  4814. /*last=*/true,
  4815. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4816. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4817. compressed_data_size);
  4818. return true;
  4819. });
  4820. ASSERT_TRUE(result);
  4821. }
  4822. std::string decompressed_data;
  4823. {
  4824. httplib::detail::gzip_decompressor decompressor;
  4825. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4826. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4827. size_t chunk_size = 130;
  4828. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4829. chunk_begin += chunk_size) {
  4830. size_t current_chunk_size =
  4831. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4832. bool result = decompressor.decompress(
  4833. compressed_data.data() + chunk_begin, current_chunk_size,
  4834. [&](const char *decompressed_data_chunk,
  4835. size_t decompressed_data_chunk_size) {
  4836. decompressed_data.insert(decompressed_data.size(),
  4837. decompressed_data_chunk,
  4838. decompressed_data_chunk_size);
  4839. return true;
  4840. });
  4841. ASSERT_TRUE(result);
  4842. }
  4843. }
  4844. ASSERT_EQ(data, decompressed_data);
  4845. }
  4846. TEST(GzipDecompressor, DeflateDecompression) {
  4847. std::string original_text = "Raw deflate without gzip";
  4848. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4849. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4850. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4851. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4852. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4853. std::string decompressed_data;
  4854. {
  4855. httplib::detail::gzip_decompressor decompressor;
  4856. bool result = decompressor.decompress(
  4857. compressed_data.data(), compressed_data.size(),
  4858. [&](const char *decompressed_data_chunk,
  4859. size_t decompressed_data_chunk_size) {
  4860. decompressed_data.insert(decompressed_data.size(),
  4861. decompressed_data_chunk,
  4862. decompressed_data_chunk_size);
  4863. return true;
  4864. });
  4865. ASSERT_TRUE(result);
  4866. }
  4867. ASSERT_EQ(original_text, decompressed_data);
  4868. }
  4869. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4870. std::string original_text = "Raw deflate without gzip";
  4871. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4872. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4873. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4874. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4875. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4876. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4877. std::string decompressed_data;
  4878. {
  4879. httplib::detail::gzip_decompressor decompressor;
  4880. bool result = decompressor.decompress(
  4881. compressed_data.data(), compressed_data.size(),
  4882. [&](const char *decompressed_data_chunk,
  4883. size_t decompressed_data_chunk_size) {
  4884. decompressed_data.insert(decompressed_data.size(),
  4885. decompressed_data_chunk,
  4886. decompressed_data_chunk_size);
  4887. return true;
  4888. });
  4889. ASSERT_TRUE(result);
  4890. }
  4891. ASSERT_EQ(original_text, decompressed_data);
  4892. }
  4893. #ifdef _WIN32
  4894. TEST(GzipDecompressor, LargeRandomData) {
  4895. // prepare large random data that is difficult to be compressed and is
  4896. // expected to have large size even when compressed
  4897. std::random_device seed_gen;
  4898. std::mt19937 random(seed_gen());
  4899. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4900. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4901. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4902. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4903. // compress data over 4GiB
  4904. std::string compressed_data;
  4905. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4906. httplib::detail::gzip_compressor compressor;
  4907. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4908. data.size() * sizeof(std::uint32_t), true,
  4909. [&](const char *data, size_t size) {
  4910. compressed_data.insert(
  4911. compressed_data.size(), data, size);
  4912. return true;
  4913. });
  4914. ASSERT_TRUE(result);
  4915. // FIXME: compressed data size is expected to be greater than 4GiB,
  4916. // but there is no guarantee
  4917. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4918. // decompress data over 4GiB
  4919. std::string decompressed_data;
  4920. decompressed_data.reserve(data_size);
  4921. httplib::detail::gzip_decompressor decompressor;
  4922. result = decompressor.decompress(
  4923. compressed_data.data(), compressed_data.size(),
  4924. [&](const char *data, size_t size) {
  4925. decompressed_data.insert(decompressed_data.size(), data, size);
  4926. return true;
  4927. });
  4928. ASSERT_TRUE(result);
  4929. // compare
  4930. ASSERT_EQ(data_size, decompressed_data.size());
  4931. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4932. 0);
  4933. }
  4934. #endif
  4935. #endif
  4936. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4937. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4938. Headers headers;
  4939. headers.emplace("Accept-Encoding", "br");
  4940. auto res = cli_.Get("/streamed-chunked", headers);
  4941. ASSERT_TRUE(res);
  4942. EXPECT_EQ(StatusCode::OK_200, res->status);
  4943. EXPECT_EQ(std::string("123456789"), res->body);
  4944. }
  4945. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4946. Headers headers;
  4947. headers.emplace("Accept-Encoding", "br");
  4948. auto res = cli_.Get("/streamed-chunked2", headers);
  4949. ASSERT_TRUE(res);
  4950. EXPECT_EQ(StatusCode::OK_200, res->status);
  4951. EXPECT_EQ(std::string("123456789"), res->body);
  4952. }
  4953. #endif
  4954. TEST_F(ServerTest, Patch) {
  4955. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4956. ASSERT_TRUE(res);
  4957. EXPECT_EQ(StatusCode::OK_200, res->status);
  4958. EXPECT_EQ("PATCH", res->body);
  4959. }
  4960. TEST_F(ServerTest, Delete) {
  4961. auto res = cli_.Delete("/delete");
  4962. ASSERT_TRUE(res);
  4963. EXPECT_EQ(StatusCode::OK_200, res->status);
  4964. EXPECT_EQ("DELETE", res->body);
  4965. }
  4966. TEST_F(ServerTest, DeleteContentReceiver) {
  4967. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4968. ASSERT_TRUE(res);
  4969. EXPECT_EQ(StatusCode::OK_200, res->status);
  4970. EXPECT_EQ("content", res->body);
  4971. }
  4972. TEST_F(ServerTest, Options) {
  4973. auto res = cli_.Options("*");
  4974. ASSERT_TRUE(res);
  4975. EXPECT_EQ(StatusCode::OK_200, res->status);
  4976. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4977. EXPECT_TRUE(res->body.empty());
  4978. }
  4979. TEST_F(ServerTest, URL) {
  4980. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4981. ASSERT_TRUE(res);
  4982. EXPECT_EQ(StatusCode::OK_200, res->status);
  4983. }
  4984. TEST_F(ServerTest, ArrayParam) {
  4985. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4986. ASSERT_TRUE(res);
  4987. EXPECT_EQ(StatusCode::OK_200, res->status);
  4988. }
  4989. TEST_F(ServerTest, NoMultipleHeaders) {
  4990. Headers headers = {{"Content-Length", "5"}};
  4991. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4992. "text/plain");
  4993. ASSERT_TRUE(res);
  4994. EXPECT_EQ(StatusCode::OK_200, res->status);
  4995. }
  4996. TEST_F(ServerTest, PostContentReceiver) {
  4997. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4998. ASSERT_TRUE(res);
  4999. ASSERT_EQ(StatusCode::OK_200, res->status);
  5000. ASSERT_EQ("content", res->body);
  5001. }
  5002. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5003. UploadFormDataItems items = {
  5004. {"text1", "text default", "", ""},
  5005. {"text2", "aωb", "", ""},
  5006. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5007. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5008. {"file3", "", "", "application/octet-stream"},
  5009. };
  5010. auto res = cli_.Post("/content_receiver", items);
  5011. ASSERT_TRUE(res);
  5012. EXPECT_EQ(StatusCode::OK_200, res->status);
  5013. }
  5014. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5015. UploadFormDataItems items = {
  5016. {"text1", "text default", "", ""},
  5017. {"text2", "aωb", "", ""},
  5018. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5019. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5020. {"file3", "", "", "application/octet-stream"},
  5021. };
  5022. auto boundary = std::string("+++++");
  5023. std::string body;
  5024. for (const auto &item : items) {
  5025. body += "--" + boundary + "\r\n";
  5026. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5027. if (!item.filename.empty()) {
  5028. body += "; filename=\"" + item.filename + "\"";
  5029. }
  5030. body += "\r\n";
  5031. if (!item.content_type.empty()) {
  5032. body += "Content-Type: " + item.content_type + "\r\n";
  5033. }
  5034. body += "\r\n";
  5035. body += item.content + "\r\n";
  5036. }
  5037. body += "--" + boundary + "--\r\n";
  5038. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5039. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5040. ASSERT_TRUE(res);
  5041. EXPECT_EQ(StatusCode::OK_200, res->status);
  5042. }
  5043. TEST_F(ServerTest, PostContentReceiverGzip) {
  5044. cli_.set_compress(true);
  5045. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5046. ASSERT_TRUE(res);
  5047. ASSERT_EQ(StatusCode::OK_200, res->status);
  5048. ASSERT_EQ("content", res->body);
  5049. }
  5050. TEST_F(ServerTest, PutContentReceiver) {
  5051. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5052. ASSERT_TRUE(res);
  5053. ASSERT_EQ(StatusCode::OK_200, res->status);
  5054. ASSERT_EQ("content", res->body);
  5055. }
  5056. TEST_F(ServerTest, PatchContentReceiver) {
  5057. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5058. ASSERT_TRUE(res);
  5059. ASSERT_EQ(StatusCode::OK_200, res->status);
  5060. ASSERT_EQ("content", res->body);
  5061. }
  5062. template <typename ClientType>
  5063. void TestWithHeadersAndContentReceiver(
  5064. ClientType &cli,
  5065. std::function<Result(ClientType &, const std::string &, const Headers &,
  5066. const std::string &, const std::string &,
  5067. ContentReceiver, DownloadProgress)>
  5068. request_func) {
  5069. Headers headers;
  5070. headers.emplace("X-Custom-Header", "test-value");
  5071. std::string received_body;
  5072. auto res = request_func(
  5073. cli, "/content_receiver", headers, "content", "application/json",
  5074. [&](const char *data, size_t data_length) {
  5075. received_body.append(data, data_length);
  5076. return true;
  5077. },
  5078. nullptr);
  5079. ASSERT_TRUE(res);
  5080. EXPECT_EQ(StatusCode::OK_200, res->status);
  5081. EXPECT_EQ("content", received_body);
  5082. }
  5083. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5084. #ifdef CPPHTTPLIB_SSL_ENABLED
  5085. using ClientT = SSLClient;
  5086. #else
  5087. using ClientT = Client;
  5088. #endif
  5089. TestWithHeadersAndContentReceiver<ClientT>(
  5090. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5091. const std::string &body, const std::string &content_type,
  5092. ContentReceiver receiver, DownloadProgress progress) {
  5093. return cli.Post(path, headers, body, content_type, receiver, progress);
  5094. });
  5095. }
  5096. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5097. #ifdef CPPHTTPLIB_SSL_ENABLED
  5098. using ClientT = SSLClient;
  5099. #else
  5100. using ClientT = Client;
  5101. #endif
  5102. TestWithHeadersAndContentReceiver<ClientT>(
  5103. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5104. const std::string &body, const std::string &content_type,
  5105. ContentReceiver receiver, DownloadProgress progress) {
  5106. return cli.Put(path, headers, body, content_type, receiver, progress);
  5107. });
  5108. }
  5109. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5110. #ifdef CPPHTTPLIB_SSL_ENABLED
  5111. using ClientT = SSLClient;
  5112. #else
  5113. using ClientT = Client;
  5114. #endif
  5115. TestWithHeadersAndContentReceiver<ClientT>(
  5116. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5117. const std::string &body, const std::string &content_type,
  5118. ContentReceiver receiver, DownloadProgress progress) {
  5119. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5120. });
  5121. }
  5122. template <typename ClientType>
  5123. void TestWithHeadersAndContentReceiverWithProgress(
  5124. ClientType &cli,
  5125. std::function<Result(ClientType &, const std::string &, const Headers &,
  5126. const std::string &, const std::string &,
  5127. ContentReceiver, DownloadProgress)>
  5128. request_func) {
  5129. Headers headers;
  5130. headers.emplace("X-Test-Header", "progress-test");
  5131. std::string received_body;
  5132. auto progress_called = false;
  5133. auto res = request_func(
  5134. cli, "/content_receiver", headers, "content", "text/plain",
  5135. [&](const char *data, size_t data_length) {
  5136. received_body.append(data, data_length);
  5137. return true;
  5138. },
  5139. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5140. progress_called = true;
  5141. return true;
  5142. });
  5143. ASSERT_TRUE(res);
  5144. EXPECT_EQ(StatusCode::OK_200, res->status);
  5145. EXPECT_EQ("content", received_body);
  5146. EXPECT_TRUE(progress_called);
  5147. }
  5148. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5149. #ifdef CPPHTTPLIB_SSL_ENABLED
  5150. using ClientT = SSLClient;
  5151. #else
  5152. using ClientT = Client;
  5153. #endif
  5154. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5155. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5156. const std::string &body, const std::string &content_type,
  5157. ContentReceiver receiver, DownloadProgress progress) {
  5158. return cli.Post(path, headers, body, content_type, receiver, progress);
  5159. });
  5160. }
  5161. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5162. #ifdef CPPHTTPLIB_SSL_ENABLED
  5163. using ClientT = SSLClient;
  5164. #else
  5165. using ClientT = Client;
  5166. #endif
  5167. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5168. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5169. const std::string &body, const std::string &content_type,
  5170. ContentReceiver receiver, DownloadProgress progress) {
  5171. return cli.Put(path, headers, body, content_type, receiver, progress);
  5172. });
  5173. }
  5174. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5175. #ifdef CPPHTTPLIB_SSL_ENABLED
  5176. using ClientT = SSLClient;
  5177. #else
  5178. using ClientT = Client;
  5179. #endif
  5180. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5181. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5182. const std::string &body, const std::string &content_type,
  5183. ContentReceiver receiver, DownloadProgress progress) {
  5184. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5185. });
  5186. }
  5187. template <typename ClientType>
  5188. void TestWithHeadersAndContentReceiverError(
  5189. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5190. const Headers &, const std::string &,
  5191. const std::string &, ContentReceiver)>
  5192. request_func) {
  5193. Headers headers;
  5194. headers.emplace("X-Error-Test", "true");
  5195. std::string received_body;
  5196. auto receiver_failed = false;
  5197. auto res =
  5198. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5199. [&](const char *data, size_t data_length) {
  5200. received_body.append(data, data_length);
  5201. receiver_failed = true;
  5202. return false;
  5203. });
  5204. ASSERT_FALSE(res);
  5205. EXPECT_TRUE(receiver_failed);
  5206. }
  5207. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5208. #ifdef CPPHTTPLIB_SSL_ENABLED
  5209. using ClientT = SSLClient;
  5210. #else
  5211. using ClientT = Client;
  5212. #endif
  5213. TestWithHeadersAndContentReceiverError<ClientT>(
  5214. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5215. const std::string &body, const std::string &content_type,
  5216. ContentReceiver receiver) {
  5217. return cli.Post(path, headers, body, content_type, receiver);
  5218. });
  5219. }
  5220. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5221. #ifdef CPPHTTPLIB_SSL_ENABLED
  5222. using ClientT = SSLClient;
  5223. #else
  5224. using ClientT = Client;
  5225. #endif
  5226. TestWithHeadersAndContentReceiverError<ClientT>(
  5227. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5228. const std::string &body, const std::string &content_type,
  5229. ContentReceiver receiver) {
  5230. return cli.Put(path, headers, body, content_type, receiver);
  5231. });
  5232. }
  5233. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5234. #ifdef CPPHTTPLIB_SSL_ENABLED
  5235. using ClientT = SSLClient;
  5236. #else
  5237. using ClientT = Client;
  5238. #endif
  5239. TestWithHeadersAndContentReceiverError<ClientT>(
  5240. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5241. const std::string &body, const std::string &content_type,
  5242. ContentReceiver receiver) {
  5243. return cli.Patch(path, headers, body, content_type, receiver);
  5244. });
  5245. }
  5246. TEST_F(ServerTest, PostQueryStringAndBody) {
  5247. auto res =
  5248. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5249. ASSERT_TRUE(res);
  5250. ASSERT_EQ(StatusCode::OK_200, res->status);
  5251. }
  5252. TEST_F(ServerTest, HTTP2Magic) {
  5253. Request req;
  5254. req.method = "PRI";
  5255. req.path = "*";
  5256. req.body = "SM";
  5257. auto res = std::make_shared<Response>();
  5258. auto error = Error::Success;
  5259. auto ret = cli_.send(req, *res, error);
  5260. ASSERT_TRUE(ret);
  5261. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5262. }
  5263. TEST_F(ServerTest, KeepAlive) {
  5264. auto res = cli_.Get("/hi");
  5265. ASSERT_TRUE(res);
  5266. EXPECT_EQ(StatusCode::OK_200, res->status);
  5267. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5268. EXPECT_EQ("Hello World!", res->body);
  5269. res = cli_.Get("/hi");
  5270. ASSERT_TRUE(res);
  5271. EXPECT_EQ(StatusCode::OK_200, res->status);
  5272. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5273. EXPECT_EQ("Hello World!", res->body);
  5274. res = cli_.Get("/hi");
  5275. ASSERT_TRUE(res);
  5276. EXPECT_EQ(StatusCode::OK_200, res->status);
  5277. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5278. EXPECT_EQ("Hello World!", res->body);
  5279. res = cli_.Get("/not-exist");
  5280. ASSERT_TRUE(res);
  5281. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5282. res = cli_.Post("/empty", "", "text/plain");
  5283. ASSERT_TRUE(res);
  5284. EXPECT_EQ(StatusCode::OK_200, res->status);
  5285. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5286. EXPECT_EQ("empty", res->body);
  5287. EXPECT_EQ("close", res->get_header_value("Connection"));
  5288. res = cli_.Post(
  5289. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5290. "text/plain");
  5291. ASSERT_TRUE(res);
  5292. EXPECT_EQ(StatusCode::OK_200, res->status);
  5293. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5294. EXPECT_EQ("empty", res->body);
  5295. cli_.set_keep_alive(false);
  5296. res = cli_.Get("/last-request");
  5297. ASSERT_TRUE(res);
  5298. EXPECT_EQ(StatusCode::OK_200, res->status);
  5299. EXPECT_EQ("close", res->get_header_value("Connection"));
  5300. }
  5301. TEST_F(ServerTest, TooManyRedirect) {
  5302. cli_.set_follow_location(true);
  5303. auto res = cli_.Get("/redirect/0");
  5304. ASSERT_TRUE(!res);
  5305. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5306. }
  5307. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5308. Request req;
  5309. req.method = "FOOBAR";
  5310. req.path = "/hi";
  5311. cli_.set_keep_alive(true);
  5312. auto res = cli_.send(req);
  5313. ASSERT_TRUE(res);
  5314. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5315. EXPECT_EQ("close", res->get_header_value("Connection"));
  5316. EXPECT_FALSE(cli_.is_socket_open());
  5317. }
  5318. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5319. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5320. TEST_F(ServerTest, Gzip) {
  5321. Headers headers;
  5322. headers.emplace("Accept-Encoding", "gzip, deflate");
  5323. auto res = cli_.Get("/compress", headers);
  5324. ASSERT_TRUE(res);
  5325. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5326. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5327. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5328. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5329. "7890123456789012345678901234567890",
  5330. res->body);
  5331. EXPECT_EQ(StatusCode::OK_200, res->status);
  5332. }
  5333. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5334. Headers headers;
  5335. headers.emplace("Accept-Encoding", "gzip, deflate");
  5336. auto res = cli_.Get("/compress-with-charset", headers);
  5337. ASSERT_TRUE(res);
  5338. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5339. EXPECT_EQ("application/json; charset=utf-8",
  5340. res->get_header_value("Content-Type"));
  5341. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5342. "7890123456789012345678901234567890",
  5343. res->body);
  5344. EXPECT_EQ(StatusCode::OK_200, res->status);
  5345. }
  5346. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5347. Headers headers;
  5348. headers.emplace("Accept-Encoding", "");
  5349. auto res = cli_.Get("/compress", headers);
  5350. ASSERT_TRUE(res);
  5351. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5352. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5353. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5354. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5355. "7890123456789012345678901234567890",
  5356. res->body);
  5357. EXPECT_EQ(StatusCode::OK_200, res->status);
  5358. }
  5359. TEST_F(ServerTest, GzipWithContentReceiver) {
  5360. Headers headers;
  5361. headers.emplace("Accept-Encoding", "gzip, deflate");
  5362. std::string body;
  5363. auto res = cli_.Get("/compress", headers,
  5364. [&](const char *data, uint64_t data_length) {
  5365. EXPECT_EQ(100U, data_length);
  5366. body.append(data, data_length);
  5367. return true;
  5368. });
  5369. ASSERT_TRUE(res);
  5370. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5371. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5372. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5373. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5374. "7890123456789012345678901234567890",
  5375. body);
  5376. EXPECT_EQ(StatusCode::OK_200, res->status);
  5377. }
  5378. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5379. Headers headers;
  5380. headers.emplace("Accept-Encoding", "gzip, deflate");
  5381. cli_.set_decompress(false);
  5382. auto res = cli_.Get("/compress", headers);
  5383. ASSERT_TRUE(res);
  5384. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5385. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5386. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5387. EXPECT_EQ(33U, res->body.size());
  5388. EXPECT_EQ(StatusCode::OK_200, res->status);
  5389. }
  5390. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5391. Headers headers;
  5392. headers.emplace("Accept-Encoding", "");
  5393. std::string body;
  5394. auto res = cli_.Get("/compress", headers,
  5395. [&](const char *data, uint64_t data_length) {
  5396. EXPECT_EQ(100U, data_length);
  5397. body.append(data, data_length);
  5398. return true;
  5399. });
  5400. ASSERT_TRUE(res);
  5401. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5402. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5403. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5404. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5405. "7890123456789012345678901234567890",
  5406. body);
  5407. EXPECT_EQ(StatusCode::OK_200, res->status);
  5408. }
  5409. TEST_F(ServerTest, NoGzip) {
  5410. Headers headers;
  5411. headers.emplace("Accept-Encoding", "gzip, deflate");
  5412. auto res = cli_.Get("/nocompress", headers);
  5413. ASSERT_TRUE(res);
  5414. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5415. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5416. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5417. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5418. "7890123456789012345678901234567890",
  5419. res->body);
  5420. EXPECT_EQ(StatusCode::OK_200, res->status);
  5421. }
  5422. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5423. Headers headers;
  5424. headers.emplace("Accept-Encoding", "gzip, deflate");
  5425. std::string body;
  5426. auto res = cli_.Get("/nocompress", headers,
  5427. [&](const char *data, uint64_t data_length) {
  5428. EXPECT_EQ(100U, data_length);
  5429. body.append(data, data_length);
  5430. return true;
  5431. });
  5432. ASSERT_TRUE(res);
  5433. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5434. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5435. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5436. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5437. "7890123456789012345678901234567890",
  5438. body);
  5439. EXPECT_EQ(StatusCode::OK_200, res->status);
  5440. }
  5441. TEST_F(ServerTest, MultipartFormDataGzip) {
  5442. UploadFormDataItems items = {
  5443. {"key1", "test", "", ""},
  5444. {"key2", "--abcdefg123", "", ""},
  5445. };
  5446. cli_.set_compress(true);
  5447. auto res = cli_.Post("/compress-multipart", items);
  5448. ASSERT_TRUE(res);
  5449. EXPECT_EQ(StatusCode::OK_200, res->status);
  5450. }
  5451. #endif
  5452. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5453. TEST_F(ServerTest, Brotli) {
  5454. Headers headers;
  5455. headers.emplace("Accept-Encoding", "br");
  5456. auto res = cli_.Get("/compress", headers);
  5457. ASSERT_TRUE(res);
  5458. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5459. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5460. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5461. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5462. "7890123456789012345678901234567890",
  5463. res->body);
  5464. EXPECT_EQ(StatusCode::OK_200, res->status);
  5465. }
  5466. #endif
  5467. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5468. TEST_F(ServerTest, Zstd) {
  5469. Headers headers;
  5470. headers.emplace("Accept-Encoding", "zstd");
  5471. auto res = cli_.Get("/compress", headers);
  5472. ASSERT_TRUE(res);
  5473. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5474. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5475. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5476. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5477. "7890123456789012345678901234567890",
  5478. res->body);
  5479. EXPECT_EQ(StatusCode::OK_200, res->status);
  5480. }
  5481. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5482. Headers headers;
  5483. headers.emplace("Accept-Encoding", "");
  5484. auto res = cli_.Get("/compress", headers);
  5485. ASSERT_TRUE(res);
  5486. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5487. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5488. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5489. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5490. "7890123456789012345678901234567890",
  5491. res->body);
  5492. EXPECT_EQ(StatusCode::OK_200, res->status);
  5493. }
  5494. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5495. Headers headers;
  5496. headers.emplace("Accept-Encoding", "zstd");
  5497. std::string body;
  5498. auto res = cli_.Get("/compress", headers,
  5499. [&](const char *data, uint64_t data_length) {
  5500. EXPECT_EQ(100U, data_length);
  5501. body.append(data, data_length);
  5502. return true;
  5503. });
  5504. ASSERT_TRUE(res);
  5505. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5506. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5507. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5508. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5509. "7890123456789012345678901234567890",
  5510. body);
  5511. EXPECT_EQ(StatusCode::OK_200, res->status);
  5512. }
  5513. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5514. Headers headers;
  5515. headers.emplace("Accept-Encoding", "zstd");
  5516. cli_.set_decompress(false);
  5517. auto res = cli_.Get("/compress", headers);
  5518. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5519. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5520. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5521. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5522. ASSERT_TRUE(res);
  5523. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5524. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5525. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5526. EXPECT_EQ(StatusCode::OK_200, res->status);
  5527. ASSERT_EQ(26U, res->body.size());
  5528. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5529. 0);
  5530. }
  5531. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5532. Headers headers;
  5533. headers.emplace("Accept-Encoding", "");
  5534. std::string body;
  5535. auto res = cli_.Get("/compress", headers,
  5536. [&](const char *data, uint64_t data_length) {
  5537. EXPECT_EQ(100U, data_length);
  5538. body.append(data, data_length);
  5539. return true;
  5540. });
  5541. ASSERT_TRUE(res);
  5542. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5543. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5544. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5545. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5546. "7890123456789012345678901234567890",
  5547. body);
  5548. EXPECT_EQ(StatusCode::OK_200, res->status);
  5549. }
  5550. TEST_F(ServerTest, NoZstd) {
  5551. Headers headers;
  5552. headers.emplace("Accept-Encoding", "zstd");
  5553. auto res = cli_.Get("/nocompress", headers);
  5554. ASSERT_TRUE(res);
  5555. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5556. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5557. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5558. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5559. "7890123456789012345678901234567890",
  5560. res->body);
  5561. EXPECT_EQ(StatusCode::OK_200, res->status);
  5562. }
  5563. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5564. Headers headers;
  5565. headers.emplace("Accept-Encoding", "zstd");
  5566. std::string body;
  5567. auto res = cli_.Get("/nocompress", headers,
  5568. [&](const char *data, uint64_t data_length) {
  5569. EXPECT_EQ(100U, data_length);
  5570. body.append(data, data_length);
  5571. return true;
  5572. });
  5573. ASSERT_TRUE(res);
  5574. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5575. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5576. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5577. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5578. "7890123456789012345678901234567890",
  5579. body);
  5580. EXPECT_EQ(StatusCode::OK_200, res->status);
  5581. }
  5582. // TODO: How to enable zstd ??
  5583. TEST_F(ServerTest, MultipartFormDataZstd) {
  5584. UploadFormDataItems items = {
  5585. {"key1", "test", "", ""},
  5586. {"key2", "--abcdefg123", "", ""},
  5587. };
  5588. Headers headers;
  5589. headers.emplace("Accept-Encoding", "zstd");
  5590. cli_.set_compress(true);
  5591. auto res = cli_.Post("/compress-multipart", headers, items);
  5592. ASSERT_TRUE(res);
  5593. EXPECT_EQ(StatusCode::OK_200, res->status);
  5594. }
  5595. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5596. Headers headers;
  5597. headers.emplace("Accept-Encoding", "zstd");
  5598. cli_.set_compress(true);
  5599. auto res = cli_.Put(
  5600. "/put", headers, 3,
  5601. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5602. sink.os << "PUT";
  5603. return true;
  5604. },
  5605. "text/plain");
  5606. ASSERT_TRUE(res);
  5607. EXPECT_EQ(StatusCode::OK_200, res->status);
  5608. EXPECT_EQ("PUT", res->body);
  5609. }
  5610. // Pre-compression logging tests
  5611. TEST_F(ServerTest, PreCompressionLogging) {
  5612. // Test data for compression (matches the actual /compress endpoint content)
  5613. const std::string test_content =
  5614. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5615. "3456789012345678901234567890";
  5616. // Variables to capture logging data
  5617. std::string pre_compression_body;
  5618. std::string pre_compression_content_type;
  5619. std::string pre_compression_content_encoding;
  5620. std::string post_compression_body;
  5621. std::string post_compression_content_type;
  5622. std::string post_compression_content_encoding;
  5623. // Set up pre-compression logger
  5624. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5625. const Response &res) {
  5626. pre_compression_body = res.body;
  5627. pre_compression_content_type = res.get_header_value("Content-Type");
  5628. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5629. });
  5630. // Set up post-compression logger
  5631. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5632. post_compression_body = res.body;
  5633. post_compression_content_type = res.get_header_value("Content-Type");
  5634. post_compression_content_encoding =
  5635. res.get_header_value("Content-Encoding");
  5636. });
  5637. // Test with gzip compression
  5638. Headers headers;
  5639. headers.emplace("Accept-Encoding", "gzip");
  5640. auto res = cli_.Get("/compress", headers);
  5641. // Verify response was compressed
  5642. ASSERT_TRUE(res);
  5643. EXPECT_EQ(StatusCode::OK_200, res->status);
  5644. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5645. // Verify pre-compression logger captured uncompressed content
  5646. EXPECT_EQ(test_content, pre_compression_body);
  5647. EXPECT_EQ("text/plain", pre_compression_content_type);
  5648. EXPECT_TRUE(pre_compression_content_encoding
  5649. .empty()); // No encoding header before compression
  5650. // Verify post-compression logger captured compressed content
  5651. EXPECT_NE(test_content,
  5652. post_compression_body); // Should be different after compression
  5653. EXPECT_EQ("text/plain", post_compression_content_type);
  5654. EXPECT_EQ("gzip", post_compression_content_encoding);
  5655. // Verify compressed content is smaller
  5656. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5657. }
  5658. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5659. const std::string test_content =
  5660. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5661. "3456789012345678901234567890";
  5662. std::string pre_compression_body;
  5663. std::string post_compression_body;
  5664. svr_.set_pre_compression_logger(
  5665. [&](const Request & /*req*/, const Response &res) {
  5666. pre_compression_body = res.body;
  5667. });
  5668. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5669. post_compression_body = res.body;
  5670. });
  5671. Headers headers;
  5672. headers.emplace("Accept-Encoding", "br");
  5673. auto res = cli_.Get("/compress", headers);
  5674. ASSERT_TRUE(res);
  5675. EXPECT_EQ(StatusCode::OK_200, res->status);
  5676. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5677. // Verify pre-compression content is uncompressed
  5678. EXPECT_EQ(test_content, pre_compression_body);
  5679. // Verify post-compression content is compressed
  5680. EXPECT_NE(test_content, post_compression_body);
  5681. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5682. }
  5683. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5684. const std::string test_content =
  5685. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5686. "3456789012345678901234567890";
  5687. std::string pre_compression_body;
  5688. std::string post_compression_body;
  5689. svr_.set_pre_compression_logger(
  5690. [&](const Request & /*req*/, const Response &res) {
  5691. pre_compression_body = res.body;
  5692. });
  5693. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5694. post_compression_body = res.body;
  5695. });
  5696. // Request without compression (use /nocompress endpoint)
  5697. Headers headers;
  5698. auto res = cli_.Get("/nocompress", headers);
  5699. ASSERT_TRUE(res);
  5700. EXPECT_EQ(StatusCode::OK_200, res->status);
  5701. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5702. // Pre-compression logger should not be called when no compression is applied
  5703. EXPECT_TRUE(
  5704. pre_compression_body.empty()); // Pre-compression logger not called
  5705. EXPECT_EQ(
  5706. test_content,
  5707. post_compression_body); // Post-compression logger captures final content
  5708. }
  5709. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5710. const std::string test_content =
  5711. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5712. "3456789012345678901234567890";
  5713. std::string pre_compression_body;
  5714. bool pre_logger_called = false;
  5715. // Set only pre-compression logger
  5716. svr_.set_pre_compression_logger(
  5717. [&](const Request & /*req*/, const Response &res) {
  5718. pre_compression_body = res.body;
  5719. pre_logger_called = true;
  5720. });
  5721. Headers headers;
  5722. headers.emplace("Accept-Encoding", "gzip");
  5723. auto res = cli_.Get("/compress", headers);
  5724. ASSERT_TRUE(res);
  5725. EXPECT_EQ(StatusCode::OK_200, res->status);
  5726. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5727. // Verify pre-compression logger was called
  5728. EXPECT_TRUE(pre_logger_called);
  5729. EXPECT_EQ(test_content, pre_compression_body);
  5730. }
  5731. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5732. {
  5733. // Test with Expect: 100-continue header - success case
  5734. // Server returns 100 Continue, client sends body, server returns 200 OK
  5735. Request req;
  5736. req.method = "POST";
  5737. req.path = "/post-large";
  5738. req.set_header("Expect", "100-continue");
  5739. req.body = LARGE_DATA;
  5740. Response res;
  5741. auto error = Error::Success;
  5742. cli_.set_keep_alive(true);
  5743. auto ret = cli_.send(req, res, error);
  5744. EXPECT_TRUE(ret);
  5745. EXPECT_EQ(StatusCode::OK_200, res.status);
  5746. EXPECT_EQ(LARGE_DATA, res.body);
  5747. }
  5748. {
  5749. // Test with Expect: 100-continue header - error case
  5750. // Client should not send the body when server returns an error
  5751. Request req;
  5752. req.method = "POST";
  5753. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5754. req.set_header("Expect", "100-continue");
  5755. req.body = LARGE_DATA;
  5756. Response res;
  5757. auto error = Error::Success;
  5758. auto start = std::chrono::high_resolution_clock::now();
  5759. cli_.set_keep_alive(true);
  5760. auto ret = cli_.send(req, res, error);
  5761. auto end = std::chrono::high_resolution_clock::now();
  5762. auto elapsed =
  5763. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5764. .count();
  5765. // With Expect: 100-continue, request completes successfully but with error
  5766. EXPECT_TRUE(ret);
  5767. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5768. EXPECT_EQ("close", res.get_header_value("Connection"));
  5769. EXPECT_FALSE(cli_.is_socket_open());
  5770. EXPECT_LE(elapsed, 200);
  5771. }
  5772. {
  5773. // Send an extra GET request to ensure error recovery without hanging
  5774. Request req;
  5775. req.method = "GET";
  5776. req.path = "/hi";
  5777. auto start = std::chrono::high_resolution_clock::now();
  5778. auto res = cli_.send(req);
  5779. auto end = std::chrono::high_resolution_clock::now();
  5780. auto elapsed =
  5781. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5782. .count();
  5783. ASSERT_TRUE(res);
  5784. EXPECT_EQ(StatusCode::OK_200, res->status);
  5785. EXPECT_EQ("Hello World!", res->body);
  5786. EXPECT_LE(elapsed, 500);
  5787. }
  5788. }
  5789. TEST(ZstdDecompressor, ChunkedDecompression) {
  5790. std::string data;
  5791. for (size_t i = 0; i < 32 * 1024; ++i) {
  5792. data.push_back(static_cast<char>('a' + i % 26));
  5793. }
  5794. std::string compressed_data;
  5795. {
  5796. httplib::detail::zstd_compressor compressor;
  5797. bool result = compressor.compress(
  5798. data.data(), data.size(),
  5799. /*last=*/true,
  5800. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5801. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5802. compressed_data_size);
  5803. return true;
  5804. });
  5805. ASSERT_TRUE(result);
  5806. }
  5807. std::string decompressed_data;
  5808. {
  5809. httplib::detail::zstd_decompressor decompressor;
  5810. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5811. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5812. size_t chunk_size = 130;
  5813. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5814. chunk_begin += chunk_size) {
  5815. size_t current_chunk_size =
  5816. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5817. bool result = decompressor.decompress(
  5818. compressed_data.data() + chunk_begin, current_chunk_size,
  5819. [&](const char *decompressed_data_chunk,
  5820. size_t decompressed_data_chunk_size) {
  5821. decompressed_data.insert(decompressed_data.size(),
  5822. decompressed_data_chunk,
  5823. decompressed_data_chunk_size);
  5824. return true;
  5825. });
  5826. ASSERT_TRUE(result);
  5827. }
  5828. }
  5829. ASSERT_EQ(data, decompressed_data);
  5830. }
  5831. TEST(ZstdDecompressor, Decompress) {
  5832. std::string original_text = "Compressed with ZSTD";
  5833. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5834. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5835. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5836. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5837. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5838. std::string decompressed_data;
  5839. {
  5840. httplib::detail::zstd_decompressor decompressor;
  5841. bool result = decompressor.decompress(
  5842. compressed_data.data(), compressed_data.size(),
  5843. [&](const char *decompressed_data_chunk,
  5844. size_t decompressed_data_chunk_size) {
  5845. decompressed_data.insert(decompressed_data.size(),
  5846. decompressed_data_chunk,
  5847. decompressed_data_chunk_size);
  5848. return true;
  5849. });
  5850. ASSERT_TRUE(result);
  5851. }
  5852. ASSERT_EQ(original_text, decompressed_data);
  5853. }
  5854. #endif
  5855. // Sends a raw request to a server listening at HOST:PORT.
  5856. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5857. std::string *resp = nullptr) {
  5858. auto error = Error::Success;
  5859. auto client_sock = detail::create_client_socket(
  5860. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5861. /*connection_timeout_sec=*/5, 0,
  5862. /*read_timeout_sec=*/5, 0,
  5863. /*write_timeout_sec=*/5, 0, std::string(), error);
  5864. if (client_sock == INVALID_SOCKET) { return false; }
  5865. auto ret = detail::process_client_socket(
  5866. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5867. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5868. if (req.size() !=
  5869. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5870. return false;
  5871. }
  5872. char buf[512];
  5873. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5874. while (line_reader.getline()) {
  5875. if (resp) { *resp += line_reader.ptr(); }
  5876. }
  5877. return true;
  5878. });
  5879. detail::close_socket(client_sock);
  5880. return ret;
  5881. }
  5882. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5883. Server svr;
  5884. std::string header_value;
  5885. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5886. header_value = req.get_header_value("foo");
  5887. res.set_content("ok", "text/plain");
  5888. });
  5889. thread t = thread([&] { svr.listen(HOST, PORT); });
  5890. auto se = detail::scope_exit([&] {
  5891. svr.stop();
  5892. t.join();
  5893. ASSERT_FALSE(svr.is_running());
  5894. });
  5895. svr.wait_until_ready();
  5896. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5897. // like characters are not treated the same - use vertical tab and escape.
  5898. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5899. "foo: \t \v bar \x1B\t \r\n"
  5900. "Connection: close\r\n"
  5901. "\r\n";
  5902. std::string res;
  5903. ASSERT_TRUE(send_request(5, req, &res));
  5904. EXPECT_EQ(header_value, "");
  5905. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5906. }
  5907. // Sends a raw request and verifies that there isn't a crash or exception.
  5908. static void test_raw_request(const std::string &req,
  5909. std::string *out = nullptr) {
  5910. Server svr;
  5911. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5912. res.set_content("ok", "text/plain");
  5913. });
  5914. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5915. res.set_content("ok", "text/plain");
  5916. });
  5917. svr.Get("/header_field_value_check",
  5918. [&](const Request & /*req*/, Response &res) {
  5919. res.set_content("ok", "text/plain");
  5920. });
  5921. // Server read timeout must be longer than the client read timeout for the
  5922. // bug to reproduce, probably to force the server to process a request
  5923. // without a trailing blank line.
  5924. const time_t client_read_timeout_sec = 1;
  5925. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5926. bool listen_thread_ok = false;
  5927. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5928. auto se = detail::scope_exit([&] {
  5929. svr.stop();
  5930. t.join();
  5931. ASSERT_FALSE(svr.is_running());
  5932. EXPECT_TRUE(listen_thread_ok);
  5933. });
  5934. svr.wait_until_ready();
  5935. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5936. }
  5937. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5938. // A certain header line causes an exception if the header property is parsed
  5939. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5940. test_raw_request(
  5941. "GET /hi HTTP/1.1\r\n"
  5942. " : "
  5943. " "
  5944. " ");
  5945. }
  5946. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5947. // A certain header line causes an exception if the header property *name* is
  5948. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5949. // greedy matcher and requires backtracking when there are a lot of ":"
  5950. // characters.
  5951. // This occurs with libc++ but not libstdc++.
  5952. test_raw_request(
  5953. "GET /hi HTTP/1.1\r\n"
  5954. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5955. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5956. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5957. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5958. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5959. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5960. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5961. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5962. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5963. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5964. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5965. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5966. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5967. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5968. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5969. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5970. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5971. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5972. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5973. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5974. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5975. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5976. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5977. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5978. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5979. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5980. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5981. "&&&%%%");
  5982. }
  5983. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5984. // Make sure this doesn't crash the server.
  5985. // In a previous version of the header line regex, the "\r" rendered the line
  5986. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5987. // a new position where the leading white space ended and the field value
  5988. // began.
  5989. // The crash occurs with libc++ but not libstdc++.
  5990. test_raw_request("GET /hi HTTP/1.1\r\n"
  5991. "a:" +
  5992. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5993. "\r\n"
  5994. "\r\n");
  5995. }
  5996. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5997. std::string out;
  5998. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5999. "Content-Type: text/plain\r\n"
  6000. "Transfer-Encoding: chunked\r\n"
  6001. "\r\n"
  6002. "nothex\r\n",
  6003. &out);
  6004. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6005. }
  6006. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6007. std::string out;
  6008. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6009. "Content-Type: text/plain\r\n"
  6010. "Transfer-Encoding: chunked\r\n"
  6011. "\r\n"
  6012. "3\r\n"
  6013. "xyz\r\n"
  6014. "NaN\r\n",
  6015. &out);
  6016. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6017. }
  6018. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6019. std::string out;
  6020. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6021. "Content-Type: text/plain\r\n"
  6022. "Transfer-Encoding: chunked\r\n"
  6023. "\r\n"
  6024. // Length is too large for 64 bits.
  6025. "1ffffffffffffffff\r\n"
  6026. "xyz\r\n",
  6027. &out);
  6028. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6029. }
  6030. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6031. test_raw_request("GET /hi HTTP/1.1\r\n"
  6032. "Content-Type: text/plain\r\n\r");
  6033. }
  6034. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6035. std::string out;
  6036. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6037. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6038. }
  6039. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6040. Server svr;
  6041. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6042. EXPECT_TRUE(!req.remote_addr.empty());
  6043. });
  6044. thread t = thread([&] { svr.listen(HOST, PORT); });
  6045. auto se = detail::scope_exit([&] {
  6046. svr.stop();
  6047. t.join();
  6048. ASSERT_FALSE(svr.is_running());
  6049. });
  6050. svr.wait_until_ready();
  6051. // Send an invalid request line to trigger Bad Request
  6052. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6053. std::string out;
  6054. ASSERT_TRUE(send_request(5, bad_req, &out));
  6055. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6056. }
  6057. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6058. std::string out;
  6059. std::string request(
  6060. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6061. test_raw_request(request, &out);
  6062. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6063. }
  6064. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6065. std::string out;
  6066. std::string request(
  6067. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6068. test_raw_request(request, &out);
  6069. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6070. }
  6071. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6072. std::string out;
  6073. std::string request(
  6074. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6075. test_raw_request(request, &out);
  6076. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6077. }
  6078. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6079. std::string out;
  6080. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6081. "Test: \r\n\r\n",
  6082. &out);
  6083. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6084. }
  6085. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6086. Server svr;
  6087. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6088. res.set_header("Cache-Control", "no-cache");
  6089. res.set_chunked_content_provider(
  6090. "text/event-stream", [](size_t offset, DataSink &sink) {
  6091. std::string s = "data:";
  6092. s += std::to_string(offset);
  6093. s += "\n\n";
  6094. auto ret = sink.write(s.data(), s.size());
  6095. EXPECT_TRUE(ret);
  6096. std::this_thread::sleep_for(std::chrono::seconds(1));
  6097. return true;
  6098. });
  6099. });
  6100. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6101. svr.wait_until_ready();
  6102. Client client(HOST, PORT);
  6103. const Headers headers = {{"Accept", "text/event-stream"}};
  6104. auto get_thread = std::thread([&client, &headers]() {
  6105. auto res = client.Get(
  6106. "/events", headers,
  6107. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6108. });
  6109. auto se = detail::scope_exit([&] {
  6110. svr.stop();
  6111. get_thread.join();
  6112. listen_thread.join();
  6113. ASSERT_FALSE(svr.is_running());
  6114. });
  6115. // Give GET time to get a few messages.
  6116. std::this_thread::sleep_for(std::chrono::seconds(2));
  6117. }
  6118. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6119. httplib::Server svr;
  6120. svr.Post("/hi",
  6121. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6122. res.status = StatusCode::OK_200;
  6123. });
  6124. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6125. svr.wait_until_ready();
  6126. Client cli(HOST, PORT);
  6127. auto res = cli.Post("/hi", "data", "text/plain");
  6128. ASSERT_TRUE(res);
  6129. EXPECT_EQ(StatusCode::OK_200, res->status);
  6130. svr.stop();
  6131. thread.join();
  6132. ASSERT_FALSE(svr.is_running());
  6133. res = cli.Post("/hi", "data", "text/plain");
  6134. ASSERT_FALSE(res);
  6135. }
  6136. TEST(ServerStopTest, ListenFailure) {
  6137. Server svr;
  6138. auto t = thread([&]() {
  6139. auto ret = svr.listen("????", PORT);
  6140. EXPECT_FALSE(ret);
  6141. });
  6142. svr.wait_until_ready();
  6143. svr.stop();
  6144. t.join();
  6145. }
  6146. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6147. TEST(ServerStopTest, Decommision) {
  6148. Server svr;
  6149. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6150. for (int i = 0; i < 4; i++) {
  6151. auto is_even = !(i % 2);
  6152. std::thread t{[&] {
  6153. try {
  6154. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6155. if (is_even) {
  6156. throw std::runtime_error("Some thing that happens to go wrong.");
  6157. }
  6158. svr.listen(HOST, PORT);
  6159. } catch (...) { svr.decommission(); }
  6160. }};
  6161. svr.wait_until_ready();
  6162. // Server is up
  6163. {
  6164. Client cli(HOST, PORT);
  6165. auto res = cli.Get("/hi");
  6166. if (is_even) {
  6167. EXPECT_FALSE(res);
  6168. } else {
  6169. EXPECT_TRUE(res);
  6170. EXPECT_EQ("hi...", res->body);
  6171. }
  6172. }
  6173. svr.stop();
  6174. t.join();
  6175. // Server is down...
  6176. {
  6177. Client cli(HOST, PORT);
  6178. auto res = cli.Get("/hi");
  6179. EXPECT_FALSE(res);
  6180. }
  6181. }
  6182. }
  6183. #endif
  6184. // Helper function for string body upload progress tests
  6185. template <typename SetupHandler, typename ClientCall>
  6186. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6187. ClientCall &&client_call,
  6188. const string &body) {
  6189. Server svr;
  6190. setup_handler(svr);
  6191. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6192. auto se = detail::scope_exit([&] {
  6193. svr.stop();
  6194. t.join();
  6195. });
  6196. svr.wait_until_ready();
  6197. Client cli(HOST, PORT);
  6198. vector<uint64_t> progress_values;
  6199. bool progress_called = false;
  6200. auto res =
  6201. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6202. progress_values.push_back(current);
  6203. progress_called = true;
  6204. return true;
  6205. });
  6206. ASSERT_TRUE(res);
  6207. EXPECT_EQ(200, res->status);
  6208. EXPECT_TRUE(progress_called);
  6209. }
  6210. TEST(UploadProgressTest, PostStringBodyBasic) {
  6211. TestStringBodyUploadProgress(
  6212. [](Server &svr) {
  6213. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6214. res.set_content("received", "text/plain");
  6215. });
  6216. },
  6217. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6218. return cli.Post("/test", body, "text/plain", progress_callback);
  6219. },
  6220. "test data for upload progress");
  6221. }
  6222. TEST(UploadProgressTest, PutStringBodyBasic) {
  6223. TestStringBodyUploadProgress(
  6224. [](Server &svr) {
  6225. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6226. res.set_content("put received", "text/plain");
  6227. });
  6228. },
  6229. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6230. return cli.Put("/test", body, "text/plain", progress_callback);
  6231. },
  6232. "put test data for upload progress");
  6233. }
  6234. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6235. TestStringBodyUploadProgress(
  6236. [](Server &svr) {
  6237. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6238. res.set_content("patch received", "text/plain");
  6239. });
  6240. },
  6241. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6242. return cli.Patch("/test", body, "text/plain", progress_callback);
  6243. },
  6244. "patch test data for upload progress");
  6245. }
  6246. // Helper function for content provider upload progress tests
  6247. template <typename SetupHandler, typename ClientCall>
  6248. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6249. ClientCall &&client_call) {
  6250. Server svr;
  6251. setup_handler(svr);
  6252. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6253. auto se = detail::scope_exit([&] {
  6254. svr.stop();
  6255. t.join();
  6256. });
  6257. svr.wait_until_ready();
  6258. Client cli(HOST, PORT);
  6259. vector<uint64_t> progress_values;
  6260. auto res =
  6261. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6262. progress_values.push_back(current);
  6263. return true;
  6264. });
  6265. ASSERT_TRUE(res);
  6266. EXPECT_EQ(200, res->status);
  6267. EXPECT_FALSE(progress_values.empty());
  6268. }
  6269. TEST(UploadProgressTest, PostContentProviderProgress) {
  6270. TestContentProviderUploadProgress(
  6271. [](Server &svr) {
  6272. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6273. res.set_content("provider received", "text/plain");
  6274. });
  6275. },
  6276. [](Client &cli, UploadProgress progress_callback) {
  6277. return cli.Post(
  6278. "/test", 10,
  6279. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6280. sink.os << "test data";
  6281. return true;
  6282. },
  6283. "text/plain", progress_callback);
  6284. });
  6285. }
  6286. // Helper function for multipart upload progress tests
  6287. template <typename SetupHandler, typename ClientCall>
  6288. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6289. ClientCall &&client_call,
  6290. const string &endpoint) {
  6291. Server svr;
  6292. setup_handler(svr);
  6293. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6294. auto se = detail::scope_exit([&] {
  6295. svr.stop();
  6296. t.join();
  6297. });
  6298. svr.wait_until_ready();
  6299. Client cli(HOST, PORT);
  6300. vector<uint64_t> progress_values;
  6301. UploadFormDataItems items = {
  6302. {"field1", "value1", "", ""},
  6303. {"field2", "longer value for progress tracking test", "", ""},
  6304. {"file1", "file content data for upload progress", "test.txt",
  6305. "text/plain"}};
  6306. auto res = client_call(cli, endpoint, items,
  6307. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6308. progress_values.push_back(current);
  6309. return true;
  6310. });
  6311. ASSERT_TRUE(res);
  6312. EXPECT_EQ(200, res->status);
  6313. EXPECT_FALSE(progress_values.empty());
  6314. }
  6315. TEST(UploadProgressTest, PostMultipartProgress) {
  6316. TestMultipartUploadProgress(
  6317. [](Server &svr) {
  6318. svr.Post("/multipart", [](const Request &req, Response &res) {
  6319. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6320. res.set_content("multipart received", "text/plain");
  6321. });
  6322. },
  6323. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6324. UploadProgress progress_callback) {
  6325. return cli.Post(endpoint, items, progress_callback);
  6326. },
  6327. "/multipart");
  6328. }
  6329. // Helper function for basic download progress tests
  6330. template <typename SetupHandler, typename ClientCall>
  6331. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6332. ClientCall &&client_call, const string &endpoint,
  6333. size_t expected_content_size) {
  6334. Server svr;
  6335. setup_handler(svr);
  6336. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6337. auto se = detail::scope_exit([&] {
  6338. svr.stop();
  6339. t.join();
  6340. });
  6341. svr.wait_until_ready();
  6342. Client cli(HOST, PORT);
  6343. vector<uint64_t> progress_values;
  6344. auto res = client_call(cli, endpoint,
  6345. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6346. progress_values.push_back(current);
  6347. return true;
  6348. });
  6349. ASSERT_TRUE(res);
  6350. EXPECT_EQ(200, res->status);
  6351. EXPECT_FALSE(progress_values.empty());
  6352. EXPECT_EQ(expected_content_size, res->body.size());
  6353. }
  6354. TEST(DownloadProgressTest, GetBasic) {
  6355. TestBasicDownloadProgress(
  6356. [](Server &svr) {
  6357. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6358. string content(1000, 'D');
  6359. res.set_content(content, "text/plain");
  6360. });
  6361. },
  6362. [](Client &cli, const string &endpoint,
  6363. DownloadProgress progress_callback) {
  6364. return cli.Get(endpoint, progress_callback);
  6365. },
  6366. "/download", 1000u);
  6367. }
  6368. // Helper function for content receiver download progress tests
  6369. template <typename SetupHandler, typename ClientCall>
  6370. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6371. ClientCall &&client_call,
  6372. const string &endpoint,
  6373. size_t expected_content_size) {
  6374. Server svr;
  6375. setup_handler(svr);
  6376. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6377. auto se = detail::scope_exit([&] {
  6378. svr.stop();
  6379. t.join();
  6380. });
  6381. svr.wait_until_ready();
  6382. Client cli(HOST, PORT);
  6383. vector<uint64_t> progress_values;
  6384. string received_body;
  6385. auto res = client_call(
  6386. cli, endpoint,
  6387. [&](const char *data, size_t data_length) -> bool {
  6388. received_body.append(data, data_length);
  6389. return true;
  6390. },
  6391. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6392. progress_values.push_back(current);
  6393. return true;
  6394. });
  6395. ASSERT_TRUE(res);
  6396. EXPECT_EQ(200, res->status);
  6397. EXPECT_FALSE(progress_values.empty());
  6398. EXPECT_EQ(expected_content_size, received_body.size());
  6399. EXPECT_TRUE(res->body.empty());
  6400. }
  6401. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6402. TestContentReceiverDownloadProgress(
  6403. [](Server &svr) {
  6404. svr.Get("/download-receiver",
  6405. [](const Request & /*req*/, Response &res) {
  6406. string content(2000, 'R');
  6407. res.set_content(content, "text/plain");
  6408. });
  6409. },
  6410. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6411. DownloadProgress progress_callback) {
  6412. return cli.Get(endpoint, content_receiver, progress_callback);
  6413. },
  6414. "/download-receiver", 2000u);
  6415. }
  6416. TEST(StreamingTest, NoContentLengthStreaming) {
  6417. Server svr;
  6418. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6419. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6420. if (offset < 6) {
  6421. sink.os << (offset < 3 ? "a" : "b");
  6422. } else {
  6423. sink.done();
  6424. }
  6425. return true;
  6426. });
  6427. });
  6428. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6429. auto listen_se = detail::scope_exit([&] {
  6430. svr.stop();
  6431. listen_thread.join();
  6432. ASSERT_FALSE(svr.is_running());
  6433. });
  6434. svr.wait_until_ready();
  6435. Client client(HOST, PORT);
  6436. auto get_thread = std::thread([&client]() {
  6437. std::string s;
  6438. auto res =
  6439. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6440. s += std::string(data, len);
  6441. return true;
  6442. });
  6443. ASSERT_TRUE(res);
  6444. EXPECT_EQ(StatusCode::OK_200, res->status);
  6445. EXPECT_EQ("aaabbb", s);
  6446. });
  6447. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6448. // Give GET time to get a few messages.
  6449. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6450. }
  6451. TEST(MountTest, Unmount) {
  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.wait_until_ready();
  6460. Client cli("localhost", PORT);
  6461. svr.set_mount_point("/mount2", "./www2");
  6462. auto res = cli.Get("/");
  6463. ASSERT_TRUE(res);
  6464. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6465. res = cli.Get("/mount2/dir/test.html");
  6466. ASSERT_TRUE(res);
  6467. EXPECT_EQ(StatusCode::OK_200, res->status);
  6468. svr.set_mount_point("/", "./www");
  6469. res = cli.Get("/dir/");
  6470. ASSERT_TRUE(res);
  6471. EXPECT_EQ(StatusCode::OK_200, res->status);
  6472. svr.remove_mount_point("/");
  6473. res = cli.Get("/dir/");
  6474. ASSERT_TRUE(res);
  6475. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6476. svr.remove_mount_point("/mount2");
  6477. res = cli.Get("/mount2/dir/test.html");
  6478. ASSERT_TRUE(res);
  6479. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6480. }
  6481. TEST(MountTest, Redicect) {
  6482. Server svr;
  6483. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6484. auto se = detail::scope_exit([&] {
  6485. svr.stop();
  6486. listen_thread.join();
  6487. ASSERT_FALSE(svr.is_running());
  6488. });
  6489. svr.set_mount_point("/", "./www");
  6490. svr.wait_until_ready();
  6491. Client cli("localhost", PORT);
  6492. auto res = cli.Get("/dir/");
  6493. ASSERT_TRUE(res);
  6494. EXPECT_EQ(StatusCode::OK_200, res->status);
  6495. res = cli.Get("/dir");
  6496. ASSERT_TRUE(res);
  6497. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6498. res = cli.Get("/file");
  6499. ASSERT_TRUE(res);
  6500. EXPECT_EQ(StatusCode::OK_200, res->status);
  6501. res = cli.Get("/file/");
  6502. ASSERT_TRUE(res);
  6503. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6504. cli.set_follow_location(true);
  6505. res = cli.Get("/dir");
  6506. ASSERT_TRUE(res);
  6507. EXPECT_EQ(StatusCode::OK_200, res->status);
  6508. }
  6509. TEST(MountTest, MultibytesPathName) {
  6510. Server svr;
  6511. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6512. auto se = detail::scope_exit([&] {
  6513. svr.stop();
  6514. listen_thread.join();
  6515. ASSERT_FALSE(svr.is_running());
  6516. });
  6517. svr.set_mount_point("/", "./www");
  6518. svr.wait_until_ready();
  6519. Client cli("localhost", PORT);
  6520. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6521. ASSERT_TRUE(res);
  6522. EXPECT_EQ(StatusCode::OK_200, res->status);
  6523. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6524. }
  6525. TEST(KeepAliveTest, ReadTimeout) {
  6526. Server svr;
  6527. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6528. std::this_thread::sleep_for(std::chrono::seconds(2));
  6529. res.set_content("a", "text/plain");
  6530. });
  6531. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6532. res.set_content("b", "text/plain");
  6533. });
  6534. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6535. auto se = detail::scope_exit([&] {
  6536. svr.stop();
  6537. listen_thread.join();
  6538. ASSERT_FALSE(svr.is_running());
  6539. });
  6540. svr.wait_until_ready();
  6541. Client cli("localhost", PORT);
  6542. cli.set_keep_alive(true);
  6543. cli.set_read_timeout(std::chrono::seconds(1));
  6544. auto resa = cli.Get("/a");
  6545. ASSERT_FALSE(resa);
  6546. EXPECT_EQ(Error::Read, resa.error());
  6547. auto resb = cli.Get("/b");
  6548. ASSERT_TRUE(resb);
  6549. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6550. EXPECT_EQ("b", resb->body);
  6551. }
  6552. TEST(KeepAliveTest, MaxCount) {
  6553. size_t keep_alive_max_count = 3;
  6554. Server svr;
  6555. svr.set_keep_alive_max_count(keep_alive_max_count);
  6556. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6557. res.set_content("Hello World!", "text/plain");
  6558. });
  6559. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6560. auto se = detail::scope_exit([&] {
  6561. svr.stop();
  6562. listen_thread.join();
  6563. ASSERT_FALSE(svr.is_running());
  6564. });
  6565. svr.wait_until_ready();
  6566. Client cli(HOST, PORT);
  6567. cli.set_keep_alive(true);
  6568. for (size_t i = 0; i < 5; i++) {
  6569. auto result = cli.Get("/hi");
  6570. ASSERT_TRUE(result);
  6571. EXPECT_EQ(StatusCode::OK_200, result->status);
  6572. if (i == keep_alive_max_count - 1) {
  6573. EXPECT_EQ("close", result->get_header_value("Connection"));
  6574. } else {
  6575. EXPECT_FALSE(result->has_header("Connection"));
  6576. }
  6577. }
  6578. }
  6579. TEST(KeepAliveTest, Issue1041) {
  6580. Server svr;
  6581. svr.set_keep_alive_timeout(3);
  6582. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6583. res.set_content("Hello World!", "text/plain");
  6584. });
  6585. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6586. auto se = detail::scope_exit([&] {
  6587. svr.stop();
  6588. listen_thread.join();
  6589. ASSERT_FALSE(svr.is_running());
  6590. });
  6591. svr.wait_until_ready();
  6592. Client cli(HOST, PORT);
  6593. cli.set_keep_alive(true);
  6594. auto result = cli.Get("/hi");
  6595. ASSERT_TRUE(result);
  6596. EXPECT_EQ(StatusCode::OK_200, result->status);
  6597. std::this_thread::sleep_for(std::chrono::seconds(5));
  6598. result = cli.Get("/hi");
  6599. ASSERT_TRUE(result);
  6600. EXPECT_EQ(StatusCode::OK_200, result->status);
  6601. }
  6602. TEST(KeepAliveTest, Issue1959) {
  6603. Server svr;
  6604. svr.set_keep_alive_timeout(5);
  6605. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6606. res.set_content("a", "text/plain");
  6607. });
  6608. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6609. auto se = detail::scope_exit([&] {
  6610. if (!svr.is_running()) return;
  6611. svr.stop();
  6612. listen_thread.join();
  6613. ASSERT_FALSE(svr.is_running());
  6614. });
  6615. svr.wait_until_ready();
  6616. Client cli("localhost", PORT);
  6617. cli.set_keep_alive(true);
  6618. using namespace std::chrono;
  6619. auto start = steady_clock::now();
  6620. cli.Get("/a");
  6621. svr.stop();
  6622. listen_thread.join();
  6623. auto end = steady_clock::now();
  6624. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6625. EXPECT_LT(elapsed, 5000);
  6626. }
  6627. #ifdef CPPHTTPLIB_SSL_ENABLED
  6628. TEST(KeepAliveTest, SSLClientReconnection) {
  6629. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6630. ASSERT_TRUE(svr.is_valid());
  6631. svr.set_keep_alive_timeout(1);
  6632. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6633. res.set_content("Hello World!", "text/plain");
  6634. });
  6635. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6636. auto se = detail::scope_exit([&] {
  6637. svr.stop();
  6638. listen_thread.join();
  6639. ASSERT_FALSE(svr.is_running());
  6640. });
  6641. svr.wait_until_ready();
  6642. SSLClient cli(HOST, PORT);
  6643. cli.enable_server_certificate_verification(false);
  6644. cli.set_keep_alive(true);
  6645. auto result = cli.Get("/hi");
  6646. ASSERT_TRUE(result);
  6647. EXPECT_EQ(StatusCode::OK_200, result->status);
  6648. result = cli.Get("/hi");
  6649. ASSERT_TRUE(result);
  6650. EXPECT_EQ(StatusCode::OK_200, result->status);
  6651. std::this_thread::sleep_for(std::chrono::seconds(2));
  6652. // Recoonect
  6653. result = cli.Get("/hi");
  6654. ASSERT_TRUE(result);
  6655. EXPECT_EQ(StatusCode::OK_200, result->status);
  6656. result = cli.Get("/hi");
  6657. ASSERT_TRUE(result);
  6658. EXPECT_EQ(StatusCode::OK_200, result->status);
  6659. }
  6660. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6661. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6662. ASSERT_TRUE(svr.is_valid());
  6663. svr.set_keep_alive_timeout(1);
  6664. std::string content = "reconnect";
  6665. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6666. res.set_content("Hello World!", "text/plain");
  6667. });
  6668. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6669. auto se = detail::scope_exit([&] {
  6670. svr.stop();
  6671. listen_thread.join();
  6672. ASSERT_FALSE(svr.is_running());
  6673. });
  6674. svr.wait_until_ready();
  6675. SSLClient cli(HOST, PORT);
  6676. cli.enable_server_certificate_verification(false);
  6677. cli.set_keep_alive(true);
  6678. auto result = cli.Post(
  6679. "/hi", content.size(),
  6680. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6681. sink.write(content.c_str(), content.size());
  6682. return true;
  6683. },
  6684. "text/plain");
  6685. ASSERT_TRUE(result);
  6686. EXPECT_EQ(200, result->status);
  6687. std::this_thread::sleep_for(std::chrono::seconds(2));
  6688. // Recoonect
  6689. result = cli.Post(
  6690. "/hi", content.size(),
  6691. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6692. sink.write(content.c_str(), content.size());
  6693. return true;
  6694. },
  6695. "text/plain");
  6696. ASSERT_TRUE(result);
  6697. EXPECT_EQ(200, result->status);
  6698. result = cli.Post(
  6699. "/hi", content.size(),
  6700. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6701. sink.write(content.c_str(), content.size());
  6702. return true;
  6703. },
  6704. "text/plain");
  6705. ASSERT_TRUE(result);
  6706. EXPECT_EQ(200, result->status);
  6707. }
  6708. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6709. using namespace httplib::tls;
  6710. {
  6711. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6712. ASSERT_TRUE(svr.is_valid());
  6713. svr.Get("/sni", [&](const Request &req, Response &res) {
  6714. std::string expected = req.sni();
  6715. EXPECT_EQ(expected, req.get_param_value("expected"));
  6716. res.set_content("ok", "text/plain");
  6717. });
  6718. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6719. auto se = detail::scope_exit([&] {
  6720. svr.stop();
  6721. listen_thread.join();
  6722. ASSERT_FALSE(svr.is_running());
  6723. });
  6724. svr.wait_until_ready();
  6725. {
  6726. SSLClient cli("localhost", PORT);
  6727. cli.enable_server_certificate_verification(false);
  6728. auto res = cli.Get("/sni?expected=localhost");
  6729. ASSERT_TRUE(res);
  6730. }
  6731. {
  6732. SSLClient cli("::1", PORT);
  6733. cli.enable_server_certificate_verification(false);
  6734. auto res = cli.Get("/sni?expected=");
  6735. // NOTE: This may fail if the server is listening on IPv4 only
  6736. // (e.g., when localhost resolves to 127.0.0.1 only)
  6737. if (res) {
  6738. EXPECT_EQ(StatusCode::OK_200, res->status);
  6739. } else {
  6740. EXPECT_EQ(Error::Connection, res.error());
  6741. }
  6742. }
  6743. }
  6744. }
  6745. #endif
  6746. TEST(ClientProblemDetectionTest, ContentProvider) {
  6747. Server svr;
  6748. size_t content_length = 1024 * 1024;
  6749. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6750. res.set_content_provider(
  6751. content_length, "text/plain",
  6752. [&](size_t offset, size_t length, DataSink &sink) {
  6753. auto out_len = std::min(length, static_cast<size_t>(1024));
  6754. std::string out(out_len, '@');
  6755. sink.write(out.data(), out_len);
  6756. return offset < 4096;
  6757. },
  6758. [](bool success) { ASSERT_FALSE(success); });
  6759. });
  6760. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6761. res.set_content_provider(
  6762. 0, "text/plain",
  6763. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6764. EXPECT_TRUE(false);
  6765. return true;
  6766. },
  6767. [](bool success) { ASSERT_FALSE(success); });
  6768. });
  6769. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6770. auto se = detail::scope_exit([&] {
  6771. svr.stop();
  6772. listen_thread.join();
  6773. ASSERT_FALSE(svr.is_running());
  6774. });
  6775. svr.wait_until_ready();
  6776. Client cli("localhost", PORT);
  6777. {
  6778. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6779. size_t /*data_length*/) { return false; });
  6780. ASSERT_FALSE(res);
  6781. }
  6782. {
  6783. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6784. size_t /*data_length*/) { return false; });
  6785. ASSERT_TRUE(res);
  6786. }
  6787. }
  6788. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6789. Server svr;
  6790. svr.set_error_handler([](Request const &, Response &res) -> void {
  6791. res.set_chunked_content_provider(
  6792. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6793. sink.os << "hello";
  6794. sink.os << "world";
  6795. sink.done();
  6796. return true;
  6797. });
  6798. });
  6799. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6800. auto se = detail::scope_exit([&] {
  6801. svr.stop();
  6802. listen_thread.join();
  6803. ASSERT_FALSE(svr.is_running());
  6804. });
  6805. svr.wait_until_ready();
  6806. Client cli("localhost", PORT);
  6807. auto res = cli.Get("/");
  6808. ASSERT_TRUE(res);
  6809. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6810. EXPECT_EQ("helloworld", res->body);
  6811. }
  6812. TEST(LongPollingTest, ClientCloseDetection) {
  6813. Server svr;
  6814. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6815. res.set_chunked_content_provider(
  6816. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6817. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6818. sink.os << "hello";
  6819. auto count = 10;
  6820. while (count > 0 && sink.is_writable()) {
  6821. this_thread::sleep_for(chrono::milliseconds(10));
  6822. count--;
  6823. }
  6824. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6825. return true;
  6826. });
  6827. });
  6828. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6829. auto se = detail::scope_exit([&] {
  6830. svr.stop();
  6831. listen_thread.join();
  6832. ASSERT_FALSE(svr.is_running());
  6833. });
  6834. svr.wait_until_ready();
  6835. Client cli("localhost", PORT);
  6836. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6837. EXPECT_EQ("hello", string(data, data_length));
  6838. return false; // close the socket immediately.
  6839. });
  6840. ASSERT_FALSE(res);
  6841. }
  6842. TEST(GetWithParametersTest, GetWithParameters) {
  6843. Server svr;
  6844. svr.Get("/", [&](const Request &req, Response &) {
  6845. EXPECT_EQ("world", req.get_param_value("hello"));
  6846. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6847. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6848. });
  6849. svr.Get("/params", [&](const Request &req, Response &) {
  6850. EXPECT_EQ("world", req.get_param_value("hello"));
  6851. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6852. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6853. });
  6854. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6855. EXPECT_EQ("resource-id", req.matches[1]);
  6856. EXPECT_EQ("foo", req.get_param_value("param1"));
  6857. EXPECT_EQ("bar", req.get_param_value("param2"));
  6858. });
  6859. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6860. EXPECT_EQ("user-id", req.path_params.at("id"));
  6861. EXPECT_EQ("foo", req.get_param_value("param1"));
  6862. EXPECT_EQ("bar", req.get_param_value("param2"));
  6863. });
  6864. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6865. auto se = detail::scope_exit([&] {
  6866. svr.stop();
  6867. listen_thread.join();
  6868. ASSERT_FALSE(svr.is_running());
  6869. });
  6870. svr.wait_until_ready();
  6871. {
  6872. Client cli(HOST, PORT);
  6873. Params params;
  6874. params.emplace("hello", "world");
  6875. params.emplace("hello2", "world2");
  6876. params.emplace("hello3", "world3");
  6877. auto res = cli.Get("/", params, Headers{});
  6878. ASSERT_TRUE(res);
  6879. EXPECT_EQ(StatusCode::OK_200, res->status);
  6880. }
  6881. {
  6882. Client cli(HOST, PORT);
  6883. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6884. ASSERT_TRUE(res);
  6885. EXPECT_EQ(StatusCode::OK_200, res->status);
  6886. }
  6887. {
  6888. Client cli(HOST, PORT);
  6889. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6890. ASSERT_TRUE(res);
  6891. EXPECT_EQ(StatusCode::OK_200, res->status);
  6892. }
  6893. {
  6894. Client cli(HOST, PORT);
  6895. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6896. ASSERT_TRUE(res);
  6897. EXPECT_EQ(StatusCode::OK_200, res->status);
  6898. }
  6899. }
  6900. TEST(GetWithParametersTest, GetWithParameters2) {
  6901. Server svr;
  6902. svr.Get("/", [&](const Request &req, Response &res) {
  6903. auto text = req.get_param_value("hello");
  6904. res.set_content(text, "text/plain");
  6905. });
  6906. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6907. auto se = detail::scope_exit([&] {
  6908. svr.stop();
  6909. listen_thread.join();
  6910. ASSERT_FALSE(svr.is_running());
  6911. });
  6912. svr.wait_until_ready();
  6913. Client cli("localhost", PORT);
  6914. Params params;
  6915. params.emplace("hello", "world");
  6916. std::string body;
  6917. auto res = cli.Get("/", params, Headers{},
  6918. [&](const char *data, size_t data_length) {
  6919. body.append(data, data_length);
  6920. return true;
  6921. });
  6922. ASSERT_TRUE(res);
  6923. EXPECT_EQ(StatusCode::OK_200, res->status);
  6924. EXPECT_EQ("world", body);
  6925. }
  6926. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6927. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6928. auto host = "httpcan.org";
  6929. auto path = std::string{"/range/32"};
  6930. #else
  6931. auto host = "nghttp2.org";
  6932. auto path = std::string{"/httpbin/range/32"};
  6933. #endif
  6934. #ifdef CPPHTTPLIB_SSL_ENABLED
  6935. SSLClient cli(host);
  6936. #else
  6937. Client cli(host);
  6938. #endif
  6939. cli.set_default_headers({make_range_header({{1, 10}})});
  6940. cli.set_connection_timeout(5);
  6941. {
  6942. auto res = cli.Get(path);
  6943. ASSERT_TRUE(res);
  6944. EXPECT_EQ("bcdefghijk", res->body);
  6945. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6946. }
  6947. {
  6948. auto res = cli.Get(path);
  6949. ASSERT_TRUE(res);
  6950. EXPECT_EQ("bcdefghijk", res->body);
  6951. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6952. }
  6953. }
  6954. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6955. Server svr;
  6956. svr.set_default_headers({{"Hello", "World"}});
  6957. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6958. res.set_content("ok", "text/plain");
  6959. });
  6960. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6961. auto se = detail::scope_exit([&] {
  6962. svr.stop();
  6963. listen_thread.join();
  6964. ASSERT_FALSE(svr.is_running());
  6965. });
  6966. svr.wait_until_ready();
  6967. Client cli("localhost", PORT);
  6968. auto res = cli.Get("/");
  6969. ASSERT_TRUE(res);
  6970. EXPECT_EQ(StatusCode::OK_200, res->status);
  6971. EXPECT_EQ("ok", res->body);
  6972. EXPECT_EQ("World", res->get_header_value("Hello"));
  6973. }
  6974. #ifdef CPPHTTPLIB_SSL_ENABLED
  6975. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6976. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6977. ASSERT_TRUE(svr.is_valid());
  6978. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6979. std::this_thread::sleep_for(std::chrono::seconds(2));
  6980. res.set_content("a", "text/plain");
  6981. });
  6982. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6983. res.set_content("b", "text/plain");
  6984. });
  6985. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6986. auto se = detail::scope_exit([&] {
  6987. svr.stop();
  6988. listen_thread.join();
  6989. ASSERT_FALSE(svr.is_running());
  6990. });
  6991. svr.wait_until_ready();
  6992. SSLClient cli("localhost", PORT);
  6993. cli.enable_server_certificate_verification(false);
  6994. cli.set_keep_alive(true);
  6995. cli.set_read_timeout(std::chrono::seconds(1));
  6996. auto resa = cli.Get("/a");
  6997. ASSERT_TRUE(!resa);
  6998. EXPECT_EQ(Error::Read, resa.error());
  6999. auto resb = cli.Get("/b");
  7000. ASSERT_TRUE(resb);
  7001. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7002. EXPECT_EQ("b", resb->body);
  7003. }
  7004. #endif
  7005. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7006. protected:
  7007. ServerTestWithAI_PASSIVE()
  7008. : cli_(HOST, PORT)
  7009. #ifdef CPPHTTPLIB_SSL_ENABLED
  7010. ,
  7011. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7012. #endif
  7013. {
  7014. #ifdef CPPHTTPLIB_SSL_ENABLED
  7015. cli_.enable_server_certificate_verification(false);
  7016. #endif
  7017. }
  7018. virtual void SetUp() {
  7019. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7020. res.set_content("Hello World!", "text/plain");
  7021. });
  7022. t_ = thread(
  7023. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7024. svr_.wait_until_ready();
  7025. }
  7026. virtual void TearDown() {
  7027. svr_.stop();
  7028. t_.join();
  7029. }
  7030. #ifdef CPPHTTPLIB_SSL_ENABLED
  7031. SSLClient cli_;
  7032. SSLServer svr_;
  7033. #else
  7034. Client cli_;
  7035. Server svr_;
  7036. #endif
  7037. thread t_;
  7038. };
  7039. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7040. auto res = cli_.Get("/hi");
  7041. ASSERT_TRUE(res);
  7042. EXPECT_EQ(StatusCode::OK_200, res->status);
  7043. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7044. EXPECT_EQ("Hello World!", res->body);
  7045. }
  7046. class ServerUpDownTest : public ::testing::Test {
  7047. protected:
  7048. ServerUpDownTest() : cli_(HOST, PORT) {}
  7049. virtual void SetUp() {
  7050. t_ = thread([&]() {
  7051. svr_.bind_to_any_port(HOST);
  7052. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7053. ASSERT_TRUE(svr_.listen_after_bind());
  7054. });
  7055. svr_.wait_until_ready();
  7056. }
  7057. virtual void TearDown() {
  7058. svr_.stop();
  7059. t_.join();
  7060. }
  7061. Client cli_;
  7062. Server svr_;
  7063. thread t_;
  7064. };
  7065. TEST_F(ServerUpDownTest, QuickStartStop) {
  7066. // Should not crash, especially when run with
  7067. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7068. }
  7069. class PayloadMaxLengthTest : public ::testing::Test {
  7070. protected:
  7071. PayloadMaxLengthTest()
  7072. : cli_(HOST, PORT)
  7073. #ifdef CPPHTTPLIB_SSL_ENABLED
  7074. ,
  7075. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7076. #endif
  7077. {
  7078. #ifdef CPPHTTPLIB_SSL_ENABLED
  7079. cli_.enable_server_certificate_verification(false);
  7080. #endif
  7081. }
  7082. virtual void SetUp() {
  7083. svr_.set_payload_max_length(8);
  7084. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7085. res.set_content("test", "text/plain");
  7086. });
  7087. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7088. svr_.wait_until_ready();
  7089. }
  7090. virtual void TearDown() {
  7091. svr_.stop();
  7092. t_.join();
  7093. }
  7094. #ifdef CPPHTTPLIB_SSL_ENABLED
  7095. SSLClient cli_;
  7096. SSLServer svr_;
  7097. #else
  7098. Client cli_;
  7099. Server svr_;
  7100. #endif
  7101. thread t_;
  7102. };
  7103. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7104. auto res = cli_.Post("/test", "123456789", "text/plain");
  7105. ASSERT_TRUE(res);
  7106. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7107. res = cli_.Post("/test", "12345678", "text/plain");
  7108. ASSERT_TRUE(res);
  7109. EXPECT_EQ(StatusCode::OK_200, res->status);
  7110. }
  7111. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7112. // Test chunked encoding with payload exceeding the 8-byte limit
  7113. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7114. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7115. ASSERT_TRUE(res);
  7116. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7117. }
  7118. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7119. // Test chunked encoding with payload within the 8-byte limit
  7120. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7121. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7122. ASSERT_TRUE(res);
  7123. EXPECT_EQ(StatusCode::OK_200, res->status);
  7124. }
  7125. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7126. // Test using send_request to send chunked data exceeding payload limit
  7127. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7128. "Host: " +
  7129. std::string(HOST) + ":" + std::to_string(PORT) +
  7130. "\r\n"
  7131. "Transfer-Encoding: chunked\r\n"
  7132. "Connection: close\r\n"
  7133. "\r\n"
  7134. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7135. "0123456789\r\n"
  7136. "0\r\n" // End chunk
  7137. "\r\n";
  7138. std::string response;
  7139. bool result = send_request(1, chunked_request, &response);
  7140. if (!result) {
  7141. // If send_request fails, it might be because the server closed the
  7142. // connection due to payload limit enforcement, which is acceptable
  7143. SUCCEED()
  7144. << "Server rejected oversized chunked request (connection closed)";
  7145. } else {
  7146. // If we got a response, check if it's an error response or connection was
  7147. // closed early Short response length indicates connection was closed due to
  7148. // payload limit
  7149. if (response.length() <= 10) {
  7150. SUCCEED() << "Server closed connection for oversized chunked request";
  7151. } else {
  7152. // Check for error status codes
  7153. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7154. response.find("Payload Too Large") != std::string::npos ||
  7155. response.find("400") != std::string::npos);
  7156. }
  7157. }
  7158. }
  7159. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7160. // Test request without Content-Length header exceeding payload limit
  7161. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7162. "Host: " +
  7163. std::string(HOST) + ":" +
  7164. std::to_string(PORT) +
  7165. "\r\n"
  7166. "Connection: close\r\n"
  7167. "\r\n";
  7168. // Add payload exceeding the 8-byte limit
  7169. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7170. request_without_content_length += large_payload;
  7171. std::string response;
  7172. bool result = send_request(1, request_without_content_length, &response);
  7173. if (!result) {
  7174. // If send_request fails, server likely closed connection due to payload
  7175. // limit
  7176. SUCCEED() << "Server rejected oversized request without Content-Length "
  7177. "(connection closed)";
  7178. } else {
  7179. // Check if server responded with error or closed connection early
  7180. if (response.length() <= 10) {
  7181. SUCCEED() << "Server closed connection for oversized request without "
  7182. "Content-Length";
  7183. } else {
  7184. // Check for error status codes
  7185. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7186. response.find("Payload Too Large") != std::string::npos ||
  7187. response.find("400") != std::string::npos);
  7188. }
  7189. }
  7190. }
  7191. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7192. // Test request without Content-Length header within payload limit
  7193. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7194. "Host: " +
  7195. std::string(HOST) + ":" +
  7196. std::to_string(PORT) +
  7197. "\r\n"
  7198. "Connection: close\r\n"
  7199. "\r\n";
  7200. // Add payload within the 8-byte limit
  7201. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7202. request_without_content_length += small_payload;
  7203. std::string response;
  7204. bool result = send_request(1, request_without_content_length, &response);
  7205. // For requests without Content-Length, the server may have different behavior
  7206. // The key is that it should not reject due to payload limit for small
  7207. // payloads
  7208. if (result) {
  7209. // Check for any HTTP response (success or error, but not connection closed)
  7210. if (response.length() > 10) {
  7211. SUCCEED()
  7212. << "Server processed request without Content-Length within limit";
  7213. } else {
  7214. // Short response might indicate connection closed, which is acceptable
  7215. SUCCEED() << "Server closed connection for request without "
  7216. "Content-Length (acceptable behavior)";
  7217. }
  7218. } else {
  7219. // Connection failure might be due to protocol requirements
  7220. SUCCEED() << "Connection issue with request without Content-Length "
  7221. "(environment-specific)";
  7222. }
  7223. }
  7224. class LargePayloadMaxLengthTest : public ::testing::Test {
  7225. protected:
  7226. LargePayloadMaxLengthTest()
  7227. : cli_(HOST, PORT)
  7228. #ifdef CPPHTTPLIB_SSL_ENABLED
  7229. ,
  7230. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7231. #endif
  7232. {
  7233. #ifdef CPPHTTPLIB_SSL_ENABLED
  7234. cli_.enable_server_certificate_verification(false);
  7235. #endif
  7236. }
  7237. virtual void SetUp() {
  7238. // Set 10MB payload limit
  7239. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7240. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7241. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7242. res.set_content("Large payload test", "text/plain");
  7243. });
  7244. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7245. svr_.wait_until_ready();
  7246. }
  7247. virtual void TearDown() {
  7248. svr_.stop();
  7249. t_.join();
  7250. }
  7251. #ifdef CPPHTTPLIB_SSL_ENABLED
  7252. SSLClient cli_;
  7253. SSLServer svr_;
  7254. #else
  7255. Client cli_;
  7256. Server svr_;
  7257. #endif
  7258. thread t_;
  7259. };
  7260. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7261. // Test chunked encoding with payload within 10MB limit
  7262. std::string medium_payload(5 * 1024 * 1024,
  7263. 'A'); // 5MB payload, within 10MB limit
  7264. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7265. ASSERT_TRUE(res);
  7266. EXPECT_EQ(StatusCode::OK_200, res->status);
  7267. }
  7268. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7269. // Test chunked encoding with payload exceeding 10MB limit
  7270. std::string large_payload(12 * 1024 * 1024,
  7271. 'B'); // 12MB payload, exceeds 10MB limit
  7272. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7273. // Server may either return 413 or close the connection
  7274. if (res) {
  7275. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7276. } else {
  7277. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7278. }
  7279. }
  7280. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7281. // Test request without Content-Length header within 10MB limit
  7282. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7283. "Host: " +
  7284. std::string(HOST) + ":" +
  7285. std::to_string(PORT) +
  7286. "\r\n"
  7287. "Connection: close\r\n"
  7288. "\r\n";
  7289. // Add 1MB payload (within 10MB limit)
  7290. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7291. request_without_content_length += medium_payload;
  7292. std::string response;
  7293. bool result = send_request(5, request_without_content_length, &response);
  7294. if (result) {
  7295. // Should get a proper HTTP response for payloads within limit
  7296. if (response.length() > 10) {
  7297. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7298. "10MB limit";
  7299. } else {
  7300. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7301. "Content-Length)";
  7302. }
  7303. } else {
  7304. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7305. }
  7306. }
  7307. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7308. // Test request without Content-Length header exceeding 10MB limit
  7309. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7310. "Host: " +
  7311. std::string(HOST) + ":" +
  7312. std::to_string(PORT) +
  7313. "\r\n"
  7314. "Connection: close\r\n"
  7315. "\r\n";
  7316. // Add 12MB payload (exceeds 10MB limit)
  7317. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7318. request_without_content_length += large_payload;
  7319. std::string response;
  7320. bool result = send_request(10, request_without_content_length, &response);
  7321. if (!result) {
  7322. // Server should close connection due to payload limit
  7323. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7324. "(connection closed)";
  7325. } else {
  7326. // Check for error response
  7327. if (response.length() <= 10) {
  7328. SUCCEED()
  7329. << "Server closed connection for 12MB request exceeding 10MB limit";
  7330. } else {
  7331. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7332. response.find("Payload Too Large") != std::string::npos ||
  7333. response.find("400") != std::string::npos);
  7334. }
  7335. }
  7336. }
  7337. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7338. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7339. // path.
  7340. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7341. Server svr;
  7342. const size_t LIMIT = 64 * 1024; // 64KB
  7343. svr.set_payload_max_length(LIMIT);
  7344. size_t total = 0;
  7345. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7346. const ContentReader &content_reader) {
  7347. content_reader([&](const char * /*data*/, size_t len) {
  7348. total += len;
  7349. return true;
  7350. });
  7351. res.status = 200;
  7352. res.set_content("stream_ok", "text/plain");
  7353. });
  7354. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7355. auto se = detail::scope_exit([&] {
  7356. svr.stop();
  7357. thread.join();
  7358. ASSERT_FALSE(svr.is_running());
  7359. });
  7360. svr.wait_until_ready();
  7361. // Prepare 256KB raw data and gzip-compress it
  7362. std::string raw(256 * 1024, 'A');
  7363. std::string gz;
  7364. {
  7365. z_stream zs{};
  7366. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7367. Z_DEFAULT_STRATEGY);
  7368. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7369. zs.avail_in = static_cast<uInt>(raw.size());
  7370. char outbuf[4096];
  7371. int ret;
  7372. do {
  7373. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7374. zs.avail_out = sizeof(outbuf);
  7375. ret = deflate(&zs, Z_FINISH);
  7376. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7377. } while (ret != Z_STREAM_END);
  7378. deflateEnd(&zs);
  7379. }
  7380. Client cli(HOST, PORT);
  7381. cli.set_connection_timeout(std::chrono::seconds(5));
  7382. Headers headers = {{"Content-Encoding", "gzip"}};
  7383. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7384. "application/octet-stream");
  7385. ASSERT_TRUE(res);
  7386. // Server must reject oversized decompressed payloads with 413.
  7387. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7388. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7389. EXPECT_LE(total, LIMIT);
  7390. }
  7391. #endif
  7392. // Regression test for DoS vulnerability: a malicious server sending a response
  7393. // without Content-Length header must not cause unbounded memory consumption on
  7394. // the client side. The client should stop reading after a reasonable limit,
  7395. // similar to the server-side set_payload_max_length protection.
  7396. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7397. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7398. #ifndef _WIN32
  7399. signal(SIGPIPE, SIG_IGN);
  7400. #endif
  7401. auto server_thread = std::thread([] {
  7402. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7403. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7404. default_socket_options(srv);
  7405. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7406. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7407. sockaddr_in addr{};
  7408. addr.sin_family = AF_INET;
  7409. addr.sin_port = htons(PORT + 2);
  7410. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7411. int opt = 1;
  7412. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7413. #ifdef _WIN32
  7414. reinterpret_cast<const char *>(&opt),
  7415. #else
  7416. &opt,
  7417. #endif
  7418. sizeof(opt));
  7419. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7420. ::listen(srv, 1);
  7421. sockaddr_in cli_addr{};
  7422. socklen_t cli_len = sizeof(cli_addr);
  7423. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7424. if (cli != INVALID_SOCKET) {
  7425. char buf[4096];
  7426. ::recv(cli, buf, sizeof(buf), 0);
  7427. // Malicious response: no Content-Length, no chunked encoding
  7428. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7429. "Connection: close\r\n"
  7430. "\r\n";
  7431. ::send(cli,
  7432. #ifdef _WIN32
  7433. static_cast<const char *>(response_header.c_str()),
  7434. static_cast<int>(response_header.size()),
  7435. #else
  7436. response_header.c_str(), response_header.size(),
  7437. #endif
  7438. 0);
  7439. // Send 10MB of data
  7440. std::string chunk(64 * 1024, 'A');
  7441. size_t total_sent = 0;
  7442. while (total_sent < MALICIOUS_DATA_SIZE) {
  7443. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7444. auto sent = ::send(cli,
  7445. #ifdef _WIN32
  7446. static_cast<const char *>(chunk.c_str()),
  7447. static_cast<int>(to_send),
  7448. #else
  7449. chunk.c_str(), to_send,
  7450. #endif
  7451. 0);
  7452. if (sent <= 0) break;
  7453. total_sent += static_cast<size_t>(sent);
  7454. }
  7455. detail::close_socket(cli);
  7456. }
  7457. detail::close_socket(srv);
  7458. });
  7459. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7460. size_t total_read = 0;
  7461. {
  7462. Client cli("127.0.0.1", PORT + 2);
  7463. cli.set_read_timeout(5, 0);
  7464. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7465. auto stream = cli.open_stream("GET", "/malicious");
  7466. ASSERT_TRUE(stream.is_valid());
  7467. char buffer[64 * 1024];
  7468. ssize_t n;
  7469. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7470. total_read += static_cast<size_t>(n);
  7471. }
  7472. } // StreamHandle and Client destroyed here, closing the socket
  7473. server_thread.join();
  7474. // With set_payload_max_length, the client must stop reading before consuming
  7475. // all 10MB. The read loop should be cut off at or near the configured limit.
  7476. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7477. << "Client read " << total_read << " bytes, exceeding the configured "
  7478. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7479. }
  7480. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7481. // the entire response body without truncation.
  7482. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7483. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7484. #ifndef _WIN32
  7485. signal(SIGPIPE, SIG_IGN);
  7486. #endif
  7487. auto server_thread = std::thread([] {
  7488. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7489. default_socket_options(srv);
  7490. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7491. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7492. sockaddr_in addr{};
  7493. addr.sin_family = AF_INET;
  7494. addr.sin_port = htons(PORT + 2);
  7495. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7496. int opt = 1;
  7497. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7498. #ifdef _WIN32
  7499. reinterpret_cast<const char *>(&opt),
  7500. #else
  7501. &opt,
  7502. #endif
  7503. sizeof(opt));
  7504. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7505. ::listen(srv, 1);
  7506. sockaddr_in cli_addr{};
  7507. socklen_t cli_len = sizeof(cli_addr);
  7508. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7509. if (cli != INVALID_SOCKET) {
  7510. char buf[4096];
  7511. ::recv(cli, buf, sizeof(buf), 0);
  7512. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7513. "Connection: close\r\n"
  7514. "\r\n";
  7515. ::send(cli,
  7516. #ifdef _WIN32
  7517. static_cast<const char *>(response_header.c_str()),
  7518. static_cast<int>(response_header.size()),
  7519. #else
  7520. response_header.c_str(), response_header.size(),
  7521. #endif
  7522. 0);
  7523. std::string chunk(64 * 1024, 'A');
  7524. size_t total_sent = 0;
  7525. while (total_sent < DATA_SIZE) {
  7526. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7527. auto sent = ::send(cli,
  7528. #ifdef _WIN32
  7529. static_cast<const char *>(chunk.c_str()),
  7530. static_cast<int>(to_send),
  7531. #else
  7532. chunk.c_str(), to_send,
  7533. #endif
  7534. 0);
  7535. if (sent <= 0) break;
  7536. total_sent += static_cast<size_t>(sent);
  7537. }
  7538. #ifdef _WIN32
  7539. ::shutdown(cli, SD_SEND);
  7540. #else
  7541. ::shutdown(cli, SHUT_WR);
  7542. #endif
  7543. // Drain until the client closes its end, ensuring all data is delivered
  7544. char drain[1024];
  7545. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7546. detail::close_socket(cli);
  7547. }
  7548. detail::close_socket(srv);
  7549. });
  7550. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7551. size_t total_read = 0;
  7552. {
  7553. Client cli("127.0.0.1", PORT + 2);
  7554. cli.set_read_timeout(5, 0);
  7555. cli.set_payload_max_length(0); // 0 means no limit
  7556. auto stream = cli.open_stream("GET", "/data");
  7557. ASSERT_TRUE(stream.is_valid());
  7558. char buffer[64 * 1024];
  7559. ssize_t n;
  7560. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7561. total_read += static_cast<size_t>(n);
  7562. }
  7563. }
  7564. server_thread.join();
  7565. EXPECT_EQ(total_read, DATA_SIZE)
  7566. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7567. << " bytes without truncation, but only read " << total_read << " bytes.";
  7568. }
  7569. // Verify that content_receiver bypasses the default payload_max_length,
  7570. // allowing streaming downloads larger than 100MB without requiring an explicit
  7571. // set_payload_max_length call.
  7572. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  7573. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7574. #ifndef _WIN32
  7575. signal(SIGPIPE, SIG_IGN);
  7576. #endif
  7577. auto server_thread = std::thread([] {
  7578. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7579. default_socket_options(srv);
  7580. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7581. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7582. sockaddr_in addr{};
  7583. addr.sin_family = AF_INET;
  7584. addr.sin_port = htons(PORT + 2);
  7585. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7586. int opt = 1;
  7587. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7588. #ifdef _WIN32
  7589. reinterpret_cast<const char *>(&opt),
  7590. #else
  7591. &opt,
  7592. #endif
  7593. sizeof(opt));
  7594. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7595. ::listen(srv, 1);
  7596. sockaddr_in cli_addr{};
  7597. socklen_t cli_len = sizeof(cli_addr);
  7598. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7599. if (cli != INVALID_SOCKET) {
  7600. char buf[4096];
  7601. ::recv(cli, buf, sizeof(buf), 0);
  7602. // Response with Content-Length larger than default 100MB limit
  7603. auto content_length = std::to_string(DATA_SIZE);
  7604. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7605. "Content-Length: " +
  7606. content_length +
  7607. "\r\n"
  7608. "Connection: close\r\n"
  7609. "\r\n";
  7610. ::send(cli,
  7611. #ifdef _WIN32
  7612. static_cast<const char *>(response_header.c_str()),
  7613. static_cast<int>(response_header.size()),
  7614. #else
  7615. response_header.c_str(), response_header.size(),
  7616. #endif
  7617. 0);
  7618. std::string chunk(64 * 1024, 'A');
  7619. size_t total_sent = 0;
  7620. while (total_sent < DATA_SIZE) {
  7621. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7622. auto sent = ::send(cli,
  7623. #ifdef _WIN32
  7624. static_cast<const char *>(chunk.c_str()),
  7625. static_cast<int>(to_send),
  7626. #else
  7627. chunk.c_str(), to_send,
  7628. #endif
  7629. 0);
  7630. if (sent <= 0) break;
  7631. total_sent += static_cast<size_t>(sent);
  7632. }
  7633. detail::close_socket(cli);
  7634. }
  7635. detail::close_socket(srv);
  7636. });
  7637. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7638. size_t total_received = 0;
  7639. {
  7640. Client cli("127.0.0.1", PORT + 2);
  7641. cli.set_read_timeout(10, 0);
  7642. // Do NOT call set_payload_max_length — use the default 100MB limit
  7643. auto res =
  7644. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7645. total_received += data_length;
  7646. return true;
  7647. });
  7648. ASSERT_TRUE(res);
  7649. EXPECT_EQ(StatusCode::OK_200, res->status);
  7650. }
  7651. server_thread.join();
  7652. EXPECT_EQ(total_received, DATA_SIZE)
  7653. << "With content_receiver, the client should read all " << DATA_SIZE
  7654. << " bytes despite the default 100MB payload_max_length, but only read "
  7655. << total_received << " bytes.";
  7656. }
  7657. // Verify that an explicit set_payload_max_length smaller than the response is
  7658. // enforced even when a content_receiver is used.
  7659. TEST(ClientVulnerabilityTest,
  7660. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  7661. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7662. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  7663. #ifndef _WIN32
  7664. signal(SIGPIPE, SIG_IGN);
  7665. #endif
  7666. auto server_thread = std::thread([] {
  7667. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7668. default_socket_options(srv);
  7669. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7670. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7671. sockaddr_in addr{};
  7672. addr.sin_family = AF_INET;
  7673. addr.sin_port = htons(PORT + 2);
  7674. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7675. int opt = 1;
  7676. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7677. #ifdef _WIN32
  7678. reinterpret_cast<const char *>(&opt),
  7679. #else
  7680. &opt,
  7681. #endif
  7682. sizeof(opt));
  7683. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7684. ::listen(srv, 1);
  7685. sockaddr_in cli_addr{};
  7686. socklen_t cli_len = sizeof(cli_addr);
  7687. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7688. if (cli != INVALID_SOCKET) {
  7689. char buf[4096];
  7690. ::recv(cli, buf, sizeof(buf), 0);
  7691. auto content_length = std::to_string(DATA_SIZE);
  7692. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7693. "Content-Length: " +
  7694. content_length +
  7695. "\r\n"
  7696. "Connection: close\r\n"
  7697. "\r\n";
  7698. ::send(cli,
  7699. #ifdef _WIN32
  7700. static_cast<const char *>(response_header.c_str()),
  7701. static_cast<int>(response_header.size()),
  7702. #else
  7703. response_header.c_str(), response_header.size(),
  7704. #endif
  7705. 0);
  7706. std::string chunk(64 * 1024, 'A');
  7707. size_t total_sent = 0;
  7708. while (total_sent < DATA_SIZE) {
  7709. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7710. auto sent = ::send(cli,
  7711. #ifdef _WIN32
  7712. static_cast<const char *>(chunk.c_str()),
  7713. static_cast<int>(to_send),
  7714. #else
  7715. chunk.c_str(), to_send,
  7716. #endif
  7717. 0);
  7718. if (sent <= 0) break;
  7719. total_sent += static_cast<size_t>(sent);
  7720. }
  7721. detail::close_socket(cli);
  7722. }
  7723. detail::close_socket(srv);
  7724. });
  7725. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7726. size_t total_received = 0;
  7727. {
  7728. Client cli("127.0.0.1", PORT + 2);
  7729. cli.set_read_timeout(10, 0);
  7730. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  7731. auto res =
  7732. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7733. total_received += data_length;
  7734. return true;
  7735. });
  7736. // Should fail because 200MB exceeds the explicit 150MB limit
  7737. EXPECT_FALSE(res);
  7738. }
  7739. server_thread.join();
  7740. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  7741. << "Client with content_receiver should respect the explicit "
  7742. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  7743. << total_received << " bytes.";
  7744. }
  7745. // Verify that an explicit set_payload_max_length larger than the response
  7746. // allows the content_receiver to read all data successfully.
  7747. TEST(ClientVulnerabilityTest,
  7748. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  7749. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7750. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  7751. #ifndef _WIN32
  7752. signal(SIGPIPE, SIG_IGN);
  7753. #endif
  7754. auto server_thread = std::thread([] {
  7755. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7756. default_socket_options(srv);
  7757. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7758. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7759. sockaddr_in addr{};
  7760. addr.sin_family = AF_INET;
  7761. addr.sin_port = htons(PORT + 2);
  7762. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7763. int opt = 1;
  7764. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7765. #ifdef _WIN32
  7766. reinterpret_cast<const char *>(&opt),
  7767. #else
  7768. &opt,
  7769. #endif
  7770. sizeof(opt));
  7771. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7772. ::listen(srv, 1);
  7773. sockaddr_in cli_addr{};
  7774. socklen_t cli_len = sizeof(cli_addr);
  7775. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7776. if (cli != INVALID_SOCKET) {
  7777. char buf[4096];
  7778. ::recv(cli, buf, sizeof(buf), 0);
  7779. auto content_length = std::to_string(DATA_SIZE);
  7780. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7781. "Content-Length: " +
  7782. content_length +
  7783. "\r\n"
  7784. "Connection: close\r\n"
  7785. "\r\n";
  7786. ::send(cli,
  7787. #ifdef _WIN32
  7788. static_cast<const char *>(response_header.c_str()),
  7789. static_cast<int>(response_header.size()),
  7790. #else
  7791. response_header.c_str(), response_header.size(),
  7792. #endif
  7793. 0);
  7794. std::string chunk(64 * 1024, 'A');
  7795. size_t total_sent = 0;
  7796. while (total_sent < DATA_SIZE) {
  7797. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7798. auto sent = ::send(cli,
  7799. #ifdef _WIN32
  7800. static_cast<const char *>(chunk.c_str()),
  7801. static_cast<int>(to_send),
  7802. #else
  7803. chunk.c_str(), to_send,
  7804. #endif
  7805. 0);
  7806. if (sent <= 0) break;
  7807. total_sent += static_cast<size_t>(sent);
  7808. }
  7809. #ifdef _WIN32
  7810. ::shutdown(cli, SD_SEND);
  7811. #else
  7812. ::shutdown(cli, SHUT_WR);
  7813. #endif
  7814. char drain[1024];
  7815. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7816. detail::close_socket(cli);
  7817. }
  7818. detail::close_socket(srv);
  7819. });
  7820. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7821. size_t total_received = 0;
  7822. {
  7823. Client cli("127.0.0.1", PORT + 2);
  7824. cli.set_read_timeout(10, 0);
  7825. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  7826. auto res =
  7827. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7828. total_received += data_length;
  7829. return true;
  7830. });
  7831. ASSERT_TRUE(res);
  7832. EXPECT_EQ(StatusCode::OK_200, res->status);
  7833. }
  7834. server_thread.join();
  7835. EXPECT_EQ(total_received, DATA_SIZE)
  7836. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  7837. << " bytes (larger than " << DATA_SIZE
  7838. << " bytes response), content_receiver should read all data, but only "
  7839. "read "
  7840. << total_received << " bytes.";
  7841. }
  7842. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  7843. // Regression test for "zip bomb" attack on the client side: a malicious server
  7844. // sends a small gzip-compressed response that decompresses to a huge payload.
  7845. // The client must enforce payload_max_length on the decompressed size.
  7846. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  7847. constexpr size_t DECOMPRESSED_SIZE =
  7848. 10 * 1024 * 1024; // 10MB after decompression
  7849. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7850. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  7851. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  7852. std::string compressed;
  7853. {
  7854. httplib::detail::gzip_compressor compressor;
  7855. bool ok =
  7856. compressor.compress(uncompressed.data(), uncompressed.size(),
  7857. /*last=*/true, [&](const char *buf, size_t len) {
  7858. compressed.append(buf, len);
  7859. return true;
  7860. });
  7861. ASSERT_TRUE(ok);
  7862. }
  7863. // Sanity: compressed data should be much smaller than the decompressed size
  7864. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  7865. #ifndef _WIN32
  7866. signal(SIGPIPE, SIG_IGN);
  7867. #endif
  7868. // Set up the listening socket in the main thread so the server is guaranteed
  7869. // to be ready before the client connects (eliminates race condition).
  7870. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7871. default_socket_options(srv);
  7872. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7873. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7874. sockaddr_in addr{};
  7875. addr.sin_family = AF_INET;
  7876. addr.sin_port = htons(PORT + 3);
  7877. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7878. int opt = 1;
  7879. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7880. #ifdef _WIN32
  7881. reinterpret_cast<const char *>(&opt),
  7882. #else
  7883. &opt,
  7884. #endif
  7885. sizeof(opt));
  7886. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  7887. ASSERT_EQ(0, ::listen(srv, 1));
  7888. auto server_thread = std::thread([&compressed, srv] {
  7889. sockaddr_in cli_addr{};
  7890. socklen_t cli_len = sizeof(cli_addr);
  7891. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7892. if (cli != INVALID_SOCKET) {
  7893. // Read the full HTTP request (until \r\n\r\n)
  7894. char buf[4096];
  7895. size_t total = 0;
  7896. while (total < sizeof(buf)) {
  7897. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  7898. if (n <= 0) break;
  7899. total += static_cast<size_t>(n);
  7900. // Check for end of headers
  7901. if (total >= 4) {
  7902. std::string req(buf, total);
  7903. if (req.find("\r\n\r\n") != std::string::npos) break;
  7904. }
  7905. }
  7906. // Malicious response: gzip-compressed body, no Content-Length
  7907. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7908. "Content-Encoding: gzip\r\n"
  7909. "Connection: close\r\n"
  7910. "\r\n";
  7911. ::send(cli,
  7912. #ifdef _WIN32
  7913. static_cast<const char *>(response_header.c_str()),
  7914. static_cast<int>(response_header.size()),
  7915. #else
  7916. response_header.c_str(), response_header.size(),
  7917. #endif
  7918. 0);
  7919. // Send the compressed payload (small on the wire, huge when decompressed)
  7920. size_t total_sent = 0;
  7921. while (total_sent < compressed.size()) {
  7922. auto to_send = std::min(compressed.size() - total_sent,
  7923. static_cast<size_t>(64 * 1024));
  7924. auto sent =
  7925. ::send(cli,
  7926. #ifdef _WIN32
  7927. static_cast<const char *>(compressed.c_str() + total_sent),
  7928. static_cast<int>(to_send),
  7929. #else
  7930. compressed.c_str() + total_sent, to_send,
  7931. #endif
  7932. 0);
  7933. if (sent <= 0) break;
  7934. total_sent += static_cast<size_t>(sent);
  7935. }
  7936. detail::close_socket(cli);
  7937. }
  7938. });
  7939. auto se = detail::scope_exit([&] {
  7940. detail::close_socket(srv);
  7941. server_thread.join();
  7942. });
  7943. size_t total_decompressed = 0;
  7944. {
  7945. Client cli("127.0.0.1", PORT + 3);
  7946. cli.set_read_timeout(5, 0);
  7947. cli.set_decompress(true);
  7948. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7949. auto stream = cli.open_stream("GET", "/zipbomb");
  7950. ASSERT_TRUE(stream.is_valid());
  7951. char buffer[64 * 1024];
  7952. ssize_t n;
  7953. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7954. total_decompressed += static_cast<size_t>(n);
  7955. }
  7956. }
  7957. // The decompressed size must be capped by payload_max_length. Without
  7958. // protection, the client would decompress the full 10MB from a tiny
  7959. // compressed payload, enabling a zip bomb DoS attack.
  7960. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  7961. << "Client decompressed " << total_decompressed
  7962. << " bytes from a gzip response. The decompressed size should be "
  7963. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  7964. }
  7965. #endif
  7966. TEST(HostAndPortPropertiesTest, NoSSL) {
  7967. httplib::Client cli("www.google.com", 1234);
  7968. ASSERT_EQ("www.google.com", cli.host());
  7969. ASSERT_EQ(1234, cli.port());
  7970. }
  7971. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7972. httplib::Client cli("www.google.com:1234");
  7973. ASSERT_EQ("www.google.com", cli.host());
  7974. ASSERT_EQ(1234, cli.port());
  7975. }
  7976. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  7977. // Port number that overflows int — should not crash, client becomes invalid
  7978. httplib::Client cli("http://www.google.com:99999999999999999999");
  7979. ASSERT_FALSE(cli.is_valid());
  7980. }
  7981. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  7982. // Port 99999 exceeds valid range (1-65535) — should not crash
  7983. httplib::Client cli("http://www.google.com:99999");
  7984. ASSERT_FALSE(cli.is_valid());
  7985. }
  7986. #ifdef CPPHTTPLIB_SSL_ENABLED
  7987. TEST(HostAndPortPropertiesTest, SSL) {
  7988. httplib::SSLClient cli("www.google.com");
  7989. ASSERT_EQ("www.google.com", cli.host());
  7990. ASSERT_EQ(443, cli.port());
  7991. }
  7992. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  7993. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  7994. std::string cert;
  7995. read_file(CA_CERT_FILE, cert);
  7996. httplib::SSLClient httplib_client("www.google.com");
  7997. // Load CA store first time
  7998. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  7999. // Load CA store second time (update)
  8000. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8001. // Verify client is still valid and can make connections
  8002. httplib_client.enable_server_certificate_verification(true);
  8003. auto res = httplib_client.Get("/");
  8004. ASSERT_TRUE(res);
  8005. // Google may return 200 or 301 depending on various factors
  8006. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8007. res->status == StatusCode::MovedPermanently_301);
  8008. }
  8009. TEST(SSLClientTest, ServerNameIndication_Online) {
  8010. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  8011. auto host = "httpcan.org";
  8012. auto path = std::string{"/get"};
  8013. #else
  8014. auto host = "nghttp2.org";
  8015. auto path = std::string{"/httpbin/get"};
  8016. #endif
  8017. SSLClient cli(host, 443);
  8018. auto res = cli.Get(path);
  8019. ASSERT_TRUE(res);
  8020. ASSERT_EQ(StatusCode::OK_200, res->status);
  8021. }
  8022. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8023. // Use a site that will cause SSL verification failure due to self-signed cert
  8024. SSLClient cli("self-signed.badssl.com", 443);
  8025. cli.enable_server_certificate_verification(true);
  8026. auto res = cli.Get("/");
  8027. ASSERT_TRUE(!res);
  8028. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8029. // Verify backend error is captured for SSLServerVerification
  8030. // This occurs when certificate verification fails
  8031. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8032. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8033. EXPECT_NE(0UL, res.ssl_backend_error());
  8034. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8035. // For OpenSSL, ssl_error is 0 for verification errors
  8036. EXPECT_EQ(0, res.ssl_error());
  8037. #if !defined(_WIN32) || \
  8038. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8039. // On non-Windows or when Windows Schannel is disabled, the error comes
  8040. // from OpenSSL's verification
  8041. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8042. res.ssl_backend_error());
  8043. #endif
  8044. #endif
  8045. }
  8046. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8047. // Use a site where hostname doesn't match the certificate
  8048. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8049. SSLClient cli("wrong.host.badssl.com", 443);
  8050. cli.enable_server_certificate_verification(true);
  8051. cli.enable_server_hostname_verification(true);
  8052. auto res = cli.Get("/");
  8053. ASSERT_TRUE(!res);
  8054. // The error type depends on when hostname verification occurs:
  8055. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8056. // - Mbed TLS: SSLServerVerification (during handshake)
  8057. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8058. res.error() == Error::SSLServerVerification);
  8059. // Verify backend error is captured for hostname verification failure
  8060. EXPECT_NE(0UL, res.ssl_backend_error());
  8061. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8062. // For OpenSSL, ssl_error is 0 for verification errors
  8063. EXPECT_EQ(0, res.ssl_error());
  8064. #if !defined(_WIN32) || \
  8065. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8066. // On non-Windows or when Windows Schannel is disabled, the error comes
  8067. // from OpenSSL's hostname verification
  8068. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8069. res.ssl_backend_error());
  8070. #endif
  8071. #endif
  8072. }
  8073. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8074. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8075. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8076. SSLClient cli("www.google.com", 443);
  8077. cli.enable_server_certificate_verification(true);
  8078. auto res = cli.Get("/");
  8079. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8080. }
  8081. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8082. SSLClient cli("www.google.com", 443);
  8083. cli.enable_server_certificate_verification(true);
  8084. cli.enable_windows_certificate_verification(false);
  8085. auto res = cli.Get("/");
  8086. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8087. }
  8088. #endif
  8089. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8090. Client cli("https://google.com");
  8091. auto res = cli.Get("/");
  8092. ASSERT_TRUE(res);
  8093. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8094. }
  8095. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8096. SSLClient cli("google.com");
  8097. cli.set_ca_cert_path(CA_CERT_FILE);
  8098. auto res = cli.Get("/");
  8099. ASSERT_TRUE(res);
  8100. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8101. }
  8102. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8103. SSLClient cli("google.com");
  8104. cli.enable_server_certificate_verification(true);
  8105. cli.set_ca_cert_path("hello");
  8106. auto res = cli.Get("/");
  8107. ASSERT_TRUE(!res);
  8108. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8109. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8110. // should be set
  8111. EXPECT_EQ(0, res.ssl_error());
  8112. // Verify backend error is captured for SSLLoadingCerts
  8113. // This error occurs when loading CA certificates fails
  8114. EXPECT_NE(0UL, res.ssl_backend_error());
  8115. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8116. // OpenSSL specific error codes:
  8117. // > openssl errstr 0x80000002
  8118. // error:80000002:system library::No such file or directory
  8119. // > openssl errstr 0xA000126
  8120. // error:0A000126:SSL routines::unexpected eof while reading
  8121. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8122. res.ssl_backend_error() == 0xA000126);
  8123. #endif
  8124. }
  8125. TEST(SSLClientTest, ServerCertificateVerification4) {
  8126. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8127. ASSERT_TRUE(svr.is_valid());
  8128. svr.Get("/test", [&](const Request &, Response &res) {
  8129. res.set_content("test", "text/plain");
  8130. svr.stop();
  8131. ASSERT_TRUE(true);
  8132. });
  8133. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8134. auto se = detail::scope_exit([&] {
  8135. t.join();
  8136. ASSERT_FALSE(svr.is_running());
  8137. });
  8138. svr.wait_until_ready();
  8139. SSLClient cli("127.0.0.1", PORT);
  8140. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8141. cli.enable_server_certificate_verification(true);
  8142. cli.set_connection_timeout(30);
  8143. auto res = cli.Get("/test");
  8144. ASSERT_TRUE(res);
  8145. ASSERT_EQ(StatusCode::OK_200, res->status);
  8146. }
  8147. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8148. std::string cert;
  8149. read_file(CA_CERT_FILE, cert);
  8150. SSLClient cli("google.com");
  8151. cli.load_ca_cert_store(cert.data(), cert.size());
  8152. const auto res = cli.Get("/");
  8153. ASSERT_TRUE(res);
  8154. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8155. }
  8156. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8157. // clang-format off
  8158. static constexpr char cert[] =
  8159. "GlobalSign Root CA\n"
  8160. "==================\n"
  8161. "-----BEGIN CERTIFICATE-----\n"
  8162. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8163. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8164. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8165. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8166. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8167. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8168. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8169. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8170. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8171. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8172. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8173. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8174. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8175. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8176. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8177. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8178. "-----END CERTIFICATE-----\n";
  8179. // clang-format on
  8180. SSLClient cli("google.com");
  8181. cli.load_ca_cert_store(cert, sizeof(cert));
  8182. const auto res = cli.Get("/");
  8183. ASSERT_TRUE(res);
  8184. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8185. }
  8186. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8187. SSLClient cli("www.youtube.com");
  8188. cli.set_ca_cert_path(CA_CERT_FILE);
  8189. cli.enable_server_certificate_verification(true);
  8190. cli.set_follow_location(true);
  8191. auto res = cli.Get("/");
  8192. ASSERT_TRUE(res);
  8193. ASSERT_EQ(StatusCode::OK_200, res->status);
  8194. }
  8195. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8196. SSLClient cli("wWw.YouTube.Com");
  8197. cli.set_ca_cert_path(CA_CERT_FILE);
  8198. cli.enable_server_certificate_verification(true);
  8199. cli.enable_server_hostname_verification(true);
  8200. cli.set_follow_location(true);
  8201. auto res = cli.Get("/");
  8202. ASSERT_TRUE(res);
  8203. ASSERT_EQ(StatusCode::OK_200, res->status);
  8204. }
  8205. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8206. SSLClient cli("gOoGlE.COm");
  8207. cli.enable_server_certificate_verification(true);
  8208. cli.enable_server_hostname_verification(true);
  8209. cli.set_follow_location(true);
  8210. auto res = cli.Get("/");
  8211. ASSERT_TRUE(res);
  8212. ASSERT_EQ(StatusCode::OK_200, res->status);
  8213. }
  8214. TEST(SSLClientTest, Issue2004_Online) {
  8215. Client client("https://google.com");
  8216. client.set_follow_location(true);
  8217. auto res = client.Get("/");
  8218. ASSERT_TRUE(res);
  8219. ASSERT_EQ(StatusCode::OK_200, res->status);
  8220. auto body = res->body;
  8221. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8222. }
  8223. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8224. // Create SSLClient with invalid cert/key to make is_valid() return false
  8225. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8226. "nonexistent_key.pem");
  8227. // is_valid() should be false due to cert loading failure
  8228. ASSERT_FALSE(cli.is_valid());
  8229. auto res = cli.Get("/");
  8230. ASSERT_FALSE(res);
  8231. EXPECT_EQ(Error::SSLConnection, res.error());
  8232. }
  8233. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8234. // Test for Issue #2251: SSL error not properly reported when client cert
  8235. // and key paths are swapped or mismatched
  8236. // This simulates the scenario where user accidentally swaps the cert and key
  8237. // files
  8238. // Using client cert file as private key and vice versa (completely wrong)
  8239. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8240. // Should fail validation due to cert/key mismatch
  8241. ASSERT_FALSE(cli.is_valid());
  8242. // Attempt to make a request should fail with proper error
  8243. auto res = cli.Get("/");
  8244. ASSERT_FALSE(res);
  8245. EXPECT_EQ(Error::SSLConnection, res.error());
  8246. // SSL error should be recorded in the Result object (this is the key fix for
  8247. // Issue #2251)
  8248. auto backend_error = res.ssl_backend_error();
  8249. EXPECT_NE(0u, backend_error);
  8250. }
  8251. // Tests cert/key mismatch detection at the TLS context level
  8252. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8253. // Test that using mismatched cert/key causes connection failure.
  8254. // We verify this at the SSLClient level rather than through internal
  8255. // TLS API functions.
  8256. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8257. cli.enable_server_certificate_verification(false);
  8258. cli.set_connection_timeout(2);
  8259. // The mismatch should cause a connection or handshake error
  8260. auto res = cli.Get("/test");
  8261. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8262. // Either way, the request should fail
  8263. EXPECT_FALSE(res);
  8264. }
  8265. #endif
  8266. #if 0
  8267. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8268. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8269. ASSERT_TRUE(cli != nullptr);
  8270. cli->set_address_family(AF_INET6);
  8271. cli->set_interface("en0");
  8272. auto res = cli->Get("/get");
  8273. ASSERT_TRUE(res);
  8274. ASSERT_EQ(StatusCode::OK_200, res->status);
  8275. }
  8276. #endif
  8277. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8278. #ifdef CPPHTTPLIB_SSL_ENABLED
  8279. void ClientCertPresent(
  8280. const std::string &client_cert_file,
  8281. const std::string &client_private_key_file,
  8282. const std::string &client_encrypted_private_key_pass = std::string()) {
  8283. using namespace httplib::tls;
  8284. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8285. CLIENT_CA_CERT_DIR);
  8286. ASSERT_TRUE(svr.is_valid());
  8287. svr.Get("/test", [&](const Request &req, Response &res) {
  8288. res.set_content("test", "text/plain");
  8289. auto cert = req.peer_cert();
  8290. ASSERT_TRUE(static_cast<bool>(cert));
  8291. std::string common_name = cert.subject_cn();
  8292. EXPECT_EQ("Common Name", common_name);
  8293. });
  8294. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8295. auto se = detail::scope_exit([&] {
  8296. svr.stop();
  8297. t.join();
  8298. ASSERT_FALSE(svr.is_running());
  8299. });
  8300. svr.wait_until_ready();
  8301. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8302. client_encrypted_private_key_pass);
  8303. cli.enable_server_certificate_verification(false);
  8304. cli.set_connection_timeout(30);
  8305. auto res = cli.Get("/test");
  8306. ASSERT_TRUE(res);
  8307. ASSERT_EQ(StatusCode::OK_200, res->status);
  8308. }
  8309. TEST(SSLClientServerTest, ClientCertPresent) {
  8310. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8311. }
  8312. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8313. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8314. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8315. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8316. }
  8317. // PEM memory-based constructor tests (works with all TLS backends)
  8318. void PemMemoryClientCertPresent(
  8319. const std::string &client_cert_file,
  8320. const std::string &client_private_key_file,
  8321. const std::string &client_encrypted_private_key_pass = std::string()) {
  8322. // Read PEM files into memory
  8323. std::string server_cert_pem, server_key_pem;
  8324. std::string client_ca_pem;
  8325. std::string client_cert_pem, client_key_pem;
  8326. read_file(SERVER_CERT_FILE, server_cert_pem);
  8327. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8328. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8329. read_file(client_cert_file, client_cert_pem);
  8330. read_file(client_private_key_file, client_key_pem);
  8331. // Create server with PEM memory
  8332. SSLServer::PemMemory server_pem = {
  8333. server_cert_pem.c_str(),
  8334. server_cert_pem.size(),
  8335. server_key_pem.c_str(),
  8336. server_key_pem.size(),
  8337. client_ca_pem.c_str(),
  8338. client_ca_pem.size(),
  8339. nullptr // no password for server key
  8340. };
  8341. SSLServer svr(server_pem);
  8342. ASSERT_TRUE(svr.is_valid());
  8343. svr.Get("/test", [&](const Request &, Response &res) {
  8344. res.set_content("test", "text/plain");
  8345. });
  8346. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8347. auto se = detail::scope_exit([&] {
  8348. svr.stop();
  8349. t.join();
  8350. ASSERT_FALSE(svr.is_running());
  8351. });
  8352. svr.wait_until_ready();
  8353. // Create client with PEM memory
  8354. const char *password = client_encrypted_private_key_pass.empty()
  8355. ? nullptr
  8356. : client_encrypted_private_key_pass.c_str();
  8357. SSLClient::PemMemory client_pem = {
  8358. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8359. client_key_pem.size(), password};
  8360. SSLClient cli(HOST, PORT, client_pem);
  8361. cli.enable_server_certificate_verification(false);
  8362. cli.set_connection_timeout(30);
  8363. auto res = cli.Get("/test");
  8364. ASSERT_TRUE(res);
  8365. ASSERT_EQ(StatusCode::OK_200, res->status);
  8366. }
  8367. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8368. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8369. }
  8370. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8371. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8372. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8373. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8374. }
  8375. TEST(SSLClientServerTest, ClientCertMissing) {
  8376. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8377. CLIENT_CA_CERT_DIR);
  8378. ASSERT_TRUE(svr.is_valid());
  8379. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8380. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8381. auto se = detail::scope_exit([&] {
  8382. svr.stop();
  8383. t.join();
  8384. ASSERT_FALSE(svr.is_running());
  8385. });
  8386. svr.wait_until_ready();
  8387. SSLClient cli(HOST, PORT);
  8388. cli.set_connection_timeout(30);
  8389. auto res = cli.Get("/test");
  8390. ASSERT_TRUE(!res);
  8391. // When client cert is missing and server requires it, connection fails
  8392. // Error type depends on backend implementation
  8393. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8394. res.error() == Error::SSLConnection);
  8395. // Verify backend error is captured
  8396. // Note: This test may have different error codes depending on the exact
  8397. // verification failure
  8398. EXPECT_NE(0UL, res.ssl_backend_error());
  8399. }
  8400. TEST(SSLClientServerTest, TrustDirOptional) {
  8401. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8402. ASSERT_TRUE(svr.is_valid());
  8403. svr.Get("/test", [&](const Request &, Response &res) {
  8404. res.set_content("test", "text/plain");
  8405. });
  8406. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8407. auto se = detail::scope_exit([&] {
  8408. svr.stop();
  8409. t.join();
  8410. ASSERT_FALSE(svr.is_running());
  8411. });
  8412. svr.wait_until_ready();
  8413. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8414. cli.enable_server_certificate_verification(false);
  8415. cli.set_connection_timeout(30);
  8416. auto res = cli.Get("/test");
  8417. ASSERT_TRUE(res);
  8418. ASSERT_EQ(StatusCode::OK_200, res->status);
  8419. }
  8420. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8421. class NoListenSSLServer : public SSLServer {
  8422. public:
  8423. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8424. const char *client_ca_cert_file_path,
  8425. const char *client_ca_cert_dir_path = nullptr)
  8426. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8427. client_ca_cert_dir_path),
  8428. stop_(false) {}
  8429. std::atomic_bool stop_;
  8430. private:
  8431. bool process_and_close_socket(socket_t /*sock*/) override {
  8432. // Don't create SSL context
  8433. while (!stop_.load()) {
  8434. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8435. }
  8436. return true;
  8437. }
  8438. };
  8439. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8440. CLIENT_CA_CERT_FILE);
  8441. ASSERT_TRUE(svr.is_valid());
  8442. svr.Get("/test", [&](const Request &, Response &res) {
  8443. res.set_content("test", "text/plain");
  8444. });
  8445. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8446. auto se = detail::scope_exit([&] {
  8447. svr.stop_ = true;
  8448. svr.stop();
  8449. t.join();
  8450. ASSERT_FALSE(svr.is_running());
  8451. });
  8452. svr.wait_until_ready();
  8453. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8454. cli.enable_server_certificate_verification(false);
  8455. cli.set_connection_timeout(1);
  8456. auto res = cli.Get("/test");
  8457. ASSERT_TRUE(!res);
  8458. EXPECT_EQ(Error::SSLConnection, res.error());
  8459. // Timeout results in WantRead error code (maps to backend-specific value)
  8460. EXPECT_NE(0, res.ssl_error());
  8461. }
  8462. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8463. // Test SSLServer with client certificate verification using the standard
  8464. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8465. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8466. CLIENT_CA_CERT_DIR);
  8467. ASSERT_TRUE(svr.is_valid());
  8468. svr.Get("/test", [&](const Request &req, Response &res) {
  8469. res.set_content("test", "text/plain");
  8470. auto cert = req.peer_cert();
  8471. ASSERT_TRUE(static_cast<bool>(cert));
  8472. auto common_name = cert.subject_cn();
  8473. EXPECT_EQ("Common Name", common_name);
  8474. });
  8475. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8476. auto se = detail::scope_exit([&] {
  8477. svr.stop();
  8478. t.join();
  8479. ASSERT_FALSE(svr.is_running());
  8480. });
  8481. svr.wait_until_ready();
  8482. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8483. cli.enable_server_certificate_verification(false);
  8484. cli.set_connection_timeout(30);
  8485. auto res = cli.Get("/test");
  8486. ASSERT_TRUE(res);
  8487. ASSERT_EQ(StatusCode::OK_200, res->status);
  8488. }
  8489. // Test verify_hostname for both OpenSSL and MbedTLS backends
  8490. // Verifies that wildcard matching and exact matching work consistently
  8491. TEST(SSLClientServerTest, TlsVerifyHostname) {
  8492. using namespace httplib::tls;
  8493. // We need a running server to test against
  8494. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8495. ASSERT_TRUE(svr.is_valid());
  8496. svr.Get("/test", [](const Request &, Response &res) {
  8497. res.set_content("ok", "text/plain");
  8498. });
  8499. thread t([&]() { svr.listen(HOST, PORT); });
  8500. auto se = detail::scope_exit([&] {
  8501. svr.stop();
  8502. t.join();
  8503. });
  8504. svr.wait_until_ready();
  8505. bool verify_callback_called = false;
  8506. bool verify_result_wrong = false;
  8507. SSLClient cli(HOST, PORT);
  8508. cli.enable_server_certificate_verification(true);
  8509. cli.set_ca_cert_path(CA_CERT_FILE);
  8510. cli.set_connection_timeout(5);
  8511. // Note: Test certificate has CN="Common Name", not "localhost"
  8512. bool verify_result_cn = false;
  8513. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8514. verify_callback_called = true;
  8515. if (!ctx.cert) return false;
  8516. // Test 1: "Common Name" should match (our test server cert CN)
  8517. verify_result_cn = ctx.check_hostname("Common Name");
  8518. // Test 2: wrong hostname should not match
  8519. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  8520. return true; // Accept for the purpose of this test
  8521. });
  8522. auto res = cli.Get("/test");
  8523. // The request may succeed or fail depending on cert configuration
  8524. // but the callback should have been called
  8525. ASSERT_TRUE(verify_callback_called)
  8526. << "Verify callback should have been called";
  8527. // CN="Common Name" should match our test certificate
  8528. EXPECT_TRUE(verify_result_cn)
  8529. << "verify_hostname should match 'Common Name' (certificate CN)";
  8530. // Wrong hostname should not match
  8531. EXPECT_FALSE(verify_result_wrong)
  8532. << "verify_hostname should not match 'wronghost.example.com'";
  8533. }
  8534. #endif
  8535. // mbedTLS-specific callback constructor test
  8536. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8537. #ifdef CPPHTTPLIB_SSL_ENABLED
  8538. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8539. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8540. ASSERT_TRUE(svr.is_valid());
  8541. // Set up a handler to verify client certificate is present
  8542. bool client_cert_verified = false;
  8543. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8544. // Verify that client certificate was provided
  8545. client_cert_verified = true;
  8546. res.set_content("success", "text/plain");
  8547. });
  8548. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8549. auto se = detail::scope_exit([&] {
  8550. svr.stop();
  8551. t.join();
  8552. ASSERT_FALSE(svr.is_running());
  8553. });
  8554. svr.wait_until_ready();
  8555. // Client with certificate
  8556. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8557. cli.enable_server_certificate_verification(false);
  8558. cli.set_connection_timeout(30);
  8559. auto res = cli.Get("/test");
  8560. ASSERT_TRUE(res);
  8561. ASSERT_EQ(StatusCode::OK_200, res->status);
  8562. ASSERT_TRUE(client_cert_verified);
  8563. EXPECT_EQ("success", res->body);
  8564. }
  8565. #endif
  8566. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  8567. // backends
  8568. #ifdef CPPHTTPLIB_SSL_ENABLED
  8569. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  8570. using namespace httplib::tls;
  8571. // Test that when client CA cert file is provided,
  8572. // the server properly requests and validates client certificates
  8573. // Create a server with client authentication
  8574. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8575. ASSERT_TRUE(svr.is_valid());
  8576. bool handler_called = false;
  8577. svr.Get("/test", [&](const Request &req, Response &res) {
  8578. handler_called = true;
  8579. // Verify that a client certificate was provided
  8580. auto cert = req.peer_cert();
  8581. ASSERT_TRUE(static_cast<bool>(cert));
  8582. // Get the issuer name
  8583. std::string issuer_str = cert.issuer_name();
  8584. ASSERT_FALSE(issuer_str.empty());
  8585. // The client certificate should be issued by our test CA
  8586. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  8587. res.set_content("authenticated", "text/plain");
  8588. });
  8589. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8590. auto se = detail::scope_exit([&] {
  8591. svr.stop();
  8592. t.join();
  8593. ASSERT_FALSE(svr.is_running());
  8594. });
  8595. svr.wait_until_ready();
  8596. // Connect with a client certificate issued by the CA
  8597. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8598. cli.enable_server_certificate_verification(false);
  8599. cli.set_connection_timeout(30);
  8600. auto res = cli.Get("/test");
  8601. ASSERT_TRUE(res);
  8602. ASSERT_EQ(StatusCode::OK_200, res->status);
  8603. ASSERT_TRUE(handler_called);
  8604. EXPECT_EQ("authenticated", res->body);
  8605. }
  8606. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  8607. using namespace httplib::tls;
  8608. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8609. ASSERT_TRUE(svr.is_valid());
  8610. svr.Get("/test", [](const Request &, Response &res) {
  8611. res.set_content("ok", "text/plain");
  8612. });
  8613. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8614. auto se = detail::scope_exit([&] {
  8615. svr.stop();
  8616. t.join();
  8617. });
  8618. svr.wait_until_ready();
  8619. SSLClient cli(HOST, PORT);
  8620. cli.enable_server_certificate_verification(false);
  8621. cli.set_connection_timeout(30);
  8622. bool cert_checked = false;
  8623. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8624. if (ctx.cert) {
  8625. auto sans = ctx.sans();
  8626. // Test certificate may or may not have SANs - just verify the API
  8627. // works If SANs exist, verify the types are valid
  8628. for (const auto &san : sans) {
  8629. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  8630. san.type == SanType::EMAIL || san.type == SanType::URI ||
  8631. san.type == SanType::OTHER);
  8632. EXPECT_FALSE(san.value.empty());
  8633. }
  8634. cert_checked = true;
  8635. }
  8636. return true;
  8637. });
  8638. auto res = cli.Get("/test");
  8639. ASSERT_TRUE(res);
  8640. EXPECT_TRUE(cert_checked);
  8641. }
  8642. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  8643. using namespace httplib::tls;
  8644. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8645. ASSERT_TRUE(svr.is_valid());
  8646. svr.Get("/test", [](const Request &, Response &res) {
  8647. res.set_content("ok", "text/plain");
  8648. });
  8649. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8650. auto se = detail::scope_exit([&] {
  8651. svr.stop();
  8652. t.join();
  8653. });
  8654. svr.wait_until_ready();
  8655. SSLClient cli(HOST, PORT);
  8656. cli.enable_server_certificate_verification(false);
  8657. cli.set_connection_timeout(30);
  8658. bool validity_checked = false;
  8659. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8660. if (ctx.cert) {
  8661. time_t not_before = 0, not_after = 0;
  8662. bool result = ctx.validity(not_before, not_after);
  8663. EXPECT_TRUE(result);
  8664. // Verify that not_before < now < not_after for a valid cert
  8665. time_t now = time(nullptr);
  8666. EXPECT_LT(not_before, now);
  8667. EXPECT_GT(not_after, now);
  8668. validity_checked = true;
  8669. }
  8670. return true;
  8671. });
  8672. auto res = cli.Get("/test");
  8673. ASSERT_TRUE(res);
  8674. EXPECT_TRUE(validity_checked);
  8675. }
  8676. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  8677. using namespace httplib::tls;
  8678. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8679. ASSERT_TRUE(svr.is_valid());
  8680. svr.Get("/test", [](const Request &, Response &res) {
  8681. res.set_content("ok", "text/plain");
  8682. });
  8683. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8684. auto se = detail::scope_exit([&] {
  8685. svr.stop();
  8686. t.join();
  8687. });
  8688. svr.wait_until_ready();
  8689. SSLClient cli(HOST, PORT);
  8690. cli.enable_server_certificate_verification(false);
  8691. cli.set_connection_timeout(30);
  8692. bool serial_checked = false;
  8693. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8694. if (ctx.cert) {
  8695. std::string serial = ctx.serial();
  8696. EXPECT_FALSE(serial.empty());
  8697. // Serial should be a hex string
  8698. for (char c : serial) {
  8699. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  8700. (c >= 'a' && c <= 'f'));
  8701. }
  8702. serial_checked = true;
  8703. }
  8704. return true;
  8705. });
  8706. auto res = cli.Get("/test");
  8707. ASSERT_TRUE(res);
  8708. EXPECT_TRUE(serial_checked);
  8709. }
  8710. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  8711. // Test 1: Valid CA file - no error should be recorded
  8712. {
  8713. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8714. CLIENT_CA_CERT_FILE);
  8715. ASSERT_TRUE(svr.is_valid());
  8716. // With valid setup, last_ssl_error should be 0
  8717. EXPECT_EQ(0, svr.ssl_last_error());
  8718. }
  8719. // Test 2: Invalid CA file content
  8720. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  8721. {
  8722. // Create a temporary file with completely invalid content
  8723. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  8724. {
  8725. std::ofstream ofs(temp_invalid_ca);
  8726. ofs << "This is not a certificate file at all\n";
  8727. ofs << "Just plain text content\n";
  8728. }
  8729. // Create server with invalid CA file
  8730. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  8731. // Clean up temporary file
  8732. std::remove(temp_invalid_ca);
  8733. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  8734. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  8735. // Note: SSL_CTX_load_verify_locations typically fails first,
  8736. // but our error handling code path is still exercised
  8737. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  8738. }
  8739. }
  8740. TEST(VerifyCallbackTest, VerifyContextFields) {
  8741. using namespace httplib::tls;
  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. SSLClient cli(HOST, PORT);
  8754. cli.enable_server_certificate_verification(false);
  8755. cli.set_connection_timeout(30);
  8756. int callback_count = 0;
  8757. bool saw_leaf_cert = false;
  8758. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8759. if (ctx.cert) {
  8760. callback_count++;
  8761. // We should see at least one certificate (the leaf)
  8762. std::string cn = ctx.subject_cn();
  8763. if (!cn.empty()) { saw_leaf_cert = true; }
  8764. // Verify context fields are populated
  8765. EXPECT_NE(ctx.session, nullptr);
  8766. EXPECT_GE(ctx.depth, 0);
  8767. }
  8768. return true;
  8769. });
  8770. auto res = cli.Get("/test");
  8771. ASSERT_TRUE(res);
  8772. EXPECT_GT(callback_count, 0);
  8773. EXPECT_TRUE(saw_leaf_cert);
  8774. }
  8775. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  8776. using httplib::tls::TlsError;
  8777. // Test that verify_error_to_string returns empty for success
  8778. std::string success_str = TlsError::verify_error_to_string(0);
  8779. EXPECT_TRUE(success_str.empty());
  8780. // Test that verify_error_to_string returns non-empty for error codes
  8781. // Using a common error code (certificate expired)
  8782. std::string error_str =
  8783. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  8784. EXPECT_FALSE(error_str.empty());
  8785. }
  8786. TEST(SessionVerifierTest, CertificateAccepted) {
  8787. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8788. ASSERT_TRUE(svr.is_valid());
  8789. svr.Get("/test", [](const Request &, Response &res) {
  8790. res.set_content("ok", "text/plain");
  8791. });
  8792. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8793. auto se = detail::scope_exit([&] {
  8794. svr.stop();
  8795. t.join();
  8796. });
  8797. svr.wait_until_ready();
  8798. SSLClient cli(HOST, PORT);
  8799. cli.enable_server_certificate_verification(false);
  8800. cli.set_connection_timeout(30);
  8801. bool callback_called = false;
  8802. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8803. EXPECT_NE(session, nullptr);
  8804. callback_called = true;
  8805. return SSLVerifierResponse::CertificateAccepted;
  8806. });
  8807. auto res = cli.Get("/test");
  8808. ASSERT_TRUE(res);
  8809. EXPECT_EQ(200, res->status);
  8810. EXPECT_TRUE(callback_called);
  8811. }
  8812. TEST(SessionVerifierTest, CertificateRejected) {
  8813. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8814. ASSERT_TRUE(svr.is_valid());
  8815. svr.Get("/test", [](const Request &, Response &res) {
  8816. res.set_content("ok", "text/plain");
  8817. });
  8818. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8819. auto se = detail::scope_exit([&] {
  8820. svr.stop();
  8821. t.join();
  8822. });
  8823. svr.wait_until_ready();
  8824. SSLClient cli(HOST, PORT);
  8825. cli.enable_server_certificate_verification(false);
  8826. cli.set_connection_timeout(30);
  8827. bool callback_called = false;
  8828. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8829. EXPECT_NE(session, nullptr);
  8830. callback_called = true;
  8831. return SSLVerifierResponse::CertificateRejected;
  8832. });
  8833. auto res = cli.Get("/test");
  8834. EXPECT_FALSE(res);
  8835. EXPECT_TRUE(callback_called);
  8836. }
  8837. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  8838. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8839. ASSERT_TRUE(svr.is_valid());
  8840. svr.Get("/test", [](const Request &, Response &res) {
  8841. res.set_content("ok", "text/plain");
  8842. });
  8843. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8844. auto se = detail::scope_exit([&] {
  8845. svr.stop();
  8846. t.join();
  8847. });
  8848. svr.wait_until_ready();
  8849. // NoDecisionMade with verification disabled should succeed (no default check)
  8850. SSLClient cli(HOST, PORT);
  8851. cli.enable_server_certificate_verification(false);
  8852. cli.set_connection_timeout(30);
  8853. bool callback_called = false;
  8854. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8855. EXPECT_NE(session, nullptr);
  8856. callback_called = true;
  8857. return SSLVerifierResponse::NoDecisionMade;
  8858. });
  8859. auto res = cli.Get("/test");
  8860. ASSERT_TRUE(res);
  8861. EXPECT_EQ(200, res->status);
  8862. EXPECT_TRUE(callback_called);
  8863. }
  8864. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  8865. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8866. ASSERT_TRUE(svr.is_valid());
  8867. svr.Get("/test", [](const Request &, Response &res) {
  8868. res.set_content("ok", "text/plain");
  8869. });
  8870. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8871. auto se = detail::scope_exit([&] {
  8872. svr.stop();
  8873. t.join();
  8874. });
  8875. svr.wait_until_ready();
  8876. // NoDecisionMade with verification enabled should fail (self-signed cert).
  8877. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  8878. // so we only check that the request fails, not whether the callback was
  8879. // called.
  8880. SSLClient cli(HOST, PORT);
  8881. cli.enable_server_certificate_verification(true);
  8882. cli.set_connection_timeout(30);
  8883. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8884. EXPECT_NE(session, nullptr);
  8885. return SSLVerifierResponse::NoDecisionMade;
  8886. });
  8887. auto res = cli.Get("/test");
  8888. EXPECT_FALSE(res);
  8889. }
  8890. TEST(SSLClientServerTest, ClientCAListFromPem) {
  8891. // Test SSL server using PemMemory constructor with client CA certificates
  8892. // Read PEM files
  8893. std::string server_cert_pem, server_key_pem, client_ca_pem;
  8894. read_file(SERVER_CERT_FILE, server_cert_pem);
  8895. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8896. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8897. // Create SSLServer with PemMemory constructor including client CA
  8898. SSLServer::PemMemory server_pem = {
  8899. server_cert_pem.c_str(),
  8900. server_cert_pem.size(),
  8901. server_key_pem.c_str(),
  8902. server_key_pem.size(),
  8903. client_ca_pem.c_str(),
  8904. client_ca_pem.size(),
  8905. nullptr // no password for server key
  8906. };
  8907. SSLServer svr(server_pem);
  8908. ASSERT_TRUE(svr.is_valid());
  8909. // No SSL error should be recorded for valid setup
  8910. EXPECT_EQ(0, svr.ssl_last_error());
  8911. // Set up server endpoints
  8912. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  8913. res.set_content("ok", "text/plain");
  8914. });
  8915. // Start server in a thread
  8916. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  8917. svr.wait_until_ready();
  8918. // Connect with client certificate (using constructor with paths)
  8919. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8920. cli.enable_server_certificate_verification(false);
  8921. auto res = cli.Get("/test-pem-ca");
  8922. ASSERT_TRUE(res);
  8923. EXPECT_EQ(200, res->status);
  8924. EXPECT_EQ("ok", res->body);
  8925. svr.stop();
  8926. server_thread.join();
  8927. }
  8928. #endif
  8929. #ifdef _WIN32
  8930. TEST(CleanupTest, WSACleanup) {
  8931. int ret = WSACleanup();
  8932. ASSERT_EQ(0, ret);
  8933. }
  8934. #endif
  8935. #ifndef CPPHTTPLIB_SSL_ENABLED
  8936. TEST(NoSSLSupport, SimpleInterface) {
  8937. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  8938. }
  8939. #endif
  8940. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8941. TEST(InvalidScheme, SimpleInterface) {
  8942. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  8943. }
  8944. #endif
  8945. TEST(NoScheme, SimpleInterface) {
  8946. Client cli("yahoo.com:80");
  8947. ASSERT_TRUE(cli.is_valid());
  8948. }
  8949. TEST(SendAPI, SimpleInterface_Online) {
  8950. Client cli("http://yahoo.com");
  8951. Request req;
  8952. req.method = "GET";
  8953. req.path = "/";
  8954. auto res = cli.send(req);
  8955. ASSERT_TRUE(res);
  8956. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8957. }
  8958. TEST(SendAPI, WithParamsInRequest) {
  8959. Server svr;
  8960. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  8961. EXPECT_TRUE(req.has_param("test"));
  8962. EXPECT_EQ("test_value", req.get_param_value("test"));
  8963. });
  8964. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  8965. auto se = detail::scope_exit([&] {
  8966. svr.stop();
  8967. t.join();
  8968. ASSERT_FALSE(svr.is_running());
  8969. });
  8970. svr.wait_until_ready();
  8971. Client cli(HOST, PORT);
  8972. {
  8973. Request req;
  8974. req.method = "GET";
  8975. req.path = "/";
  8976. req.params.emplace("test", "test_value");
  8977. auto res = cli.send(req);
  8978. ASSERT_TRUE(res);
  8979. }
  8980. {
  8981. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  8982. ASSERT_TRUE(res);
  8983. }
  8984. }
  8985. TEST(ClientImplMethods, GetSocketTest) {
  8986. httplib::Server svr;
  8987. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  8988. res.status = StatusCode::OK_200;
  8989. });
  8990. auto port = svr.bind_to_any_port("127.0.0.1");
  8991. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  8992. auto se = detail::scope_exit([&] {
  8993. svr.stop();
  8994. thread.join();
  8995. ASSERT_FALSE(svr.is_running());
  8996. });
  8997. svr.wait_until_ready();
  8998. {
  8999. httplib::Client cli("127.0.0.1", port);
  9000. cli.set_keep_alive(true);
  9001. // Use the behavior of cpp-httplib of opening the connection
  9002. // only when the first request happens. If that changes,
  9003. // this test would be obsolete.
  9004. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9005. // This also implicitly tests the server. But other tests would fail much
  9006. // earlier than this one to be considered.
  9007. auto res = cli.Get("/");
  9008. ASSERT_TRUE(res);
  9009. EXPECT_EQ(StatusCode::OK_200, res->status);
  9010. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9011. }
  9012. }
  9013. // Disabled due to out-of-memory problem on GitHub Actions
  9014. #ifdef _WIN64
  9015. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  9016. // allocate content size larger than 2GB in memory
  9017. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  9018. char *content = (char *)malloc(content_size);
  9019. ASSERT_TRUE(content);
  9020. Server svr;
  9021. svr.Get("/foo",
  9022. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  9023. res.set_content(content, content_size, "application/octet-stream");
  9024. });
  9025. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9026. auto se = detail::scope_exit([&] {
  9027. svr.stop();
  9028. listen_thread.join();
  9029. if (content) free(content);
  9030. ASSERT_FALSE(svr.is_running());
  9031. });
  9032. svr.wait_until_ready();
  9033. Client cli(HOST, PORT);
  9034. auto res = cli.Get("/foo");
  9035. ASSERT_TRUE(res);
  9036. EXPECT_EQ(StatusCode::OK_200, res->status);
  9037. EXPECT_EQ(content_size, res->body.length());
  9038. }
  9039. #endif
  9040. #ifdef CPPHTTPLIB_SSL_ENABLED
  9041. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9042. Client cli("http://yahoo.com");
  9043. auto res = cli.Get("/");
  9044. ASSERT_TRUE(res);
  9045. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9046. cli.set_follow_location(true);
  9047. res = cli.Get("/");
  9048. ASSERT_TRUE(res);
  9049. EXPECT_EQ(StatusCode::OK_200, res->status);
  9050. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9051. }
  9052. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9053. Client cli("https://yahoo.com");
  9054. auto res = cli.Get("/");
  9055. ASSERT_TRUE(res);
  9056. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9057. cli.set_follow_location(true);
  9058. res = cli.Get("/");
  9059. ASSERT_TRUE(res);
  9060. EXPECT_EQ(StatusCode::OK_200, res->status);
  9061. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9062. }
  9063. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9064. Client cli("https://yahoo.com");
  9065. auto res = cli.Get("/");
  9066. ASSERT_TRUE(res);
  9067. ASSERT_FALSE(!res);
  9068. ASSERT_TRUE(res);
  9069. ASSERT_FALSE(res == nullptr);
  9070. ASSERT_TRUE(res != nullptr);
  9071. EXPECT_EQ(Error::Success, res.error());
  9072. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9073. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9074. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9075. cli.set_follow_location(true);
  9076. res = cli.Get("/");
  9077. ASSERT_TRUE(res);
  9078. EXPECT_EQ(Error::Success, res.error());
  9079. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9080. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9081. EXPECT_EQ(StatusCode::OK_200, res->status);
  9082. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9083. }
  9084. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9085. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9086. Client cli("https://cdnjs.cloudflare.com");
  9087. auto res =
  9088. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9089. ASSERT_TRUE(res);
  9090. EXPECT_EQ(StatusCode::OK_200, res->status);
  9091. EXPECT_EQ(287630U, res->body.size());
  9092. EXPECT_EQ("application/javascript; charset=utf-8",
  9093. res->get_header_value("Content-Type"));
  9094. }
  9095. #endif
  9096. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9097. #undef REDIR_HOST // Silence compiler warning
  9098. #define REDIR_HOST "https://httpbingo.org"
  9099. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9100. Client cli(REDIR_HOST);
  9101. cli.set_follow_location(true);
  9102. auto res =
  9103. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9104. ASSERT_TRUE(res);
  9105. EXPECT_EQ(StatusCode::OK_200, res->status);
  9106. }
  9107. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9108. Client cli(REDIR_HOST);
  9109. cli.set_follow_location(true);
  9110. Params params;
  9111. params.emplace("url", "http://example.com");
  9112. params.emplace("status_code", "302");
  9113. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9114. ASSERT_TRUE(res);
  9115. EXPECT_EQ(StatusCode::OK_200, res->status);
  9116. }
  9117. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9118. Client cli(REDIR_HOST);
  9119. cli.set_follow_location(true);
  9120. Params params;
  9121. params.emplace("url", "http://example.com");
  9122. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9123. ASSERT_TRUE(res);
  9124. EXPECT_EQ(StatusCode::OK_200, res->status);
  9125. }
  9126. TEST(HttpToHttpsRedirectTest, CertFile) {
  9127. auto ssl_port = PORT + 1;
  9128. Server svr;
  9129. ASSERT_TRUE(svr.is_valid());
  9130. svr.Get("/index", [&](const Request &, Response &res) {
  9131. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9132. "/index");
  9133. svr.stop();
  9134. });
  9135. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9136. ASSERT_TRUE(ssl_svr.is_valid());
  9137. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9138. res.set_content("test", "text/plain");
  9139. ssl_svr.stop();
  9140. });
  9141. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9142. thread t2 =
  9143. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9144. auto se = detail::scope_exit([&] {
  9145. t2.join();
  9146. t.join();
  9147. ASSERT_FALSE(svr.is_running());
  9148. });
  9149. svr.wait_until_ready();
  9150. ssl_svr.wait_until_ready();
  9151. Client cli("127.0.0.1", PORT);
  9152. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9153. cli.enable_server_certificate_verification(true);
  9154. cli.set_follow_location(true);
  9155. cli.set_connection_timeout(30);
  9156. auto res = cli.Get("/index");
  9157. ASSERT_TRUE(res);
  9158. ASSERT_EQ(StatusCode::OK_200, res->status);
  9159. }
  9160. TEST(SSLClientRedirectTest, CertFile) {
  9161. auto ssl_port = PORT + 1;
  9162. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9163. ASSERT_TRUE(ssl_svr1.is_valid());
  9164. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9165. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9166. "/index");
  9167. ssl_svr1.stop();
  9168. });
  9169. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9170. ASSERT_TRUE(ssl_svr2.is_valid());
  9171. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9172. res.set_content("test", "text/plain");
  9173. ssl_svr2.stop();
  9174. });
  9175. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9176. thread t2 =
  9177. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9178. auto se = detail::scope_exit([&] {
  9179. t2.join();
  9180. t.join();
  9181. ASSERT_FALSE(ssl_svr1.is_running());
  9182. });
  9183. ssl_svr1.wait_until_ready();
  9184. ssl_svr2.wait_until_ready();
  9185. SSLClient cli("127.0.0.1", PORT);
  9186. std::string cert;
  9187. read_file(SERVER_CERT2_FILE, cert);
  9188. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9189. cli.enable_server_certificate_verification(true);
  9190. cli.set_follow_location(true);
  9191. cli.set_connection_timeout(30);
  9192. auto res = cli.Get("/index");
  9193. ASSERT_TRUE(res);
  9194. ASSERT_EQ(StatusCode::OK_200, res->status);
  9195. }
  9196. #endif
  9197. #ifdef CPPHTTPLIB_SSL_ENABLED
  9198. // Test that set_ca_cert_store() skips system certs (consistent with
  9199. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9200. // should be trusted - system certs should NOT be loaded.
  9201. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9202. // Load a specific cert that is NOT a system CA cert
  9203. std::string cert;
  9204. read_file(SERVER_CERT2_FILE, cert);
  9205. SSLClient cli("google.com");
  9206. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9207. cli.enable_server_certificate_verification(true);
  9208. // This should FAIL because:
  9209. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9210. // 2. System certs should NOT be loaded when custom store is set
  9211. // If system certs WERE loaded, this would succeed
  9212. auto res = cli.Get("/");
  9213. ASSERT_FALSE(res);
  9214. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9215. }
  9216. TEST(MultipartFormDataTest, LargeData) {
  9217. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9218. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9219. const ContentReader &content_reader) {
  9220. if (req.is_multipart_form_data()) {
  9221. std::vector<FormData> items;
  9222. content_reader(
  9223. [&](const FormData &file) {
  9224. items.push_back(file);
  9225. return true;
  9226. },
  9227. [&](const char *data, size_t data_length) {
  9228. items.back().content.append(data, data_length);
  9229. return true;
  9230. });
  9231. EXPECT_TRUE(std::string(items[0].name) == "document");
  9232. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9233. EXPECT_TRUE(items[0].filename == "2MB_data");
  9234. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9235. EXPECT_TRUE(items[1].name == "hello");
  9236. EXPECT_TRUE(items[1].content == "world");
  9237. EXPECT_TRUE(items[1].filename == "");
  9238. EXPECT_TRUE(items[1].content_type == "");
  9239. } else {
  9240. std::string body;
  9241. content_reader([&](const char *data, size_t data_length) {
  9242. body.append(data, data_length);
  9243. return true;
  9244. });
  9245. }
  9246. });
  9247. auto port = svr.bind_to_any_port(HOST);
  9248. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9249. auto se = detail::scope_exit([&] {
  9250. svr.stop();
  9251. t.join();
  9252. ASSERT_FALSE(svr.is_running());
  9253. });
  9254. svr.wait_until_ready();
  9255. {
  9256. std::string data(1024 * 1024 * 2, '.');
  9257. std::stringstream buffer;
  9258. buffer << data;
  9259. SSLClient cli(HOST, port);
  9260. cli.enable_server_certificate_verification(false);
  9261. UploadFormDataItems items{
  9262. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9263. {"hello", "world", "", ""},
  9264. };
  9265. auto res = cli.Post("/post", items);
  9266. ASSERT_TRUE(res);
  9267. ASSERT_EQ(StatusCode::OK_200, res->status);
  9268. }
  9269. }
  9270. TEST(MultipartFormDataTest, DataProviderItems) {
  9271. std::random_device seed_gen;
  9272. std::mt19937 random(seed_gen());
  9273. std::string rand1;
  9274. rand1.resize(1000);
  9275. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9276. std::string rand2;
  9277. rand2.resize(3000);
  9278. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9279. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9280. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9281. const ContentReader &content_reader) {
  9282. ASSERT_FALSE(req.is_multipart_form_data());
  9283. std::string body;
  9284. content_reader([&](const char *data, size_t data_length) {
  9285. body.append(data, data_length);
  9286. return true;
  9287. });
  9288. EXPECT_EQ(body, "");
  9289. });
  9290. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9291. const ContentReader &content_reader) {
  9292. ASSERT_TRUE(req.is_multipart_form_data());
  9293. std::vector<FormData> items;
  9294. content_reader(
  9295. [&](const FormData &file) {
  9296. items.push_back(file);
  9297. return true;
  9298. },
  9299. [&](const char *data, size_t data_length) {
  9300. items.back().content.append(data, data_length);
  9301. return true;
  9302. });
  9303. ASSERT_TRUE(items.size() == 2);
  9304. EXPECT_EQ(std::string(items[0].name), "name1");
  9305. EXPECT_EQ(items[0].content, "Testing123");
  9306. EXPECT_EQ(items[0].filename, "filename1");
  9307. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9308. EXPECT_EQ(items[1].name, "name2");
  9309. EXPECT_EQ(items[1].content, "Testing456");
  9310. EXPECT_EQ(items[1].filename, "");
  9311. EXPECT_EQ(items[1].content_type, "");
  9312. });
  9313. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9314. const ContentReader &content_reader) {
  9315. ASSERT_TRUE(req.is_multipart_form_data());
  9316. std::vector<FormData> items;
  9317. content_reader(
  9318. [&](const FormData &file) {
  9319. items.push_back(file);
  9320. return true;
  9321. },
  9322. [&](const char *data, size_t data_length) {
  9323. items.back().content.append(data, data_length);
  9324. return true;
  9325. });
  9326. ASSERT_TRUE(items.size() == 2);
  9327. EXPECT_EQ(items[0].name, "name3");
  9328. EXPECT_EQ(items[0].content, rand1);
  9329. EXPECT_EQ(items[0].filename, "filename3");
  9330. EXPECT_EQ(items[0].content_type, "");
  9331. EXPECT_EQ(items[1].name, "name4");
  9332. EXPECT_EQ(items[1].content, rand2);
  9333. EXPECT_EQ(items[1].filename, "filename4");
  9334. EXPECT_EQ(items[1].content_type, "");
  9335. });
  9336. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9337. const ContentReader &content_reader) {
  9338. ASSERT_TRUE(req.is_multipart_form_data());
  9339. std::vector<FormData> items;
  9340. content_reader(
  9341. [&](const FormData &file) {
  9342. items.push_back(file);
  9343. return true;
  9344. },
  9345. [&](const char *data, size_t data_length) {
  9346. items.back().content.append(data, data_length);
  9347. return true;
  9348. });
  9349. ASSERT_TRUE(items.size() == 4);
  9350. EXPECT_EQ(std::string(items[0].name), "name1");
  9351. EXPECT_EQ(items[0].content, "Testing123");
  9352. EXPECT_EQ(items[0].filename, "filename1");
  9353. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9354. EXPECT_EQ(items[1].name, "name2");
  9355. EXPECT_EQ(items[1].content, "Testing456");
  9356. EXPECT_EQ(items[1].filename, "");
  9357. EXPECT_EQ(items[1].content_type, "");
  9358. EXPECT_EQ(items[2].name, "name3");
  9359. EXPECT_EQ(items[2].content, rand1);
  9360. EXPECT_EQ(items[2].filename, "filename3");
  9361. EXPECT_EQ(items[2].content_type, "");
  9362. EXPECT_EQ(items[3].name, "name4");
  9363. EXPECT_EQ(items[3].content, rand2);
  9364. EXPECT_EQ(items[3].filename, "filename4");
  9365. EXPECT_EQ(items[3].content_type, "");
  9366. });
  9367. auto port = svr.bind_to_any_port("localhost");
  9368. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9369. auto se = detail::scope_exit([&] {
  9370. svr.stop();
  9371. t.join();
  9372. ASSERT_FALSE(svr.is_running());
  9373. });
  9374. svr.wait_until_ready();
  9375. {
  9376. SSLClient cli("localhost", port);
  9377. cli.enable_server_certificate_verification(false);
  9378. UploadFormDataItems items{
  9379. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9380. {"name2", "Testing456", "", ""}, // not a file
  9381. };
  9382. {
  9383. auto res = cli.Post("/post-none", {}, {}, {});
  9384. ASSERT_TRUE(res);
  9385. ASSERT_EQ(StatusCode::OK_200, res->status);
  9386. }
  9387. FormDataProviderItems providers;
  9388. {
  9389. auto res =
  9390. cli.Post("/post-items", {}, items, providers); // empty providers
  9391. ASSERT_TRUE(res);
  9392. ASSERT_EQ(StatusCode::OK_200, res->status);
  9393. }
  9394. providers.push_back({"name3",
  9395. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9396. // test the offset is given correctly at each step
  9397. if (!offset)
  9398. sink.os.write(rand1.data(), 30);
  9399. else if (offset == 30)
  9400. sink.os.write(rand1.data() + 30, 300);
  9401. else if (offset == 330)
  9402. sink.os.write(rand1.data() + 330, 670);
  9403. else if (offset == rand1.size())
  9404. sink.done();
  9405. return true;
  9406. },
  9407. "filename3",
  9408. {}});
  9409. providers.push_back({"name4",
  9410. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9411. // test the offset is given correctly at each step
  9412. if (!offset)
  9413. sink.os.write(rand2.data(), 2000);
  9414. else if (offset == 2000)
  9415. sink.os.write(rand2.data() + 2000, 1);
  9416. else if (offset == 2001)
  9417. sink.os.write(rand2.data() + 2001, 999);
  9418. else if (offset == rand2.size())
  9419. sink.done();
  9420. return true;
  9421. },
  9422. "filename4",
  9423. {}});
  9424. {
  9425. auto res = cli.Post("/post-providers", {}, {}, providers);
  9426. ASSERT_TRUE(res);
  9427. ASSERT_EQ(StatusCode::OK_200, res->status);
  9428. }
  9429. {
  9430. auto res = cli.Post("/post-both", {}, items, providers);
  9431. ASSERT_TRUE(res);
  9432. ASSERT_EQ(StatusCode::OK_200, res->status);
  9433. }
  9434. }
  9435. }
  9436. TEST(MultipartFormDataTest, BadHeader) {
  9437. Server svr;
  9438. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9439. res.set_content("ok", "text/plain");
  9440. });
  9441. thread t = thread([&] { svr.listen(HOST, PORT); });
  9442. auto se = detail::scope_exit([&] {
  9443. svr.stop();
  9444. t.join();
  9445. ASSERT_FALSE(svr.is_running());
  9446. });
  9447. svr.wait_until_ready();
  9448. const std::string body =
  9449. "This is the preamble. It is to be ignored, though it\r\n"
  9450. "is a handy place for composition agents to include an\r\n"
  9451. "explanatory note to non-MIME conformant readers.\r\n"
  9452. "\r\n"
  9453. "\r\n"
  9454. "--simple boundary\r\n"
  9455. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9456. ": BAD...\r\n"
  9457. "\r\n"
  9458. "value1\r\n"
  9459. "--simple boundary\r\n"
  9460. "Content-Disposition: form-data; name=\"field2\"; "
  9461. "filename=\"example.txt\"\r\n"
  9462. "\r\n"
  9463. "value2\r\n"
  9464. "--simple boundary--\r\n"
  9465. "This is the epilogue. It is also to be ignored.\r\n";
  9466. std::string content_type =
  9467. R"(multipart/form-data; boundary="simple boundary")";
  9468. Client cli(HOST, PORT);
  9469. auto res = cli.Post("/post", body, content_type.c_str());
  9470. ASSERT_TRUE(res);
  9471. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9472. }
  9473. TEST(MultipartFormDataTest, WithPreamble) {
  9474. Server svr;
  9475. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9476. res.set_content("ok", "text/plain");
  9477. });
  9478. thread t = thread([&] { svr.listen(HOST, PORT); });
  9479. auto se = detail::scope_exit([&] {
  9480. svr.stop();
  9481. t.join();
  9482. ASSERT_FALSE(svr.is_running());
  9483. });
  9484. svr.wait_until_ready();
  9485. const std::string body =
  9486. "This is the preamble. It is to be ignored, though it\r\n"
  9487. "is a handy place for composition agents to include an\r\n"
  9488. "explanatory note to non-MIME conformant readers.\r\n"
  9489. "\r\n"
  9490. "\r\n"
  9491. "--simple boundary\r\n"
  9492. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9493. "\r\n"
  9494. "value1\r\n"
  9495. "--simple boundary\r\n"
  9496. "Content-Disposition: form-data; name=\"field2\"; "
  9497. "filename=\"example.txt\"\r\n"
  9498. "\r\n"
  9499. "value2\r\n"
  9500. "--simple boundary--\r\n"
  9501. "This is the epilogue. It is also to be ignored.\r\n";
  9502. std::string content_type =
  9503. R"(multipart/form-data; boundary="simple boundary")";
  9504. Client cli(HOST, PORT);
  9505. auto res = cli.Post("/post", body, content_type.c_str());
  9506. ASSERT_TRUE(res);
  9507. EXPECT_EQ(StatusCode::OK_200, res->status);
  9508. }
  9509. TEST(MultipartFormDataTest, PostCustomBoundary) {
  9510. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9511. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  9512. const ContentReader &content_reader) {
  9513. if (req.is_multipart_form_data()) {
  9514. std::vector<FormData> items;
  9515. content_reader(
  9516. [&](const FormData &file) {
  9517. items.push_back(file);
  9518. return true;
  9519. },
  9520. [&](const char *data, size_t data_length) {
  9521. items.back().content.append(data, data_length);
  9522. return true;
  9523. });
  9524. EXPECT_TRUE(std::string(items[0].name) == "document");
  9525. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9526. EXPECT_TRUE(items[0].filename == "2MB_data");
  9527. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9528. EXPECT_TRUE(items[1].name == "hello");
  9529. EXPECT_TRUE(items[1].content == "world");
  9530. EXPECT_TRUE(items[1].filename == "");
  9531. EXPECT_TRUE(items[1].content_type == "");
  9532. } else {
  9533. std::string body;
  9534. content_reader([&](const char *data, size_t data_length) {
  9535. body.append(data, data_length);
  9536. return true;
  9537. });
  9538. }
  9539. });
  9540. auto port = svr.bind_to_any_port("localhost");
  9541. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9542. auto se = detail::scope_exit([&] {
  9543. svr.stop();
  9544. t.join();
  9545. ASSERT_FALSE(svr.is_running());
  9546. });
  9547. svr.wait_until_ready();
  9548. {
  9549. std::string data(1024 * 1024 * 2, '.');
  9550. std::stringstream buffer;
  9551. buffer << data;
  9552. SSLClient cli("localhost", port);
  9553. cli.enable_server_certificate_verification(false);
  9554. UploadFormDataItems items{
  9555. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9556. {"hello", "world", "", ""},
  9557. };
  9558. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9559. ASSERT_TRUE(res);
  9560. ASSERT_EQ(StatusCode::OK_200, res->status);
  9561. }
  9562. }
  9563. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9564. std::string data(1024 * 1024 * 2, '&');
  9565. std::stringstream buffer;
  9566. buffer << data;
  9567. Client cli("https://localhost:8080");
  9568. UploadFormDataItems items{
  9569. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9570. {"hello", "world", "", ""},
  9571. };
  9572. for (const char &c : " \t\r\n") {
  9573. auto res =
  9574. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9575. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9576. ASSERT_FALSE(res);
  9577. }
  9578. }
  9579. TEST(MultipartFormDataTest, PutFormData) {
  9580. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9581. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9582. const ContentReader &content_reader) {
  9583. if (req.is_multipart_form_data()) {
  9584. std::vector<FormData> items;
  9585. content_reader(
  9586. [&](const FormData &file) {
  9587. items.push_back(file);
  9588. return true;
  9589. },
  9590. [&](const char *data, size_t data_length) {
  9591. items.back().content.append(data, data_length);
  9592. return true;
  9593. });
  9594. EXPECT_TRUE(std::string(items[0].name) == "document");
  9595. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9596. EXPECT_TRUE(items[0].filename == "2MB_data");
  9597. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9598. EXPECT_TRUE(items[1].name == "hello");
  9599. EXPECT_TRUE(items[1].content == "world");
  9600. EXPECT_TRUE(items[1].filename == "");
  9601. EXPECT_TRUE(items[1].content_type == "");
  9602. } else {
  9603. std::string body;
  9604. content_reader([&](const char *data, size_t data_length) {
  9605. body.append(data, data_length);
  9606. return true;
  9607. });
  9608. }
  9609. });
  9610. auto port = svr.bind_to_any_port("localhost");
  9611. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9612. auto se = detail::scope_exit([&] {
  9613. svr.stop();
  9614. t.join();
  9615. ASSERT_FALSE(svr.is_running());
  9616. });
  9617. svr.wait_until_ready();
  9618. {
  9619. std::string data(1024 * 1024 * 2, '&');
  9620. std::stringstream buffer;
  9621. buffer << data;
  9622. SSLClient cli("localhost", port);
  9623. cli.enable_server_certificate_verification(false);
  9624. UploadFormDataItems items{
  9625. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9626. {"hello", "world", "", ""},
  9627. };
  9628. auto res = cli.Put("/put", items);
  9629. ASSERT_TRUE(res);
  9630. ASSERT_EQ(StatusCode::OK_200, res->status);
  9631. }
  9632. }
  9633. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  9634. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9635. svr.Put("/put_customboundary",
  9636. [&](const Request &req, const Response & /*res*/,
  9637. const ContentReader &content_reader) {
  9638. if (req.is_multipart_form_data()) {
  9639. std::vector<FormData> items;
  9640. content_reader(
  9641. [&](const FormData &file) {
  9642. items.push_back(file);
  9643. return true;
  9644. },
  9645. [&](const char *data, size_t data_length) {
  9646. items.back().content.append(data, data_length);
  9647. return true;
  9648. });
  9649. EXPECT_TRUE(std::string(items[0].name) == "document");
  9650. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9651. EXPECT_TRUE(items[0].filename == "2MB_data");
  9652. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9653. EXPECT_TRUE(items[1].name == "hello");
  9654. EXPECT_TRUE(items[1].content == "world");
  9655. EXPECT_TRUE(items[1].filename == "");
  9656. EXPECT_TRUE(items[1].content_type == "");
  9657. } else {
  9658. std::string body;
  9659. content_reader([&](const char *data, size_t data_length) {
  9660. body.append(data, data_length);
  9661. return true;
  9662. });
  9663. }
  9664. });
  9665. auto port = svr.bind_to_any_port("localhost");
  9666. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9667. auto se = detail::scope_exit([&] {
  9668. svr.stop();
  9669. t.join();
  9670. ASSERT_FALSE(svr.is_running());
  9671. });
  9672. svr.wait_until_ready();
  9673. {
  9674. std::string data(1024 * 1024 * 2, '&');
  9675. std::stringstream buffer;
  9676. buffer << data;
  9677. SSLClient cli("localhost", port);
  9678. cli.enable_server_certificate_verification(false);
  9679. UploadFormDataItems items{
  9680. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9681. {"hello", "world", "", ""},
  9682. };
  9683. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  9684. ASSERT_TRUE(res);
  9685. ASSERT_EQ(StatusCode::OK_200, res->status);
  9686. }
  9687. }
  9688. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  9689. std::string data(1024 * 1024 * 2, '&');
  9690. std::stringstream buffer;
  9691. buffer << data;
  9692. Client cli("https://localhost:8080");
  9693. cli.enable_server_certificate_verification(false);
  9694. UploadFormDataItems items{
  9695. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9696. {"hello", "world", "", ""},
  9697. };
  9698. for (const char &c : " \t\r\n") {
  9699. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  9700. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9701. ASSERT_FALSE(res);
  9702. }
  9703. }
  9704. TEST(MultipartFormDataTest, AlternateFilename) {
  9705. auto handled = false;
  9706. Server svr;
  9707. svr.Post("/test", [&](const Request &req, Response &res) {
  9708. ASSERT_EQ(2u, req.form.files.size());
  9709. ASSERT_EQ(1u, req.form.fields.size());
  9710. // Test files
  9711. const auto &file1 = req.form.get_file("file1");
  9712. ASSERT_EQ("file1", file1.name);
  9713. ASSERT_EQ("A.txt", file1.filename);
  9714. ASSERT_EQ("text/plain", file1.content_type);
  9715. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  9716. const auto &file2 = req.form.get_file("file2");
  9717. ASSERT_EQ("file2", file2.name);
  9718. ASSERT_EQ("a.html", file2.filename);
  9719. ASSERT_EQ("text/html", file2.content_type);
  9720. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  9721. file2.content);
  9722. // Test text field
  9723. const auto &text = req.form.get_field("text");
  9724. ASSERT_EQ("text default", text);
  9725. res.set_content("ok", "text/plain");
  9726. handled = true;
  9727. });
  9728. thread t = thread([&] { svr.listen(HOST, PORT); });
  9729. auto se = detail::scope_exit([&] {
  9730. svr.stop();
  9731. t.join();
  9732. ASSERT_FALSE(svr.is_running());
  9733. ASSERT_TRUE(handled);
  9734. });
  9735. svr.wait_until_ready();
  9736. auto req = "POST /test HTTP/1.1\r\n"
  9737. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9738. "Content-Length: 399\r\n"
  9739. "\r\n"
  9740. "----------\r\n"
  9741. "Content-Disposition: form-data; name=\"text\"\r\n"
  9742. "\r\n"
  9743. "text default\r\n"
  9744. "----------\r\n"
  9745. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  9746. "filename=\"a.txt\"; name=\"file1\"\r\n"
  9747. "Content-Type: text/plain\r\n"
  9748. "\r\n"
  9749. "Content of a.txt.\r\n"
  9750. "\r\n"
  9751. "----------\r\n"
  9752. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  9753. "\"a.html\"\r\n"
  9754. "Content-Type: text/html\r\n"
  9755. "\r\n"
  9756. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  9757. "\r\n"
  9758. "------------\r\n";
  9759. ASSERT_TRUE(send_request(1, req));
  9760. }
  9761. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  9762. auto handled = false;
  9763. Server svr;
  9764. svr.Post("/test", [&](const Request &req, Response &res) {
  9765. // Case-insensitive "utf-8''" prefix with a long value
  9766. const auto &file = req.form.get_file("file1");
  9767. ASSERT_EQ("file1", file.name);
  9768. // 8000 chars exercises both the Content-Disposition parser and the
  9769. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  9770. // Prior to the fix, std::regex_match on this header would cause O(N)
  9771. // stack recursion in libstdc++, leading to SIGSEGV.
  9772. std::string expected_filename(8000, 'A');
  9773. ASSERT_EQ(expected_filename, file.filename);
  9774. res.set_content("ok", "text/plain");
  9775. handled = true;
  9776. });
  9777. thread t = thread([&] { svr.listen(HOST, PORT); });
  9778. auto se = detail::scope_exit([&] {
  9779. svr.stop();
  9780. t.join();
  9781. ASSERT_FALSE(svr.is_running());
  9782. ASSERT_TRUE(handled);
  9783. });
  9784. svr.wait_until_ready();
  9785. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  9786. // Regression test for GHSA-qq6v-r583-3h69
  9787. std::string long_filename(8000, 'A');
  9788. std::string body = "----------\r\n"
  9789. "Content-Disposition: form-data; name=\"file1\"; "
  9790. "filename*=\"Utf-8''" +
  9791. long_filename +
  9792. "\"\r\n"
  9793. "\r\n"
  9794. "hello\r\n"
  9795. "------------\r\n";
  9796. auto req = "POST /test HTTP/1.1\r\n"
  9797. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9798. "Content-Length: " +
  9799. std::to_string(body.size()) + "\r\n\r\n" + body;
  9800. ASSERT_TRUE(send_request(1, req));
  9801. }
  9802. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  9803. auto handled = false;
  9804. Server svr;
  9805. svr.Post("/test", [&](const Request &req, Response &) {
  9806. ASSERT_EQ(2u, req.form.fields.size());
  9807. const auto &text1 = req.form.get_field("text1");
  9808. ASSERT_EQ("text1", text1);
  9809. const auto &text2 = req.form.get_field("text2");
  9810. ASSERT_EQ("text2", text2);
  9811. handled = true;
  9812. });
  9813. thread t = thread([&] { svr.listen(HOST, PORT); });
  9814. auto se = detail::scope_exit([&] {
  9815. svr.stop();
  9816. t.join();
  9817. ASSERT_FALSE(svr.is_running());
  9818. ASSERT_TRUE(handled);
  9819. });
  9820. svr.wait_until_ready();
  9821. auto req = "POST /test HTTP/1.1\r\n"
  9822. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9823. "Content-Length: 146\r\n"
  9824. "\r\n----------\r\n"
  9825. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9826. "\r\n"
  9827. "text1"
  9828. "\r\n----------\r\n"
  9829. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9830. "\r\n"
  9831. "text2"
  9832. "\r\n------------";
  9833. std::string response;
  9834. ASSERT_TRUE(send_request(1, req, &response));
  9835. ASSERT_EQ("200", response.substr(9, 3));
  9836. }
  9837. TEST(MultipartFormDataTest, ContentLength) {
  9838. auto handled = false;
  9839. Server svr;
  9840. svr.Post("/test", [&](const Request &req, Response &) {
  9841. ASSERT_EQ(2u, req.form.fields.size());
  9842. const auto &text1 = req.form.get_field("text1");
  9843. ASSERT_EQ("text1", text1);
  9844. const auto &text2 = req.form.get_field("text2");
  9845. ASSERT_EQ("text2", text2);
  9846. handled = true;
  9847. });
  9848. thread t = thread([&] { svr.listen(HOST, PORT); });
  9849. auto se = detail::scope_exit([&] {
  9850. svr.stop();
  9851. t.join();
  9852. ASSERT_FALSE(svr.is_running());
  9853. ASSERT_TRUE(handled);
  9854. });
  9855. svr.wait_until_ready();
  9856. auto req = "POST /test HTTP/1.1\r\n"
  9857. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9858. "Content-Length: 167\r\n"
  9859. "\r\n----------\r\n"
  9860. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9861. "Content-Length: 5\r\n"
  9862. "\r\n"
  9863. "text1"
  9864. "\r\n----------\r\n"
  9865. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9866. "\r\n"
  9867. "text2"
  9868. "\r\n------------\r\n";
  9869. std::string response;
  9870. ASSERT_TRUE(send_request(1, req, &response));
  9871. ASSERT_EQ("200", response.substr(9, 3));
  9872. }
  9873. TEST(MultipartFormDataTest, AccessPartHeaders) {
  9874. auto handled = false;
  9875. Server svr;
  9876. svr.Post("/test", [&](const Request &req, Response &) {
  9877. ASSERT_EQ(2u, req.form.fields.size());
  9878. const auto &text1 = req.form.get_field("text1");
  9879. ASSERT_EQ("text1", text1);
  9880. // TODO: Add header access for text fields if needed
  9881. const auto &text2 = req.form.get_field("text2");
  9882. ASSERT_EQ("text2", text2);
  9883. // TODO: Header access for text fields needs to be implemented
  9884. // auto &headers = it->second.headers;
  9885. // ASSERT_EQ(3U, headers.size());
  9886. // auto custom_header = headers.find("x-whatever");
  9887. // ASSERT_TRUE(custom_header != headers.end());
  9888. // ASSERT_NE("customvalue", custom_header->second);
  9889. // ASSERT_EQ("CustomValue", custom_header->second);
  9890. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  9891. handled = true;
  9892. });
  9893. thread t = thread([&] { svr.listen(HOST, PORT); });
  9894. auto se = detail::scope_exit([&] {
  9895. svr.stop();
  9896. t.join();
  9897. ASSERT_FALSE(svr.is_running());
  9898. ASSERT_TRUE(handled);
  9899. });
  9900. svr.wait_until_ready();
  9901. auto req = "POST /test HTTP/1.1\r\n"
  9902. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9903. "Content-Length: 232\r\n"
  9904. "\r\n----------\r\n"
  9905. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9906. "Content-Length: 5\r\n"
  9907. "X-Test: 1\r\n"
  9908. "\r\n"
  9909. "text1"
  9910. "\r\n----------\r\n"
  9911. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9912. "Content-Type: text/plain\r\n"
  9913. "X-Whatever: CustomValue\r\n"
  9914. "\r\n"
  9915. "text2"
  9916. "\r\n------------\r\n"
  9917. "That should be disregarded. Not even read";
  9918. std::string response;
  9919. ASSERT_TRUE(send_request(1, req, &response));
  9920. ASSERT_EQ("200", response.substr(9, 3));
  9921. }
  9922. TEST(MultipartFormDataTest, LargeHeader) {
  9923. auto handled = false;
  9924. Server svr;
  9925. svr.Post("/test", [&](const Request &req, Response &) {
  9926. ASSERT_EQ(1u, req.form.fields.size());
  9927. const auto &text = req.form.get_field("name1");
  9928. ASSERT_EQ("text1", text);
  9929. handled = true;
  9930. });
  9931. thread t = thread([&] { svr.listen(HOST, PORT); });
  9932. auto se = detail::scope_exit([&] {
  9933. svr.stop();
  9934. t.join();
  9935. ASSERT_FALSE(svr.is_running());
  9936. ASSERT_TRUE(handled);
  9937. });
  9938. svr.wait_until_ready();
  9939. auto boundary = std::string("cpp-httplib-multipart-data");
  9940. std::string content = "--" + boundary +
  9941. "\r\n"
  9942. "Content-Disposition: form-data; name=\"name1\"\r\n"
  9943. "\r\n"
  9944. "text1\r\n"
  9945. "--" +
  9946. boundary + "--\r\n";
  9947. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  9948. "Content-Type: multipart/form-data;boundary=" +
  9949. boundary +
  9950. "\r\n"
  9951. "Content-Length: " +
  9952. std::to_string(content.size()) +
  9953. "\r\n"
  9954. "Dummy-Header: ";
  9955. std::string header_suffix = "\r\n"
  9956. "\r\n";
  9957. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  9958. size_t header_dummy_size =
  9959. read_buff_size -
  9960. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  9961. auto header_dummy = std::string(header_dummy_size, '@');
  9962. auto req = header_prefix + header_dummy + header_suffix + content;
  9963. std::string response;
  9964. ASSERT_TRUE(send_request(1, req, &response));
  9965. ASSERT_EQ("200", response.substr(9, 3));
  9966. }
  9967. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  9968. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  9969. // (not chunked Transfer-Encoding) after the streaming refactor.
  9970. auto handled = false;
  9971. Server svr;
  9972. svr.Post("/upload", [&](const Request &req, Response &res) {
  9973. auto cl_it = req.headers.find("Content-Length");
  9974. EXPECT_TRUE(cl_it != req.headers.end());
  9975. auto te_it = req.headers.find("Transfer-Encoding");
  9976. EXPECT_TRUE(te_it == req.headers.end());
  9977. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  9978. res.set_content("ok", "text/plain");
  9979. handled = true;
  9980. });
  9981. auto port = svr.bind_to_any_port(HOST);
  9982. auto t = thread([&] { svr.listen_after_bind(); });
  9983. auto se = detail::scope_exit([&] {
  9984. svr.stop();
  9985. t.join();
  9986. ASSERT_FALSE(svr.is_running());
  9987. ASSERT_TRUE(handled);
  9988. });
  9989. svr.wait_until_ready();
  9990. UploadFormDataItems items = {
  9991. {"field1", "hello", "", "text/plain"},
  9992. {"file1", "world", "test.txt", "application/octet-stream"},
  9993. };
  9994. Client cli(HOST, port);
  9995. auto res = cli.Post("/upload", {}, items);
  9996. ASSERT_TRUE(res);
  9997. EXPECT_EQ(StatusCode::OK_200, res->status);
  9998. }
  9999. TEST(MultipartFormDataTest, MakeFileProvider) {
  10000. // Verify make_file_provider sends a file's contents correctly.
  10001. const std::string file_content(4096, 'Z');
  10002. const std::string tmp_path = "/tmp/httplib_test_make_file_provider.bin";
  10003. {
  10004. std::ofstream ofs(tmp_path, std::ios::binary);
  10005. ofs.write(file_content.data(),
  10006. static_cast<std::streamsize>(file_content.size()));
  10007. }
  10008. auto handled = false;
  10009. Server svr;
  10010. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  10011. const ContentReader &content_reader) {
  10012. ASSERT_TRUE(req.is_multipart_form_data());
  10013. std::vector<FormData> items;
  10014. content_reader(
  10015. [&](const FormData &file) {
  10016. items.push_back(file);
  10017. return true;
  10018. },
  10019. [&](const char *data, size_t data_length) {
  10020. items.back().content.append(data, data_length);
  10021. return true;
  10022. });
  10023. ASSERT_EQ(1u, items.size());
  10024. EXPECT_EQ("myfile", items[0].name);
  10025. EXPECT_EQ("data.bin", items[0].filename);
  10026. EXPECT_EQ("application/octet-stream", items[0].content_type);
  10027. EXPECT_EQ(file_content, items[0].content);
  10028. handled = true;
  10029. });
  10030. auto port = svr.bind_to_any_port(HOST);
  10031. auto t = thread([&] { svr.listen_after_bind(); });
  10032. auto se = detail::scope_exit([&] {
  10033. svr.stop();
  10034. t.join();
  10035. ASSERT_FALSE(svr.is_running());
  10036. ASSERT_TRUE(handled);
  10037. std::remove(tmp_path.c_str());
  10038. });
  10039. svr.wait_until_ready();
  10040. FormDataProviderItems providers;
  10041. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  10042. "application/octet-stream"));
  10043. Client cli(HOST, port);
  10044. auto res = cli.Post("/upload", {}, {}, providers);
  10045. ASSERT_TRUE(res);
  10046. EXPECT_EQ(StatusCode::OK_200, res->status);
  10047. }
  10048. TEST(MakeFileBodyTest, Basic) {
  10049. const std::string file_content(4096, 'Z');
  10050. const std::string tmp_path = "/tmp/httplib_test_make_file_body.bin";
  10051. {
  10052. std::ofstream ofs(tmp_path, std::ios::binary);
  10053. ofs.write(file_content.data(),
  10054. static_cast<std::streamsize>(file_content.size()));
  10055. }
  10056. auto handled = false;
  10057. Server svr;
  10058. svr.Post("/upload", [&](const Request &req, Response &res) {
  10059. EXPECT_EQ(file_content, req.body);
  10060. handled = true;
  10061. res.status = StatusCode::OK_200;
  10062. });
  10063. auto port = svr.bind_to_any_port(HOST);
  10064. auto t = thread([&] { svr.listen_after_bind(); });
  10065. auto se = detail::scope_exit([&] {
  10066. svr.stop();
  10067. t.join();
  10068. ASSERT_FALSE(svr.is_running());
  10069. ASSERT_TRUE(handled);
  10070. std::remove(tmp_path.c_str());
  10071. });
  10072. svr.wait_until_ready();
  10073. auto fb = make_file_body(tmp_path);
  10074. ASSERT_GT(fb.first, 0u);
  10075. Client cli(HOST, port);
  10076. auto res =
  10077. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  10078. ASSERT_TRUE(res);
  10079. EXPECT_EQ(StatusCode::OK_200, res->status);
  10080. }
  10081. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  10082. static constexpr unsigned int number_of_tasks{1000000};
  10083. std::atomic_uint count{0};
  10084. std::unique_ptr<TaskQueue> task_queue{
  10085. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  10086. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10087. auto queued = task_queue->enqueue(
  10088. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  10089. EXPECT_TRUE(queued);
  10090. }
  10091. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10092. task_queue->shutdown();
  10093. #else
  10094. EXPECT_NO_THROW(task_queue->shutdown());
  10095. #endif
  10096. EXPECT_EQ(number_of_tasks, count.load());
  10097. }
  10098. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  10099. static constexpr unsigned int number_of_tasks{1000000};
  10100. static constexpr unsigned int qlimit{2};
  10101. unsigned int queued_count{0};
  10102. std::atomic_uint count{0};
  10103. std::unique_ptr<TaskQueue> task_queue{
  10104. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  10105. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10106. if (task_queue->enqueue(
  10107. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  10108. queued_count++;
  10109. }
  10110. }
  10111. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10112. task_queue->shutdown();
  10113. #else
  10114. EXPECT_NO_THROW(task_queue->shutdown());
  10115. #endif
  10116. EXPECT_EQ(queued_count, count.load());
  10117. EXPECT_TRUE(queued_count <= number_of_tasks);
  10118. EXPECT_TRUE(queued_count >= qlimit);
  10119. }
  10120. TEST(TaskQueueTest, MaxQueuedRequests) {
  10121. static constexpr unsigned int qlimit{3};
  10122. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  10123. std::condition_variable sem_cv;
  10124. std::mutex sem_mtx;
  10125. int credits = 0;
  10126. bool queued;
  10127. /* Fill up the queue with tasks that will block until we give them credits to
  10128. * complete. */
  10129. for (unsigned int n = 0; n <= qlimit;) {
  10130. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  10131. std::unique_lock<std::mutex> lock(sem_mtx);
  10132. while (credits <= 0) {
  10133. sem_cv.wait(lock);
  10134. }
  10135. /* Consume the credit and signal the test code if they are all gone. */
  10136. if (--credits == 0) { sem_cv.notify_one(); }
  10137. });
  10138. if (n < qlimit) {
  10139. /* The first qlimit enqueues must succeed. */
  10140. EXPECT_TRUE(queued);
  10141. } else {
  10142. /* The last one will succeed only when the worker thread
  10143. * starts and dequeues the first blocking task. Although
  10144. * not necessary for the correctness of this test, we sleep for
  10145. * a short while to avoid busy waiting. */
  10146. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10147. }
  10148. if (queued) { n++; }
  10149. }
  10150. /* Further enqueues must fail since the queue is full. */
  10151. for (auto i = 0; i < 4; i++) {
  10152. queued = task_queue->enqueue([] {});
  10153. EXPECT_FALSE(queued);
  10154. }
  10155. /* Give the credits to allow the previous tasks to complete. */
  10156. {
  10157. std::unique_lock<std::mutex> lock(sem_mtx);
  10158. credits += qlimit + 1;
  10159. }
  10160. sem_cv.notify_all();
  10161. /* Wait for all the credits to be consumed. */
  10162. {
  10163. std::unique_lock<std::mutex> lock(sem_mtx);
  10164. while (credits > 0) {
  10165. sem_cv.wait(lock);
  10166. }
  10167. }
  10168. /* Check that we are able again to enqueue at least qlimit tasks. */
  10169. for (unsigned int i = 0; i < qlimit; i++) {
  10170. queued = task_queue->enqueue([] {});
  10171. EXPECT_TRUE(queued);
  10172. }
  10173. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10174. task_queue->shutdown();
  10175. #else
  10176. EXPECT_NO_THROW(task_queue->shutdown());
  10177. #endif
  10178. }
  10179. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  10180. Server svr;
  10181. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10182. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  10183. });
  10184. svr.Get("/hello", [](const Request &req, Response &res) {
  10185. res.set_content(req.get_param_value("key"), "text/plain");
  10186. });
  10187. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10188. auto se = detail::scope_exit([&] {
  10189. svr.stop();
  10190. thread.join();
  10191. ASSERT_FALSE(svr.is_running());
  10192. });
  10193. svr.wait_until_ready();
  10194. {
  10195. Client cli(HOST, PORT);
  10196. cli.set_follow_location(true);
  10197. auto res = cli.Get("/");
  10198. ASSERT_TRUE(res);
  10199. EXPECT_EQ(StatusCode::OK_200, res->status);
  10200. EXPECT_EQ("val&key2=val2", res->body);
  10201. }
  10202. }
  10203. #endif
  10204. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  10205. Server svr;
  10206. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10207. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  10208. });
  10209. svr.Get("/hello", [](const Request &req, Response &res) {
  10210. res.set_content(req.get_param_value("key"), "text/plain");
  10211. });
  10212. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10213. auto se = detail::scope_exit([&] {
  10214. svr.stop();
  10215. thread.join();
  10216. ASSERT_FALSE(svr.is_running());
  10217. });
  10218. svr.wait_until_ready();
  10219. {
  10220. Client cli(HOST, PORT);
  10221. cli.set_follow_location(true);
  10222. auto res = cli.Get("/");
  10223. ASSERT_TRUE(res);
  10224. EXPECT_EQ(StatusCode::OK_200, res->status);
  10225. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  10226. }
  10227. }
  10228. #ifdef CPPHTTPLIB_SSL_ENABLED
  10229. TEST(RedirectTest, Issue2185_Online) {
  10230. SSLClient client("github.com");
  10231. client.set_follow_location(true);
  10232. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  10233. "Coollab-Windows.zip");
  10234. ASSERT_TRUE(res);
  10235. EXPECT_EQ(StatusCode::OK_200, res->status);
  10236. EXPECT_EQ(9920427U, res->body.size());
  10237. }
  10238. #endif
  10239. TEST(VulnerabilityTest, CRLFInjection) {
  10240. Server svr;
  10241. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  10242. res.set_content("Hello 1", "text/plain");
  10243. });
  10244. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  10245. res.set_content("Hello 2", "text/plain");
  10246. });
  10247. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  10248. res.set_content("Hello 3", "text/plain");
  10249. });
  10250. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  10251. res.set_content("Hello 4", "text/plain");
  10252. });
  10253. svr.set_logger([](const Request &req, const Response & /*res*/) {
  10254. for (const auto &x : req.headers) {
  10255. auto key = x.first;
  10256. EXPECT_STRNE("evil", key.c_str());
  10257. }
  10258. });
  10259. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10260. auto se = detail::scope_exit([&] {
  10261. svr.stop();
  10262. thread.join();
  10263. ASSERT_FALSE(svr.is_running());
  10264. });
  10265. svr.wait_until_ready();
  10266. {
  10267. Client cli(HOST, PORT);
  10268. cli.Post("/test1", "A=B",
  10269. "application/x-www-form-urlencoded\r\nevil: hello1");
  10270. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  10271. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  10272. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  10273. }
  10274. }
  10275. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  10276. auto server_thread = std::thread([] {
  10277. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10278. default_socket_options(srv);
  10279. sockaddr_in addr{};
  10280. addr.sin_family = AF_INET;
  10281. addr.sin_port = htons(PORT + 1);
  10282. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10283. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10284. ::listen(srv, 1);
  10285. sockaddr_in cli_addr{};
  10286. socklen_t cli_len = sizeof(cli_addr);
  10287. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10288. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  10289. std::string buf_all;
  10290. char buf[2048];
  10291. ssize_t n;
  10292. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  10293. buf_all.append(buf, static_cast<size_t>(n));
  10294. size_t pos;
  10295. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  10296. auto request_block = buf_all.substr(0, pos + 4); // include separator
  10297. auto e = request_block.find("\r\n");
  10298. if (e != std::string::npos) {
  10299. auto request_line = request_block.substr(0, e);
  10300. std::string msg =
  10301. "CRLF injection detected in request line: '" + request_line + "'";
  10302. EXPECT_FALSE(true) << msg;
  10303. }
  10304. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  10305. ::send(cli,
  10306. #ifdef _WIN32
  10307. static_cast<const char *>(resp.c_str()),
  10308. static_cast<int>(resp.size()),
  10309. #else
  10310. resp.c_str(), resp.size(),
  10311. #endif
  10312. 0);
  10313. buf_all.erase(0, pos + 4);
  10314. }
  10315. }
  10316. detail::close_socket(cli);
  10317. detail::close_socket(srv);
  10318. });
  10319. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10320. auto cli = Client("127.0.0.1", PORT + 1);
  10321. auto headers = Headers{
  10322. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  10323. {"Connection", "keep-alive"}};
  10324. auto res = cli.Get("/hi", headers);
  10325. EXPECT_FALSE(res);
  10326. EXPECT_EQ(Error::InvalidHeaders, res.error());
  10327. server_thread.join();
  10328. }
  10329. TEST(PathParamsTest, StaticMatch) {
  10330. const auto pattern = "/users/all";
  10331. detail::PathParamsMatcher matcher(pattern);
  10332. Request request;
  10333. request.path = "/users/all";
  10334. ASSERT_TRUE(matcher.match(request));
  10335. std::unordered_map<std::string, std::string> expected_params = {};
  10336. EXPECT_EQ(request.path_params, expected_params);
  10337. }
  10338. TEST(PathParamsTest, StaticMismatch) {
  10339. const auto pattern = "/users/all";
  10340. detail::PathParamsMatcher matcher(pattern);
  10341. Request request;
  10342. request.path = "/users/1";
  10343. ASSERT_FALSE(matcher.match(request));
  10344. }
  10345. TEST(PathParamsTest, SingleParamInTheMiddle) {
  10346. const auto pattern = "/users/:id/subscriptions";
  10347. detail::PathParamsMatcher matcher(pattern);
  10348. Request request;
  10349. request.path = "/users/42/subscriptions";
  10350. ASSERT_TRUE(matcher.match(request));
  10351. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10352. EXPECT_EQ(request.path_params, expected_params);
  10353. }
  10354. TEST(PathParamsTest, SingleParamInTheEnd) {
  10355. const auto pattern = "/users/:id";
  10356. detail::PathParamsMatcher matcher(pattern);
  10357. Request request;
  10358. request.path = "/users/24";
  10359. ASSERT_TRUE(matcher.match(request));
  10360. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  10361. EXPECT_EQ(request.path_params, expected_params);
  10362. }
  10363. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  10364. const auto pattern = "/users/:id/";
  10365. detail::PathParamsMatcher matcher(pattern);
  10366. Request request;
  10367. request.path = "/users/42/";
  10368. ASSERT_TRUE(matcher.match(request));
  10369. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10370. EXPECT_EQ(request.path_params, expected_params);
  10371. }
  10372. TEST(PathParamsTest, EmptyParam) {
  10373. const auto pattern = "/users/:id/";
  10374. detail::PathParamsMatcher matcher(pattern);
  10375. Request request;
  10376. request.path = "/users//";
  10377. ASSERT_TRUE(matcher.match(request));
  10378. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10379. EXPECT_EQ(request.path_params, expected_params);
  10380. }
  10381. TEST(PathParamsTest, FragmentMismatch) {
  10382. const auto pattern = "/users/:id/";
  10383. detail::PathParamsMatcher matcher(pattern);
  10384. Request request;
  10385. request.path = "/admins/24/";
  10386. ASSERT_FALSE(matcher.match(request));
  10387. }
  10388. TEST(PathParamsTest, ExtraFragments) {
  10389. const auto pattern = "/users/:id";
  10390. detail::PathParamsMatcher matcher(pattern);
  10391. Request request;
  10392. request.path = "/users/42/subscriptions";
  10393. ASSERT_FALSE(matcher.match(request));
  10394. }
  10395. TEST(PathParamsTest, MissingTrailingParam) {
  10396. const auto pattern = "/users/:id";
  10397. detail::PathParamsMatcher matcher(pattern);
  10398. Request request;
  10399. request.path = "/users";
  10400. ASSERT_FALSE(matcher.match(request));
  10401. }
  10402. TEST(PathParamsTest, MissingParamInTheMiddle) {
  10403. const auto pattern = "/users/:id/subscriptions";
  10404. detail::PathParamsMatcher matcher(pattern);
  10405. Request request;
  10406. request.path = "/users/subscriptions";
  10407. ASSERT_FALSE(matcher.match(request));
  10408. }
  10409. TEST(PathParamsTest, MultipleParams) {
  10410. const auto pattern = "/users/:userid/subscriptions/:subid";
  10411. detail::PathParamsMatcher matcher(pattern);
  10412. Request request;
  10413. request.path = "/users/42/subscriptions/2";
  10414. ASSERT_TRUE(matcher.match(request));
  10415. std::unordered_map<std::string, std::string> expected_params = {
  10416. {"userid", "42"}, {"subid", "2"}};
  10417. EXPECT_EQ(request.path_params, expected_params);
  10418. }
  10419. TEST(PathParamsTest, SequenceOfParams) {
  10420. const auto pattern = "/values/:x/:y/:z";
  10421. detail::PathParamsMatcher matcher(pattern);
  10422. Request request;
  10423. request.path = "/values/1/2/3";
  10424. ASSERT_TRUE(matcher.match(request));
  10425. std::unordered_map<std::string, std::string> expected_params = {
  10426. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  10427. EXPECT_EQ(request.path_params, expected_params);
  10428. }
  10429. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  10430. const auto pattern = "/prefix:suffix";
  10431. detail::PathParamsMatcher matcher(pattern);
  10432. Request request;
  10433. request.path = "/prefix:suffix";
  10434. ASSERT_TRUE(matcher.match(request));
  10435. const std::unordered_map<std::string, std::string> expected_params = {};
  10436. EXPECT_EQ(request.path_params, expected_params);
  10437. }
  10438. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  10439. // If ipv6 regex working, regex match codepath is taken.
  10440. // else port will default to 80 in Client impl
  10441. int clientImplMagicPort = 80;
  10442. int port = 4321;
  10443. // above ports must be different to avoid false negative
  10444. EXPECT_NE(clientImplMagicPort, port);
  10445. std::string ipV6TestURL = "http://[ff06::c3]";
  10446. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  10447. CLIENT_PRIVATE_KEY_FILE);
  10448. EXPECT_EQ(cli.port(), port);
  10449. }
  10450. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  10451. auto file_path = "./www/dir/index.html";
  10452. auto dir_path = "./www/dir";
  10453. detail::FileStat stat_file(file_path);
  10454. EXPECT_TRUE(stat_file.is_file());
  10455. EXPECT_FALSE(stat_file.is_dir());
  10456. detail::FileStat stat_dir(dir_path);
  10457. EXPECT_FALSE(stat_dir.is_file());
  10458. EXPECT_TRUE(stat_dir.is_dir());
  10459. }
  10460. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  10461. // IPv4 with default HTTP port (80)
  10462. EXPECT_EQ("example.com",
  10463. detail::make_host_and_port_string("example.com", 80, false));
  10464. // IPv4 with default HTTPS port (443)
  10465. EXPECT_EQ("example.com",
  10466. detail::make_host_and_port_string("example.com", 443, true));
  10467. // IPv4 with non-default HTTP port
  10468. EXPECT_EQ("example.com:8080",
  10469. detail::make_host_and_port_string("example.com", 8080, false));
  10470. // IPv4 with non-default HTTPS port
  10471. EXPECT_EQ("example.com:8443",
  10472. detail::make_host_and_port_string("example.com", 8443, true));
  10473. // IPv6 with default HTTP port (80)
  10474. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  10475. // IPv6 with default HTTPS port (443)
  10476. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  10477. // IPv6 with non-default HTTP port
  10478. EXPECT_EQ("[::1]:8080",
  10479. detail::make_host_and_port_string("::1", 8080, false));
  10480. // IPv6 with non-default HTTPS port
  10481. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  10482. // IPv6 full address with default port
  10483. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  10484. detail::make_host_and_port_string(
  10485. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  10486. // IPv6 full address with non-default port
  10487. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  10488. detail::make_host_and_port_string(
  10489. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  10490. // IPv6 localhost with non-default port
  10491. EXPECT_EQ("[::1]:3000",
  10492. detail::make_host_and_port_string("::1", 3000, false));
  10493. // IPv6 with zone ID (link-local address) with default port
  10494. EXPECT_EQ("[fe80::1%eth0]",
  10495. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  10496. // IPv6 with zone ID (link-local address) with non-default port
  10497. EXPECT_EQ("[fe80::1%eth0]:8080",
  10498. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  10499. // Edge case: Port 443 with is_ssl=false (should add port)
  10500. EXPECT_EQ("example.com:443",
  10501. detail::make_host_and_port_string("example.com", 443, false));
  10502. // Edge case: Port 80 with is_ssl=true (should add port)
  10503. EXPECT_EQ("example.com:80",
  10504. detail::make_host_and_port_string("example.com", 80, true));
  10505. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  10506. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  10507. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  10508. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  10509. // Security fix: Already bracketed IPv6 should not get double brackets
  10510. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  10511. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  10512. EXPECT_EQ("[::1]:8080",
  10513. detail::make_host_and_port_string("[::1]", 8080, false));
  10514. EXPECT_EQ("[2001:db8::1]:8080",
  10515. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  10516. EXPECT_EQ("[fe80::1%eth0]",
  10517. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  10518. EXPECT_EQ("[fe80::1%eth0]:8080",
  10519. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  10520. // Edge case: Empty host (should return as-is)
  10521. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  10522. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  10523. // This is a known limitation but shouldn't crash
  10524. EXPECT_EQ("[host:name]",
  10525. detail::make_host_and_port_string("host:name", 80, false));
  10526. // Port number edge cases (no validation, but should not crash)
  10527. EXPECT_EQ("example.com:0",
  10528. detail::make_host_and_port_string("example.com", 0, false));
  10529. EXPECT_EQ("example.com:-1",
  10530. detail::make_host_and_port_string("example.com", -1, false));
  10531. EXPECT_EQ("example.com:65535",
  10532. detail::make_host_and_port_string("example.com", 65535, false));
  10533. EXPECT_EQ("example.com:65536",
  10534. detail::make_host_and_port_string("example.com", 65536, false));
  10535. }
  10536. #ifdef CPPHTTPLIB_SSL_ENABLED
  10537. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  10538. httplib::SSLClient cli("roblox.com", 443);
  10539. cli.set_follow_location(true);
  10540. auto res = cli.Get("/");
  10541. ASSERT_TRUE(res);
  10542. EXPECT_EQ(StatusCode::OK_200, res->status);
  10543. }
  10544. #endif
  10545. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  10546. Server svr;
  10547. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10548. EXPECT_EQ(res.status, 400);
  10549. });
  10550. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10551. auto se = detail::scope_exit([&] {
  10552. svr.stop();
  10553. thread.join();
  10554. ASSERT_FALSE(svr.is_running());
  10555. });
  10556. svr.wait_until_ready();
  10557. Client cli(HOST, PORT);
  10558. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  10559. }
  10560. TEST(InvalidHeaderCharsTest, is_field_name) {
  10561. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  10562. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  10563. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  10564. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  10565. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  10566. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  10567. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  10568. EXPECT_FALSE(detail::fields::is_field_name(""));
  10569. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  10570. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  10571. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  10572. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  10573. }
  10574. TEST(InvalidHeaderCharsTest, is_field_value) {
  10575. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  10576. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  10577. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  10578. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  10579. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  10580. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  10581. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  10582. EXPECT_TRUE(detail::fields::is_field_value(""));
  10583. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  10584. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  10585. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  10586. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  10587. EXPECT_TRUE(detail::fields::is_field_value("0"));
  10588. }
  10589. TEST(InvalidHeaderCharsTest, OnServer) {
  10590. Server svr;
  10591. svr.Get("/test_name", [&](const Request &req, Response &res) {
  10592. std::string header = "Not Set";
  10593. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10594. res.set_header(header, "value");
  10595. res.set_content("Page Content Page Content", "text/plain");
  10596. });
  10597. svr.Get("/test_value", [&](const Request &req, Response &res) {
  10598. std::string header = "Not Set";
  10599. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10600. res.set_header("X-Test", header);
  10601. res.set_content("Page Content Page Content", "text/plain");
  10602. });
  10603. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10604. auto se = detail::scope_exit([&] {
  10605. svr.stop();
  10606. thread.join();
  10607. ASSERT_FALSE(svr.is_running());
  10608. });
  10609. svr.wait_until_ready();
  10610. Client cli(HOST, PORT);
  10611. {
  10612. auto res = cli.Get(
  10613. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10614. ASSERT_TRUE(res);
  10615. EXPECT_EQ("Page Content Page Content", res->body);
  10616. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10617. }
  10618. {
  10619. auto res = cli.Get(
  10620. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10621. ASSERT_TRUE(res);
  10622. EXPECT_EQ("Page Content Page Content", res->body);
  10623. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10624. }
  10625. }
  10626. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  10627. auto handled = false;
  10628. Server svr;
  10629. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10630. thread t = thread([&] { svr.listen(HOST, PORT); });
  10631. auto se = detail::scope_exit([&] {
  10632. svr.stop();
  10633. t.join();
  10634. ASSERT_FALSE(svr.is_running());
  10635. ASSERT_FALSE(handled);
  10636. });
  10637. svr.wait_until_ready();
  10638. auto req = "POST /test HTTP/1.1\r\n"
  10639. "Content-Length: x\r\n"
  10640. "\r\n";
  10641. std::string response;
  10642. ASSERT_TRUE(send_request(1, req, &response));
  10643. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10644. response.substr(0, response.find("\r\n")));
  10645. }
  10646. #ifndef _WIN32
  10647. TEST(Expect100ContinueTest, ServerClosesConnection) {
  10648. static constexpr char reject[] = "Unauthorized";
  10649. static constexpr char accept[] = "Upload accepted";
  10650. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  10651. Server svr;
  10652. svr.set_expect_100_continue_handler(
  10653. [](const Request & /*req*/, Response &res) {
  10654. res.status = StatusCode::Unauthorized_401;
  10655. res.set_content(reject, "text/plain");
  10656. return res.status;
  10657. });
  10658. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  10659. res.set_content(accept, "text/plain");
  10660. });
  10661. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10662. auto se = detail::scope_exit([&] {
  10663. svr.stop();
  10664. thread.join();
  10665. ASSERT_FALSE(svr.is_running());
  10666. });
  10667. svr.wait_until_ready();
  10668. {
  10669. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  10670. curl_easy_init(), &curl_easy_cleanup};
  10671. ASSERT_NE(curl, nullptr);
  10672. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  10673. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  10674. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  10675. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  10676. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  10677. &curl_slist_free_all};
  10678. ASSERT_NE(list, nullptr);
  10679. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  10680. struct read_data {
  10681. size_t read_size;
  10682. size_t total_size;
  10683. } data = {0, total_size};
  10684. using read_callback_t =
  10685. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10686. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  10687. void *userdata) -> size_t {
  10688. read_data *data = (read_data *)userdata;
  10689. if (!userdata || data->read_size >= data->total_size) { return 0; }
  10690. std::fill_n(ptr, size * nmemb, 'A');
  10691. data->read_size += size * nmemb;
  10692. return size * nmemb;
  10693. };
  10694. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  10695. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  10696. std::vector<char> buffer;
  10697. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  10698. using write_callback_t =
  10699. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10700. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  10701. void *userdata) -> size_t {
  10702. std::vector<char> *buffer = (std::vector<char> *)userdata;
  10703. buffer->reserve(buffer->size() + size * nmemb + 1);
  10704. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  10705. return size * nmemb;
  10706. };
  10707. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  10708. {
  10709. const auto res = curl_easy_perform(curl.get());
  10710. ASSERT_EQ(res, CURLE_OK);
  10711. }
  10712. {
  10713. auto response_code = long{};
  10714. const auto res =
  10715. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  10716. ASSERT_EQ(res, CURLE_OK);
  10717. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  10718. }
  10719. {
  10720. auto dl = curl_off_t{};
  10721. const auto res =
  10722. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  10723. ASSERT_EQ(res, CURLE_OK);
  10724. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  10725. }
  10726. {
  10727. buffer.push_back('\0');
  10728. ASSERT_STRCASEEQ(buffer.data(), reject);
  10729. }
  10730. }
  10731. }
  10732. #endif
  10733. template <typename S, typename C>
  10734. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  10735. svr.Get("/stream", [&](const Request &, Response &res) {
  10736. auto data = new std::string("01234567890123456789");
  10737. res.set_content_provider(
  10738. data->size(), "text/plain",
  10739. [&, data](size_t offset, size_t length, DataSink &sink) {
  10740. const size_t DATA_CHUNK_SIZE = 4;
  10741. const auto &d = *data;
  10742. std::this_thread::sleep_for(std::chrono::seconds(1));
  10743. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  10744. return true;
  10745. },
  10746. [data](bool success) {
  10747. EXPECT_FALSE(success);
  10748. delete data;
  10749. });
  10750. });
  10751. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  10752. auto i = new size_t(0);
  10753. res.set_content_provider(
  10754. "text/plain",
  10755. [i](size_t, DataSink &sink) {
  10756. if (*i < 5) {
  10757. std::this_thread::sleep_for(std::chrono::seconds(1));
  10758. sink.write("abcd", 4);
  10759. (*i)++;
  10760. } else {
  10761. sink.done();
  10762. }
  10763. return true;
  10764. },
  10765. [i](bool success) {
  10766. EXPECT_FALSE(success);
  10767. delete i;
  10768. });
  10769. });
  10770. svr.Get("/chunked", [&](const Request &, Response &res) {
  10771. auto i = new size_t(0);
  10772. res.set_chunked_content_provider(
  10773. "text/plain",
  10774. [i](size_t, DataSink &sink) {
  10775. if (*i < 5) {
  10776. std::this_thread::sleep_for(std::chrono::seconds(1));
  10777. sink.os << "abcd";
  10778. (*i)++;
  10779. } else {
  10780. sink.done();
  10781. }
  10782. return true;
  10783. },
  10784. [i](bool success) {
  10785. EXPECT_FALSE(success);
  10786. delete i;
  10787. });
  10788. });
  10789. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10790. auto se = detail::scope_exit([&] {
  10791. svr.stop();
  10792. listen_thread.join();
  10793. ASSERT_FALSE(svr.is_running());
  10794. });
  10795. svr.wait_until_ready();
  10796. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  10797. {
  10798. auto start = std::chrono::steady_clock::now();
  10799. auto res = cli.Get("/stream");
  10800. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10801. std::chrono::steady_clock::now() - start)
  10802. .count();
  10803. ASSERT_FALSE(res);
  10804. EXPECT_EQ(Error::Read, res.error());
  10805. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10806. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10807. }
  10808. {
  10809. auto start = std::chrono::steady_clock::now();
  10810. auto res = cli.Get("/stream_without_length");
  10811. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10812. std::chrono::steady_clock::now() - start)
  10813. .count();
  10814. ASSERT_FALSE(res);
  10815. EXPECT_EQ(Error::Read, res.error());
  10816. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10817. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10818. }
  10819. {
  10820. auto start = std::chrono::steady_clock::now();
  10821. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  10822. EXPECT_EQ("abcd", string(data, data_length));
  10823. return true;
  10824. });
  10825. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10826. std::chrono::steady_clock::now() - start)
  10827. .count();
  10828. ASSERT_FALSE(res);
  10829. EXPECT_EQ(Error::Read, res.error());
  10830. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10831. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10832. }
  10833. }
  10834. TEST(MaxTimeoutTest, ContentStream) {
  10835. time_t timeout = 2000;
  10836. time_t threshold = 200;
  10837. Server svr;
  10838. Client cli("localhost", PORT);
  10839. max_timeout_test(svr, cli, timeout, threshold);
  10840. }
  10841. #ifdef CPPHTTPLIB_SSL_ENABLED
  10842. TEST(MaxTimeoutTest, ContentStreamSSL) {
  10843. time_t timeout = 2000;
  10844. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  10845. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10846. SSLClient cli("localhost", PORT);
  10847. cli.enable_server_certificate_verification(false);
  10848. max_timeout_test(svr, cli, timeout, threshold);
  10849. }
  10850. #endif
  10851. class EventDispatcher {
  10852. public:
  10853. EventDispatcher() {}
  10854. bool wait_event(DataSink *sink) {
  10855. unique_lock<mutex> lk(m_);
  10856. int id = id_;
  10857. // Wait with timeout to prevent hanging if client disconnects
  10858. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  10859. [&] { return cid_ == id; })) {
  10860. return false; // Timeout occurred
  10861. }
  10862. sink->write(message_.data(), message_.size());
  10863. return true;
  10864. }
  10865. void send_event(const string &message) {
  10866. lock_guard<mutex> lk(m_);
  10867. cid_ = id_++;
  10868. message_ = message;
  10869. cv_.notify_all();
  10870. }
  10871. private:
  10872. mutex m_;
  10873. condition_variable cv_;
  10874. atomic_int id_{0};
  10875. atomic_int cid_{-1};
  10876. string message_;
  10877. };
  10878. TEST(ClientInThreadTest, Issue2068) {
  10879. EventDispatcher ed;
  10880. Server svr;
  10881. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  10882. res.set_chunked_content_provider("text/event-stream",
  10883. [&](size_t /*offset*/, DataSink &sink) {
  10884. return ed.wait_event(&sink);
  10885. });
  10886. });
  10887. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10888. svr.wait_until_ready();
  10889. thread event_thread([&] {
  10890. int id = 0;
  10891. while (svr.is_running()) {
  10892. this_thread::sleep_for(chrono::milliseconds(500));
  10893. std::stringstream ss;
  10894. ss << "data: " << id << "\n\n";
  10895. ed.send_event(ss.str());
  10896. id++;
  10897. }
  10898. });
  10899. auto se = detail::scope_exit([&] {
  10900. svr.stop();
  10901. listen_thread.join();
  10902. event_thread.join();
  10903. ASSERT_FALSE(svr.is_running());
  10904. });
  10905. {
  10906. auto client = detail::make_unique<Client>(HOST, PORT);
  10907. client->set_read_timeout(std::chrono::minutes(10));
  10908. std::atomic<bool> stop{false};
  10909. std::thread t([&] {
  10910. client->Get("/event1",
  10911. [&](const char *, size_t) -> bool { return !stop; });
  10912. });
  10913. std::this_thread::sleep_for(std::chrono::seconds(2));
  10914. stop = true;
  10915. client->stop();
  10916. t.join();
  10917. // Reset client after thread has finished
  10918. client.reset();
  10919. }
  10920. }
  10921. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  10922. auto handled = false;
  10923. Server svr;
  10924. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10925. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10926. auto se = detail::scope_exit([&] {
  10927. svr.stop();
  10928. t.join();
  10929. ASSERT_FALSE(svr.is_running());
  10930. ASSERT_FALSE(handled);
  10931. });
  10932. svr.wait_until_ready();
  10933. // Two Content-Length headers with different values — must be rejected
  10934. auto req = "POST /test HTTP/1.1\r\n"
  10935. "Content-Length: 5\r\n"
  10936. "Content-Length: 10\r\n"
  10937. "\r\n"
  10938. "hello";
  10939. std::string response;
  10940. ASSERT_TRUE(send_request(1, req, &response));
  10941. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10942. response.substr(0, response.find("\r\n")));
  10943. }
  10944. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  10945. auto handled = false;
  10946. Server svr;
  10947. svr.Post("/test", [&](const Request &, Response &res) {
  10948. handled = true;
  10949. res.set_content("ok", "text/plain");
  10950. });
  10951. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10952. auto se = detail::scope_exit([&] {
  10953. svr.stop();
  10954. t.join();
  10955. ASSERT_FALSE(svr.is_running());
  10956. ASSERT_TRUE(handled);
  10957. });
  10958. svr.wait_until_ready();
  10959. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  10960. auto req = "POST /test HTTP/1.1\r\n"
  10961. "Content-Length: 5\r\n"
  10962. "Content-Length: 5\r\n"
  10963. "\r\n"
  10964. "hello";
  10965. std::string response;
  10966. ASSERT_TRUE(send_request(1, req, &response));
  10967. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  10968. }
  10969. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  10970. Server svr;
  10971. svr.Get("/", [](const Request &req, Response &res) {
  10972. EXPECT_EQ(2U, req.trailers.size());
  10973. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  10974. // Denied
  10975. EXPECT_FALSE(req.has_trailer("Content-Length"));
  10976. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  10977. // Accepted
  10978. EXPECT_TRUE(req.has_trailer("X-Hello"));
  10979. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  10980. EXPECT_TRUE(req.has_trailer("X-World"));
  10981. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  10982. res.set_content("ok", "text/plain");
  10983. });
  10984. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10985. auto se = detail::scope_exit([&] {
  10986. svr.stop();
  10987. t.join();
  10988. ASSERT_FALSE(svr.is_running());
  10989. });
  10990. svr.wait_until_ready();
  10991. const std::string req = "GET / HTTP/1.1\r\n"
  10992. "Transfer-Encoding: chunked\r\n"
  10993. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  10994. "\r\n"
  10995. "0\r\n"
  10996. "Content-Length: 10\r\n"
  10997. "Host: internal.local\r\n"
  10998. "Content-Type: malicious/content\r\n"
  10999. "Cookie: any\r\n"
  11000. "Set-Cookie: any\r\n"
  11001. "X-Forwarded-For: attacker.com\r\n"
  11002. "X-Real-Ip: 1.1.1.1\r\n"
  11003. "X-Hello: hello\r\n"
  11004. "X-World: world\r\n"
  11005. "\r\n";
  11006. std::string res;
  11007. ASSERT_TRUE(send_request(1, req, &res));
  11008. }
  11009. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  11010. Server svr;
  11011. std::string observed_remote_addr;
  11012. std::string observed_xff;
  11013. svr.Get("/ip", [&](const Request &req, Response &res) {
  11014. observed_remote_addr = req.remote_addr;
  11015. observed_xff = req.get_header_value("X-Forwarded-For");
  11016. res.set_content("ok", "text/plain");
  11017. });
  11018. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11019. auto se = detail::scope_exit([&] {
  11020. svr.stop();
  11021. t.join();
  11022. ASSERT_FALSE(svr.is_running());
  11023. });
  11024. svr.wait_until_ready();
  11025. Client cli(HOST, PORT);
  11026. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  11027. ASSERT_TRUE(res);
  11028. EXPECT_EQ(StatusCode::OK_200, res->status);
  11029. EXPECT_EQ(observed_xff, "203.0.113.66");
  11030. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11031. observed_remote_addr == "127.0.0.1");
  11032. }
  11033. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  11034. Server svr;
  11035. svr.set_trusted_proxies({"203.0.113.66"});
  11036. std::string observed_remote_addr;
  11037. std::string observed_xff;
  11038. svr.Get("/ip", [&](const Request &req, Response &res) {
  11039. observed_remote_addr = req.remote_addr;
  11040. observed_xff = req.get_header_value("X-Forwarded-For");
  11041. res.set_content("ok", "text/plain");
  11042. });
  11043. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11044. auto se = detail::scope_exit([&] {
  11045. svr.stop();
  11046. t.join();
  11047. ASSERT_FALSE(svr.is_running());
  11048. });
  11049. svr.wait_until_ready();
  11050. Client cli(HOST, PORT);
  11051. auto res = cli.Get("/ip");
  11052. ASSERT_TRUE(res);
  11053. EXPECT_EQ(StatusCode::OK_200, res->status);
  11054. EXPECT_EQ(observed_xff, "");
  11055. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11056. observed_remote_addr == "127.0.0.1");
  11057. }
  11058. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  11059. Server svr;
  11060. svr.set_trusted_proxies({"203.0.113.66"});
  11061. std::string observed_remote_addr;
  11062. std::string observed_xff;
  11063. svr.Get("/ip", [&](const Request &req, Response &res) {
  11064. observed_remote_addr = req.remote_addr;
  11065. observed_xff = req.get_header_value("X-Forwarded-For");
  11066. res.set_content("ok", "text/plain");
  11067. });
  11068. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11069. auto se = detail::scope_exit([&] {
  11070. svr.stop();
  11071. t.join();
  11072. ASSERT_FALSE(svr.is_running());
  11073. });
  11074. svr.wait_until_ready();
  11075. Client cli(HOST, PORT);
  11076. auto res =
  11077. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  11078. ASSERT_TRUE(res);
  11079. EXPECT_EQ(StatusCode::OK_200, res->status);
  11080. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  11081. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11082. }
  11083. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  11084. Server svr;
  11085. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  11086. std::string observed_remote_addr;
  11087. std::string observed_xff;
  11088. svr.Get("/ip", [&](const Request &req, Response &res) {
  11089. observed_remote_addr = req.remote_addr;
  11090. observed_xff = req.get_header_value("X-Forwarded-For");
  11091. res.set_content("ok", "text/plain");
  11092. });
  11093. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11094. auto se = detail::scope_exit([&] {
  11095. svr.stop();
  11096. t.join();
  11097. ASSERT_FALSE(svr.is_running());
  11098. });
  11099. svr.wait_until_ready();
  11100. Client cli(HOST, PORT);
  11101. auto res = cli.Get(
  11102. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11103. ASSERT_TRUE(res);
  11104. EXPECT_EQ(StatusCode::OK_200, res->status);
  11105. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11106. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11107. }
  11108. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  11109. Server svr;
  11110. svr.set_trusted_proxies({"192.0.2.45"});
  11111. std::string observed_remote_addr;
  11112. std::string observed_xff;
  11113. svr.Get("/ip", [&](const Request &req, Response &res) {
  11114. observed_remote_addr = req.remote_addr;
  11115. observed_xff = req.get_header_value("X-Forwarded-For");
  11116. res.set_content("ok", "text/plain");
  11117. });
  11118. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11119. auto se = detail::scope_exit([&] {
  11120. svr.stop();
  11121. t.join();
  11122. ASSERT_FALSE(svr.is_running());
  11123. });
  11124. svr.wait_until_ready();
  11125. Client cli(HOST, PORT);
  11126. auto res =
  11127. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  11128. ASSERT_TRUE(res);
  11129. EXPECT_EQ(StatusCode::OK_200, res->status);
  11130. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  11131. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11132. }
  11133. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  11134. Server svr;
  11135. svr.set_trusted_proxies({"192.0.2.45"});
  11136. std::string observed_remote_addr;
  11137. std::string observed_xff;
  11138. svr.Get("/ip", [&](const Request &req, Response &res) {
  11139. observed_remote_addr = req.remote_addr;
  11140. observed_xff = req.get_header_value("X-Forwarded-For");
  11141. res.set_content("ok", "text/plain");
  11142. });
  11143. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11144. auto se = detail::scope_exit([&] {
  11145. svr.stop();
  11146. t.join();
  11147. ASSERT_FALSE(svr.is_running());
  11148. });
  11149. svr.wait_until_ready();
  11150. Client cli(HOST, PORT);
  11151. auto res = cli.Get(
  11152. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11153. ASSERT_TRUE(res);
  11154. EXPECT_EQ(StatusCode::OK_200, res->status);
  11155. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11156. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11157. }
  11158. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  11159. Server svr;
  11160. svr.set_trusted_proxies({"192.0.2.45"});
  11161. std::string observed_remote_addr;
  11162. std::string observed_xff;
  11163. svr.Get("/ip", [&](const Request &req, Response &res) {
  11164. observed_remote_addr = req.remote_addr;
  11165. observed_xff = req.get_header_value("X-Forwarded-For");
  11166. res.set_content("ok", "text/plain");
  11167. });
  11168. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11169. auto se = detail::scope_exit([&] {
  11170. svr.stop();
  11171. t.join();
  11172. ASSERT_FALSE(svr.is_running());
  11173. });
  11174. svr.wait_until_ready();
  11175. std::string raw_req =
  11176. "GET /ip HTTP/1.1\r\n"
  11177. "Host: localhost\r\n"
  11178. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  11179. "Connection: close\r\n"
  11180. "\r\n";
  11181. std::string out;
  11182. ASSERT_TRUE(send_request(5, raw_req, &out));
  11183. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11184. // Header parser trims surrounding whitespace of the header value
  11185. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  11186. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11187. }
  11188. #ifndef _WIN32
  11189. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  11190. Server svr;
  11191. svr.Post("/post", [&](const Request &req, Response &res) {
  11192. res.set_content(req.body, "text/plain");
  11193. });
  11194. svr.Put("/put", [&](const Request &req, Response &res) {
  11195. res.set_content(req.body, "text/plain");
  11196. });
  11197. svr.Patch("/patch", [&](const Request &req, Response &res) {
  11198. res.set_content(req.body, "text/plain");
  11199. });
  11200. svr.Delete("/delete", [&](const Request &req, Response &res) {
  11201. res.set_content(req.body, "text/plain");
  11202. });
  11203. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11204. auto se = detail::scope_exit([&] {
  11205. svr.stop();
  11206. t.join();
  11207. ASSERT_FALSE(svr.is_running());
  11208. });
  11209. svr.wait_until_ready();
  11210. std::string resp;
  11211. // POST without Content-Length
  11212. ASSERT_TRUE(send_request(5,
  11213. "POST /post HTTP/1.1\r\n"
  11214. "Host: localhost\r\n"
  11215. "Connection: close\r\n"
  11216. "\r\n",
  11217. &resp));
  11218. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11219. // PUT without Content-Length
  11220. resp.clear();
  11221. ASSERT_TRUE(send_request(5,
  11222. "PUT /put HTTP/1.1\r\n"
  11223. "Host: localhost\r\n"
  11224. "Connection: close\r\n"
  11225. "\r\n",
  11226. &resp));
  11227. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11228. // PATCH without Content-Length
  11229. resp.clear();
  11230. ASSERT_TRUE(send_request(5,
  11231. "PATCH /patch HTTP/1.1\r\n"
  11232. "Host: localhost\r\n"
  11233. "Connection: close\r\n"
  11234. "\r\n",
  11235. &resp));
  11236. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11237. // DELETE without Content-Length
  11238. resp.clear();
  11239. ASSERT_TRUE(send_request(5,
  11240. "DELETE /delete HTTP/1.1\r\n"
  11241. "Host: localhost\r\n"
  11242. "Connection: close\r\n"
  11243. "\r\n",
  11244. &resp));
  11245. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11246. }
  11247. #endif
  11248. //==============================================================================
  11249. // open_stream() Tests
  11250. //==============================================================================
  11251. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  11252. std::string result;
  11253. char buf[8192];
  11254. ssize_t n;
  11255. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11256. result.append(buf, static_cast<size_t>(n));
  11257. }
  11258. return result;
  11259. }
  11260. // Mock stream for unit tests
  11261. class MockStream : public Stream {
  11262. public:
  11263. std::string data;
  11264. size_t pos = 0;
  11265. ssize_t error_after = -1; // -1 = no error
  11266. explicit MockStream(const std::string &d, ssize_t err = -1)
  11267. : data(d), error_after(err) {}
  11268. bool is_readable() const override { return true; }
  11269. bool wait_readable() const override { return true; }
  11270. bool wait_writable() const override { return true; }
  11271. ssize_t read(char *ptr, size_t size) override {
  11272. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  11273. if (pos >= data.size()) return 0;
  11274. size_t limit =
  11275. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  11276. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  11277. std::memcpy(ptr, data.data() + pos, to_read);
  11278. pos += to_read;
  11279. return static_cast<ssize_t>(to_read);
  11280. }
  11281. ssize_t write(const char *, size_t) override { return -1; }
  11282. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  11283. ip = "127.0.0.1";
  11284. port = 0;
  11285. }
  11286. void get_local_ip_and_port(std::string &ip, int &port) const override {
  11287. ip = "127.0.0.1";
  11288. port = 0;
  11289. }
  11290. socket_t socket() const override { return INVALID_SOCKET; }
  11291. time_t duration() const override { return 0; }
  11292. };
  11293. TEST(StreamHandleTest, Basic) {
  11294. ClientImpl::StreamHandle handle;
  11295. EXPECT_FALSE(handle.is_valid());
  11296. handle.response = detail::make_unique<Response>();
  11297. handle.error = Error::Connection;
  11298. EXPECT_FALSE(handle.is_valid());
  11299. handle.error = Error::Success;
  11300. EXPECT_TRUE(handle.is_valid());
  11301. }
  11302. TEST(BodyReaderTest, Basic) {
  11303. MockStream stream("Hello, World!");
  11304. detail::BodyReader reader;
  11305. reader.stream = &stream;
  11306. reader.content_length = 13;
  11307. char buf[32];
  11308. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  11309. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  11310. EXPECT_TRUE(reader.eof);
  11311. }
  11312. TEST(BodyReaderTest, NoStream) {
  11313. detail::BodyReader reader;
  11314. char buf[32];
  11315. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11316. EXPECT_EQ(Error::Connection, reader.last_error);
  11317. }
  11318. TEST(BodyReaderTest, Error) {
  11319. MockStream stream("Hello, World!", 5);
  11320. detail::BodyReader reader;
  11321. reader.stream = &stream;
  11322. reader.content_length = 13;
  11323. char buf[32];
  11324. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  11325. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11326. EXPECT_EQ(Error::Read, reader.last_error);
  11327. }
  11328. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  11329. // Mock-based StreamHandle tests relying on private internals are removed.
  11330. class OpenStreamTest : public ::testing::Test {
  11331. protected:
  11332. void SetUp() override {
  11333. svr_.Get("/hello", [](const Request &, Response &res) {
  11334. res.set_content("Hello World!", "text/plain");
  11335. });
  11336. svr_.Get("/large", [](const Request &, Response &res) {
  11337. res.set_content(std::string(10000, 'X'), "text/plain");
  11338. });
  11339. svr_.Get("/chunked", [](const Request &, Response &res) {
  11340. res.set_chunked_content_provider("text/plain",
  11341. [](size_t offset, DataSink &sink) {
  11342. if (offset < 15) {
  11343. sink.write("chunk", 5);
  11344. return true;
  11345. }
  11346. sink.done();
  11347. return true;
  11348. });
  11349. });
  11350. svr_.Get("/compressible", [](const Request &, Response &res) {
  11351. res.set_chunked_content_provider("text/plain", [](size_t offset,
  11352. DataSink &sink) {
  11353. if (offset < 100 * 1024) {
  11354. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  11355. sink.write(chunk.data(), chunk.size());
  11356. return true;
  11357. }
  11358. sink.done();
  11359. return true;
  11360. });
  11361. });
  11362. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  11363. [](const Request & /*req*/, Response &res) {
  11364. auto i = new int(0);
  11365. res.set_header("Trailer", "Content-Length, X-Allowed");
  11366. res.set_chunked_content_provider(
  11367. "text/plain",
  11368. [i](size_t /*offset*/, DataSink &sink) {
  11369. switch (*i) {
  11370. case 0: sink.os << "123"; break;
  11371. case 1: sink.os << "456"; break;
  11372. case 2: sink.os << "789"; break;
  11373. case 3: {
  11374. sink.done_with_trailer(
  11375. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  11376. } break;
  11377. }
  11378. (*i)++;
  11379. return true;
  11380. },
  11381. [i](bool success) {
  11382. EXPECT_TRUE(success);
  11383. delete i;
  11384. });
  11385. });
  11386. // Echo headers endpoint for header-related tests
  11387. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  11388. std::string body;
  11389. for (const auto &h : req.headers) {
  11390. body.append(h.first);
  11391. body.push_back(':');
  11392. body.append(h.second);
  11393. body.push_back('\n');
  11394. }
  11395. res.set_content(body, "text/plain");
  11396. });
  11397. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  11398. std::string body;
  11399. for (const auto &h : req.headers) {
  11400. body.append(h.first);
  11401. body.push_back(':');
  11402. body.append(h.second);
  11403. body.push_back('\n');
  11404. }
  11405. res.set_content(body, "text/plain");
  11406. });
  11407. port_ = svr_.bind_to_any_port("127.0.0.1");
  11408. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11409. svr_.wait_until_ready();
  11410. }
  11411. void TearDown() override {
  11412. svr_.stop();
  11413. if (thread_.joinable()) thread_.join();
  11414. }
  11415. Server svr_;
  11416. std::thread thread_;
  11417. int port_ = 0;
  11418. };
  11419. TEST_F(OpenStreamTest, Basic) {
  11420. Client cli("127.0.0.1", port_);
  11421. auto handle = cli.open_stream("GET", "/hello");
  11422. EXPECT_TRUE(handle.is_valid());
  11423. EXPECT_EQ("Hello World!", read_all(handle));
  11424. }
  11425. TEST_F(OpenStreamTest, SmallBuffer) {
  11426. Client cli("127.0.0.1", port_);
  11427. auto handle = cli.open_stream("GET", "/hello");
  11428. std::string result;
  11429. char buf[4];
  11430. ssize_t n;
  11431. while ((n = handle.read(buf, sizeof(buf))) > 0)
  11432. result.append(buf, static_cast<size_t>(n));
  11433. EXPECT_EQ("Hello World!", result);
  11434. }
  11435. TEST_F(OpenStreamTest, DefaultHeaders) {
  11436. Client cli("127.0.0.1", port_);
  11437. // open_stream GET should include Host, User-Agent and Accept-Encoding
  11438. {
  11439. auto handle = cli.open_stream("GET", "/echo-headers");
  11440. ASSERT_TRUE(handle.is_valid());
  11441. auto body = read_all(handle);
  11442. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  11443. std::string::npos);
  11444. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  11445. std::string::npos);
  11446. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  11447. }
  11448. // open_stream POST with body and no explicit content_type should NOT add
  11449. // text/plain Content-Type (behavior differs from non-streaming path), but
  11450. // should include Content-Length
  11451. {
  11452. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  11453. ASSERT_TRUE(handle.is_valid());
  11454. auto body = read_all(handle);
  11455. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  11456. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  11457. }
  11458. // open_stream POST with explicit Content-Type should preserve it
  11459. {
  11460. auto handle = cli.open_stream("POST", "/echo-headers", {},
  11461. {{"Content-Type", "application/custom"}},
  11462. "{}", "application/custom");
  11463. ASSERT_TRUE(handle.is_valid());
  11464. auto body = read_all(handle);
  11465. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  11466. }
  11467. // User-specified User-Agent must not be overwritten for stream API
  11468. {
  11469. auto handle = cli.open_stream("GET", "/echo-headers", {},
  11470. {{"User-Agent", "MyAgent/1.2"}});
  11471. ASSERT_TRUE(handle.is_valid());
  11472. auto body = read_all(handle);
  11473. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  11474. }
  11475. }
  11476. TEST_F(OpenStreamTest, Large) {
  11477. Client cli("127.0.0.1", port_);
  11478. auto handle = cli.open_stream("GET", "/large");
  11479. EXPECT_EQ(10000u, read_all(handle).size());
  11480. }
  11481. TEST_F(OpenStreamTest, ConnectionError) {
  11482. Client cli("127.0.0.1", 9999);
  11483. auto handle = cli.open_stream("GET", "/hello");
  11484. EXPECT_FALSE(handle.is_valid());
  11485. }
  11486. TEST_F(OpenStreamTest, Chunked) {
  11487. Client cli("127.0.0.1", port_);
  11488. auto handle = cli.open_stream("GET", "/chunked");
  11489. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11490. "Transfer-Encoding") == "chunked");
  11491. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  11492. }
  11493. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  11494. Client cli("127.0.0.1", port_);
  11495. auto handle =
  11496. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  11497. ASSERT_TRUE(handle.is_valid());
  11498. // Consume body to allow trailers to be received/parsed
  11499. auto body = read_all(handle);
  11500. // Explicitly parse trailers (ensure trailers are available for assertion)
  11501. handle.parse_trailers_if_needed();
  11502. EXPECT_EQ(std::string("123456789"), body);
  11503. // The response should include a Trailer header declaring both names
  11504. ASSERT_TRUE(handle.response);
  11505. EXPECT_TRUE(handle.response->has_header("Trailer"));
  11506. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  11507. handle.response->get_header_value("Trailer"));
  11508. // Prohibited trailer must not be present
  11509. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  11510. // Allowed trailer should be present
  11511. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  11512. EXPECT_EQ(std::string("yes"),
  11513. handle.response->get_trailer_value("X-Allowed"));
  11514. // Verify trailers are NOT present as regular headers
  11515. EXPECT_EQ(std::string(""),
  11516. handle.response->get_header_value("Content-Length"));
  11517. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  11518. }
  11519. static std::thread serve_single_response(int port,
  11520. const std::string &response) {
  11521. return std::thread([port, response] {
  11522. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11523. default_socket_options(srv);
  11524. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11525. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11526. sockaddr_in addr{};
  11527. addr.sin_family = AF_INET;
  11528. addr.sin_port = htons(static_cast<uint16_t>(port));
  11529. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11530. int opt = 1;
  11531. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11532. #ifdef _WIN32
  11533. reinterpret_cast<const char *>(&opt),
  11534. #else
  11535. &opt,
  11536. #endif
  11537. sizeof(opt));
  11538. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11539. ::listen(srv, 1);
  11540. sockaddr_in cli_addr{};
  11541. socklen_t cli_len = sizeof(cli_addr);
  11542. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11543. if (cli != INVALID_SOCKET) {
  11544. char buf[4096];
  11545. ::recv(cli, buf, sizeof(buf), 0);
  11546. ::send(cli,
  11547. #ifdef _WIN32
  11548. static_cast<const char *>(response.c_str()),
  11549. static_cast<int>(response.size()),
  11550. #else
  11551. response.c_str(), response.size(),
  11552. #endif
  11553. 0);
  11554. detail::close_socket(cli);
  11555. }
  11556. detail::close_socket(srv);
  11557. });
  11558. }
  11559. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  11560. #ifndef _WIN32
  11561. signal(SIGPIPE, SIG_IGN);
  11562. #endif
  11563. auto server_thread =
  11564. serve_single_response(PORT + 2, "HTTP/1.1 200 OK\r\n"
  11565. "Content-Type: text/plain\r\n"
  11566. "Content-Length: not-a-number\r\n"
  11567. "Connection: close\r\n"
  11568. "\r\n"
  11569. "hello");
  11570. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11571. Client cli("127.0.0.1", PORT + 2);
  11572. auto handle = cli.open_stream("GET", "/");
  11573. EXPECT_FALSE(handle.is_valid());
  11574. server_thread.join();
  11575. }
  11576. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  11577. #ifndef _WIN32
  11578. signal(SIGPIPE, SIG_IGN);
  11579. #endif
  11580. auto server_thread = serve_single_response(
  11581. PORT + 2, "HTTP/1.1 200 OK\r\n"
  11582. "Content-Type: text/plain\r\n"
  11583. "Content-Length: 99999999999999999999999999\r\n"
  11584. "Connection: close\r\n"
  11585. "\r\n"
  11586. "hello");
  11587. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11588. // Before the fix, std::stoull would throw std::out_of_range here and
  11589. // crash the process. After the fix, strtoull silently clamps to
  11590. // ULLONG_MAX so the stream opens without crashing. The important thing
  11591. // is that the process does NOT terminate.
  11592. Client cli("127.0.0.1", PORT + 2);
  11593. auto handle = cli.open_stream("GET", "/");
  11594. EXPECT_TRUE(handle.is_valid());
  11595. server_thread.join();
  11596. }
  11597. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11598. TEST_F(OpenStreamTest, Gzip) {
  11599. Client cli("127.0.0.1", port_);
  11600. auto handle = cli.open_stream("GET", "/compressible", {},
  11601. {{"Accept-Encoding", "gzip"}});
  11602. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  11603. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11604. }
  11605. #endif
  11606. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11607. TEST_F(OpenStreamTest, Brotli) {
  11608. Client cli("127.0.0.1", port_);
  11609. auto handle =
  11610. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  11611. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  11612. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11613. }
  11614. #endif
  11615. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11616. TEST_F(OpenStreamTest, Zstd) {
  11617. Client cli("127.0.0.1", port_);
  11618. auto handle = cli.open_stream("GET", "/compressible", {},
  11619. {{"Accept-Encoding", "zstd"}});
  11620. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  11621. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11622. }
  11623. #endif
  11624. #ifdef CPPHTTPLIB_SSL_ENABLED
  11625. class SSLOpenStreamTest : public ::testing::Test {
  11626. protected:
  11627. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  11628. void SetUp() override {
  11629. svr_.Get("/hello", [](const Request &, Response &res) {
  11630. res.set_content("Hello SSL World!", "text/plain");
  11631. });
  11632. svr_.Get("/chunked", [](const Request &, Response &res) {
  11633. res.set_chunked_content_provider("text/plain",
  11634. [](size_t offset, DataSink &sink) {
  11635. if (offset < 15) {
  11636. sink.write("chunk", 5);
  11637. return true;
  11638. }
  11639. sink.done();
  11640. return true;
  11641. });
  11642. });
  11643. svr_.Post("/echo", [](const Request &req, Response &res) {
  11644. res.set_content(req.body, req.get_header_value("Content-Type"));
  11645. });
  11646. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  11647. std::string body = req.body;
  11648. res.set_chunked_content_provider(
  11649. "text/plain", [body](size_t offset, DataSink &sink) {
  11650. if (offset < body.size()) {
  11651. sink.write(body.data() + offset, body.size() - offset);
  11652. }
  11653. sink.done();
  11654. return true;
  11655. });
  11656. });
  11657. port_ = svr_.bind_to_any_port("127.0.0.1");
  11658. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11659. svr_.wait_until_ready();
  11660. }
  11661. void TearDown() override {
  11662. svr_.stop();
  11663. if (thread_.joinable()) thread_.join();
  11664. }
  11665. SSLServer svr_;
  11666. std::thread thread_;
  11667. int port_ = 0;
  11668. };
  11669. TEST_F(SSLOpenStreamTest, Basic) {
  11670. SSLClient cli("127.0.0.1", port_);
  11671. cli.enable_server_certificate_verification(false);
  11672. auto handle = cli.open_stream("GET", "/hello");
  11673. ASSERT_TRUE(handle.is_valid());
  11674. EXPECT_EQ("Hello SSL World!", read_all(handle));
  11675. }
  11676. TEST_F(SSLOpenStreamTest, Chunked) {
  11677. SSLClient cli("127.0.0.1", port_);
  11678. cli.enable_server_certificate_verification(false);
  11679. auto handle = cli.open_stream("GET", "/chunked");
  11680. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11681. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11682. "Transfer-Encoding") == "chunked");
  11683. auto body = read_all(handle);
  11684. EXPECT_EQ("chunkchunkchunk", body);
  11685. }
  11686. TEST_F(SSLOpenStreamTest, Post) {
  11687. SSLClient cli("127.0.0.1", port_);
  11688. cli.enable_server_certificate_verification(false);
  11689. auto handle =
  11690. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  11691. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11692. EXPECT_EQ(200, handle.response->status);
  11693. auto body = read_all(handle);
  11694. EXPECT_EQ("Hello SSL POST", body);
  11695. }
  11696. TEST_F(SSLOpenStreamTest, PostChunked) {
  11697. SSLClient cli("127.0.0.1", port_);
  11698. cli.enable_server_certificate_verification(false);
  11699. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  11700. "Chunked SSL Data", "text/plain");
  11701. ASSERT_TRUE(handle.is_valid());
  11702. EXPECT_EQ(200, handle.response->status);
  11703. auto body = read_all(handle);
  11704. EXPECT_EQ("Chunked SSL Data", body);
  11705. }
  11706. #endif // CPPHTTPLIB_SSL_ENABLED
  11707. //==============================================================================
  11708. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  11709. // results for various scenarios.
  11710. //==============================================================================
  11711. TEST(ParityTest, GetVsOpenStream) {
  11712. Server svr;
  11713. const std::string path = "/parity";
  11714. const std::string content = "Parity test content: hello world";
  11715. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11716. res.set_content(content, "text/plain");
  11717. });
  11718. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11719. auto se = detail::scope_exit([&] {
  11720. svr.stop();
  11721. t.join();
  11722. ASSERT_FALSE(svr.is_running());
  11723. });
  11724. svr.wait_until_ready();
  11725. Client cli(HOST, PORT);
  11726. // Non-stream path
  11727. auto r1 = cli.Get(path);
  11728. ASSERT_TRUE(r1);
  11729. EXPECT_EQ(StatusCode::OK_200, r1->status);
  11730. // Stream path
  11731. auto h = cli.open_stream("GET", path);
  11732. ASSERT_TRUE(h.is_valid());
  11733. EXPECT_EQ(r1->body, read_all(h));
  11734. }
  11735. // Helper to compress data with provided compressor type T
  11736. template <typename Compressor>
  11737. static std::string compress_payload_for_parity(const std::string &in) {
  11738. std::string out;
  11739. Compressor compressor;
  11740. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  11741. [&](const char *data, size_t n) {
  11742. out.append(data, n);
  11743. return true;
  11744. });
  11745. EXPECT_TRUE(ok);
  11746. return out;
  11747. }
  11748. // Helper function for compression parity tests
  11749. template <typename Compressor>
  11750. static void test_compression_parity(const std::string &original,
  11751. const std::string &path,
  11752. const std::string &encoding) {
  11753. const std::string compressed =
  11754. compress_payload_for_parity<Compressor>(original);
  11755. Server svr;
  11756. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11757. res.set_content(compressed, "application/octet-stream");
  11758. res.set_header("Content-Encoding", encoding);
  11759. });
  11760. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  11761. auto se = detail::scope_exit([&] {
  11762. svr.stop();
  11763. t.join();
  11764. ASSERT_FALSE(svr.is_running());
  11765. });
  11766. svr.wait_until_ready();
  11767. Client cli(HOST, PORT);
  11768. // Non-streaming
  11769. {
  11770. auto res = cli.Get(path);
  11771. ASSERT_TRUE(res);
  11772. EXPECT_EQ(StatusCode::OK_200, res->status);
  11773. EXPECT_EQ(original, res->body);
  11774. }
  11775. // Streaming
  11776. {
  11777. auto h = cli.open_stream("GET", path);
  11778. ASSERT_TRUE(h.is_valid());
  11779. EXPECT_EQ(original, read_all(h));
  11780. }
  11781. }
  11782. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11783. TEST(ParityTest, Gzip) {
  11784. test_compression_parity<detail::gzip_compressor>(
  11785. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  11786. }
  11787. #endif
  11788. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11789. TEST(ParityTest, Brotli) {
  11790. test_compression_parity<detail::brotli_compressor>(
  11791. "Hello, brotli parity test payload", "/parity-br", "br");
  11792. }
  11793. #endif
  11794. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11795. TEST(ParityTest, Zstd) {
  11796. test_compression_parity<detail::zstd_compressor>(
  11797. "Zstandard parity test payload", "/parity-zstd", "zstd");
  11798. }
  11799. #endif
  11800. //==============================================================================
  11801. // New Stream API Tests
  11802. //==============================================================================
  11803. inline std::string read_body(httplib::stream::Result &result) {
  11804. std::string body;
  11805. while (result.next()) {
  11806. body.append(result.data(), result.size());
  11807. }
  11808. return body;
  11809. }
  11810. TEST(ClientConnectionTest, Basic) {
  11811. httplib::ClientConnection conn;
  11812. EXPECT_FALSE(conn.is_open());
  11813. conn.sock = 1;
  11814. EXPECT_TRUE(conn.is_open());
  11815. httplib::ClientConnection conn2(std::move(conn));
  11816. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  11817. conn2.sock = INVALID_SOCKET;
  11818. }
  11819. // Unified test server for all stream::* tests
  11820. class StreamApiTest : public ::testing::Test {
  11821. protected:
  11822. void SetUp() override {
  11823. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11824. res.set_content("Hello World!", "text/plain");
  11825. });
  11826. svr_.Get("/echo-params",
  11827. [](const httplib::Request &req, httplib::Response &res) {
  11828. std::string r;
  11829. for (const auto &p : req.params) {
  11830. if (!r.empty()) r += "&";
  11831. r += p.first + "=" + p.second;
  11832. }
  11833. res.set_content(r, "text/plain");
  11834. });
  11835. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11836. res.set_content(req.body, req.get_header_value("Content-Type"));
  11837. });
  11838. svr_.Post("/echo-headers",
  11839. [](const httplib::Request &req, httplib::Response &res) {
  11840. std::string r;
  11841. for (const auto &h : req.headers)
  11842. r += h.first + ": " + h.second + "\n";
  11843. res.set_content(r, "text/plain");
  11844. });
  11845. svr_.Post("/echo-params",
  11846. [](const httplib::Request &req, httplib::Response &res) {
  11847. std::string r = "params:";
  11848. for (const auto &p : req.params)
  11849. r += p.first + "=" + p.second + ";";
  11850. res.set_content(r + " body:" + req.body, "text/plain");
  11851. });
  11852. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  11853. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  11854. });
  11855. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11856. res.set_content("PUT:" + req.body, "text/plain");
  11857. });
  11858. svr_.Patch("/echo",
  11859. [](const httplib::Request &req, httplib::Response &res) {
  11860. res.set_content("PATCH:" + req.body, "text/plain");
  11861. });
  11862. svr_.Delete(
  11863. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  11864. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  11865. "text/plain");
  11866. });
  11867. svr_.Get("/head-test",
  11868. [](const httplib::Request &, httplib::Response &res) {
  11869. res.set_content("body for HEAD", "text/plain");
  11870. });
  11871. svr_.Options("/options",
  11872. [](const httplib::Request &, httplib::Response &res) {
  11873. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  11874. });
  11875. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  11876. svr_.wait_until_ready();
  11877. }
  11878. void TearDown() override {
  11879. svr_.stop();
  11880. if (thread_.joinable()) thread_.join();
  11881. }
  11882. httplib::Server svr_;
  11883. std::thread thread_;
  11884. };
  11885. // stream::Get tests
  11886. TEST_F(StreamApiTest, GetBasic) {
  11887. httplib::Client cli(HOST, PORT);
  11888. auto result = httplib::stream::Get(cli, "/hello");
  11889. ASSERT_TRUE(result.is_valid());
  11890. EXPECT_EQ(200, result.status());
  11891. EXPECT_EQ("Hello World!", read_body(result));
  11892. }
  11893. TEST_F(StreamApiTest, GetWithParams) {
  11894. httplib::Client cli(HOST, PORT);
  11895. httplib::Params params{{"foo", "bar"}};
  11896. auto result = httplib::stream::Get(cli, "/echo-params", params);
  11897. ASSERT_TRUE(result.is_valid());
  11898. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  11899. }
  11900. TEST_F(StreamApiTest, GetConnectionError) {
  11901. httplib::Client cli(HOST, 9999);
  11902. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  11903. }
  11904. TEST_F(StreamApiTest, Get404) {
  11905. httplib::Client cli(HOST, PORT);
  11906. auto result = httplib::stream::Get(cli, "/nonexistent");
  11907. EXPECT_TRUE(result.is_valid());
  11908. EXPECT_EQ(404, result.status());
  11909. }
  11910. // stream::Post tests
  11911. TEST_F(StreamApiTest, PostBasic) {
  11912. httplib::Client cli(HOST, PORT);
  11913. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  11914. "application/json");
  11915. ASSERT_TRUE(result.is_valid());
  11916. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  11917. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  11918. }
  11919. TEST_F(StreamApiTest, PostWithHeaders) {
  11920. httplib::Client cli(HOST, PORT);
  11921. httplib::Headers headers{{"X-Custom", "value"}};
  11922. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  11923. "text/plain");
  11924. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  11925. }
  11926. TEST_F(StreamApiTest, PostWithParams) {
  11927. httplib::Client cli(HOST, PORT);
  11928. httplib::Params params{{"k", "v"}};
  11929. auto result =
  11930. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  11931. auto body = read_body(result);
  11932. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  11933. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  11934. }
  11935. TEST_F(StreamApiTest, PostLarge) {
  11936. httplib::Client cli(HOST, PORT);
  11937. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  11938. size_t total = 0;
  11939. while (result.next()) {
  11940. total += result.size();
  11941. }
  11942. EXPECT_EQ(100u * 1024u, total);
  11943. }
  11944. // stream::Put/Patch tests
  11945. TEST_F(StreamApiTest, PutAndPatch) {
  11946. httplib::Client cli(HOST, PORT);
  11947. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  11948. EXPECT_EQ("PUT:test", read_body(put));
  11949. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  11950. EXPECT_EQ("PATCH:test", read_body(patch));
  11951. }
  11952. // stream::Delete tests
  11953. TEST_F(StreamApiTest, Delete) {
  11954. httplib::Client cli(HOST, PORT);
  11955. auto del1 = httplib::stream::Delete(cli, "/resource");
  11956. EXPECT_EQ("Deleted", read_body(del1));
  11957. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  11958. EXPECT_EQ("Deleted:data", read_body(del2));
  11959. }
  11960. // stream::Head/Options tests
  11961. TEST_F(StreamApiTest, HeadAndOptions) {
  11962. httplib::Client cli(HOST, PORT);
  11963. auto head = httplib::stream::Head(cli, "/head-test");
  11964. EXPECT_TRUE(head.is_valid());
  11965. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  11966. auto opts = httplib::stream::Options(cli, "/options");
  11967. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  11968. }
  11969. // SSL stream::* tests
  11970. #ifdef CPPHTTPLIB_SSL_ENABLED
  11971. class SSLStreamApiTest : public ::testing::Test {
  11972. protected:
  11973. void SetUp() override {
  11974. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11975. res.set_content("Hello SSL!", "text/plain");
  11976. });
  11977. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11978. res.set_content(req.body, "text/plain");
  11979. });
  11980. port_ = svr_.bind_to_any_port("127.0.0.1");
  11981. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11982. svr_.wait_until_ready();
  11983. }
  11984. void TearDown() override {
  11985. svr_.stop();
  11986. if (thread_.joinable()) thread_.join();
  11987. }
  11988. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  11989. std::thread thread_;
  11990. int port_ = 0;
  11991. };
  11992. TEST_F(SSLStreamApiTest, GetAndPost) {
  11993. httplib::SSLClient cli("127.0.0.1", port_);
  11994. cli.enable_server_certificate_verification(false);
  11995. auto get = httplib::stream::Get(cli, "/hello");
  11996. EXPECT_EQ("Hello SSL!", read_body(get));
  11997. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  11998. EXPECT_EQ("test", read_body(post));
  11999. }
  12000. #endif
  12001. // Tests for Error::Timeout and Error::ConnectionClosed error types
  12002. // These errors are set in SocketStream/SSLSocketStream and propagated through
  12003. // BodyReader
  12004. TEST(ErrorHandlingTest, StreamReadTimeout) {
  12005. // Test that read timeout during streaming is detected
  12006. // Use a large content-length response where server delays mid-stream
  12007. Server svr;
  12008. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12009. // Send a large response with delay in the middle
  12010. res.set_content_provider(
  12011. 1000, // content_length
  12012. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  12013. if (offset < 100) {
  12014. // Send first 100 bytes immediately
  12015. std::string data(100, 'A');
  12016. sink.write(data.c_str(), data.size());
  12017. return true;
  12018. }
  12019. // Then delay longer than client timeout
  12020. std::this_thread::sleep_for(std::chrono::seconds(3));
  12021. std::string data(900, 'B');
  12022. sink.write(data.c_str(), data.size());
  12023. return true;
  12024. });
  12025. });
  12026. auto port = 8091;
  12027. std::thread t([&]() { svr.listen("localhost", port); });
  12028. svr.wait_until_ready();
  12029. Client cli("localhost", port);
  12030. cli.set_read_timeout(1, 0); // 1 second timeout
  12031. auto handle = cli.open_stream("GET", "/slow-stream");
  12032. ASSERT_TRUE(handle.is_valid());
  12033. char buf[256];
  12034. ssize_t total = 0;
  12035. ssize_t n;
  12036. bool got_error = false;
  12037. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12038. total += n;
  12039. }
  12040. if (n < 0) {
  12041. got_error = true;
  12042. // Should be timeout or read error
  12043. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12044. handle.get_read_error() == Error::Read)
  12045. << "Actual error: " << to_string(handle.get_read_error());
  12046. }
  12047. // Either we got an error, or we got less data than expected
  12048. EXPECT_TRUE(got_error || total < 1000)
  12049. << "Expected timeout but got all " << total << " bytes";
  12050. svr.stop();
  12051. t.join();
  12052. }
  12053. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  12054. // Test connection closed detection via BodyReader
  12055. Server svr;
  12056. std::atomic<bool> close_now{false};
  12057. svr.Get("/will-close", [&](const Request &, Response &res) {
  12058. res.set_content_provider(
  12059. 10000, // Large content_length that we won't fully send
  12060. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12061. if (offset < 100) {
  12062. std::string data(100, 'X');
  12063. sink.write(data.c_str(), data.size());
  12064. return true;
  12065. }
  12066. // Wait for signal then abort
  12067. while (!close_now) {
  12068. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12069. }
  12070. return false; // Abort - server will close connection
  12071. });
  12072. });
  12073. auto port = 8092;
  12074. std::thread t([&]() { svr.listen("localhost", port); });
  12075. svr.wait_until_ready();
  12076. Client cli("localhost", port);
  12077. auto handle = cli.open_stream("GET", "/will-close");
  12078. ASSERT_TRUE(handle.is_valid());
  12079. char buf[256];
  12080. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12081. EXPECT_GT(n, 0) << "First read should succeed";
  12082. // Signal server to close
  12083. close_now = true;
  12084. // Keep reading until error or EOF
  12085. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12086. // Keep reading
  12087. }
  12088. // Should get an error since content_length wasn't satisfied
  12089. if (n < 0) {
  12090. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12091. handle.get_read_error() == Error::Read)
  12092. << "Actual error: " << to_string(handle.get_read_error());
  12093. }
  12094. svr.stop();
  12095. t.join();
  12096. }
  12097. #ifdef CPPHTTPLIB_SSL_ENABLED
  12098. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  12099. // Test that read timeout during SSL streaming is detected
  12100. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12101. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12102. res.set_content_provider(
  12103. 1000, "text/plain",
  12104. [](size_t offset, size_t /*length*/, DataSink &sink) {
  12105. if (offset < 100) {
  12106. std::string data(100, 'A');
  12107. sink.write(data.c_str(), data.size());
  12108. return true;
  12109. }
  12110. std::this_thread::sleep_for(std::chrono::seconds(3));
  12111. std::string data(900, 'B');
  12112. sink.write(data.c_str(), data.size());
  12113. return true;
  12114. });
  12115. });
  12116. auto port = 8093;
  12117. std::thread t([&]() { svr.listen("localhost", port); });
  12118. svr.wait_until_ready();
  12119. SSLClient cli("localhost", port);
  12120. cli.enable_server_certificate_verification(false);
  12121. cli.set_read_timeout(1, 0); // 1 second timeout
  12122. auto handle = cli.open_stream("GET", "/slow-stream");
  12123. ASSERT_TRUE(handle.is_valid());
  12124. char buf[256];
  12125. ssize_t total = 0;
  12126. ssize_t n;
  12127. bool got_error = false;
  12128. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12129. total += n;
  12130. }
  12131. if (n < 0) {
  12132. got_error = true;
  12133. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12134. handle.get_read_error() == Error::Read)
  12135. << "Actual error: " << to_string(handle.get_read_error());
  12136. }
  12137. EXPECT_TRUE(got_error || total < 1000)
  12138. << "Expected timeout but got all " << total << " bytes";
  12139. svr.stop();
  12140. t.join();
  12141. }
  12142. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  12143. // Test SSL connection closed detection
  12144. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12145. std::atomic<bool> close_now{false};
  12146. svr.Get("/will-close", [&](const Request &, Response &res) {
  12147. res.set_content_provider(
  12148. 10000, "text/plain",
  12149. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12150. if (offset < 100) {
  12151. std::string data(100, 'X');
  12152. sink.write(data.c_str(), data.size());
  12153. return true;
  12154. }
  12155. while (!close_now) {
  12156. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12157. }
  12158. return false;
  12159. });
  12160. });
  12161. auto port = 8094;
  12162. std::thread t([&]() { svr.listen("localhost", port); });
  12163. svr.wait_until_ready();
  12164. SSLClient cli("localhost", port);
  12165. cli.enable_server_certificate_verification(false);
  12166. auto handle = cli.open_stream("GET", "/will-close");
  12167. ASSERT_TRUE(handle.is_valid());
  12168. char buf[256];
  12169. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12170. EXPECT_GT(n, 0);
  12171. // Signal server to close
  12172. close_now = true;
  12173. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12174. // Keep reading
  12175. }
  12176. if (n < 0) {
  12177. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12178. handle.get_read_error() == Error::Read)
  12179. << "Actual error: " << to_string(handle.get_read_error());
  12180. }
  12181. svr.stop();
  12182. t.join();
  12183. }
  12184. #endif
  12185. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  12186. using namespace httplib;
  12187. // Create a test file
  12188. const char *fname = "etag_testfile.txt";
  12189. const char *content = "etag-content";
  12190. {
  12191. std::ofstream ofs(fname);
  12192. ofs << content;
  12193. ASSERT_TRUE(ofs.good());
  12194. }
  12195. Server svr;
  12196. svr.set_mount_point("/static", ".");
  12197. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12198. svr.wait_until_ready();
  12199. Client cli(HOST, PORT);
  12200. // First request: should get 200 with ETag header
  12201. auto res1 = cli.Get("/static/etag_testfile.txt");
  12202. ASSERT_TRUE(res1);
  12203. ASSERT_EQ(200, res1->status);
  12204. ASSERT_TRUE(res1->has_header("ETag"));
  12205. std::string etag = res1->get_header_value("ETag");
  12206. EXPECT_FALSE(etag.empty());
  12207. // Verify ETag format: W/"hex-hex"
  12208. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  12209. EXPECT_EQ('W', etag[0]);
  12210. EXPECT_EQ('/', etag[1]);
  12211. EXPECT_EQ('"', etag[2]);
  12212. EXPECT_EQ('"', etag.back());
  12213. // Exact match: expect 304 Not Modified
  12214. Headers h2 = {{"If-None-Match", etag}};
  12215. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  12216. ASSERT_TRUE(res2);
  12217. EXPECT_EQ(304, res2->status);
  12218. // Wildcard match: expect 304 Not Modified
  12219. Headers h3 = {{"If-None-Match", "*"}};
  12220. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  12221. ASSERT_TRUE(res3);
  12222. EXPECT_EQ(304, res3->status);
  12223. // Non-matching ETag: expect 200
  12224. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  12225. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  12226. ASSERT_TRUE(res4);
  12227. EXPECT_EQ(200, res4->status);
  12228. // Multiple ETags with one matching: expect 304
  12229. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  12230. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  12231. ASSERT_TRUE(res5);
  12232. EXPECT_EQ(304, res5->status);
  12233. svr.stop();
  12234. t.join();
  12235. std::remove(fname);
  12236. }
  12237. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  12238. using namespace httplib;
  12239. Server svr;
  12240. svr.set_mount_point("/static", ".");
  12241. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12242. svr.wait_until_ready();
  12243. Client cli(HOST, PORT);
  12244. // Send If-None-Match: * to a non-existent file
  12245. Headers h = {{"If-None-Match", "*"}};
  12246. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  12247. ASSERT_TRUE(res);
  12248. EXPECT_EQ(404, res->status);
  12249. svr.stop();
  12250. t.join();
  12251. }
  12252. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  12253. using namespace httplib;
  12254. // Create a test file
  12255. const char *fname = "etag_boundary_testfile.txt";
  12256. const char *content = "boundary-test";
  12257. {
  12258. std::ofstream ofs(fname);
  12259. ofs << content;
  12260. ASSERT_TRUE(ofs.good());
  12261. }
  12262. Server svr;
  12263. svr.set_mount_point("/static", ".");
  12264. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12265. svr.wait_until_ready();
  12266. Client cli(HOST, PORT);
  12267. // Get the actual ETag
  12268. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  12269. ASSERT_TRUE(res1);
  12270. ASSERT_EQ(200, res1->status);
  12271. ASSERT_TRUE(res1->has_header("ETag"));
  12272. std::string etag = res1->get_header_value("ETag");
  12273. // Test 1: Very long ETag value (longer than actual ETag)
  12274. // Should NOT match and return 200 (not trigger out-of-bounds read)
  12275. Headers h1 = {{"If-None-Match", "W/"
  12276. "\"very-long-etag-value-that-is-much-longer-"
  12277. "than-the-actual-etag-value\""}};
  12278. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  12279. ASSERT_TRUE(res2);
  12280. EXPECT_EQ(200, res2->status); // Should not match
  12281. // Test 2: Long string followed by wildcard
  12282. // Should match on "*" and return 304 (without out-of-bounds read on the long
  12283. // string)
  12284. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  12285. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  12286. ASSERT_TRUE(res3);
  12287. EXPECT_EQ(304, res3->status); // Should match on "*"
  12288. // Test 3: Wildcard followed by long string
  12289. // Should match on "*" immediately and return 304
  12290. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  12291. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  12292. ASSERT_TRUE(res4);
  12293. EXPECT_EQ(304, res4->status); // Should match on "*"
  12294. // Test 4: Multiple long non-matching values
  12295. // Should NOT match and return 200 (test that all comparisons are safe)
  12296. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  12297. "W/\"second-long-non-matching-value\", "
  12298. "W/\"third-long-non-matching-value\""}};
  12299. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  12300. ASSERT_TRUE(res5);
  12301. EXPECT_EQ(200, res5->status); // Should not match
  12302. // Test 5: Single character that is not "*" (edge case)
  12303. Headers h5 = {{"If-None-Match", "X"}};
  12304. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  12305. ASSERT_TRUE(res6);
  12306. EXPECT_EQ(200, res6->status); // Should not match
  12307. svr.stop();
  12308. t.join();
  12309. std::remove(fname);
  12310. }
  12311. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  12312. using namespace httplib;
  12313. // Create a test file
  12314. const char *fname = "ims_testfile.txt";
  12315. const char *content = "if-modified-since-test";
  12316. {
  12317. std::ofstream ofs(fname);
  12318. ofs << content;
  12319. ASSERT_TRUE(ofs.good());
  12320. }
  12321. Server svr;
  12322. svr.set_mount_point("/static", ".");
  12323. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12324. svr.wait_until_ready();
  12325. Client cli(HOST, PORT);
  12326. // First request: should get 200 with Last-Modified header
  12327. auto res1 = cli.Get("/static/ims_testfile.txt");
  12328. ASSERT_TRUE(res1);
  12329. ASSERT_EQ(200, res1->status);
  12330. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12331. std::string last_modified = res1->get_header_value("Last-Modified");
  12332. EXPECT_FALSE(last_modified.empty());
  12333. // If-Modified-Since with same time: expect 304
  12334. Headers h2 = {{"If-Modified-Since", last_modified}};
  12335. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  12336. ASSERT_TRUE(res2);
  12337. EXPECT_EQ(304, res2->status);
  12338. // If-Modified-Since with future time: expect 304
  12339. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12340. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  12341. ASSERT_TRUE(res3);
  12342. EXPECT_EQ(304, res3->status);
  12343. // If-Modified-Since with past time: expect 200
  12344. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12345. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  12346. ASSERT_TRUE(res4);
  12347. EXPECT_EQ(200, res4->status);
  12348. // If-None-Match takes precedence over If-Modified-Since
  12349. // (send matching ETag with old If-Modified-Since -> should still be 304)
  12350. ASSERT_TRUE(res1->has_header("ETag"));
  12351. std::string etag = res1->get_header_value("ETag");
  12352. Headers h5 = {{"If-None-Match", etag},
  12353. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12354. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  12355. ASSERT_TRUE(res5);
  12356. EXPECT_EQ(304, res5->status);
  12357. svr.stop();
  12358. t.join();
  12359. std::remove(fname);
  12360. }
  12361. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  12362. using namespace httplib;
  12363. Server svr;
  12364. // Endpoint that returns compressible content
  12365. svr.Get("/compressible", [](const Request &, Response &res) {
  12366. // Return a large enough body to trigger compression
  12367. std::string body(1000, 'a');
  12368. res.set_content(body, "text/plain");
  12369. });
  12370. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12371. svr.wait_until_ready();
  12372. Client cli(HOST, PORT);
  12373. // Request with gzip support: should get Vary header when compressed
  12374. cli.set_compress(true);
  12375. auto res1 = cli.Get("/compressible");
  12376. ASSERT_TRUE(res1);
  12377. EXPECT_EQ(200, res1->status);
  12378. // If Content-Encoding is set, Vary should also be set
  12379. if (res1->has_header("Content-Encoding")) {
  12380. EXPECT_TRUE(res1->has_header("Vary"));
  12381. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  12382. }
  12383. // Request without Accept-Encoding header: should not have compression
  12384. Headers h_no_compress;
  12385. auto res2 = cli.Get("/compressible", h_no_compress);
  12386. ASSERT_TRUE(res2);
  12387. EXPECT_EQ(200, res2->status);
  12388. // Verify Vary header is present when compression is applied
  12389. // (the exact behavior depends on server configuration)
  12390. svr.stop();
  12391. t.join();
  12392. }
  12393. TEST(ETagTest, IfRangeWithETag) {
  12394. using namespace httplib;
  12395. // Create a test file with known content
  12396. const char *fname = "if_range_testfile.txt";
  12397. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  12398. {
  12399. std::ofstream ofs(fname);
  12400. ofs << content;
  12401. ASSERT_TRUE(ofs.good());
  12402. }
  12403. Server svr;
  12404. svr.set_mount_point("/static", ".");
  12405. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12406. svr.wait_until_ready();
  12407. Client cli(HOST, PORT);
  12408. // First request: get ETag
  12409. auto res1 = cli.Get("/static/if_range_testfile.txt");
  12410. ASSERT_TRUE(res1);
  12411. ASSERT_EQ(200, res1->status);
  12412. ASSERT_TRUE(res1->has_header("ETag"));
  12413. std::string etag = res1->get_header_value("ETag");
  12414. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  12415. // Since our server generates weak ETags (W/"..."), If-Range with our
  12416. // ETag should NOT result in partial content - it should return full content.
  12417. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  12418. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  12419. ASSERT_TRUE(res2);
  12420. // Weak ETag in If-Range -> full content (200), not partial (206)
  12421. EXPECT_EQ(200, res2->status);
  12422. EXPECT_EQ(content, res2->body);
  12423. EXPECT_FALSE(res2->has_header("Content-Range"));
  12424. // Range request with non-matching If-Range (ETag): should get 200 (full
  12425. // content)
  12426. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  12427. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  12428. ASSERT_TRUE(res3);
  12429. EXPECT_EQ(200, res3->status);
  12430. EXPECT_EQ(content, res3->body);
  12431. EXPECT_FALSE(res3->has_header("Content-Range"));
  12432. // Range request with strong ETag (hypothetical - our server doesn't generate
  12433. // strong ETags, but if client sends a strong ETag that doesn't match, it
  12434. // should return full content)
  12435. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  12436. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  12437. ASSERT_TRUE(res4);
  12438. EXPECT_EQ(200, res4->status);
  12439. EXPECT_EQ(content, res4->body);
  12440. EXPECT_FALSE(res4->has_header("Content-Range"));
  12441. svr.stop();
  12442. t.join();
  12443. std::remove(fname);
  12444. }
  12445. TEST(ETagTest, IfRangeWithDate) {
  12446. using namespace httplib;
  12447. // Create a test file
  12448. const char *fname = "if_range_date_testfile.txt";
  12449. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  12450. {
  12451. std::ofstream ofs(fname);
  12452. ofs << content;
  12453. ASSERT_TRUE(ofs.good());
  12454. }
  12455. Server svr;
  12456. svr.set_mount_point("/static", ".");
  12457. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12458. svr.wait_until_ready();
  12459. Client cli(HOST, PORT);
  12460. // First request: get Last-Modified
  12461. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  12462. ASSERT_TRUE(res1);
  12463. ASSERT_EQ(200, res1->status);
  12464. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12465. std::string last_modified = res1->get_header_value("Last-Modified");
  12466. // Range request with matching If-Range (date): should get 206
  12467. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  12468. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  12469. ASSERT_TRUE(res2);
  12470. EXPECT_EQ(206, res2->status);
  12471. EXPECT_EQ("FGHIJ", res2->body);
  12472. // Range request with old If-Range date: should get 200 (full content)
  12473. Headers h3 = {{"Range", "bytes=5-9"},
  12474. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12475. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  12476. ASSERT_TRUE(res3);
  12477. EXPECT_EQ(200, res3->status);
  12478. EXPECT_EQ(content, res3->body);
  12479. // Range request with future If-Range date: should get 206
  12480. Headers h4 = {{"Range", "bytes=0-4"},
  12481. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12482. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  12483. ASSERT_TRUE(res4);
  12484. EXPECT_EQ(206, res4->status);
  12485. EXPECT_EQ("ABCDE", res4->body);
  12486. svr.stop();
  12487. t.join();
  12488. std::remove(fname);
  12489. }
  12490. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  12491. using namespace httplib;
  12492. const char *fname = "etag_malformed.txt";
  12493. const char *content = "malformed-etag";
  12494. {
  12495. std::ofstream ofs(fname);
  12496. ofs << content;
  12497. ASSERT_TRUE(ofs.good());
  12498. }
  12499. Server svr;
  12500. svr.set_mount_point("/static", ".");
  12501. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12502. svr.wait_until_ready();
  12503. Client cli(HOST, PORT);
  12504. // baseline: should get 200 and an ETag
  12505. auto res1 = cli.Get("/static/etag_malformed.txt");
  12506. ASSERT_TRUE(res1);
  12507. ASSERT_EQ(200, res1->status);
  12508. ASSERT_TRUE(res1->has_header("ETag"));
  12509. // Malformed ETag value (missing quotes) should be treated as non-matching
  12510. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  12511. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  12512. ASSERT_TRUE(res_bad);
  12513. EXPECT_EQ(200, res_bad->status);
  12514. // Whitespace-only header value should be considered invalid / non-matching
  12515. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  12516. "Host: localhost\r\n"
  12517. "If-None-Match: \r\n"
  12518. "Connection: close\r\n"
  12519. "\r\n";
  12520. std::string out;
  12521. ASSERT_TRUE(send_request(5, raw_req, &out));
  12522. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12523. svr.stop();
  12524. t.join();
  12525. std::remove(fname);
  12526. }
  12527. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  12528. using namespace httplib;
  12529. const char *fname = "ims_invalid_format.txt";
  12530. const char *content = "ims-bad-format";
  12531. {
  12532. std::ofstream ofs(fname);
  12533. ofs << content;
  12534. ASSERT_TRUE(ofs.good());
  12535. }
  12536. Server svr;
  12537. svr.set_mount_point("/static", ".");
  12538. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12539. svr.wait_until_ready();
  12540. Client cli(HOST, PORT);
  12541. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  12542. ASSERT_TRUE(res1);
  12543. ASSERT_EQ(200, res1->status);
  12544. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12545. // If-Modified-Since with invalid format should not result in 304
  12546. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  12547. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  12548. ASSERT_TRUE(res_bad);
  12549. EXPECT_EQ(200, res_bad->status);
  12550. // If-Range with invalid date format should be treated as mismatch -> full
  12551. // content (200)
  12552. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  12553. {"If-Range", "invalid-date"}};
  12554. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  12555. ASSERT_TRUE(res_ifrange);
  12556. EXPECT_EQ(200, res_ifrange->status);
  12557. svr.stop();
  12558. t.join();
  12559. std::remove(fname);
  12560. }
  12561. TEST(ETagTest, IfRangeWithMalformedETag) {
  12562. using namespace httplib;
  12563. const char *fname = "ifrange_malformed.txt";
  12564. const std::string content = "0123456789";
  12565. {
  12566. std::ofstream ofs(fname);
  12567. ofs << content;
  12568. ASSERT_TRUE(ofs.good());
  12569. }
  12570. Server svr;
  12571. svr.set_mount_point("/static", ".");
  12572. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12573. svr.wait_until_ready();
  12574. Client cli(HOST, PORT);
  12575. // First request: get ETag
  12576. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  12577. ASSERT_TRUE(res1);
  12578. ASSERT_EQ(200, res1->status);
  12579. ASSERT_TRUE(res1->has_header("ETag"));
  12580. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  12581. // full content (200)
  12582. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  12583. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  12584. ASSERT_TRUE(res2);
  12585. EXPECT_EQ(200, res2->status);
  12586. EXPECT_EQ(content, res2->body);
  12587. svr.stop();
  12588. t.join();
  12589. std::remove(fname);
  12590. }
  12591. TEST(ETagTest, ExtremeLargeDateValues) {
  12592. using namespace httplib;
  12593. const char *fname = "ims_extreme_date.txt";
  12594. const char *content = "ims-extreme-date";
  12595. {
  12596. std::ofstream ofs(fname);
  12597. ofs << content;
  12598. ASSERT_TRUE(ofs.good());
  12599. }
  12600. Server svr;
  12601. svr.set_mount_point("/static", ".");
  12602. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12603. svr.wait_until_ready();
  12604. Client cli(HOST, PORT);
  12605. auto res1 = cli.Get(std::string("/static/") + fname);
  12606. ASSERT_TRUE(res1);
  12607. ASSERT_EQ(200, res1->status);
  12608. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12609. // Extremely large year that may overflow date parsing routines.
  12610. Headers h_large_date = {
  12611. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12612. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  12613. ASSERT_TRUE(res_bad);
  12614. // Expect server to treat this as invalid/mismatch and return full content
  12615. EXPECT_EQ(200, res_bad->status);
  12616. // If-Range with extremely large date should be treated as mismatch -> full
  12617. // content (200)
  12618. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  12619. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12620. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  12621. ASSERT_TRUE(res_ifrange);
  12622. EXPECT_EQ(200, res_ifrange->status);
  12623. svr.stop();
  12624. t.join();
  12625. std::remove(fname);
  12626. }
  12627. TEST(ETagTest, NegativeFileModificationTime) {
  12628. using namespace httplib;
  12629. const char *fname = "ims_negative_mtime.txt";
  12630. const std::string content = "negative-mtime";
  12631. {
  12632. std::ofstream ofs(fname);
  12633. ofs << content;
  12634. ASSERT_TRUE(ofs.good());
  12635. }
  12636. // Try to set file mtime to a negative value. This may fail on some
  12637. // platforms/filesystems; if it fails, the test will still verify server
  12638. // behaves safely by performing a regular conditional request.
  12639. #if defined(__APPLE__) || defined(__linux__)
  12640. bool set_negative = false;
  12641. do {
  12642. struct timeval times[2];
  12643. // access time: now
  12644. times[0].tv_sec = time(nullptr);
  12645. times[0].tv_usec = 0;
  12646. // modification time: negative (e.g., -1)
  12647. times[1].tv_sec = -1;
  12648. times[1].tv_usec = 0;
  12649. if (utimes(fname, times) == 0) { set_negative = true; }
  12650. } while (0);
  12651. #else
  12652. bool set_negative = false;
  12653. #endif
  12654. Server svr;
  12655. svr.set_mount_point("/static", ".");
  12656. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12657. svr.wait_until_ready();
  12658. Client cli(HOST, PORT);
  12659. auto res1 = cli.Get(std::string("/static/") + fname);
  12660. ASSERT_TRUE(res1);
  12661. ASSERT_EQ(200, res1->status);
  12662. bool has_last_modified = res1->has_header("Last-Modified");
  12663. std::string last_modified;
  12664. if (has_last_modified) {
  12665. last_modified = res1->get_header_value("Last-Modified");
  12666. }
  12667. if (set_negative) {
  12668. // If we successfully set a negative mtime, ensure server returns a
  12669. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  12670. // with an old date and ensure server handles it without crash.
  12671. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  12672. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  12673. ASSERT_TRUE(res2);
  12674. // Behavior may vary; at minimum ensure server responds (200 or 304).
  12675. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  12676. } else {
  12677. // Could not set negative mtime on this platform; fall back to verifying
  12678. // that normal invalid/malformed dates are treated safely (non-304).
  12679. Headers h_bad_date = {
  12680. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12681. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  12682. ASSERT_TRUE(res_bad);
  12683. EXPECT_EQ(200, res_bad->status);
  12684. }
  12685. svr.stop();
  12686. t.join();
  12687. std::remove(fname);
  12688. }
  12689. //==============================================================================
  12690. // SSE Parsing Tests
  12691. //==============================================================================
  12692. class SSEParsingTest : public ::testing::Test {
  12693. protected:
  12694. // Test helper that mimics SSE parsing behavior
  12695. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  12696. int &retry_ms) {
  12697. // Blank line signals end of event
  12698. if (line.empty() || line == "\r") { return true; }
  12699. // Lines starting with ':' are comments (ignored)
  12700. if (!line.empty() && line[0] == ':') { return false; }
  12701. // Find the colon separator
  12702. auto colon_pos = line.find(':');
  12703. if (colon_pos == std::string::npos) {
  12704. // Line with no colon is treated as field name with empty value
  12705. return false;
  12706. }
  12707. std::string field = line.substr(0, colon_pos);
  12708. std::string value;
  12709. // Value starts after colon, skip optional single space
  12710. if (colon_pos + 1 < line.size()) {
  12711. size_t value_start = colon_pos + 1;
  12712. if (line[value_start] == ' ') { value_start++; }
  12713. value = line.substr(value_start);
  12714. // Remove trailing \r if present
  12715. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  12716. }
  12717. // Handle known fields
  12718. if (field == "event") {
  12719. msg.event = value;
  12720. } else if (field == "data") {
  12721. // Multiple data lines are concatenated with newlines
  12722. if (!msg.data.empty()) { msg.data += "\n"; }
  12723. msg.data += value;
  12724. } else if (field == "id") {
  12725. // Empty id is valid (clears the last event ID)
  12726. msg.id = value;
  12727. } else if (field == "retry") {
  12728. // Parse retry interval in milliseconds
  12729. {
  12730. int v = 0;
  12731. auto res =
  12732. detail::from_chars(value.data(), value.data() + value.size(), v);
  12733. if (res.ec == std::errc{}) { retry_ms = v; }
  12734. }
  12735. }
  12736. // Unknown fields are ignored per SSE spec
  12737. return false;
  12738. }
  12739. };
  12740. // Test: Single-line data
  12741. TEST_F(SSEParsingTest, SingleLineData) {
  12742. sse::SSEMessage msg;
  12743. int retry_ms = 3000;
  12744. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  12745. EXPECT_EQ(msg.data, "hello");
  12746. EXPECT_EQ(msg.event, "message");
  12747. // Blank line ends event
  12748. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12749. }
  12750. // Test: Multi-line data
  12751. TEST_F(SSEParsingTest, MultiLineData) {
  12752. sse::SSEMessage msg;
  12753. int retry_ms = 3000;
  12754. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  12755. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  12756. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  12757. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  12758. }
  12759. // Test: Custom event types
  12760. TEST_F(SSEParsingTest, CustomEventType) {
  12761. sse::SSEMessage msg;
  12762. int retry_ms = 3000;
  12763. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  12764. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  12765. EXPECT_EQ(msg.event, "update");
  12766. EXPECT_EQ(msg.data, "payload");
  12767. }
  12768. // Test: Event ID handling
  12769. TEST_F(SSEParsingTest, EventIdHandling) {
  12770. sse::SSEMessage msg;
  12771. int retry_ms = 3000;
  12772. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  12773. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  12774. EXPECT_EQ(msg.id, "12345");
  12775. }
  12776. // Test: Empty event ID (clears last event ID)
  12777. TEST_F(SSEParsingTest, EmptyEventId) {
  12778. sse::SSEMessage msg;
  12779. msg.id = "previous";
  12780. int retry_ms = 3000;
  12781. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  12782. EXPECT_EQ(msg.id, "");
  12783. }
  12784. // Test: Retry field parsing
  12785. TEST_F(SSEParsingTest, RetryFieldParsing) {
  12786. sse::SSEMessage msg;
  12787. int retry_ms = 3000;
  12788. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  12789. EXPECT_EQ(retry_ms, 5000);
  12790. }
  12791. // Test: Invalid retry value
  12792. TEST_F(SSEParsingTest, InvalidRetryValue) {
  12793. sse::SSEMessage msg;
  12794. int retry_ms = 3000;
  12795. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  12796. EXPECT_EQ(retry_ms, 3000); // Unchanged
  12797. }
  12798. // Test: Comments (lines starting with :)
  12799. TEST_F(SSEParsingTest, CommentsIgnored) {
  12800. sse::SSEMessage msg;
  12801. int retry_ms = 3000;
  12802. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  12803. EXPECT_EQ(msg.data, "");
  12804. EXPECT_EQ(msg.event, "message");
  12805. }
  12806. // Test: Colon in value
  12807. TEST_F(SSEParsingTest, ColonInValue) {
  12808. sse::SSEMessage msg;
  12809. int retry_ms = 3000;
  12810. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  12811. EXPECT_EQ(msg.data, "hello:world:test");
  12812. }
  12813. // Test: Line with no colon (field name only)
  12814. TEST_F(SSEParsingTest, FieldNameOnly) {
  12815. sse::SSEMessage msg;
  12816. int retry_ms = 3000;
  12817. // According to SSE spec, this is treated as field name with empty value
  12818. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  12819. // Since we don't recognize "data" without colon, data should be empty
  12820. EXPECT_EQ(msg.data, "");
  12821. }
  12822. // Test: Trailing \r handling
  12823. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  12824. sse::SSEMessage msg;
  12825. int retry_ms = 3000;
  12826. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  12827. EXPECT_EQ(msg.data, "hello");
  12828. }
  12829. // Test: Unknown fields ignored
  12830. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  12831. sse::SSEMessage msg;
  12832. int retry_ms = 3000;
  12833. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  12834. EXPECT_EQ(msg.data, "");
  12835. EXPECT_EQ(msg.event, "message");
  12836. }
  12837. // Test: Space after colon is optional
  12838. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  12839. sse::SSEMessage msg1, msg2;
  12840. int retry_ms = 3000;
  12841. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  12842. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  12843. EXPECT_EQ(msg1.data, "hello");
  12844. EXPECT_EQ(msg2.data, "hello");
  12845. }
  12846. // Test: SSEMessage clear
  12847. TEST_F(SSEParsingTest, MessageClear) {
  12848. sse::SSEMessage msg;
  12849. msg.event = "custom";
  12850. msg.data = "some data";
  12851. msg.id = "123";
  12852. msg.clear();
  12853. EXPECT_EQ(msg.event, "message");
  12854. EXPECT_EQ(msg.data, "");
  12855. EXPECT_EQ(msg.id, "");
  12856. }
  12857. // Test: Complete event parsing
  12858. TEST_F(SSEParsingTest, CompleteEventParsing) {
  12859. sse::SSEMessage msg;
  12860. int retry_ms = 3000;
  12861. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  12862. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  12863. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  12864. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  12865. // Blank line ends event
  12866. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12867. EXPECT_EQ(msg.event, "notification");
  12868. EXPECT_EQ(msg.id, "evt-42");
  12869. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  12870. EXPECT_EQ(retry_ms, 1000);
  12871. }
  12872. //==============================================================================
  12873. // Integration Tests with Server
  12874. //==============================================================================
  12875. class SSEIntegrationTest : public ::testing::Test {
  12876. protected:
  12877. void SetUp() override {
  12878. stop_server_.store(false);
  12879. events_.clear();
  12880. server_ = httplib::detail::make_unique<Server>();
  12881. setup_server();
  12882. start_server();
  12883. }
  12884. void TearDown() override {
  12885. stop_server_.store(true);
  12886. event_cv_.notify_all();
  12887. server_->stop();
  12888. if (server_thread_.joinable()) { server_thread_.join(); }
  12889. }
  12890. void setup_server() {
  12891. // Simple SSE endpoint
  12892. server_->Get("/events", [this](const Request &req, Response &res) {
  12893. auto last_id = req.get_header_value("Last-Event-ID");
  12894. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  12895. res.set_chunked_content_provider(
  12896. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  12897. std::unique_lock<std::mutex> lock(event_mutex_);
  12898. if (event_cv_.wait_for(
  12899. lock, std::chrono::milliseconds(200), [this] {
  12900. return !events_.empty() || stop_server_.load();
  12901. })) {
  12902. if (stop_server_.load()) { return false; }
  12903. if (!events_.empty()) {
  12904. std::string event = events_.front();
  12905. events_.erase(events_.begin());
  12906. sink.write(event.data(), event.size());
  12907. return true;
  12908. }
  12909. }
  12910. return !stop_server_.load();
  12911. });
  12912. });
  12913. // Endpoint that returns error
  12914. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  12915. res.status = 500;
  12916. res.set_content("Internal Server Error", "text/plain");
  12917. });
  12918. // Endpoint for custom event types
  12919. server_->Get("/custom-events", [](const Request &, Response &res) {
  12920. res.set_chunked_content_provider(
  12921. "text/event-stream", [](size_t offset, DataSink &sink) {
  12922. if (offset == 0) {
  12923. std::string event = "event: update\ndata: updated\n\n"
  12924. "event: delete\ndata: deleted\n\n";
  12925. sink.write(event.data(), event.size());
  12926. }
  12927. return false; // End stream after sending
  12928. });
  12929. });
  12930. }
  12931. void start_server() {
  12932. port_ = server_->bind_to_any_port(HOST);
  12933. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  12934. // Wait for server to start
  12935. while (!server_->is_running()) {
  12936. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12937. }
  12938. }
  12939. int get_port() const { return port_; }
  12940. void send_event(const std::string &event) {
  12941. std::lock_guard<std::mutex> lock(event_mutex_);
  12942. events_.push_back(event);
  12943. event_cv_.notify_all();
  12944. }
  12945. std::unique_ptr<Server> server_;
  12946. std::thread server_thread_;
  12947. std::mutex event_mutex_;
  12948. std::condition_variable event_cv_;
  12949. std::vector<std::string> events_;
  12950. std::atomic<bool> stop_server_{false};
  12951. std::string last_received_event_id_;
  12952. int port_ = 0;
  12953. };
  12954. // Test: Successful connection and on_open callback
  12955. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  12956. // Add a simple endpoint that sends one event and closes
  12957. server_->Get("/simple-event", [](const Request &, Response &res) {
  12958. res.set_chunked_content_provider(
  12959. "text/event-stream", [](size_t offset, DataSink &sink) {
  12960. if (offset == 0) {
  12961. std::string event = "data: hello\n\n";
  12962. sink.write(event.data(), event.size());
  12963. }
  12964. return false; // Close stream after sending
  12965. });
  12966. });
  12967. Client client("localhost", get_port());
  12968. sse::SSEClient sse(client, "/simple-event");
  12969. std::atomic<bool> open_called{false};
  12970. std::atomic<bool> message_received{false};
  12971. sse.on_open([&open_called]() { open_called.store(true); });
  12972. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  12973. if (msg.data == "hello") { message_received.store(true); }
  12974. });
  12975. sse.set_reconnect_interval(100);
  12976. sse.set_max_reconnect_attempts(1);
  12977. // Start async
  12978. sse.start_async();
  12979. // Wait for message to be processed
  12980. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12981. sse.stop();
  12982. EXPECT_TRUE(open_called.load());
  12983. EXPECT_TRUE(message_received.load());
  12984. }
  12985. // Test: on_message callback
  12986. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  12987. // Endpoint that sends multiple events then closes
  12988. server_->Get("/multi-event", [](const Request &, Response &res) {
  12989. res.set_chunked_content_provider(
  12990. "text/event-stream", [](size_t offset, DataSink &sink) {
  12991. if (offset == 0) {
  12992. std::string events = "data: message1\n\ndata: message2\n\n";
  12993. sink.write(events.data(), events.size());
  12994. }
  12995. return false;
  12996. });
  12997. });
  12998. Client client("localhost", get_port());
  12999. sse::SSEClient sse(client, "/multi-event");
  13000. std::vector<std::string> received_messages;
  13001. std::mutex messages_mutex;
  13002. sse.on_message([&](const sse::SSEMessage &msg) {
  13003. std::lock_guard<std::mutex> lock(messages_mutex);
  13004. received_messages.push_back(msg.data);
  13005. });
  13006. sse.set_reconnect_interval(100);
  13007. sse.set_max_reconnect_attempts(1);
  13008. sse.start_async();
  13009. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13010. sse.stop();
  13011. std::lock_guard<std::mutex> lock(messages_mutex);
  13012. EXPECT_GE(received_messages.size(), 2u);
  13013. if (received_messages.size() >= 2) {
  13014. EXPECT_EQ(received_messages[0], "message1");
  13015. EXPECT_EQ(received_messages[1], "message2");
  13016. }
  13017. }
  13018. // Test: on_event for specific types
  13019. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  13020. Client client("localhost", get_port());
  13021. sse::SSEClient sse(client, "/custom-events");
  13022. std::atomic<bool> update_received{false};
  13023. std::atomic<bool> delete_received{false};
  13024. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  13025. if (msg.data == "updated") { update_received.store(true); }
  13026. });
  13027. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  13028. if (msg.data == "deleted") { delete_received.store(true); }
  13029. });
  13030. sse.set_max_reconnect_attempts(1);
  13031. sse.start_async();
  13032. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  13033. sse.stop();
  13034. EXPECT_TRUE(update_received.load());
  13035. EXPECT_TRUE(delete_received.load());
  13036. }
  13037. // Test: on_error callback on connection failure
  13038. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  13039. // Connect to a non-existent port
  13040. Client client("localhost", 59999);
  13041. sse::SSEClient sse(client, "/events");
  13042. std::atomic<bool> error_called{false};
  13043. Error received_error = Error::Success;
  13044. sse.on_error([&](Error err) {
  13045. error_called.store(true);
  13046. received_error = err;
  13047. });
  13048. sse.set_reconnect_interval(50);
  13049. sse.set_max_reconnect_attempts(1);
  13050. sse.start_async();
  13051. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13052. sse.stop();
  13053. EXPECT_TRUE(error_called.load());
  13054. EXPECT_NE(received_error, Error::Success);
  13055. }
  13056. // Test: Last-Event-ID header sent on reconnect
  13057. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  13058. // Endpoint that sends event with ID
  13059. server_->Get("/event-with-id", [](const Request &, Response &res) {
  13060. res.set_chunked_content_provider(
  13061. "text/event-stream", [](size_t offset, DataSink &sink) {
  13062. if (offset == 0) {
  13063. std::string event = "id: evt-123\ndata: test\n\n";
  13064. sink.write(event.data(), event.size());
  13065. }
  13066. return false;
  13067. });
  13068. });
  13069. Client client("localhost", get_port());
  13070. sse::SSEClient sse(client, "/event-with-id");
  13071. std::atomic<bool> id_received{false};
  13072. sse.on_message([&](const sse::SSEMessage &msg) {
  13073. if (!msg.id.empty()) { id_received.store(true); }
  13074. });
  13075. sse.set_reconnect_interval(100);
  13076. sse.set_max_reconnect_attempts(1);
  13077. sse.start_async();
  13078. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13079. sse.stop();
  13080. EXPECT_TRUE(id_received.load());
  13081. EXPECT_EQ(sse.last_event_id(), "evt-123");
  13082. }
  13083. // Test: Manual stop
  13084. TEST_F(SSEIntegrationTest, ManualStop) {
  13085. // Endpoint that sends one event and stays open briefly
  13086. std::atomic<bool> handler_running{true};
  13087. server_->Get("/stay-open", [&handler_running](const Request &,
  13088. Response &res) {
  13089. res.set_chunked_content_provider(
  13090. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  13091. if (offset == 0) {
  13092. std::string event = "data: connected\n\n";
  13093. sink.write(event.data(), event.size());
  13094. }
  13095. // Keep connection open while handler_running is true
  13096. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  13097. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13098. }
  13099. return false;
  13100. });
  13101. });
  13102. Client client("localhost", get_port());
  13103. sse::SSEClient sse(client, "/stay-open");
  13104. std::atomic<bool> connected{false};
  13105. sse.on_open([&connected]() { connected.store(true); });
  13106. sse.set_reconnect_interval(100);
  13107. sse.set_max_reconnect_attempts(1);
  13108. sse.start_async();
  13109. // Wait for connection to establish
  13110. for (int i = 0; i < 20 && !connected.load(); ++i) {
  13111. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13112. }
  13113. EXPECT_TRUE(connected.load());
  13114. EXPECT_TRUE(sse.is_connected());
  13115. // Signal handler to stop
  13116. handler_running.store(false);
  13117. // Stop SSE client
  13118. sse.stop();
  13119. EXPECT_FALSE(sse.is_connected());
  13120. }
  13121. // Test: SSEClient with custom headers
  13122. TEST_F(SSEIntegrationTest, CustomHeaders) {
  13123. // Setup a server endpoint that checks for custom header
  13124. std::atomic<bool> header_received{false};
  13125. server_->Get("/header-check", [&](const Request &req, Response &res) {
  13126. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  13127. header_received.store(true);
  13128. }
  13129. res.set_chunked_content_provider("text/event-stream",
  13130. [](size_t, DataSink &) { return false; });
  13131. });
  13132. Client client("localhost", get_port());
  13133. Headers headers = {{"X-Custom-Header", "custom-value"}};
  13134. sse::SSEClient sse(client, "/header-check", headers);
  13135. sse.set_max_reconnect_attempts(1);
  13136. sse.start_async();
  13137. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13138. sse.stop();
  13139. EXPECT_TRUE(header_received.load());
  13140. }
  13141. // Test: Reconnect interval configuration
  13142. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  13143. Client client("localhost", get_port());
  13144. sse::SSEClient sse(client, "/events");
  13145. auto &result = sse.set_reconnect_interval(500);
  13146. // Builder pattern should return reference to self
  13147. EXPECT_EQ(&result, &sse);
  13148. }
  13149. // Test: Max reconnect attempts
  13150. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  13151. // Connect to non-existent port to force reconnects
  13152. Client client("localhost", 59998);
  13153. sse::SSEClient sse(client, "/events");
  13154. std::atomic<int> error_count{0};
  13155. sse.on_error([&](Error) { error_count.fetch_add(1); });
  13156. sse.set_reconnect_interval(50);
  13157. sse.set_max_reconnect_attempts(2);
  13158. auto start = std::chrono::steady_clock::now();
  13159. sse.start(); // Blocking call
  13160. auto end = std::chrono::steady_clock::now();
  13161. // Should have stopped after 2 failed attempts
  13162. EXPECT_GE(error_count.load(), 2);
  13163. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  13164. auto duration =
  13165. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  13166. #ifdef _WIN32
  13167. // Windows is much slower for socket connection failures
  13168. EXPECT_LT(duration.count(), 7000);
  13169. #else
  13170. EXPECT_LT(duration.count(), 1000);
  13171. #endif
  13172. }
  13173. // Test: Multi-line data in integration
  13174. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  13175. // Endpoint with multi-line data
  13176. server_->Get("/multiline-data", [](const Request &, Response &res) {
  13177. res.set_chunked_content_provider(
  13178. "text/event-stream", [](size_t offset, DataSink &sink) {
  13179. if (offset == 0) {
  13180. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  13181. sink.write(event.data(), event.size());
  13182. }
  13183. return false;
  13184. });
  13185. });
  13186. Client client("localhost", get_port());
  13187. sse::SSEClient sse(client, "/multiline-data");
  13188. std::string received_data;
  13189. std::mutex data_mutex;
  13190. sse.on_message([&](const sse::SSEMessage &msg) {
  13191. std::lock_guard<std::mutex> lock(data_mutex);
  13192. received_data = msg.data;
  13193. });
  13194. sse.set_reconnect_interval(100);
  13195. sse.set_max_reconnect_attempts(1);
  13196. sse.start_async();
  13197. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13198. sse.stop();
  13199. std::lock_guard<std::mutex> lock(data_mutex);
  13200. EXPECT_EQ(received_data, "line1\nline2\nline3");
  13201. }
  13202. // Test: Auto-reconnect after server disconnection
  13203. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  13204. std::atomic<int> connection_count{0};
  13205. std::atomic<int> message_count{0};
  13206. // Endpoint that sends one event and closes, forcing reconnect
  13207. server_->Get("/reconnect-test",
  13208. [&connection_count](const Request &, Response &res) {
  13209. connection_count.fetch_add(1);
  13210. res.set_chunked_content_provider(
  13211. "text/event-stream", [](size_t offset, DataSink &sink) {
  13212. if (offset == 0) {
  13213. std::string event = "data: hello\n\n";
  13214. sink.write(event.data(), event.size());
  13215. }
  13216. return false; // Close connection after sending
  13217. });
  13218. });
  13219. Client client("localhost", get_port());
  13220. sse::SSEClient sse(client, "/reconnect-test");
  13221. sse.on_message([&message_count](const sse::SSEMessage &) {
  13222. message_count.fetch_add(1);
  13223. });
  13224. sse.set_reconnect_interval(100);
  13225. sse.set_max_reconnect_attempts(3);
  13226. sse.start_async();
  13227. // Wait long enough for multiple reconnects
  13228. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13229. sse.stop();
  13230. // Should have connected multiple times (initial + reconnects)
  13231. EXPECT_GE(connection_count.load(), 2);
  13232. // Should have received messages from multiple connections
  13233. EXPECT_GE(message_count.load(), 2);
  13234. }
  13235. // Test: Last-Event-ID sent on reconnect
  13236. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  13237. std::atomic<int> connection_count{0};
  13238. std::vector<std::string> received_last_event_ids;
  13239. std::mutex id_mutex;
  13240. // Endpoint that checks Last-Event-ID header and sends event with ID
  13241. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  13242. int conn = connection_count.fetch_add(1);
  13243. // Capture the Last-Event-ID header from each connection
  13244. {
  13245. std::lock_guard<std::mutex> lock(id_mutex);
  13246. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  13247. }
  13248. res.set_chunked_content_provider(
  13249. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  13250. if (offset == 0) {
  13251. std::string event =
  13252. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  13253. sink.write(event.data(), event.size());
  13254. }
  13255. return false;
  13256. });
  13257. });
  13258. Client client("localhost", get_port());
  13259. sse::SSEClient sse(client, "/reconnect-with-id");
  13260. sse.set_reconnect_interval(100);
  13261. sse.set_max_reconnect_attempts(3);
  13262. sse.start_async();
  13263. // Wait for at least 2 connections
  13264. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13265. sse.stop();
  13266. // Verify behavior
  13267. std::lock_guard<std::mutex> lock(id_mutex);
  13268. EXPECT_GE(received_last_event_ids.size(), 2u);
  13269. // First connection should have no Last-Event-ID
  13270. if (!received_last_event_ids.empty()) {
  13271. EXPECT_EQ(received_last_event_ids[0], "");
  13272. }
  13273. // Second connection should have Last-Event-ID from first connection
  13274. if (received_last_event_ids.size() >= 2) {
  13275. EXPECT_EQ(received_last_event_ids[1], "event-0");
  13276. }
  13277. }
  13278. TEST(Issue2318Test, EmptyHostString) {
  13279. {
  13280. httplib::Client cli_empty("", PORT);
  13281. auto res = cli_empty.Get("/");
  13282. ASSERT_FALSE(res);
  13283. EXPECT_EQ(httplib::Error::Connection, res.error());
  13284. }
  13285. {
  13286. httplib::Client cli(" ", PORT);
  13287. auto res = cli.Get("/");
  13288. ASSERT_FALSE(res);
  13289. EXPECT_EQ(httplib::Error::Connection, res.error());
  13290. }
  13291. }
  13292. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13293. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  13294. Server svr;
  13295. // Set a small payload limit (1KB)
  13296. svr.set_payload_max_length(1024);
  13297. svr.Post("/test", [&](const Request &req, Response &res) {
  13298. res.set_content("Body size: " + std::to_string(req.body.size()),
  13299. "text/plain");
  13300. });
  13301. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13302. auto se = detail::scope_exit([&] {
  13303. svr.stop();
  13304. listen_thread.join();
  13305. });
  13306. svr.wait_until_ready();
  13307. // Create data that compresses well but exceeds limit when decompressed
  13308. // 8KB of repeated null bytes compresses to a very small size
  13309. std::string original_data(8 * 1024, '\0');
  13310. // Compress the data using gzip
  13311. std::string compressed_data;
  13312. detail::gzip_compressor compressor;
  13313. compressor.compress(original_data.data(), original_data.size(), true,
  13314. [&](const char *data, size_t size) {
  13315. compressed_data.append(data, size);
  13316. return true;
  13317. });
  13318. // Verify compression worked (compressed should be much smaller)
  13319. ASSERT_LT(compressed_data.size(), original_data.size());
  13320. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  13321. // Send compressed data with Content-Encoding: gzip
  13322. Client cli(HOST, PORT);
  13323. Headers headers = {{"Content-Encoding", "gzip"}};
  13324. auto res =
  13325. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  13326. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  13327. ASSERT_TRUE(res);
  13328. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13329. }
  13330. #endif
  13331. // ============================================================================
  13332. // OpenSSL-Specific Tests
  13333. // ============================================================================
  13334. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13335. X509 *readCertificate(const std::string &strFileName) {
  13336. std::ifstream inStream(strFileName);
  13337. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  13338. std::istreambuf_iterator<char>());
  13339. if (strCertPEM.empty()) return (nullptr);
  13340. BIO *pbCert = BIO_new(BIO_s_mem());
  13341. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  13342. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  13343. BIO_free(pbCert);
  13344. return (pCert);
  13345. }
  13346. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  13347. std::ifstream inStream(strFileName);
  13348. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  13349. std::istreambuf_iterator<char>());
  13350. if (strPrivateKeyPEM.empty()) return (nullptr);
  13351. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  13352. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  13353. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  13354. BIO_free(pbPrivKey);
  13355. return (pPrivateKey);
  13356. }
  13357. TEST(BindServerTest, UpdateCerts) {
  13358. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13359. int port = svr.bind_to_any_port("0.0.0.0");
  13360. ASSERT_TRUE(svr.is_valid());
  13361. ASSERT_TRUE(port > 0);
  13362. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13363. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13364. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13365. ASSERT_TRUE(cert != nullptr);
  13366. ASSERT_TRUE(ca_cert != nullptr);
  13367. ASSERT_TRUE(key != nullptr);
  13368. X509_STORE *cert_store = X509_STORE_new();
  13369. X509_STORE_add_cert(cert_store, ca_cert);
  13370. // svr.update_certs(cert, key, cert_store); // deprecated
  13371. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13372. CLIENT_CA_CERT_FILE);
  13373. ASSERT_TRUE(svr.is_valid());
  13374. svr.stop();
  13375. X509_STORE_free(cert_store);
  13376. X509_free(cert);
  13377. X509_free(ca_cert);
  13378. EVP_PKEY_free(key);
  13379. }
  13380. // Test that SSLServer(X509*, EVP_PKEY*, X509_STORE*) constructor sets
  13381. // client CA list correctly for TLS handshake
  13382. TEST(SSLClientServerTest, X509ConstructorSetsClientCAList) {
  13383. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13384. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13385. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13386. ASSERT_TRUE(cert != nullptr);
  13387. ASSERT_TRUE(ca_cert != nullptr);
  13388. ASSERT_TRUE(key != nullptr);
  13389. X509_STORE *cert_store = X509_STORE_new();
  13390. X509_STORE_add_cert(cert_store, ca_cert);
  13391. // Use X509-based constructor (deprecated but should still work correctly)
  13392. #pragma GCC diagnostic push
  13393. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  13394. SSLServer svr(cert, key, cert_store);
  13395. #pragma GCC diagnostic pop
  13396. ASSERT_TRUE(svr.is_valid());
  13397. // Verify that client CA list is set in SSL_CTX
  13398. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13399. ASSERT_TRUE(ssl_ctx != nullptr);
  13400. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13401. ASSERT_TRUE(ca_list != nullptr);
  13402. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13403. X509_free(cert);
  13404. X509_free(ca_cert);
  13405. EVP_PKEY_free(key);
  13406. }
  13407. // Test that update_certs() updates client CA list correctly
  13408. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  13409. // Start with file-based constructor
  13410. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13411. ASSERT_TRUE(svr.is_valid());
  13412. // Initially no client CA list should be set
  13413. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13414. ASSERT_TRUE(ssl_ctx != nullptr);
  13415. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  13416. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  13417. EXPECT_EQ(0, count_before);
  13418. // Now update with client CA (PEM string)
  13419. std::string cert_pem, key_pem, ca_pem;
  13420. read_file(SERVER_CERT_FILE, cert_pem);
  13421. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13422. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13423. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  13424. ASSERT_TRUE(svr.is_valid());
  13425. // Now client CA list should be set
  13426. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  13427. ASSERT_TRUE(ca_list_after != nullptr);
  13428. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  13429. }
  13430. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  13431. // Test that the file-path SSLServer constructor properly sets the client CA
  13432. // list that is sent to clients during the TLS handshake (CertificateRequest)
  13433. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13434. ASSERT_TRUE(svr.is_valid());
  13435. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13436. ASSERT_TRUE(ssl_ctx != nullptr);
  13437. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13438. ASSERT_TRUE(ca_list != nullptr);
  13439. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13440. }
  13441. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  13442. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  13443. // prepare large data
  13444. std::random_device seed_gen;
  13445. std::mt19937 random(seed_gen());
  13446. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  13447. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  13448. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  13449. // server
  13450. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13451. ASSERT_TRUE(svr.is_valid());
  13452. svr.Post("/binary", [&](const Request &req, Response &res) {
  13453. EXPECT_EQ(large_size_byte, req.body.size());
  13454. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  13455. res.set_content(req.body, "application/octet-stream");
  13456. });
  13457. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  13458. auto se = detail::scope_exit([&] {
  13459. svr.stop();
  13460. listen_thread.join();
  13461. ASSERT_FALSE(svr.is_running());
  13462. });
  13463. svr.wait_until_ready();
  13464. // client POST
  13465. SSLClient cli("localhost", PORT);
  13466. cli.enable_server_certificate_verification(false);
  13467. cli.set_read_timeout(std::chrono::seconds(100));
  13468. cli.set_write_timeout(std::chrono::seconds(100));
  13469. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  13470. large_size_byte, "application/octet-stream");
  13471. // compare
  13472. EXPECT_EQ(StatusCode::OK_200, res->status);
  13473. EXPECT_EQ(large_size_byte, res->body.size());
  13474. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  13475. }
  13476. #endif
  13477. // ============================================================================
  13478. // MbedTLS-Specific Tests
  13479. // ============================================================================
  13480. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  13481. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  13482. using namespace httplib::tls;
  13483. // Track if callback was invoked
  13484. bool callback_invoked = false;
  13485. // The callback receives void* ctx which is actually MbedTlsContext*
  13486. // We can access the mbedtls_ssl_config via the context
  13487. auto setup_callback = [&callback_invoked](void *ctx) {
  13488. callback_invoked = true;
  13489. // Cast to MbedTlsContext* to access the ssl config
  13490. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  13491. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  13492. // Use static variables to hold certificate data (simplified for test)
  13493. static mbedtls_x509_crt own_cert;
  13494. static mbedtls_pk_context own_key;
  13495. static mbedtls_x509_crt ca_chain;
  13496. static bool initialized = false;
  13497. if (!initialized) {
  13498. mbedtls_x509_crt_init(&own_cert);
  13499. mbedtls_pk_init(&own_key);
  13500. mbedtls_x509_crt_init(&ca_chain);
  13501. // Load server certificate
  13502. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  13503. return false;
  13504. }
  13505. // Load server private key
  13506. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  13507. #if MBEDTLS_VERSION_MAJOR >= 3
  13508. ,
  13509. mbedtls_ctr_drbg_random, nullptr
  13510. #endif
  13511. ) != 0) {
  13512. return false;
  13513. }
  13514. // Load CA chain for client verification
  13515. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  13516. return false;
  13517. }
  13518. initialized = true;
  13519. }
  13520. // Configure the SSL config
  13521. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  13522. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  13523. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  13524. // Set minimum TLS version using mbedTLS native API
  13525. #if MBEDTLS_VERSION_MAJOR >= 3
  13526. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  13527. #else
  13528. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  13529. MBEDTLS_SSL_MINOR_VERSION_3);
  13530. #endif
  13531. return true;
  13532. };
  13533. SSLServer svr(setup_callback);
  13534. ASSERT_TRUE(svr.is_valid());
  13535. ASSERT_TRUE(callback_invoked);
  13536. svr.Get("/test", [&](const Request &req, Response &res) {
  13537. res.set_content("test", "text/plain");
  13538. auto cert = req.peer_cert();
  13539. ASSERT_TRUE(static_cast<bool>(cert));
  13540. auto common_name = cert.subject_cn();
  13541. EXPECT_EQ("Common Name", common_name);
  13542. });
  13543. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13544. auto se = detail::scope_exit([&] {
  13545. svr.stop();
  13546. t.join();
  13547. ASSERT_FALSE(svr.is_running());
  13548. });
  13549. svr.wait_until_ready();
  13550. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13551. cli.enable_server_certificate_verification(false);
  13552. cli.set_connection_timeout(30);
  13553. auto res = cli.Get("/test");
  13554. ASSERT_TRUE(res);
  13555. ASSERT_EQ(StatusCode::OK_200, res->status);
  13556. }
  13557. #endif
  13558. // WebSocket Tests
  13559. TEST(WebSocketTest, RSVBitsMustBeZero) {
  13560. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  13561. // defining the meaning of these bits has been negotiated.
  13562. auto make_frame = [](uint8_t first_byte) {
  13563. std::string frame;
  13564. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  13565. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  13566. frame += "Hello";
  13567. return frame;
  13568. };
  13569. // RSV1 set (0x40)
  13570. {
  13571. detail::BufferStream strm;
  13572. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  13573. ws::Opcode opcode;
  13574. std::string payload;
  13575. bool fin;
  13576. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13577. false, 1024));
  13578. }
  13579. // RSV2 set (0x20)
  13580. {
  13581. detail::BufferStream strm;
  13582. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  13583. ws::Opcode opcode;
  13584. std::string payload;
  13585. bool fin;
  13586. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13587. false, 1024));
  13588. }
  13589. // RSV3 set (0x10)
  13590. {
  13591. detail::BufferStream strm;
  13592. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  13593. ws::Opcode opcode;
  13594. std::string payload;
  13595. bool fin;
  13596. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13597. false, 1024));
  13598. }
  13599. // No RSV bits set - should succeed
  13600. {
  13601. detail::BufferStream strm;
  13602. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  13603. ws::Opcode opcode;
  13604. std::string payload;
  13605. bool fin;
  13606. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13607. false, 1024));
  13608. EXPECT_EQ(ws::Opcode::Text, opcode);
  13609. EXPECT_EQ("Hello", payload);
  13610. EXPECT_TRUE(fin);
  13611. }
  13612. }
  13613. TEST(WebSocketTest, ControlFrameValidation) {
  13614. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  13615. // payload length <= 125.
  13616. // Ping with FIN=0 - must be rejected
  13617. {
  13618. detail::BufferStream strm;
  13619. std::string frame;
  13620. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  13621. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13622. strm.write(frame.data(), frame.size());
  13623. ws::Opcode opcode;
  13624. std::string payload;
  13625. bool fin;
  13626. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13627. false, 1024));
  13628. }
  13629. // Close with FIN=0 - must be rejected
  13630. {
  13631. detail::BufferStream strm;
  13632. std::string frame;
  13633. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  13634. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13635. strm.write(frame.data(), frame.size());
  13636. ws::Opcode opcode;
  13637. std::string payload;
  13638. bool fin;
  13639. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13640. false, 1024));
  13641. }
  13642. // Ping with payload_len=126 (extended length) - must be rejected
  13643. {
  13644. detail::BufferStream strm;
  13645. std::string frame;
  13646. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13647. frame += static_cast<char>(126); // payload_len=126 (>125)
  13648. frame += static_cast<char>(0x00); // extended length high byte
  13649. frame += static_cast<char>(126); // extended length low byte
  13650. frame += std::string(126, 'x');
  13651. strm.write(frame.data(), frame.size());
  13652. ws::Opcode opcode;
  13653. std::string payload;
  13654. bool fin;
  13655. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13656. false, 1024));
  13657. }
  13658. // Ping with FIN=1 and payload_len=125 - should succeed
  13659. {
  13660. detail::BufferStream strm;
  13661. std::string frame;
  13662. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13663. frame += static_cast<char>(125); // payload_len=125
  13664. frame += std::string(125, 'x');
  13665. strm.write(frame.data(), frame.size());
  13666. ws::Opcode opcode;
  13667. std::string payload;
  13668. bool fin;
  13669. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13670. false, 1024));
  13671. EXPECT_EQ(ws::Opcode::Ping, opcode);
  13672. EXPECT_EQ(125u, payload.size());
  13673. EXPECT_TRUE(fin);
  13674. }
  13675. }
  13676. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  13677. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  13678. // length MUST be 0.
  13679. // MSB set - must be rejected
  13680. {
  13681. detail::BufferStream strm;
  13682. std::string frame;
  13683. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13684. frame += static_cast<char>(127); // 64-bit extended length
  13685. frame += static_cast<char>(0x80); // MSB set (invalid)
  13686. frame += std::string(7, '\0'); // remaining 7 bytes of length
  13687. strm.write(frame.data(), frame.size());
  13688. ws::Opcode opcode;
  13689. std::string payload;
  13690. bool fin;
  13691. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13692. false, 1024));
  13693. }
  13694. // MSB clear - should pass length parsing (will be rejected by max_len,
  13695. // but that's a different check; use a small length to verify)
  13696. {
  13697. detail::BufferStream strm;
  13698. std::string frame;
  13699. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13700. frame += static_cast<char>(127); // 64-bit extended length
  13701. frame += std::string(7, '\0'); // high bytes = 0
  13702. frame += static_cast<char>(0x03); // length = 3
  13703. frame += "abc";
  13704. strm.write(frame.data(), frame.size());
  13705. ws::Opcode opcode;
  13706. std::string payload;
  13707. bool fin;
  13708. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13709. false, 1024));
  13710. EXPECT_EQ(ws::Opcode::Text, opcode);
  13711. EXPECT_EQ("abc", payload);
  13712. }
  13713. }
  13714. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  13715. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  13716. // Valid UTF-8
  13717. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  13718. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  13719. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  13720. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  13721. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  13722. // Invalid UTF-8
  13723. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  13724. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  13725. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  13726. EXPECT_FALSE(
  13727. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  13728. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  13729. }
  13730. TEST(WebSocketTest, ConnectAndDisconnect) {
  13731. Server svr;
  13732. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  13733. std::string msg;
  13734. while (ws.read(msg)) {}
  13735. });
  13736. auto port = svr.bind_to_any_port(HOST);
  13737. std::thread t([&]() { svr.listen_after_bind(); });
  13738. svr.wait_until_ready();
  13739. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  13740. ASSERT_TRUE(client.connect());
  13741. EXPECT_TRUE(client.is_open());
  13742. client.close();
  13743. EXPECT_FALSE(client.is_open());
  13744. svr.stop();
  13745. t.join();
  13746. }
  13747. TEST(WebSocketTest, ValidURL) {
  13748. ws::WebSocketClient ws1("ws://localhost:8080/path");
  13749. EXPECT_TRUE(ws1.is_valid());
  13750. ws::WebSocketClient ws2("ws://example.com/path");
  13751. EXPECT_TRUE(ws2.is_valid());
  13752. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  13753. EXPECT_TRUE(ws3.is_valid());
  13754. #ifdef CPPHTTPLIB_SSL_ENABLED
  13755. ws::WebSocketClient wss1("wss://example.com/path");
  13756. EXPECT_TRUE(wss1.is_valid());
  13757. ws::WebSocketClient wss2("wss://example.com:443/path");
  13758. EXPECT_TRUE(wss2.is_valid());
  13759. #endif
  13760. }
  13761. TEST(WebSocketTest, InvalidURL) {
  13762. // No scheme
  13763. ws::WebSocketClient ws1("localhost:8080/path");
  13764. EXPECT_FALSE(ws1.is_valid());
  13765. // No path
  13766. ws::WebSocketClient ws2("ws://localhost:8080");
  13767. EXPECT_FALSE(ws2.is_valid());
  13768. // Empty string
  13769. ws::WebSocketClient ws3("");
  13770. EXPECT_FALSE(ws3.is_valid());
  13771. // Missing host
  13772. ws::WebSocketClient ws4("ws://:8080/path");
  13773. EXPECT_FALSE(ws4.is_valid());
  13774. // Port number overflow — should not crash
  13775. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  13776. EXPECT_FALSE(ws5.is_valid());
  13777. // Port out of range
  13778. ws::WebSocketClient ws6("ws://localhost:99999/path");
  13779. EXPECT_FALSE(ws6.is_valid());
  13780. }
  13781. TEST(WebSocketTest, UnsupportedScheme) {
  13782. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13783. ws::WebSocketClient ws1("http://localhost:8080/path");
  13784. EXPECT_FALSE(ws1.is_valid());
  13785. ws::WebSocketClient ws2("https://localhost:8080/path");
  13786. EXPECT_FALSE(ws2.is_valid());
  13787. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  13788. EXPECT_FALSE(ws3.is_valid());
  13789. #else
  13790. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  13791. std::invalid_argument);
  13792. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  13793. std::invalid_argument);
  13794. #endif
  13795. }
  13796. TEST(WebSocketTest, ConnectWhenInvalid) {
  13797. ws::WebSocketClient ws("not a valid url");
  13798. EXPECT_FALSE(ws.is_valid());
  13799. EXPECT_FALSE(ws.connect());
  13800. }
  13801. TEST(WebSocketTest, DefaultPort) {
  13802. ws::WebSocketClient ws1("ws://example.com/path");
  13803. EXPECT_TRUE(ws1.is_valid());
  13804. // ws:// defaults to port 80 (verified by successful parse)
  13805. #ifdef CPPHTTPLIB_SSL_ENABLED
  13806. ws::WebSocketClient ws2("wss://example.com/path");
  13807. EXPECT_TRUE(ws2.is_valid());
  13808. // wss:// defaults to port 443 (verified by successful parse)
  13809. #endif
  13810. }
  13811. TEST(WebSocketTest, IPv6LiteralAddress) {
  13812. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  13813. EXPECT_TRUE(ws1.is_valid());
  13814. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  13815. EXPECT_TRUE(ws2.is_valid());
  13816. }
  13817. TEST(WebSocketTest, ComplexPath) {
  13818. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  13819. EXPECT_TRUE(ws1.is_valid());
  13820. ws::WebSocketClient ws2("ws://localhost:8080/");
  13821. EXPECT_TRUE(ws2.is_valid());
  13822. }
  13823. class WebSocketIntegrationTest : public ::testing::Test {
  13824. protected:
  13825. void SetUp() override {
  13826. server_ = httplib::detail::make_unique<Server>();
  13827. setup_server();
  13828. start_server();
  13829. }
  13830. void TearDown() override {
  13831. server_->stop();
  13832. if (server_thread_.joinable()) { server_thread_.join(); }
  13833. }
  13834. void setup_server() {
  13835. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  13836. std::string msg;
  13837. ws::ReadResult ret;
  13838. while ((ret = ws.read(msg))) {
  13839. if (ret == ws::Binary) {
  13840. ws.send(msg.data(), msg.size());
  13841. } else {
  13842. ws.send(msg);
  13843. }
  13844. }
  13845. });
  13846. server_->WebSocket("/ws-echo-string",
  13847. [](const Request &, ws::WebSocket &ws) {
  13848. std::string msg;
  13849. while (ws.read(msg)) {
  13850. ws.send("echo: " + msg);
  13851. }
  13852. });
  13853. server_->WebSocket(
  13854. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  13855. // Echo back request metadata
  13856. ws.send("path:" + req.path);
  13857. ws.send("header:" + req.get_header_value("X-Test-Header"));
  13858. std::string msg;
  13859. while (ws.read(msg)) {}
  13860. });
  13861. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  13862. std::string msg;
  13863. ws.read(msg); // wait for a message
  13864. ws.close();
  13865. });
  13866. server_->WebSocket("/ws-close-status",
  13867. [](const Request &, ws::WebSocket &ws) {
  13868. std::string msg;
  13869. ws.read(msg); // wait for a message
  13870. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  13871. });
  13872. server_->WebSocket(
  13873. "/ws-subprotocol",
  13874. [](const Request &, ws::WebSocket &ws) {
  13875. std::string msg;
  13876. while (ws.read(msg)) {
  13877. ws.send(msg);
  13878. }
  13879. },
  13880. [](const std::vector<std::string> &protocols) -> std::string {
  13881. for (const auto &p : protocols) {
  13882. if (p == "graphql-ws") { return p; }
  13883. }
  13884. return "";
  13885. });
  13886. }
  13887. void start_server() {
  13888. port_ = server_->bind_to_any_port(HOST);
  13889. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13890. server_->wait_until_ready();
  13891. }
  13892. std::unique_ptr<Server> server_;
  13893. std::thread server_thread_;
  13894. int port_ = 0;
  13895. };
  13896. TEST_F(WebSocketIntegrationTest, TextEcho) {
  13897. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13898. "/ws-echo");
  13899. ASSERT_TRUE(client.connect());
  13900. ASSERT_TRUE(client.is_open());
  13901. ASSERT_TRUE(client.send("Hello WebSocket"));
  13902. std::string msg;
  13903. EXPECT_EQ(ws::Text, client.read(msg));
  13904. EXPECT_EQ("Hello WebSocket", msg);
  13905. client.close();
  13906. }
  13907. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  13908. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13909. "/ws-echo");
  13910. ASSERT_TRUE(client.connect());
  13911. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  13912. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  13913. std::string msg;
  13914. EXPECT_EQ(ws::Binary, client.read(msg));
  13915. EXPECT_EQ(binary_data, msg);
  13916. client.close();
  13917. }
  13918. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  13919. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13920. "/ws-echo");
  13921. ASSERT_TRUE(client.connect());
  13922. for (int i = 0; i < 10; i++) {
  13923. auto text = "message " + std::to_string(i);
  13924. ASSERT_TRUE(client.send(text));
  13925. std::string msg;
  13926. ASSERT_TRUE(client.read(msg));
  13927. EXPECT_EQ(text, msg);
  13928. }
  13929. client.close();
  13930. }
  13931. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  13932. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13933. "/ws-close");
  13934. ASSERT_TRUE(client.connect());
  13935. // Send a message to trigger the server to close
  13936. ASSERT_TRUE(client.send("trigger close"));
  13937. // The server will close, so read should return false
  13938. std::string msg;
  13939. EXPECT_FALSE(client.read(msg));
  13940. EXPECT_FALSE(client.is_open());
  13941. }
  13942. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  13943. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13944. "/ws-echo");
  13945. ASSERT_TRUE(client.connect());
  13946. // 128KB message
  13947. std::string large_data(128 * 1024, 'X');
  13948. ASSERT_TRUE(client.send(large_data));
  13949. std::string msg;
  13950. ASSERT_TRUE(client.read(msg));
  13951. EXPECT_EQ(large_data, msg);
  13952. client.close();
  13953. }
  13954. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  13955. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13956. "/ws-echo");
  13957. ASSERT_TRUE(client.connect());
  13958. const int num_threads = 4;
  13959. std::vector<std::thread> threads;
  13960. std::atomic<int> send_count{0};
  13961. for (int t = 0; t < num_threads; t++) {
  13962. threads.emplace_back([&client, &send_count, t]() {
  13963. for (int i = 0; i < 5; i++) {
  13964. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  13965. if (client.send(text)) { send_count++; }
  13966. }
  13967. });
  13968. }
  13969. for (auto &th : threads) {
  13970. th.join();
  13971. }
  13972. int received = 0;
  13973. std::string msg;
  13974. while (received < send_count.load()) {
  13975. if (!client.read(msg)) { break; }
  13976. received++;
  13977. }
  13978. EXPECT_EQ(send_count.load(), received);
  13979. client.close();
  13980. }
  13981. TEST_F(WebSocketIntegrationTest, ReadString) {
  13982. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13983. "/ws-echo-string");
  13984. ASSERT_TRUE(client.connect());
  13985. ASSERT_TRUE(client.send("hello"));
  13986. std::string msg;
  13987. ASSERT_TRUE(client.read(msg));
  13988. EXPECT_EQ("echo: hello", msg);
  13989. ASSERT_TRUE(client.send("world"));
  13990. ASSERT_TRUE(client.read(msg));
  13991. EXPECT_EQ("echo: world", msg);
  13992. client.close();
  13993. }
  13994. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  13995. Headers headers = {{"X-Test-Header", "test-value"}};
  13996. ws::WebSocketClient client(
  13997. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  13998. ASSERT_TRUE(client.connect());
  13999. std::string msg;
  14000. ASSERT_TRUE(client.read(msg));
  14001. EXPECT_EQ("path:/ws-request-info", msg);
  14002. ASSERT_TRUE(client.read(msg));
  14003. EXPECT_EQ("header:test-value", msg);
  14004. client.close();
  14005. }
  14006. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  14007. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14008. "/ws-echo");
  14009. client.set_read_timeout(1, 0); // 1 second
  14010. ASSERT_TRUE(client.connect());
  14011. // Don't send anything — server echo handler waits for a message,
  14012. // so read() should time out and return false.
  14013. std::string msg;
  14014. EXPECT_FALSE(client.read(msg));
  14015. }
  14016. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  14017. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14018. "/ws-echo");
  14019. client.set_read_timeout(5, 0);
  14020. ASSERT_TRUE(client.connect());
  14021. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14022. // The server should reject it and close the connection.
  14023. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  14024. client.send(oversized);
  14025. // The server's read() should have failed due to payload limit,
  14026. // so our read() should return false (connection closed).
  14027. std::string msg;
  14028. EXPECT_FALSE(client.read(msg));
  14029. }
  14030. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  14031. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14032. "/ws-echo");
  14033. client.set_read_timeout(10, 0);
  14034. ASSERT_TRUE(client.connect());
  14035. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14036. // This should succeed.
  14037. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  14038. ASSERT_TRUE(client.send(at_limit));
  14039. std::string msg;
  14040. ASSERT_TRUE(client.read(msg));
  14041. EXPECT_EQ(at_limit.size(), msg.size());
  14042. client.close();
  14043. }
  14044. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  14045. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14046. "/nonexistent");
  14047. EXPECT_FALSE(client.connect());
  14048. EXPECT_FALSE(client.is_open());
  14049. }
  14050. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  14051. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14052. "/ws-echo");
  14053. ASSERT_TRUE(client.connect());
  14054. ASSERT_TRUE(client.send(""));
  14055. std::string msg;
  14056. EXPECT_EQ(ws::Text, client.read(msg));
  14057. EXPECT_EQ("", msg);
  14058. client.close();
  14059. }
  14060. TEST_F(WebSocketIntegrationTest, Reconnect) {
  14061. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14062. "/ws-echo");
  14063. // First connection
  14064. ASSERT_TRUE(client.connect());
  14065. ASSERT_TRUE(client.send("first"));
  14066. std::string msg;
  14067. ASSERT_TRUE(client.read(msg));
  14068. EXPECT_EQ("first", msg);
  14069. client.close();
  14070. EXPECT_FALSE(client.is_open());
  14071. // Reconnect using the same client object
  14072. ASSERT_TRUE(client.connect());
  14073. ASSERT_TRUE(client.is_open());
  14074. ASSERT_TRUE(client.send("second"));
  14075. ASSERT_TRUE(client.read(msg));
  14076. EXPECT_EQ("second", msg);
  14077. client.close();
  14078. }
  14079. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  14080. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14081. "/ws-close-status");
  14082. ASSERT_TRUE(client.connect());
  14083. // Trigger the server to close with GoingAway status
  14084. ASSERT_TRUE(client.send("trigger"));
  14085. // read() should return false after receiving the close frame
  14086. std::string msg;
  14087. EXPECT_FALSE(client.read(msg));
  14088. EXPECT_FALSE(client.is_open());
  14089. }
  14090. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  14091. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14092. "/ws-echo");
  14093. ASSERT_TRUE(client.connect());
  14094. client.close(ws::CloseStatus::GoingAway, "client leaving");
  14095. EXPECT_FALSE(client.is_open());
  14096. }
  14097. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  14098. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  14099. ws::WebSocketClient client(
  14100. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14101. ASSERT_TRUE(client.connect());
  14102. // Server should have selected graphql-ws
  14103. EXPECT_EQ("graphql-ws", client.subprotocol());
  14104. client.close();
  14105. }
  14106. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  14107. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  14108. ws::WebSocketClient client(
  14109. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14110. ASSERT_TRUE(client.connect());
  14111. // Server should not have selected any subprotocol
  14112. EXPECT_TRUE(client.subprotocol().empty());
  14113. client.close();
  14114. }
  14115. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  14116. // Connect without requesting any subprotocol
  14117. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14118. "/ws-subprotocol");
  14119. ASSERT_TRUE(client.connect());
  14120. EXPECT_TRUE(client.subprotocol().empty());
  14121. client.close();
  14122. }
  14123. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  14124. Server svr;
  14125. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  14126. if (!req.has_header("Authorization")) {
  14127. res.status = StatusCode::Unauthorized_401;
  14128. res.set_content("Unauthorized", "text/plain");
  14129. return Server::HandlerResponse::Handled;
  14130. }
  14131. return Server::HandlerResponse::Unhandled;
  14132. });
  14133. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14134. std::string msg;
  14135. while (ws.read(msg)) {
  14136. ws.send(msg);
  14137. }
  14138. });
  14139. auto port = svr.bind_to_any_port("localhost");
  14140. std::thread t([&]() { svr.listen_after_bind(); });
  14141. svr.wait_until_ready();
  14142. // Without Authorization header - should be rejected before upgrade
  14143. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  14144. EXPECT_FALSE(client1.connect());
  14145. // With Authorization header - should succeed
  14146. Headers headers = {{"Authorization", "Bearer token123"}};
  14147. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  14148. headers);
  14149. ASSERT_TRUE(client2.connect());
  14150. ASSERT_TRUE(client2.send("hello"));
  14151. std::string msg;
  14152. ASSERT_TRUE(client2.read(msg));
  14153. EXPECT_EQ("hello", msg);
  14154. client2.close();
  14155. svr.stop();
  14156. t.join();
  14157. }
  14158. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14159. class WebSocketSSLIntegrationTest : public ::testing::Test {
  14160. protected:
  14161. void SetUp() override {
  14162. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  14163. SERVER_PRIVATE_KEY_FILE);
  14164. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14165. std::string msg;
  14166. ws::ReadResult ret;
  14167. while ((ret = ws.read(msg))) {
  14168. if (ret == ws::Binary) {
  14169. ws.send(msg.data(), msg.size());
  14170. } else {
  14171. ws.send(msg);
  14172. }
  14173. }
  14174. });
  14175. port_ = server_->bind_to_any_port(HOST);
  14176. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14177. server_->wait_until_ready();
  14178. }
  14179. void TearDown() override {
  14180. server_->stop();
  14181. if (server_thread_.joinable()) { server_thread_.join(); }
  14182. }
  14183. std::unique_ptr<SSLServer> server_;
  14184. std::thread server_thread_;
  14185. int port_ = 0;
  14186. };
  14187. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  14188. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  14189. "/ws-echo");
  14190. client.enable_server_certificate_verification(false);
  14191. ASSERT_TRUE(client.connect());
  14192. ASSERT_TRUE(client.is_open());
  14193. ASSERT_TRUE(client.send("Hello WSS"));
  14194. std::string msg;
  14195. EXPECT_EQ(ws::Text, client.read(msg));
  14196. EXPECT_EQ("Hello WSS", msg);
  14197. client.close();
  14198. }
  14199. #endif