test.cc 505 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460
  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_EQ(0, close(fds[1]));
  269. EXPECT_FALSE(s0.wait_writable());
  270. return true;
  271. });
  272. EXPECT_EQ(0, close(fds[0]));
  273. }
  274. TEST(SocketStream, wait_writable_INET) {
  275. sockaddr_in addr;
  276. memset(&addr, 0, sizeof(addr));
  277. addr.sin_family = AF_INET;
  278. addr.sin_port = htons(PORT + 1);
  279. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  280. int disconnected_svr_sock = -1;
  281. std::thread svr{[&] {
  282. const int s = socket(AF_INET, SOCK_STREAM, 0);
  283. ASSERT_LE(0, s);
  284. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  285. ASSERT_EQ(0, listen(s, 1));
  286. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  287. ASSERT_EQ(0, close(s));
  288. }};
  289. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  290. std::thread cli{[&] {
  291. const int s = socket(AF_INET, SOCK_STREAM, 0);
  292. ASSERT_LE(0, s);
  293. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  294. ASSERT_EQ(0, close(s));
  295. }};
  296. cli.join();
  297. svr.join();
  298. ASSERT_NE(disconnected_svr_sock, -1);
  299. const auto asSocketStream = [&](socket_t fd,
  300. std::function<bool(Stream &)> func) {
  301. return detail::process_client_socket(
  302. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  303. };
  304. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  305. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  306. EXPECT_FALSE(ss.wait_writable());
  307. return true;
  308. });
  309. ASSERT_EQ(0, close(disconnected_svr_sock));
  310. }
  311. #endif // #ifndef _WIN32
  312. TEST(ClientTest, MoveConstructible) {
  313. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  314. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  315. }
  316. TEST(ClientTest, MoveAssignable) {
  317. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  318. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  319. }
  320. #ifdef _WIN32
  321. TEST(StartupTest, WSAStartup) {
  322. WSADATA wsaData;
  323. int ret = WSAStartup(0x0002, &wsaData);
  324. ASSERT_EQ(0, ret);
  325. }
  326. #endif
  327. TEST(DecodePathTest, PercentCharacter) {
  328. EXPECT_EQ(
  329. decode_path_component(
  330. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  331. U8("descrip=Gastos áéíóúñÑ 6"));
  332. }
  333. TEST(DecodePathTest, PercentCharacterNUL) {
  334. string expected;
  335. expected.push_back('x');
  336. expected.push_back('\0');
  337. expected.push_back('x');
  338. EXPECT_EQ(decode_path_component("x%00x"), expected);
  339. }
  340. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  341. string unescapedCharacters = "-_.!~*'()";
  342. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  343. }
  344. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  345. string reservedCharacters = ";,/?:@&=+$";
  346. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  347. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  348. }
  349. TEST(ClientQueryOrder, PreserveOrder) {
  350. // This test reproduces Issue #2259: client may reorder query parameters
  351. // when sending a GET request. The expected behavior is that the client
  352. // preserves the original query string order when the caller supplied it
  353. // as part of the path.
  354. Server svr;
  355. svr.Get("/", [&](const Request &req, Response &res) {
  356. // Echo back the raw target so the test can assert ordering
  357. res.set_content(req.target, "text/plain");
  358. });
  359. std::thread t{[&] { svr.listen(HOST, PORT); }};
  360. auto se = detail::scope_exit([&] {
  361. svr.stop();
  362. t.join();
  363. ASSERT_FALSE(svr.is_running());
  364. });
  365. svr.wait_until_ready();
  366. Client cli(HOST, PORT);
  367. ASSERT_TRUE(cli.is_valid());
  368. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  369. auto res = cli.Get(original);
  370. ASSERT_TRUE(res);
  371. // Expect the echoed target to exactly match the original path (order
  372. // preserved)
  373. EXPECT_EQ(res->body, original);
  374. }
  375. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  376. string chineseCharacters = U8("中国語");
  377. string russianCharacters = U8("дом");
  378. string brazilianCharacters = U8("óculos");
  379. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  380. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  381. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  382. "%D0%B4%D0%BE%D0%BC");
  383. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  384. }
  385. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  386. string unescapedCharacters = "-_.!~*'()";
  387. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  388. }
  389. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  390. string reservedCharacters = ";,/?:@&=+$";
  391. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  392. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  393. }
  394. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  395. string chineseCharacters = U8("中国語");
  396. string russianCharacters = U8("дом");
  397. string brazilianCharacters = U8("óculos");
  398. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  399. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  400. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  401. "%D0%B4%D0%BE%D0%BC");
  402. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  403. }
  404. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  405. // Issue #2082 use case: encoding path component with ampersand
  406. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  407. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  408. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  409. }
  410. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  411. string unescapedCharacters = "-_.!~*'()";
  412. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  413. }
  414. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  415. string reservedCharacters = ";,/?:@&=+$#";
  416. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  417. }
  418. TEST(EncodeUriTest, TestUTF8Characters) {
  419. string chineseCharacters = U8("中国語");
  420. string russianCharacters = U8("дом");
  421. string brazilianCharacters = U8("óculos");
  422. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  423. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  424. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  425. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  426. }
  427. TEST(EncodeUriTest, TestCompleteUri) {
  428. string uri =
  429. "https://example.com/path/to/resource?query=value&param=test#fragment";
  430. EXPECT_EQ(
  431. httplib::encode_uri(uri),
  432. "https://example.com/path/to/resource?query=value&param=test#fragment");
  433. }
  434. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  435. string uri =
  436. "https://example.com/path with spaces/file name.html?q=hello world";
  437. EXPECT_EQ(httplib::encode_uri(uri),
  438. "https://example.com/path%20with%20spaces/"
  439. "file%20name.html?q=hello%20world");
  440. }
  441. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  442. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  443. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  444. }
  445. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  446. string unescapedCharacters = "-_.!~*'()";
  447. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  448. }
  449. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  450. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  451. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  452. string encodedBrazilian = "%C3%B3culos";
  453. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  454. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  455. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  456. }
  457. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  458. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  459. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  460. "Piri Tommy Villiers - on & on");
  461. }
  462. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  463. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  464. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  465. }
  466. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  467. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  468. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  469. }
  470. TEST(DecodeUriTest, 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(encodedChinese), U8("中国語"));
  475. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  476. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  477. }
  478. TEST(DecodeUriTest, TestCompleteUri) {
  479. string encodedUri = "https://example.com/path%20with%20spaces/"
  480. "file%20name.html?q=hello%20world";
  481. EXPECT_EQ(
  482. httplib::decode_uri(encodedUri),
  483. "https://example.com/path with spaces/file name.html?q=hello world");
  484. }
  485. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  486. string original =
  487. "https://example.com/path with spaces/file name.html?q=hello world";
  488. string encoded = httplib::encode_uri(original);
  489. string decoded = httplib::decode_uri(encoded);
  490. EXPECT_EQ(decoded, original);
  491. }
  492. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  493. string original = "Piri Tommy Villiers - on & on";
  494. string encoded = httplib::encode_uri_component(original);
  495. string decoded = httplib::decode_uri_component(encoded);
  496. EXPECT_EQ(decoded, original);
  497. }
  498. TEST(TrimTests, TrimStringTests) {
  499. EXPECT_EQ("abc", detail::trim_copy("abc"));
  500. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  501. EXPECT_TRUE(detail::trim_copy("").empty());
  502. }
  503. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  504. // Simple case without quality values
  505. std::vector<std::string> result1;
  506. EXPECT_TRUE(detail::parse_accept_header(
  507. "text/html,application/json,text/plain", result1));
  508. EXPECT_EQ(result1.size(), 3U);
  509. EXPECT_EQ(result1[0], "text/html");
  510. EXPECT_EQ(result1[1], "application/json");
  511. EXPECT_EQ(result1[2], "text/plain");
  512. // With quality values
  513. std::vector<std::string> result2;
  514. EXPECT_TRUE(detail::parse_accept_header(
  515. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  516. EXPECT_EQ(result2.size(), 3U);
  517. EXPECT_EQ(result2[0], "application/json"); // highest q value
  518. EXPECT_EQ(result2[1], "text/html");
  519. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  520. }
  521. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  522. // Mixed with and without quality values
  523. std::vector<std::string> result;
  524. EXPECT_TRUE(detail::parse_accept_header(
  525. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  526. EXPECT_EQ(result.size(), 3U);
  527. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  528. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  529. EXPECT_EQ(result[2], "application/json"); // q=0.5
  530. }
  531. TEST(ParseAcceptHeaderTest, EdgeCases) {
  532. // Empty header
  533. std::vector<std::string> empty_result;
  534. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  535. EXPECT_TRUE(empty_result.empty());
  536. // Single type
  537. std::vector<std::string> single_result;
  538. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  539. EXPECT_EQ(single_result.size(), 1U);
  540. EXPECT_EQ(single_result[0], "application/json");
  541. // Wildcard types
  542. std::vector<std::string> wildcard_result;
  543. EXPECT_TRUE(detail::parse_accept_header(
  544. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  545. EXPECT_EQ(wildcard_result.size(), 3U);
  546. EXPECT_EQ(wildcard_result[0], "application/json");
  547. EXPECT_EQ(wildcard_result[1], "text/*");
  548. EXPECT_EQ(wildcard_result[2], "*/*");
  549. }
  550. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  551. // Common browser Accept header
  552. std::vector<std::string> browser_result;
  553. EXPECT_TRUE(
  554. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  555. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  556. browser_result));
  557. EXPECT_EQ(browser_result.size(), 6U);
  558. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  559. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  560. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  561. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  562. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  563. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  564. // API client header
  565. std::vector<std::string> api_result;
  566. EXPECT_TRUE(detail::parse_accept_header(
  567. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  568. api_result));
  569. EXPECT_EQ(api_result.size(), 3U);
  570. EXPECT_EQ(api_result[0], "application/json");
  571. EXPECT_EQ(api_result[1], "application/xml");
  572. EXPECT_EQ(api_result[2], "text/plain");
  573. }
  574. TEST(ParseAcceptHeaderTest, SpecialCases) {
  575. // Quality value with 3 decimal places
  576. std::vector<std::string> decimal_result;
  577. EXPECT_TRUE(detail::parse_accept_header(
  578. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  579. EXPECT_EQ(decimal_result.size(), 2U);
  580. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  581. EXPECT_EQ(decimal_result[1], "text/html");
  582. // Zero quality (should still be included but with lowest priority)
  583. std::vector<std::string> zero_q_result;
  584. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  585. zero_q_result));
  586. EXPECT_EQ(zero_q_result.size(), 2U);
  587. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  588. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  589. // No spaces around commas
  590. std::vector<std::string> no_space_result;
  591. EXPECT_TRUE(detail::parse_accept_header(
  592. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  593. no_space_result));
  594. EXPECT_EQ(no_space_result.size(), 3U);
  595. EXPECT_EQ(no_space_result[0], "text/html");
  596. EXPECT_EQ(no_space_result[1], "application/json");
  597. EXPECT_EQ(no_space_result[2], "text/plain");
  598. }
  599. TEST(ParseAcceptHeaderTest, InvalidCases) {
  600. std::vector<std::string> result;
  601. // Invalid quality value (> 1.0)
  602. EXPECT_FALSE(
  603. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  604. // Invalid quality value (< 0.0)
  605. EXPECT_FALSE(
  606. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  607. // Invalid quality value (not a number)
  608. EXPECT_FALSE(detail::parse_accept_header(
  609. "text/html;q=invalid,application/json", result));
  610. // Empty quality value
  611. EXPECT_FALSE(
  612. detail::parse_accept_header("text/html;q=,application/json", result));
  613. // Invalid media type format (no slash and not wildcard)
  614. EXPECT_FALSE(
  615. detail::parse_accept_header("invalidtype,application/json", result));
  616. // Empty media type
  617. result.clear();
  618. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  619. // Only commas
  620. result.clear();
  621. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  622. // Valid cases should still work
  623. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  624. EXPECT_EQ(result.size(), 1U);
  625. EXPECT_EQ(result[0], "*/*");
  626. EXPECT_TRUE(detail::parse_accept_header("*", result));
  627. EXPECT_EQ(result.size(), 1U);
  628. EXPECT_EQ(result[0], "*");
  629. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  630. EXPECT_EQ(result.size(), 1U);
  631. EXPECT_EQ(result[0], "text/*");
  632. }
  633. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  634. Server svr;
  635. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  636. EXPECT_EQ(req.accept_content_types.size(), 3U);
  637. EXPECT_EQ(req.accept_content_types[0], "application/json");
  638. EXPECT_EQ(req.accept_content_types[1], "text/html");
  639. EXPECT_EQ(req.accept_content_types[2], "*/*");
  640. res.set_content("ok", "text/plain");
  641. });
  642. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  643. EXPECT_TRUE(false);
  644. res.set_content("bad request", "text/plain");
  645. });
  646. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  647. auto se = detail::scope_exit([&] {
  648. svr.stop();
  649. listen_thread.join();
  650. ASSERT_FALSE(svr.is_running());
  651. });
  652. svr.wait_until_ready();
  653. Client cli("localhost", PORT);
  654. {
  655. auto res =
  656. cli.Get("/accept_ok",
  657. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  658. ASSERT_TRUE(res);
  659. EXPECT_EQ(StatusCode::OK_200, res->status);
  660. }
  661. {
  662. auto res = cli.Get("/accept_bad_request",
  663. {{"Accept", "text/html;q=abc,application/json"}});
  664. ASSERT_TRUE(res);
  665. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  666. }
  667. }
  668. TEST(DivideTest, DivideStringTests) {
  669. auto divide = [](const std::string &str, char d) {
  670. std::string lhs;
  671. std::string rhs;
  672. detail::divide(str, d,
  673. [&](const char *lhs_data, std::size_t lhs_size,
  674. const char *rhs_data, std::size_t rhs_size) {
  675. lhs.assign(lhs_data, lhs_size);
  676. rhs.assign(rhs_data, rhs_size);
  677. });
  678. return std::make_pair(std::move(lhs), std::move(rhs));
  679. };
  680. {
  681. const auto res = divide("", '=');
  682. EXPECT_EQ(res.first, "");
  683. EXPECT_EQ(res.second, "");
  684. }
  685. {
  686. const auto res = divide("=", '=');
  687. EXPECT_EQ(res.first, "");
  688. EXPECT_EQ(res.second, "");
  689. }
  690. {
  691. const auto res = divide(" ", '=');
  692. EXPECT_EQ(res.first, " ");
  693. EXPECT_EQ(res.second, "");
  694. }
  695. {
  696. const auto res = divide("a", '=');
  697. EXPECT_EQ(res.first, "a");
  698. EXPECT_EQ(res.second, "");
  699. }
  700. {
  701. const auto res = divide("a=", '=');
  702. EXPECT_EQ(res.first, "a");
  703. EXPECT_EQ(res.second, "");
  704. }
  705. {
  706. const auto res = divide("=b", '=');
  707. EXPECT_EQ(res.first, "");
  708. EXPECT_EQ(res.second, "b");
  709. }
  710. {
  711. const auto res = divide("a=b", '=');
  712. EXPECT_EQ(res.first, "a");
  713. EXPECT_EQ(res.second, "b");
  714. }
  715. {
  716. const auto res = divide("a=b=", '=');
  717. EXPECT_EQ(res.first, "a");
  718. EXPECT_EQ(res.second, "b=");
  719. }
  720. {
  721. const auto res = divide("a=b=c", '=');
  722. EXPECT_EQ(res.first, "a");
  723. EXPECT_EQ(res.second, "b=c");
  724. }
  725. }
  726. TEST(SplitTest, ParseQueryString) {
  727. string s = "key1=val1&key2=val2&key3=val3";
  728. Params dic;
  729. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  730. [&](const char *b, const char *e) {
  731. string key, val;
  732. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  733. if (key.empty()) {
  734. key.assign(b2, e2);
  735. } else {
  736. val.assign(b2, e2);
  737. }
  738. });
  739. dic.emplace(key, val);
  740. });
  741. EXPECT_EQ("val1", dic.find("key1")->second);
  742. EXPECT_EQ("val2", dic.find("key2")->second);
  743. EXPECT_EQ("val3", dic.find("key3")->second);
  744. }
  745. TEST(SplitTest, ParseInvalidQueryTests) {
  746. {
  747. string s = " ";
  748. Params dict;
  749. detail::parse_query_text(s, dict);
  750. EXPECT_TRUE(dict.empty());
  751. }
  752. {
  753. string s = " = =";
  754. Params dict;
  755. detail::parse_query_text(s, dict);
  756. EXPECT_TRUE(dict.empty());
  757. }
  758. }
  759. TEST(ParseQueryTest, ParseQueryString) {
  760. {
  761. std::string s = "key1=val1&key2=val2&key3=val3";
  762. Params dic;
  763. detail::parse_query_text(s, dic);
  764. EXPECT_EQ("val1", dic.find("key1")->second);
  765. EXPECT_EQ("val2", dic.find("key2")->second);
  766. EXPECT_EQ("val3", dic.find("key3")->second);
  767. }
  768. {
  769. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  770. Params dic;
  771. detail::parse_query_text(s, dic);
  772. EXPECT_EQ("", dic.find("key1")->second);
  773. EXPECT_EQ("val1", dic.find("key2")->second);
  774. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  775. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  776. }
  777. }
  778. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  779. Params dic;
  780. EXPECT_EQ(detail::params_to_query_str(dic), "");
  781. dic.emplace("key1", "val1");
  782. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  783. dic.emplace("key2", "val2");
  784. dic.emplace("key3", "val3");
  785. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  786. }
  787. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  788. string content_type = "multipart/form-data; boundary=something";
  789. string boundary;
  790. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  791. EXPECT_TRUE(ret);
  792. EXPECT_EQ(boundary, "something");
  793. }
  794. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  795. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  796. string boundary;
  797. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  798. EXPECT_TRUE(ret);
  799. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  800. }
  801. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  802. string content_type =
  803. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  804. string boundary;
  805. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  806. EXPECT_TRUE(ret);
  807. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  808. }
  809. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  810. string content_type =
  811. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  812. string boundary;
  813. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  814. EXPECT_TRUE(ret);
  815. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  816. }
  817. TEST(GetHeaderValueTest, DefaultValue) {
  818. Headers headers = {{"Dummy", "Dummy"}};
  819. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  820. EXPECT_STREQ("text/plain", val);
  821. }
  822. TEST(GetHeaderValueTest, DefaultValueInt) {
  823. Headers headers = {{"Dummy", "Dummy"}};
  824. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  825. EXPECT_EQ(100ull, val);
  826. }
  827. TEST(GetHeaderValueTest, RegularValue) {
  828. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  829. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  830. EXPECT_STREQ("text/html", val);
  831. }
  832. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  833. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  834. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  835. EXPECT_STREQ("text/html", val);
  836. }
  837. TEST(GetHeaderValueTest, SetContent) {
  838. Response res;
  839. res.set_content("html", "text/html");
  840. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  841. res.set_content("text", "text/plain");
  842. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  843. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  844. }
  845. TEST(GetHeaderValueTest, RegularValueInt) {
  846. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  847. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  848. EXPECT_EQ(100ull, val);
  849. }
  850. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  851. Headers headers = {{"Content-Length", "x"}};
  852. auto is_invalid_value = false;
  853. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  854. is_invalid_value);
  855. EXPECT_EQ(0ull, val);
  856. EXPECT_TRUE(is_invalid_value);
  857. }
  858. TEST(GetHeaderValueTest, Range) {
  859. {
  860. Headers headers = {make_range_header({{1, -1}})};
  861. auto val = detail::get_header_value(headers, "Range", 0, 0);
  862. EXPECT_STREQ("bytes=1-", val);
  863. }
  864. {
  865. Headers headers = {make_range_header({{-1, 1}})};
  866. auto val = detail::get_header_value(headers, "Range", 0, 0);
  867. EXPECT_STREQ("bytes=-1", val);
  868. }
  869. {
  870. Headers headers = {make_range_header({{1, 10}})};
  871. auto val = detail::get_header_value(headers, "Range", 0, 0);
  872. EXPECT_STREQ("bytes=1-10", val);
  873. }
  874. {
  875. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  876. auto val = detail::get_header_value(headers, "Range", 0, 0);
  877. EXPECT_STREQ("bytes=1-10, 100-", val);
  878. }
  879. {
  880. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  881. auto val = detail::get_header_value(headers, "Range", 0, 0);
  882. EXPECT_STREQ("bytes=1-10, 100-200", val);
  883. }
  884. {
  885. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  886. auto val = detail::get_header_value(headers, "Range", 0, 0);
  887. EXPECT_STREQ("bytes=0-0, -1", val);
  888. }
  889. }
  890. TEST(ParseHeaderValueTest, Range) {
  891. {
  892. Ranges ranges;
  893. auto ret = detail::parse_range_header("bytes=1-", ranges);
  894. EXPECT_TRUE(ret);
  895. EXPECT_EQ(1u, ranges.size());
  896. EXPECT_EQ(1u, ranges[0].first);
  897. EXPECT_EQ(-1, ranges[0].second);
  898. }
  899. {
  900. Ranges ranges;
  901. auto ret = detail::parse_range_header("bytes=-1", ranges);
  902. EXPECT_TRUE(ret);
  903. EXPECT_EQ(1u, ranges.size());
  904. EXPECT_EQ(-1, ranges[0].first);
  905. EXPECT_EQ(1u, ranges[0].second);
  906. }
  907. {
  908. Ranges ranges;
  909. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  910. EXPECT_TRUE(ret);
  911. EXPECT_EQ(1u, ranges.size());
  912. EXPECT_EQ(1u, ranges[0].first);
  913. EXPECT_EQ(10u, ranges[0].second);
  914. }
  915. {
  916. Ranges ranges;
  917. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  918. EXPECT_FALSE(ret);
  919. }
  920. {
  921. Ranges ranges;
  922. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  923. EXPECT_TRUE(ret);
  924. EXPECT_EQ(2u, ranges.size());
  925. EXPECT_EQ(1u, ranges[0].first);
  926. EXPECT_EQ(10u, ranges[0].second);
  927. EXPECT_EQ(100u, ranges[1].first);
  928. EXPECT_EQ(-1, ranges[1].second);
  929. }
  930. {
  931. Ranges ranges;
  932. auto ret =
  933. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  934. EXPECT_TRUE(ret);
  935. EXPECT_EQ(3u, ranges.size());
  936. EXPECT_EQ(1u, ranges[0].first);
  937. EXPECT_EQ(10u, ranges[0].second);
  938. EXPECT_EQ(100u, ranges[1].first);
  939. EXPECT_EQ(200u, ranges[1].second);
  940. EXPECT_EQ(300u, ranges[2].first);
  941. EXPECT_EQ(400u, ranges[2].second);
  942. }
  943. {
  944. Ranges ranges;
  945. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  946. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  947. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  948. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  949. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  950. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  951. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  952. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  953. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  954. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  955. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  956. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  957. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  958. EXPECT_TRUE(ranges.empty());
  959. }
  960. }
  961. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  962. Request req;
  963. req.set_header("Accept-Encoding", "gzip");
  964. Response res;
  965. res.set_header("Content-Type", "text/plain");
  966. auto ret = detail::encoding_type(req, res);
  967. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  968. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  969. #else
  970. EXPECT_TRUE(ret == detail::EncodingType::None);
  971. #endif
  972. }
  973. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  974. Request req;
  975. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  976. Response res;
  977. res.set_header("Content-Type", "text/plain");
  978. auto ret = detail::encoding_type(req, res);
  979. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  980. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  981. #elif CPPHTTPLIB_ZLIB_SUPPORT
  982. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  983. #elif CPPHTTPLIB_ZSTD_SUPPORT
  984. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  985. #else
  986. EXPECT_TRUE(ret == detail::EncodingType::None);
  987. #endif
  988. }
  989. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  990. Request req;
  991. req.set_header("Accept-Encoding",
  992. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  993. Response res;
  994. res.set_header("Content-Type", "text/plain");
  995. auto ret = detail::encoding_type(req, res);
  996. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  997. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  998. #elif CPPHTTPLIB_ZLIB_SUPPORT
  999. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1000. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1001. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1002. #else
  1003. EXPECT_TRUE(ret == detail::EncodingType::None);
  1004. #endif
  1005. }
  1006. TEST(BufferStreamTest, read) {
  1007. detail::BufferStream strm1;
  1008. Stream &strm = strm1;
  1009. EXPECT_EQ(5, strm.write("hello"));
  1010. char buf[512];
  1011. EXPECT_EQ(2, strm.read(buf, 2));
  1012. EXPECT_EQ('h', buf[0]);
  1013. EXPECT_EQ('e', buf[1]);
  1014. EXPECT_EQ(2, strm.read(buf, 2));
  1015. EXPECT_EQ('l', buf[0]);
  1016. EXPECT_EQ('l', buf[1]);
  1017. EXPECT_EQ(1, strm.read(buf, 1));
  1018. EXPECT_EQ('o', buf[0]);
  1019. EXPECT_EQ(0, strm.read(buf, 1));
  1020. }
  1021. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1022. auto host = "www.httpwatch.com";
  1023. auto ip = hosted_at(host);
  1024. EXPECT_EQ("23.96.13.243", ip);
  1025. std::vector<std::string> addrs;
  1026. hosted_at(host, addrs);
  1027. EXPECT_EQ(1u, addrs.size());
  1028. }
  1029. #if 0 // It depends on each test environment...
  1030. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1031. auto host = "www.youtube.com";
  1032. std::vector<std::string> addrs;
  1033. hosted_at(host, addrs);
  1034. EXPECT_EQ(20u, addrs.size());
  1035. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1036. EXPECT_TRUE(it != addrs.end());
  1037. }
  1038. #endif
  1039. class ChunkedEncodingTest : public ::testing::Test {
  1040. protected:
  1041. ChunkedEncodingTest()
  1042. : cli_(HOST, PORT)
  1043. #ifdef CPPHTTPLIB_SSL_ENABLED
  1044. ,
  1045. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1046. #endif
  1047. {
  1048. cli_.set_connection_timeout(2);
  1049. #ifdef CPPHTTPLIB_SSL_ENABLED
  1050. cli_.enable_server_certificate_verification(false);
  1051. #endif
  1052. }
  1053. virtual void SetUp() {
  1054. read_file("./image.jpg", image_data_);
  1055. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1056. res.set_content("Hello World!", "text/plain");
  1057. });
  1058. svr_.Get(
  1059. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1060. res.set_chunked_content_provider(
  1061. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1062. size_t remaining = image_data_.size() - offset;
  1063. if (remaining == 0) {
  1064. sink.done();
  1065. } else {
  1066. constexpr size_t CHUNK_SIZE = 1024;
  1067. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1068. sink.write(&image_data_[offset], send_size);
  1069. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1070. }
  1071. return true;
  1072. });
  1073. });
  1074. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1075. svr_.wait_until_ready();
  1076. }
  1077. virtual void TearDown() {
  1078. svr_.stop();
  1079. if (!request_threads_.empty()) {
  1080. std::this_thread::sleep_for(std::chrono::seconds(1));
  1081. for (auto &t : request_threads_) {
  1082. t.join();
  1083. }
  1084. }
  1085. t_.join();
  1086. }
  1087. #ifdef CPPHTTPLIB_SSL_ENABLED
  1088. SSLClient cli_;
  1089. SSLServer svr_;
  1090. #else
  1091. Client cli_;
  1092. Server svr_;
  1093. #endif
  1094. thread t_;
  1095. std::vector<thread> request_threads_;
  1096. std::string image_data_;
  1097. };
  1098. TEST_F(ChunkedEncodingTest, NormalGet) {
  1099. auto res = cli_.Get("/chunked");
  1100. ASSERT_TRUE(res);
  1101. std::string out;
  1102. read_file("./image.jpg", out);
  1103. EXPECT_EQ(StatusCode::OK_200, res->status);
  1104. EXPECT_EQ(out, res->body);
  1105. }
  1106. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1107. std::string body;
  1108. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1109. body.append(data, data_length);
  1110. return true;
  1111. });
  1112. ASSERT_TRUE(res);
  1113. std::string out;
  1114. read_file("./image.jpg", out);
  1115. EXPECT_EQ(StatusCode::OK_200, res->status);
  1116. EXPECT_EQ(out, body);
  1117. }
  1118. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1119. std::string body;
  1120. auto res = cli_.Get(
  1121. "/chunked",
  1122. [&](const Response &response) {
  1123. EXPECT_EQ(StatusCode::OK_200, response.status);
  1124. return true;
  1125. },
  1126. [&](const char *data, size_t data_length) {
  1127. body.append(data, data_length);
  1128. return true;
  1129. });
  1130. ASSERT_TRUE(res);
  1131. std::string out;
  1132. read_file("./image.jpg", out);
  1133. EXPECT_EQ(StatusCode::OK_200, res->status);
  1134. EXPECT_EQ(out, body);
  1135. }
  1136. TEST(RangeTest, FromHTTPBin_Online) {
  1137. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1138. auto host = "httpcan.org";
  1139. auto path = std::string{"/range/32"};
  1140. #else
  1141. auto host = "nghttp2.org";
  1142. auto path = std::string{"/httpbin/range/32"};
  1143. #endif
  1144. #ifdef CPPHTTPLIB_SSL_ENABLED
  1145. auto port = 443;
  1146. SSLClient cli(host, port);
  1147. #else
  1148. auto port = 80;
  1149. Client cli(host, port);
  1150. #endif
  1151. cli.set_connection_timeout(5);
  1152. {
  1153. auto res = cli.Get(path);
  1154. ASSERT_TRUE(res);
  1155. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1156. EXPECT_EQ(StatusCode::OK_200, res->status);
  1157. }
  1158. {
  1159. Headers headers = {make_range_header({{1, -1}})};
  1160. auto res = cli.Get(path, headers);
  1161. ASSERT_TRUE(res);
  1162. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1163. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1164. }
  1165. {
  1166. Headers headers = {make_range_header({{1, 10}})};
  1167. auto res = cli.Get(path, headers);
  1168. ASSERT_TRUE(res);
  1169. EXPECT_EQ("bcdefghijk", res->body);
  1170. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1171. }
  1172. {
  1173. Headers headers = {make_range_header({{0, 31}})};
  1174. auto res = cli.Get(path, headers);
  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({{0, -1}})};
  1181. auto res = cli.Get(path, headers);
  1182. ASSERT_TRUE(res);
  1183. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1184. EXPECT_EQ(StatusCode::OK_200, res->status);
  1185. }
  1186. {
  1187. Headers headers = {make_range_header({{0, 32}})};
  1188. auto res = cli.Get(path, headers);
  1189. ASSERT_TRUE(res);
  1190. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1191. }
  1192. }
  1193. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1194. auto host = "unresolvableaddress.local";
  1195. auto path = std::string{"/"};
  1196. #ifdef CPPHTTPLIB_SSL_ENABLED
  1197. auto port = 443;
  1198. SSLClient cli(host, port);
  1199. #else
  1200. auto port = 80;
  1201. Client cli(host, port);
  1202. #endif
  1203. cli.set_connection_timeout(1);
  1204. {
  1205. auto res = cli.Get(path);
  1206. ASSERT_FALSE(res);
  1207. }
  1208. std::this_thread::sleep_for(std::chrono::seconds(8));
  1209. }
  1210. TEST(ConnectionErrorTest, InvalidHost) {
  1211. auto host = "-abcde.com";
  1212. #ifdef CPPHTTPLIB_SSL_ENABLED
  1213. auto port = 443;
  1214. SSLClient cli(host, port);
  1215. #else
  1216. auto port = 80;
  1217. Client cli(host, port);
  1218. #endif
  1219. cli.set_connection_timeout(std::chrono::seconds(2));
  1220. auto res = cli.Get("/");
  1221. ASSERT_TRUE(!res);
  1222. EXPECT_EQ(Error::Connection, res.error());
  1223. }
  1224. TEST(ConnectionErrorTest, InvalidHost2) {
  1225. auto host = "httpcan.org/";
  1226. #ifdef CPPHTTPLIB_SSL_ENABLED
  1227. SSLClient cli(host);
  1228. #else
  1229. Client cli(host);
  1230. #endif
  1231. cli.set_connection_timeout(std::chrono::seconds(2));
  1232. auto res = cli.Get("/");
  1233. ASSERT_TRUE(!res);
  1234. EXPECT_EQ(Error::Connection, res.error());
  1235. }
  1236. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1237. auto host = "httpcan.org/";
  1238. #ifdef CPPHTTPLIB_SSL_ENABLED
  1239. SSLClient cli(host);
  1240. #else
  1241. Client cli(host);
  1242. #endif
  1243. cli.set_connection_timeout(std::chrono::seconds(2));
  1244. auto res = cli.Get("/");
  1245. ASSERT_TRUE(!res);
  1246. stringstream s;
  1247. s << "error code: " << res.error();
  1248. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1249. }
  1250. TEST(ConnectionErrorTest, InvalidPort) {
  1251. auto host = "localhost";
  1252. auto port = 44380;
  1253. #ifdef CPPHTTPLIB_SSL_ENABLED
  1254. SSLClient cli(host, port);
  1255. #else
  1256. Client cli(host, port);
  1257. #endif
  1258. cli.set_connection_timeout(std::chrono::seconds(2));
  1259. auto res = cli.Get("/");
  1260. ASSERT_TRUE(!res);
  1261. EXPECT_TRUE(Error::Connection == res.error() ||
  1262. Error::ConnectionTimeout == res.error());
  1263. }
  1264. TEST(ConnectionErrorTest, Timeout_Online) {
  1265. auto host = "google.com";
  1266. #ifdef CPPHTTPLIB_SSL_ENABLED
  1267. auto port = 44380;
  1268. SSLClient cli(host, port);
  1269. #else
  1270. auto port = 8080;
  1271. Client cli(host, port);
  1272. #endif
  1273. cli.set_connection_timeout(std::chrono::seconds(2));
  1274. // only probe one address type so that the error reason
  1275. // correlates to the timed-out IPv4, not the unsupported
  1276. // IPv6 connection attempt
  1277. cli.set_address_family(AF_INET);
  1278. auto res = cli.Get("/");
  1279. ASSERT_TRUE(!res);
  1280. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1281. }
  1282. TEST(CancelTest, NoCancel_Online) {
  1283. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1284. auto host = "httpcan.org";
  1285. auto path = std::string{"/range/32"};
  1286. #else
  1287. auto host = "nghttp2.org";
  1288. auto path = std::string{"/httpbin/range/32"};
  1289. #endif
  1290. #ifdef CPPHTTPLIB_SSL_ENABLED
  1291. auto port = 443;
  1292. SSLClient cli(host, port);
  1293. #else
  1294. auto port = 80;
  1295. Client cli(host, port);
  1296. #endif
  1297. cli.set_connection_timeout(std::chrono::seconds(5));
  1298. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1299. ASSERT_TRUE(res);
  1300. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1301. EXPECT_EQ(StatusCode::OK_200, res->status);
  1302. }
  1303. TEST(CancelTest, WithCancelSmallPayload_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. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1319. cli.set_connection_timeout(std::chrono::seconds(5));
  1320. ASSERT_TRUE(!res);
  1321. EXPECT_EQ(Error::Canceled, res.error());
  1322. }
  1323. TEST(CancelTest, WithCancelLargePayload_Online) {
  1324. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1325. auto host = "httpcan.org";
  1326. auto path = std::string{"/range/65536"};
  1327. #else
  1328. auto host = "nghttp2.org";
  1329. auto path = std::string{"/httpbin/range/65536"};
  1330. #endif
  1331. #ifdef CPPHTTPLIB_SSL_ENABLED
  1332. auto port = 443;
  1333. SSLClient cli(host, port);
  1334. #else
  1335. auto port = 80;
  1336. Client cli(host, port);
  1337. #endif
  1338. cli.set_connection_timeout(std::chrono::seconds(5));
  1339. uint32_t count = 0;
  1340. auto res =
  1341. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1342. ASSERT_TRUE(!res);
  1343. EXPECT_EQ(Error::Canceled, res.error());
  1344. }
  1345. TEST(CancelTest, NoCancelPost) {
  1346. Server svr;
  1347. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1348. res.set_content("Hello World!", "text/plain");
  1349. });
  1350. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1351. auto se = detail::scope_exit([&] {
  1352. svr.stop();
  1353. thread.join();
  1354. ASSERT_FALSE(svr.is_running());
  1355. });
  1356. svr.wait_until_ready();
  1357. Client cli(HOST, PORT);
  1358. cli.set_connection_timeout(std::chrono::seconds(5));
  1359. auto res =
  1360. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1361. "application/json", [](uint64_t, uint64_t) { return true; });
  1362. ASSERT_TRUE(res);
  1363. EXPECT_EQ("Hello World!", res->body);
  1364. EXPECT_EQ(StatusCode::OK_200, res->status);
  1365. }
  1366. TEST(CancelTest, WithCancelSmallPayloadPost) {
  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 false; });
  1383. ASSERT_TRUE(!res);
  1384. EXPECT_EQ(Error::Canceled, res.error());
  1385. }
  1386. TEST(CancelTest, WithCancelLargePayloadPost) {
  1387. Server svr;
  1388. svr.set_payload_max_length(200 * 1024 * 1024);
  1389. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1390. res.set_content(LARGE_DATA, "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_payload_max_length(200 * 1024 * 1024);
  1401. cli.set_connection_timeout(std::chrono::seconds(5));
  1402. auto res =
  1403. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1404. "application/json", [](uint64_t, uint64_t) { return false; });
  1405. ASSERT_TRUE(!res);
  1406. EXPECT_EQ(Error::Canceled, res.error());
  1407. }
  1408. TEST(CancelTest, NoCancelPut) {
  1409. Server svr;
  1410. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1411. res.set_content("Hello World!", "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_connection_timeout(std::chrono::seconds(5));
  1422. auto res =
  1423. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1424. "application/json", [](uint64_t, uint64_t) { return true; });
  1425. ASSERT_TRUE(res);
  1426. EXPECT_EQ("Hello World!", res->body);
  1427. EXPECT_EQ(StatusCode::OK_200, res->status);
  1428. }
  1429. TEST(CancelTest, WithCancelSmallPayloadPut) {
  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 false; });
  1446. ASSERT_TRUE(!res);
  1447. EXPECT_EQ(Error::Canceled, res.error());
  1448. }
  1449. TEST(CancelTest, WithCancelLargePayloadPut) {
  1450. Server svr;
  1451. svr.set_payload_max_length(200 * 1024 * 1024);
  1452. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1453. res.set_content(LARGE_DATA, "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_payload_max_length(200 * 1024 * 1024);
  1464. cli.set_connection_timeout(std::chrono::seconds(5));
  1465. auto res =
  1466. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1467. "application/json", [](uint64_t, uint64_t) { return false; });
  1468. ASSERT_TRUE(!res);
  1469. EXPECT_EQ(Error::Canceled, res.error());
  1470. }
  1471. TEST(CancelTest, NoCancelPatch) {
  1472. Server svr;
  1473. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1474. res.set_content("Hello World!", "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_connection_timeout(std::chrono::seconds(5));
  1485. auto res =
  1486. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1487. "application/json", [](uint64_t, uint64_t) { return true; });
  1488. ASSERT_TRUE(res);
  1489. EXPECT_EQ("Hello World!", res->body);
  1490. EXPECT_EQ(StatusCode::OK_200, res->status);
  1491. }
  1492. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  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 false; });
  1509. ASSERT_TRUE(!res);
  1510. EXPECT_EQ(Error::Canceled, res.error());
  1511. }
  1512. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1513. Server svr;
  1514. svr.set_payload_max_length(200 * 1024 * 1024);
  1515. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1516. res.set_content(LARGE_DATA, "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_payload_max_length(200 * 1024 * 1024);
  1527. cli.set_connection_timeout(std::chrono::seconds(5));
  1528. auto res =
  1529. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1530. "application/json", [](uint64_t, uint64_t) { return false; });
  1531. ASSERT_TRUE(!res);
  1532. EXPECT_EQ(Error::Canceled, res.error());
  1533. }
  1534. TEST(CancelTest, NoCancelDelete) {
  1535. Server svr;
  1536. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1537. res.set_content("Hello World!", "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_connection_timeout(std::chrono::seconds(5));
  1548. auto res =
  1549. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1550. "application/json", [](uint64_t, uint64_t) { return true; });
  1551. ASSERT_TRUE(res);
  1552. EXPECT_EQ("Hello World!", res->body);
  1553. EXPECT_EQ(StatusCode::OK_200, res->status);
  1554. }
  1555. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  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 false; });
  1572. ASSERT_TRUE(!res);
  1573. EXPECT_EQ(Error::Canceled, res.error());
  1574. }
  1575. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1576. Server svr;
  1577. svr.set_payload_max_length(200 * 1024 * 1024);
  1578. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1579. res.set_content(LARGE_DATA, "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_payload_max_length(200 * 1024 * 1024);
  1590. cli.set_connection_timeout(std::chrono::seconds(5));
  1591. auto res =
  1592. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1593. "application/json", [](uint64_t, uint64_t) { return false; });
  1594. ASSERT_TRUE(!res);
  1595. EXPECT_EQ(Error::Canceled, res.error());
  1596. }
  1597. static std::string remove_whitespace(const std::string &input) {
  1598. std::string output;
  1599. output.reserve(input.size());
  1600. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1601. [](unsigned char c) { return !std::isspace(c); });
  1602. return output;
  1603. }
  1604. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1605. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1606. auto host = "httpcan.org";
  1607. auto path = std::string{"/basic-auth/hello/world"};
  1608. #else
  1609. auto host = "nghttp2.org";
  1610. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1611. #endif
  1612. #ifdef CPPHTTPLIB_SSL_ENABLED
  1613. auto port = 443;
  1614. SSLClient cli(host, port);
  1615. #else
  1616. auto port = 80;
  1617. Client cli(host, port);
  1618. #endif
  1619. {
  1620. auto res = cli.Get(path);
  1621. ASSERT_TRUE(res);
  1622. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1623. }
  1624. {
  1625. auto res =
  1626. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1627. ASSERT_TRUE(res);
  1628. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1629. remove_whitespace(res->body));
  1630. EXPECT_EQ(StatusCode::OK_200, res->status);
  1631. }
  1632. {
  1633. cli.set_basic_auth("hello", "world");
  1634. auto res = cli.Get(path);
  1635. ASSERT_TRUE(res);
  1636. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1637. remove_whitespace(res->body));
  1638. EXPECT_EQ(StatusCode::OK_200, res->status);
  1639. }
  1640. {
  1641. cli.set_basic_auth("hello", "bad");
  1642. auto res = cli.Get(path);
  1643. ASSERT_TRUE(res);
  1644. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1645. }
  1646. {
  1647. cli.set_basic_auth("bad", "world");
  1648. auto res = cli.Get(path);
  1649. ASSERT_TRUE(res);
  1650. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1651. }
  1652. }
  1653. #ifdef CPPHTTPLIB_SSL_ENABLED
  1654. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1655. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1656. auto host = "httpcan.org";
  1657. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1658. auto paths = std::vector<std::string>{
  1659. "/digest-auth/auth/hello/world/MD5",
  1660. "/digest-auth/auth/hello/world/SHA-256",
  1661. "/digest-auth/auth/hello/world/SHA-512",
  1662. };
  1663. #else
  1664. auto host = "nghttp2.org";
  1665. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1666. auto paths = std::vector<std::string>{
  1667. "/httpbin/digest-auth/auth/hello/world/MD5",
  1668. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1669. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1670. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1671. };
  1672. #endif
  1673. auto port = 443;
  1674. SSLClient cli(host, port);
  1675. {
  1676. auto res = cli.Get(unauth_path);
  1677. ASSERT_TRUE(res);
  1678. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1679. }
  1680. {
  1681. cli.set_digest_auth("hello", "world");
  1682. for (const auto &path : paths) {
  1683. auto res = cli.Get(path.c_str());
  1684. ASSERT_TRUE(res);
  1685. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1686. std::string algo(path.substr(path.rfind('/') + 1));
  1687. EXPECT_EQ(
  1688. remove_whitespace("{\"algorithm\":\"" + algo +
  1689. "\",\"authenticated\":true,\"user\":\"hello\"}\n"),
  1690. remove_whitespace(res->body));
  1691. #else
  1692. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1693. remove_whitespace(res->body));
  1694. #endif
  1695. EXPECT_EQ(StatusCode::OK_200, res->status);
  1696. }
  1697. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1698. cli.set_digest_auth("hello", "bad");
  1699. for (const auto &path : paths) {
  1700. auto res = cli.Get(path.c_str());
  1701. ASSERT_TRUE(res);
  1702. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1703. }
  1704. #endif
  1705. }
  1706. }
  1707. #endif
  1708. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1709. auto host = "google.com";
  1710. auto another_host = "example.com";
  1711. auto wrong_ip = "0.0.0.0";
  1712. #ifdef CPPHTTPLIB_SSL_ENABLED
  1713. SSLClient cli(host);
  1714. #else
  1715. Client cli(host);
  1716. #endif
  1717. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1718. auto res = cli.Get("/");
  1719. ASSERT_TRUE(res);
  1720. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1721. }
  1722. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1723. auto host = "google.com";
  1724. auto wrong_ip = "0.0.0.0";
  1725. #ifdef CPPHTTPLIB_SSL_ENABLED
  1726. SSLClient cli(host);
  1727. #else
  1728. Client cli(host);
  1729. #endif
  1730. cli.set_hostname_addr_map({{host, wrong_ip}});
  1731. auto res = cli.Get("/");
  1732. ASSERT_TRUE(!res);
  1733. EXPECT_EQ(Error::Connection, res.error());
  1734. }
  1735. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1736. auto host = "nghttp2.org";
  1737. #ifdef CPPHTTPLIB_SSL_ENABLED
  1738. SSLClient cli(host);
  1739. #else
  1740. Client cli(host);
  1741. #endif
  1742. cli.set_follow_location(true);
  1743. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1744. ASSERT_TRUE(res);
  1745. EXPECT_EQ(StatusCode::OK_200, res->status);
  1746. }
  1747. TEST(RedirectTest, Redirect_Online) {
  1748. auto host = "nghttp2.org";
  1749. #ifdef CPPHTTPLIB_SSL_ENABLED
  1750. SSLClient cli(host);
  1751. #else
  1752. Client cli(host);
  1753. #endif
  1754. cli.set_follow_location(true);
  1755. auto res = cli.Get("/httpbin/redirect/3");
  1756. ASSERT_TRUE(res);
  1757. EXPECT_EQ(StatusCode::OK_200, res->status);
  1758. }
  1759. TEST(RelativeRedirectTest, Redirect_Online) {
  1760. auto host = "nghttp2.org";
  1761. #ifdef CPPHTTPLIB_SSL_ENABLED
  1762. SSLClient cli(host);
  1763. #else
  1764. Client cli(host);
  1765. #endif
  1766. cli.set_follow_location(true);
  1767. auto res = cli.Get("/httpbin/relative-redirect/3");
  1768. ASSERT_TRUE(res);
  1769. EXPECT_EQ(StatusCode::OK_200, res->status);
  1770. }
  1771. TEST(TooManyRedirectTest, Redirect_Online) {
  1772. auto host = "nghttp2.org";
  1773. #ifdef CPPHTTPLIB_SSL_ENABLED
  1774. SSLClient cli(host);
  1775. #else
  1776. Client cli(host);
  1777. #endif
  1778. cli.set_follow_location(true);
  1779. auto res = cli.Get("/httpbin/redirect/21");
  1780. ASSERT_TRUE(!res);
  1781. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1782. }
  1783. #ifdef CPPHTTPLIB_SSL_ENABLED
  1784. TEST(YahooRedirectTest, Redirect_Online) {
  1785. Client cli("yahoo.com");
  1786. auto res = cli.Get("/");
  1787. ASSERT_TRUE(res);
  1788. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1789. cli.set_follow_location(true);
  1790. res = cli.Get("/");
  1791. ASSERT_TRUE(res);
  1792. EXPECT_EQ(StatusCode::OK_200, res->status);
  1793. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1794. }
  1795. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1796. #define REDIR_HOST "httpbingo.org"
  1797. #define REDIR_PATH "/redirect-to"
  1798. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1799. SSLClient cli(REDIR_HOST);
  1800. cli.set_follow_location(true);
  1801. auto res =
  1802. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1803. ASSERT_TRUE(res);
  1804. EXPECT_EQ(StatusCode::OK_200, res->status);
  1805. }
  1806. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1807. SSLClient cli(REDIR_HOST);
  1808. cli.set_follow_location(true);
  1809. Params params;
  1810. params.emplace("url", "http://example.com");
  1811. params.emplace("status_code", "302");
  1812. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1813. ASSERT_TRUE(res);
  1814. EXPECT_EQ(StatusCode::OK_200, res->status);
  1815. }
  1816. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1817. SSLClient cli(REDIR_HOST);
  1818. cli.set_follow_location(true);
  1819. Params params;
  1820. params.emplace("url", "http://example.com");
  1821. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1822. ASSERT_TRUE(res);
  1823. EXPECT_EQ(StatusCode::OK_200, res->status);
  1824. }
  1825. TEST(UrlWithSpace, Redirect_Online) {
  1826. SSLClient cli("edge.forgecdn.net");
  1827. cli.set_follow_location(true);
  1828. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1829. ASSERT_TRUE(res);
  1830. EXPECT_EQ(StatusCode::OK_200, res->status);
  1831. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1832. }
  1833. #endif
  1834. #if !defined(_WIN32) && !defined(_WIN64)
  1835. TEST(ReceiveSignals, Signal) {
  1836. auto setupSignalHandlers = []() {
  1837. struct sigaction act;
  1838. sigemptyset(&act.sa_mask);
  1839. act.sa_flags = SA_SIGINFO;
  1840. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1841. switch (sig) {
  1842. case SIGINT:
  1843. default: break;
  1844. }
  1845. };
  1846. ::sigaction(SIGINT, &act, nullptr);
  1847. };
  1848. Server svr;
  1849. int port = 0;
  1850. auto thread = std::thread([&]() {
  1851. setupSignalHandlers();
  1852. port = svr.bind_to_any_port(HOST);
  1853. svr.listen_after_bind();
  1854. });
  1855. auto se = detail::scope_exit([&] {
  1856. svr.stop();
  1857. thread.join();
  1858. ASSERT_FALSE(svr.is_running());
  1859. });
  1860. svr.wait_until_ready();
  1861. ASSERT_TRUE(svr.is_running());
  1862. pthread_kill(thread.native_handle(), SIGINT);
  1863. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1864. ASSERT_TRUE(svr.is_running());
  1865. }
  1866. #endif
  1867. TEST(RedirectToDifferentPort, Redirect) {
  1868. Server svr1;
  1869. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1870. res.set_content("Hello World!", "text/plain");
  1871. });
  1872. int svr1_port = 0;
  1873. auto thread1 = std::thread([&]() {
  1874. svr1_port = svr1.bind_to_any_port(HOST);
  1875. svr1.listen_after_bind();
  1876. });
  1877. Server svr2;
  1878. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1879. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1880. });
  1881. int svr2_port = 0;
  1882. auto thread2 = std::thread([&]() {
  1883. svr2_port = svr2.bind_to_any_port(HOST);
  1884. svr2.listen_after_bind();
  1885. });
  1886. auto se = detail::scope_exit([&] {
  1887. svr2.stop();
  1888. thread2.join();
  1889. svr1.stop();
  1890. thread1.join();
  1891. ASSERT_FALSE(svr2.is_running());
  1892. ASSERT_FALSE(svr1.is_running());
  1893. });
  1894. svr1.wait_until_ready();
  1895. svr2.wait_until_ready();
  1896. Client cli("localhost", svr2_port);
  1897. cli.set_follow_location(true);
  1898. auto res = cli.Get("/2");
  1899. ASSERT_TRUE(res);
  1900. EXPECT_EQ(StatusCode::OK_200, res->status);
  1901. EXPECT_EQ("Hello World!", res->body);
  1902. }
  1903. TEST(RedirectFromPageWithContent, Redirect) {
  1904. Server svr;
  1905. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1906. res.set_content("___", "text/plain");
  1907. res.set_redirect("/2");
  1908. });
  1909. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1910. res.set_content("Hello World!", "text/plain");
  1911. });
  1912. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1913. auto se = detail::scope_exit([&] {
  1914. svr.stop();
  1915. th.join();
  1916. ASSERT_FALSE(svr.is_running());
  1917. });
  1918. svr.wait_until_ready();
  1919. {
  1920. Client cli("localhost", PORT);
  1921. cli.set_follow_location(true);
  1922. std::string body;
  1923. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1924. body.append(data, data_length);
  1925. return true;
  1926. });
  1927. ASSERT_TRUE(res);
  1928. EXPECT_EQ(StatusCode::OK_200, res->status);
  1929. EXPECT_EQ("Hello World!", body);
  1930. }
  1931. {
  1932. Client cli("localhost", PORT);
  1933. std::string body;
  1934. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1935. body.append(data, data_length);
  1936. return true;
  1937. });
  1938. ASSERT_TRUE(res);
  1939. EXPECT_EQ(StatusCode::Found_302, res->status);
  1940. EXPECT_EQ("___", body);
  1941. }
  1942. }
  1943. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1944. Server svr;
  1945. auto port_str = std::to_string(PORT);
  1946. auto redirect_url = "http://[::1]:" + port_str + "/2";
  1947. auto expected_host = "[::1]:" + port_str;
  1948. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1949. res.set_content("___", "text/plain");
  1950. // res.set_redirect("/2");
  1951. res.set_redirect(redirect_url);
  1952. });
  1953. svr.Get("/2", [&](const Request &req, Response &res) {
  1954. auto host_header = req.headers.find("Host");
  1955. ASSERT_TRUE(host_header != req.headers.end());
  1956. EXPECT_EQ(expected_host, host_header->second);
  1957. res.set_content("Hello World!", "text/plain");
  1958. });
  1959. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  1960. auto se = detail::scope_exit([&] {
  1961. svr.stop();
  1962. th.join();
  1963. ASSERT_FALSE(svr.is_running());
  1964. });
  1965. // When IPV6 support isn't available svr.listen("::1", PORT) never
  1966. // actually starts anything, so the condition !svr.is_running() will
  1967. // always remain true, and the loop never stops.
  1968. // This basically counts how many milliseconds have passed since the
  1969. // call to svr.listen(), and if after 5 seconds nothing started yet
  1970. // aborts the test.
  1971. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1972. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1973. ASSERT_LT(milliseconds, 5000U);
  1974. }
  1975. {
  1976. Client cli("::1", PORT);
  1977. cli.set_follow_location(true);
  1978. std::string body;
  1979. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1980. body.append(data, data_length);
  1981. return true;
  1982. });
  1983. ASSERT_TRUE(res);
  1984. EXPECT_EQ(StatusCode::OK_200, res->status);
  1985. EXPECT_EQ("Hello World!", body);
  1986. }
  1987. {
  1988. Client cli("::1", PORT);
  1989. std::string body;
  1990. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1991. body.append(data, data_length);
  1992. return true;
  1993. });
  1994. ASSERT_TRUE(res);
  1995. EXPECT_EQ(StatusCode::Found_302, res->status);
  1996. EXPECT_EQ("___", body);
  1997. }
  1998. }
  1999. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2000. Server svr;
  2001. svr.Get("/foo", [](const Request &req, Response &res) {
  2002. auto a = req.params.find("a");
  2003. if (a != req.params.end()) {
  2004. res.set_content((*a).second, "text/plain");
  2005. res.status = StatusCode::OK_200;
  2006. } else {
  2007. res.status = StatusCode::BadRequest_400;
  2008. }
  2009. });
  2010. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2011. auto se = detail::scope_exit([&] {
  2012. svr.stop();
  2013. thread.join();
  2014. ASSERT_FALSE(svr.is_running());
  2015. });
  2016. svr.wait_until_ready();
  2017. {
  2018. Client cli(HOST, PORT);
  2019. cli.set_path_encode(false);
  2020. auto res = cli.Get("/foo?a=explicitly+encoded");
  2021. ASSERT_TRUE(res);
  2022. EXPECT_EQ(StatusCode::OK_200, res->status);
  2023. // This expects it back with a space, as the `+` won't have been
  2024. // url-encoded, and server-side the params get decoded turning `+`
  2025. // into spaces.
  2026. EXPECT_EQ("explicitly encoded", res->body);
  2027. }
  2028. }
  2029. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2030. Server svr;
  2031. svr.Get("/", [](const Request &req, Response &) {
  2032. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2033. });
  2034. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2035. auto se = detail::scope_exit([&] {
  2036. svr.stop();
  2037. thread.join();
  2038. ASSERT_FALSE(svr.is_running());
  2039. });
  2040. svr.wait_until_ready();
  2041. {
  2042. Client cli(HOST, PORT);
  2043. cli.set_path_encode(false);
  2044. auto res = cli.Get("/?something=%0A");
  2045. ASSERT_TRUE(res);
  2046. EXPECT_EQ(StatusCode::OK_200, res->status);
  2047. }
  2048. }
  2049. TEST(BindServerTest, DISABLED_BindDualStack) {
  2050. Server svr;
  2051. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2052. res.set_content("Hello World!", "text/plain");
  2053. });
  2054. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2055. auto se = detail::scope_exit([&] {
  2056. svr.stop();
  2057. thread.join();
  2058. ASSERT_FALSE(svr.is_running());
  2059. });
  2060. svr.wait_until_ready();
  2061. {
  2062. Client cli("127.0.0.1", PORT);
  2063. auto res = cli.Get("/1");
  2064. ASSERT_TRUE(res);
  2065. EXPECT_EQ(StatusCode::OK_200, res->status);
  2066. EXPECT_EQ("Hello World!", res->body);
  2067. }
  2068. {
  2069. Client cli("::1", PORT);
  2070. auto res = cli.Get("/1");
  2071. ASSERT_TRUE(res);
  2072. EXPECT_EQ(StatusCode::OK_200, res->status);
  2073. EXPECT_EQ("Hello World!", res->body);
  2074. }
  2075. }
  2076. TEST(BindServerTest, BindAndListenSeparately) {
  2077. Server svr;
  2078. int port = svr.bind_to_any_port("0.0.0.0");
  2079. ASSERT_TRUE(svr.is_valid());
  2080. ASSERT_TRUE(port > 0);
  2081. svr.stop();
  2082. }
  2083. #ifdef CPPHTTPLIB_SSL_ENABLED
  2084. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2085. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2086. CLIENT_CA_CERT_DIR);
  2087. int port = svr.bind_to_any_port("0.0.0.0");
  2088. ASSERT_TRUE(svr.is_valid());
  2089. ASSERT_TRUE(port > 0);
  2090. svr.stop();
  2091. }
  2092. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2093. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2094. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2095. int port = svr.bind_to_any_port("0.0.0.0");
  2096. ASSERT_TRUE(svr.is_valid());
  2097. ASSERT_TRUE(port > 0);
  2098. svr.stop();
  2099. }
  2100. TEST(BindServerTest, UpdateCertsPem) {
  2101. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2102. int port = svr.bind_to_any_port("0.0.0.0");
  2103. ASSERT_TRUE(svr.is_valid());
  2104. ASSERT_TRUE(port > 0);
  2105. // Read PEM files
  2106. std::string cert_pem, key_pem, ca_pem;
  2107. read_file(SERVER_CERT_FILE, cert_pem);
  2108. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2109. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2110. // Update server certificates using PEM API
  2111. ASSERT_TRUE(
  2112. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2113. ASSERT_TRUE(svr.is_valid());
  2114. svr.stop();
  2115. }
  2116. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2117. // Start server with client CA (enables client auth)
  2118. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2119. ASSERT_TRUE(svr.is_valid());
  2120. bool handler_called = false;
  2121. svr.Get("/test", [&](const Request &req, Response &res) {
  2122. handler_called = true;
  2123. // Verify client certificate is present
  2124. auto cert = req.peer_cert();
  2125. EXPECT_TRUE(static_cast<bool>(cert));
  2126. res.set_content("ok", "text/plain");
  2127. });
  2128. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2129. auto se = detail::scope_exit([&] {
  2130. svr.stop();
  2131. t.join();
  2132. ASSERT_FALSE(svr.is_running());
  2133. });
  2134. svr.wait_until_ready();
  2135. // Read PEM files
  2136. std::string cert_pem, key_pem, ca_pem;
  2137. read_file(SERVER_CERT_FILE, cert_pem);
  2138. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2139. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2140. // Update server certificates and client CA using PEM API while server running
  2141. ASSERT_TRUE(
  2142. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2143. // Connect with client certificate
  2144. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2145. cli.enable_server_certificate_verification(false);
  2146. cli.set_connection_timeout(30);
  2147. auto res = cli.Get("/test");
  2148. ASSERT_TRUE(res);
  2149. ASSERT_EQ(StatusCode::OK_200, res->status);
  2150. ASSERT_TRUE(handler_called);
  2151. EXPECT_EQ("ok", res->body);
  2152. }
  2153. #endif
  2154. TEST(ErrorHandlerTest, ContentLength) {
  2155. Server svr;
  2156. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2157. res.status = StatusCode::OK_200;
  2158. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2159. "text/html"); // <= Content-Length still 13
  2160. });
  2161. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2162. res.set_content("Hello World!\n", "text/plain");
  2163. res.status = 524;
  2164. });
  2165. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2166. auto se = detail::scope_exit([&] {
  2167. svr.stop();
  2168. thread.join();
  2169. ASSERT_FALSE(svr.is_running());
  2170. });
  2171. svr.wait_until_ready();
  2172. {
  2173. Client cli(HOST, PORT);
  2174. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2175. ASSERT_TRUE(res);
  2176. EXPECT_EQ(StatusCode::OK_200, res->status);
  2177. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2178. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2179. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2180. }
  2181. }
  2182. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2183. TEST(ExceptionTest, WithoutExceptionHandler) {
  2184. Server svr;
  2185. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2186. throw std::runtime_error("exception...");
  2187. });
  2188. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2189. throw std::runtime_error("exception\r\n...");
  2190. });
  2191. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2192. auto se = detail::scope_exit([&] {
  2193. svr.stop();
  2194. listen_thread.join();
  2195. ASSERT_FALSE(svr.is_running());
  2196. });
  2197. svr.wait_until_ready();
  2198. Client cli("localhost", PORT);
  2199. {
  2200. auto res = cli.Get("/exception");
  2201. ASSERT_TRUE(res);
  2202. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2203. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2204. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2205. }
  2206. {
  2207. auto res = cli.Get("/unknown");
  2208. ASSERT_TRUE(res);
  2209. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2210. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2211. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2212. }
  2213. }
  2214. TEST(ExceptionTest, WithExceptionHandler) {
  2215. Server svr;
  2216. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2217. std::exception_ptr ep) {
  2218. EXPECT_FALSE(ep == nullptr);
  2219. try {
  2220. std::rethrow_exception(ep);
  2221. } catch (std::exception &e) {
  2222. EXPECT_EQ("abc", std::string(e.what()));
  2223. } catch (...) {}
  2224. res.status = StatusCode::InternalServerError_500;
  2225. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2226. "text/html"); // <= Content-Length still 13 at this point
  2227. });
  2228. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2229. res.set_content("Hello World!\n", "text/plain");
  2230. throw std::runtime_error("abc");
  2231. });
  2232. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2233. auto se = detail::scope_exit([&] {
  2234. svr.stop();
  2235. thread.join();
  2236. ASSERT_FALSE(svr.is_running());
  2237. });
  2238. svr.wait_until_ready();
  2239. for (size_t i = 0; i < 10; i++) {
  2240. Client cli(HOST, PORT);
  2241. for (size_t j = 0; j < 100; j++) {
  2242. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2243. ASSERT_TRUE(res);
  2244. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2245. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2246. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2247. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2248. }
  2249. cli.set_keep_alive(true);
  2250. for (size_t j = 0; j < 100; j++) {
  2251. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2252. ASSERT_TRUE(res);
  2253. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2254. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2255. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2256. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2257. }
  2258. }
  2259. }
  2260. TEST(ExceptionTest, AndErrorHandler) {
  2261. Server svr;
  2262. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2263. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2264. });
  2265. svr.set_exception_handler(
  2266. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2267. EXPECT_FALSE(ep == nullptr);
  2268. try {
  2269. std::rethrow_exception(ep);
  2270. } catch (std::exception &e) {
  2271. res.set_content(e.what(), "text/html");
  2272. } catch (...) {}
  2273. res.status = StatusCode::InternalServerError_500;
  2274. });
  2275. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2276. throw std::runtime_error("EXCEPTION");
  2277. });
  2278. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2279. res.set_content("ERROR", "text/html");
  2280. res.status = StatusCode::InternalServerError_500;
  2281. });
  2282. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2283. auto se = detail::scope_exit([&] {
  2284. svr.stop();
  2285. thread.join();
  2286. ASSERT_FALSE(svr.is_running());
  2287. });
  2288. svr.wait_until_ready();
  2289. Client cli(HOST, PORT);
  2290. {
  2291. auto res = cli.Get("/exception");
  2292. ASSERT_TRUE(res);
  2293. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2294. EXPECT_EQ("EXCEPTION", res->body);
  2295. }
  2296. {
  2297. auto res = cli.Get("/error");
  2298. ASSERT_TRUE(res);
  2299. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2300. EXPECT_EQ("ERROR", res->body);
  2301. }
  2302. {
  2303. auto res = cli.Get("/invalid");
  2304. ASSERT_TRUE(res);
  2305. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2306. EXPECT_EQ("NOT_FOUND", res->body);
  2307. }
  2308. }
  2309. #endif
  2310. TEST(NoContentTest, ContentLength) {
  2311. Server svr;
  2312. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2313. res.status = StatusCode::NoContent_204;
  2314. });
  2315. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2316. auto se = detail::scope_exit([&] {
  2317. svr.stop();
  2318. thread.join();
  2319. ASSERT_FALSE(svr.is_running());
  2320. });
  2321. svr.wait_until_ready();
  2322. {
  2323. Client cli(HOST, PORT);
  2324. auto res = cli.Get("/hi");
  2325. ASSERT_TRUE(res);
  2326. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2327. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2328. }
  2329. }
  2330. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2331. #ifdef CPPHTTPLIB_SSL_ENABLED
  2332. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2333. ASSERT_TRUE(svr.is_valid());
  2334. #else
  2335. Server svr;
  2336. #endif
  2337. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2338. if (req.path == "/routing_handler") {
  2339. res.set_header("PRE_ROUTING", "on");
  2340. res.set_content("Routing Handler", "text/plain");
  2341. return httplib::Server::HandlerResponse::Handled;
  2342. }
  2343. return httplib::Server::HandlerResponse::Unhandled;
  2344. });
  2345. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2346. res.set_content("Error", "text/html");
  2347. });
  2348. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2349. if (req.path == "/routing_handler") {
  2350. res.set_header("POST_ROUTING", "on");
  2351. }
  2352. });
  2353. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2354. res.set_content("Hello World!\n", "text/plain");
  2355. });
  2356. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2357. auto se = detail::scope_exit([&] {
  2358. svr.stop();
  2359. thread.join();
  2360. ASSERT_FALSE(svr.is_running());
  2361. });
  2362. svr.wait_until_ready();
  2363. {
  2364. #ifdef CPPHTTPLIB_SSL_ENABLED
  2365. SSLClient cli(HOST, PORT);
  2366. cli.enable_server_certificate_verification(false);
  2367. #else
  2368. Client cli(HOST, PORT);
  2369. #endif
  2370. auto res = cli.Get("/routing_handler");
  2371. ASSERT_TRUE(res);
  2372. EXPECT_EQ(StatusCode::OK_200, res->status);
  2373. EXPECT_EQ("Routing Handler", res->body);
  2374. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2375. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2376. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2377. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2378. }
  2379. {
  2380. #ifdef CPPHTTPLIB_SSL_ENABLED
  2381. SSLClient cli(HOST, PORT);
  2382. cli.enable_server_certificate_verification(false);
  2383. #else
  2384. Client cli(HOST, PORT);
  2385. #endif
  2386. auto res = cli.Get("/hi");
  2387. ASSERT_TRUE(res);
  2388. EXPECT_EQ(StatusCode::OK_200, res->status);
  2389. EXPECT_EQ("Hello World!\n", res->body);
  2390. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2391. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2392. }
  2393. {
  2394. #ifdef CPPHTTPLIB_SSL_ENABLED
  2395. SSLClient cli(HOST, PORT);
  2396. cli.enable_server_certificate_verification(false);
  2397. #else
  2398. Client cli(HOST, PORT);
  2399. #endif
  2400. auto res = cli.Get("/aaa");
  2401. ASSERT_TRUE(res);
  2402. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2403. EXPECT_EQ("Error", res->body);
  2404. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2405. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2406. }
  2407. }
  2408. TEST(RequestHandlerTest, PreRequestHandler) {
  2409. auto route_path = "/user/:user";
  2410. Server svr;
  2411. svr.Get("/hi", [](const Request &, Response &res) {
  2412. res.set_content("hi", "text/plain");
  2413. });
  2414. svr.Get(route_path, [](const Request &req, Response &res) {
  2415. res.set_content(req.path_params.at("user"), "text/plain");
  2416. });
  2417. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2418. if (req.matched_route == route_path) {
  2419. auto user = req.path_params.at("user");
  2420. if (user != "john") {
  2421. res.status = StatusCode::Forbidden_403;
  2422. res.set_content("error", "text/html");
  2423. return Server::HandlerResponse::Handled;
  2424. }
  2425. }
  2426. return Server::HandlerResponse::Unhandled;
  2427. });
  2428. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2429. auto se = detail::scope_exit([&] {
  2430. svr.stop();
  2431. thread.join();
  2432. ASSERT_FALSE(svr.is_running());
  2433. });
  2434. svr.wait_until_ready();
  2435. Client cli(HOST, PORT);
  2436. {
  2437. auto res = cli.Get("/hi");
  2438. ASSERT_TRUE(res);
  2439. EXPECT_EQ(StatusCode::OK_200, res->status);
  2440. EXPECT_EQ("hi", res->body);
  2441. }
  2442. {
  2443. auto res = cli.Get("/user/john");
  2444. ASSERT_TRUE(res);
  2445. EXPECT_EQ(StatusCode::OK_200, res->status);
  2446. EXPECT_EQ("john", res->body);
  2447. }
  2448. {
  2449. auto res = cli.Get("/user/invalid-user");
  2450. ASSERT_TRUE(res);
  2451. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2452. EXPECT_EQ("error", res->body);
  2453. }
  2454. }
  2455. TEST(InvalidFormatTest, StatusCode) {
  2456. Server svr;
  2457. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2458. res.set_content("Hello World!\n", "text/plain");
  2459. res.status = 9999; // Status should be a three-digit code...
  2460. });
  2461. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2462. auto se = detail::scope_exit([&] {
  2463. svr.stop();
  2464. thread.join();
  2465. ASSERT_FALSE(svr.is_running());
  2466. });
  2467. svr.wait_until_ready();
  2468. {
  2469. Client cli(HOST, PORT);
  2470. auto res = cli.Get("/hi");
  2471. ASSERT_FALSE(res);
  2472. }
  2473. }
  2474. TEST(URLFragmentTest, WithFragment) {
  2475. Server svr;
  2476. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2477. EXPECT_TRUE(req.target == "/hi");
  2478. });
  2479. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2480. auto se = detail::scope_exit([&] {
  2481. svr.stop();
  2482. thread.join();
  2483. ASSERT_FALSE(svr.is_running());
  2484. });
  2485. svr.wait_until_ready();
  2486. {
  2487. Client cli(HOST, PORT);
  2488. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2489. EXPECT_TRUE(res);
  2490. EXPECT_EQ(StatusCode::OK_200, res->status);
  2491. res = cli.Get("/hi%23key1=val1=key2=val2");
  2492. EXPECT_TRUE(res);
  2493. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2494. }
  2495. }
  2496. TEST(HeaderWriter, SetHeaderWriter) {
  2497. Server svr;
  2498. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2499. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2500. return detail::write_headers(strm, hdrs);
  2501. });
  2502. svr.Get("/hi", [](const Request &req, Response &res) {
  2503. auto it = req.headers.find("CustomClientHeader");
  2504. EXPECT_TRUE(it != req.headers.end());
  2505. EXPECT_EQ(it->second, "CustomClientValue");
  2506. res.set_content("Hello World!\n", "text/plain");
  2507. });
  2508. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2509. auto se = detail::scope_exit([&] {
  2510. svr.stop();
  2511. thread.join();
  2512. ASSERT_FALSE(svr.is_running());
  2513. });
  2514. svr.wait_until_ready();
  2515. {
  2516. Client cli(HOST, PORT);
  2517. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2518. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2519. return detail::write_headers(strm, hdrs);
  2520. });
  2521. auto res = cli.Get("/hi");
  2522. EXPECT_TRUE(res);
  2523. EXPECT_EQ(StatusCode::OK_200, res->status);
  2524. auto it = res->headers.find("CustomServerHeader");
  2525. EXPECT_TRUE(it != res->headers.end());
  2526. EXPECT_EQ(it->second, "CustomServerValue");
  2527. }
  2528. }
  2529. class ServerTest : public ::testing::Test {
  2530. protected:
  2531. ServerTest()
  2532. : cli_(HOST, PORT)
  2533. #ifdef CPPHTTPLIB_SSL_ENABLED
  2534. ,
  2535. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2536. #endif
  2537. {
  2538. #ifdef CPPHTTPLIB_SSL_ENABLED
  2539. cli_.enable_server_certificate_verification(false);
  2540. #endif
  2541. // Allow LARGE_DATA (100MB) responses
  2542. cli_.set_payload_max_length(200 * 1024 * 1024);
  2543. }
  2544. virtual void SetUp() {
  2545. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2546. svr_.set_payload_max_length(200 * 1024 * 1024);
  2547. svr_.set_mount_point("/", "./www");
  2548. svr_.set_mount_point("/mount", "./www2");
  2549. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2550. svr_.Get("/hi",
  2551. [&](const Request & /*req*/, Response &res) {
  2552. res.set_content("Hello World!", "text/plain");
  2553. })
  2554. .Get("/file_content",
  2555. [&](const Request & /*req*/, Response &res) {
  2556. res.set_file_content("./www/dir/test.html");
  2557. })
  2558. .Get("/file_content_with_content_type",
  2559. [&](const Request & /*req*/, Response &res) {
  2560. res.set_file_content("./www/file", "text/plain");
  2561. })
  2562. .Get("/invalid_file_content",
  2563. [&](const Request & /*req*/, Response &res) {
  2564. res.set_file_content("./www/dir/invalid_file_path");
  2565. })
  2566. .Get("/http_response_splitting",
  2567. [&](const Request & /*req*/, Response &res) {
  2568. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2569. EXPECT_EQ(0U, res.headers.size());
  2570. EXPECT_FALSE(res.has_header("a"));
  2571. res.set_header("a", "1\nSet-Cookie: a=1");
  2572. EXPECT_EQ(0U, res.headers.size());
  2573. EXPECT_FALSE(res.has_header("a"));
  2574. res.set_header("a", "1\rSet-Cookie: a=1");
  2575. EXPECT_EQ(0U, res.headers.size());
  2576. EXPECT_FALSE(res.has_header("a"));
  2577. res.set_header("a\r\nb", "0");
  2578. EXPECT_EQ(0U, res.headers.size());
  2579. EXPECT_FALSE(res.has_header("a"));
  2580. res.set_header("a\rb", "0");
  2581. EXPECT_EQ(0U, res.headers.size());
  2582. EXPECT_FALSE(res.has_header("a"));
  2583. res.set_header("a\nb", "0");
  2584. EXPECT_EQ(0U, res.headers.size());
  2585. EXPECT_FALSE(res.has_header("a"));
  2586. res.set_redirect("1\r\nSet-Cookie: a=1");
  2587. EXPECT_EQ(0U, res.headers.size());
  2588. EXPECT_FALSE(res.has_header("Location"));
  2589. })
  2590. .Get("/slow",
  2591. [&](const Request & /*req*/, Response &res) {
  2592. std::this_thread::sleep_for(std::chrono::seconds(2));
  2593. res.set_content("slow", "text/plain");
  2594. })
  2595. #if 0
  2596. .Post("/slowpost",
  2597. [&](const Request & /*req*/, Response &res) {
  2598. std::this_thread::sleep_for(std::chrono::seconds(2));
  2599. res.set_content("slow", "text/plain");
  2600. })
  2601. #endif
  2602. .Get("/remote_addr",
  2603. [&](const Request &req, Response &res) {
  2604. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2605. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2606. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2607. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2608. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2609. #endif
  2610. res.set_content(req.remote_addr, "text/plain");
  2611. })
  2612. .Get("/local_addr",
  2613. [&](const Request &req, Response &res) {
  2614. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2615. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2616. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2617. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2618. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2619. #endif
  2620. auto local_addr = req.local_addr;
  2621. auto local_port = std::to_string(req.local_port);
  2622. res.set_content(local_addr.append(":").append(local_port),
  2623. "text/plain");
  2624. })
  2625. .Get("/endwith%",
  2626. [&](const Request & /*req*/, Response &res) {
  2627. res.set_content("Hello World!", "text/plain");
  2628. })
  2629. .Get("/a\\+\\+b",
  2630. [&](const Request &req, Response &res) {
  2631. ASSERT_TRUE(req.has_param("a +b"));
  2632. auto val = req.get_param_value("a +b");
  2633. res.set_content(val, "text/plain");
  2634. })
  2635. .Get("/", [&](const Request & /*req*/,
  2636. Response &res) { res.set_redirect("/hi"); })
  2637. .Post("/1",
  2638. [](const Request & /*req*/, Response &res) {
  2639. res.set_redirect("/2", StatusCode::SeeOther_303);
  2640. })
  2641. .Get("/2",
  2642. [](const Request & /*req*/, Response &res) {
  2643. res.set_content("redirected.", "text/plain");
  2644. res.status = StatusCode::OK_200;
  2645. })
  2646. .Post("/person",
  2647. [&](const Request &req, Response &res) {
  2648. if (req.has_param("name") && req.has_param("note")) {
  2649. persons_[req.get_param_value("name")] =
  2650. req.get_param_value("note");
  2651. } else {
  2652. res.status = StatusCode::BadRequest_400;
  2653. }
  2654. })
  2655. .Put("/person",
  2656. [&](const Request &req, Response &res) {
  2657. if (req.has_param("name") && req.has_param("note")) {
  2658. persons_[req.get_param_value("name")] =
  2659. req.get_param_value("note");
  2660. } else {
  2661. res.status = StatusCode::BadRequest_400;
  2662. }
  2663. })
  2664. .Get("/person/(.*)",
  2665. [&](const Request &req, Response &res) {
  2666. string name = req.matches[1];
  2667. if (persons_.find(name) != persons_.end()) {
  2668. auto note = persons_[name];
  2669. res.set_content(note, "text/plain");
  2670. } else {
  2671. res.status = StatusCode::NotFound_404;
  2672. }
  2673. })
  2674. .Delete("/person",
  2675. [&](const Request &req, Response &res) {
  2676. if (req.has_param("name")) {
  2677. string name = req.get_param_value("name");
  2678. if (persons_.find(name) != persons_.end()) {
  2679. persons_.erase(name);
  2680. res.set_content("DELETED", "text/plain");
  2681. } else {
  2682. res.status = StatusCode::NotFound_404;
  2683. }
  2684. } else {
  2685. res.status = StatusCode::BadRequest_400;
  2686. }
  2687. })
  2688. .Post("/x-www-form-urlencoded-json",
  2689. [&](const Request &req, Response &res) {
  2690. auto json = req.get_param_value("json");
  2691. ASSERT_EQ(JSON_DATA, json);
  2692. res.set_content(json, "appliation/json");
  2693. res.status = StatusCode::OK_200;
  2694. })
  2695. .Get("/streamed-chunked",
  2696. [&](const Request & /*req*/, Response &res) {
  2697. res.set_chunked_content_provider(
  2698. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2699. sink.os << "123";
  2700. sink.os << "456";
  2701. sink.os << "789";
  2702. sink.done();
  2703. return true;
  2704. });
  2705. })
  2706. .Get("/streamed-chunked-with-prohibited-trailer",
  2707. [&](const Request & /*req*/, Response &res) {
  2708. auto i = new int(0);
  2709. // Declare both a prohibited trailer (Content-Length) and an
  2710. // allowed one
  2711. res.set_header("Trailer", "Content-Length, X-Allowed");
  2712. res.set_chunked_content_provider(
  2713. "text/plain",
  2714. [i](size_t /*offset*/, DataSink &sink) {
  2715. switch (*i) {
  2716. case 0: sink.os << "123"; break;
  2717. case 1: sink.os << "456"; break;
  2718. case 2: sink.os << "789"; break;
  2719. case 3: {
  2720. sink.done_with_trailer(
  2721. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2722. } break;
  2723. }
  2724. (*i)++;
  2725. return true;
  2726. },
  2727. [i](bool success) {
  2728. EXPECT_TRUE(success);
  2729. delete i;
  2730. });
  2731. })
  2732. .Get("/streamed-chunked2",
  2733. [&](const Request & /*req*/, Response &res) {
  2734. auto i = new int(0);
  2735. res.set_chunked_content_provider(
  2736. "text/plain",
  2737. [i](size_t /*offset*/, DataSink &sink) {
  2738. switch (*i) {
  2739. case 0: sink.os << "123"; break;
  2740. case 1: sink.os << "456"; break;
  2741. case 2: sink.os << "789"; break;
  2742. case 3: sink.done(); break;
  2743. }
  2744. (*i)++;
  2745. return true;
  2746. },
  2747. [i](bool success) {
  2748. EXPECT_TRUE(success);
  2749. delete i;
  2750. });
  2751. })
  2752. .Get("/streamed-chunked-with-trailer",
  2753. [&](const Request & /*req*/, Response &res) {
  2754. auto i = new int(0);
  2755. res.set_header("Trailer", "Dummy1, Dummy2");
  2756. res.set_chunked_content_provider(
  2757. "text/plain",
  2758. [i](size_t /*offset*/, DataSink &sink) {
  2759. switch (*i) {
  2760. case 0: sink.os << "123"; break;
  2761. case 1: sink.os << "456"; break;
  2762. case 2: sink.os << "789"; break;
  2763. case 3: {
  2764. sink.done_with_trailer(
  2765. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2766. } break;
  2767. }
  2768. (*i)++;
  2769. return true;
  2770. },
  2771. [i](bool success) {
  2772. EXPECT_TRUE(success);
  2773. delete i;
  2774. });
  2775. })
  2776. .Get("/streamed",
  2777. [&](const Request & /*req*/, Response &res) {
  2778. res.set_content_provider(
  2779. 6, "text/plain",
  2780. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2781. sink.os << (offset < 3 ? "a" : "b");
  2782. return true;
  2783. });
  2784. })
  2785. .Get("/streamed-with-range",
  2786. [&](const Request &req, Response &res) {
  2787. auto data = new std::string("abcdefg");
  2788. res.set_content_provider(
  2789. data->size(), "text/plain",
  2790. [data](size_t offset, size_t length, DataSink &sink) {
  2791. size_t DATA_CHUNK_SIZE = 4;
  2792. const auto &d = *data;
  2793. auto out_len =
  2794. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2795. auto ret =
  2796. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2797. EXPECT_TRUE(ret);
  2798. return true;
  2799. },
  2800. [data, &req](bool success) {
  2801. EXPECT_EQ(success, !req.has_param("error"));
  2802. delete data;
  2803. });
  2804. })
  2805. .Get("/streamed-cancel",
  2806. [&](const Request & /*req*/, Response &res) {
  2807. res.set_content_provider(
  2808. size_t(-1), "text/plain",
  2809. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2810. sink.os << "data_chunk";
  2811. return true;
  2812. });
  2813. })
  2814. .Get("/regex-with-delimiter",
  2815. [&](const Request &req, Response & /*res*/) {
  2816. ASSERT_TRUE(req.has_param("key"));
  2817. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2818. })
  2819. .Get("/with-range",
  2820. [&](const Request & /*req*/, Response &res) {
  2821. res.set_content("abcdefg", "text/plain");
  2822. })
  2823. .Get("/test-start-time",
  2824. [&](const Request &req, Response & /*res*/) {
  2825. EXPECT_NE(req.start_time_,
  2826. std::chrono::steady_clock::time_point::min());
  2827. })
  2828. .Get("/with-range-customized-response",
  2829. [&](const Request & /*req*/, Response &res) {
  2830. res.status = StatusCode::BadRequest_400;
  2831. res.set_content(JSON_DATA, "application/json");
  2832. })
  2833. .Post("/chunked",
  2834. [&](const Request &req, Response & /*res*/) {
  2835. EXPECT_EQ(req.body, "dechunked post body");
  2836. })
  2837. .Post("/large-chunked",
  2838. [&](const Request &req, Response & /*res*/) {
  2839. std::string expected(6 * 30 * 1024u, 'a');
  2840. EXPECT_EQ(req.body, expected);
  2841. })
  2842. .Post("/multipart",
  2843. [&](const Request &req, Response & /*res*/) {
  2844. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2845. req.form.get_field_count("text2") +
  2846. req.form.get_field_count("file3") +
  2847. req.form.get_field_count("file4"));
  2848. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2849. req.form.get_file_count("file2"));
  2850. ASSERT_TRUE(!req.form.has_file("???"));
  2851. ASSERT_TRUE(!req.form.has_field("???"));
  2852. ASSERT_TRUE(req.body.empty());
  2853. {
  2854. const auto &text = req.form.get_field("text1");
  2855. EXPECT_EQ("text default", text);
  2856. }
  2857. {
  2858. const auto &text = req.form.get_field("text2");
  2859. EXPECT_EQ("aωb", text);
  2860. }
  2861. {
  2862. const auto &file = req.form.get_file("file1");
  2863. EXPECT_EQ("hello.txt", file.filename);
  2864. EXPECT_EQ("text/plain", file.content_type);
  2865. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2866. }
  2867. {
  2868. const auto &file = req.form.get_file("file2");
  2869. EXPECT_EQ("world.json", file.filename);
  2870. EXPECT_EQ("application/json", file.content_type);
  2871. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2872. }
  2873. {
  2874. const auto &text = req.form.get_field("file3");
  2875. EXPECT_EQ(0u, text.size());
  2876. }
  2877. {
  2878. const auto &text = req.form.get_field("file4");
  2879. EXPECT_EQ(0u, text.size());
  2880. }
  2881. })
  2882. .Post("/multipart/multi_file_values",
  2883. [&](const Request &req, Response & /*res*/) {
  2884. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2885. req.form.get_field_count("multi_text1"));
  2886. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2887. ASSERT_TRUE(!req.form.has_file("???"));
  2888. ASSERT_TRUE(!req.form.has_field("???"));
  2889. ASSERT_TRUE(req.body.empty());
  2890. {
  2891. const auto &text = req.form.get_field("text");
  2892. EXPECT_EQ("default text", text);
  2893. }
  2894. {
  2895. const auto &text1_values = req.form.get_fields("multi_text1");
  2896. EXPECT_EQ(2u, text1_values.size());
  2897. EXPECT_EQ("aaaaa", text1_values[0]);
  2898. EXPECT_EQ("bbbbb", text1_values[1]);
  2899. }
  2900. {
  2901. const auto &file1_values = req.form.get_files("multi_file1");
  2902. EXPECT_EQ(2u, file1_values.size());
  2903. auto file1 = file1_values[0];
  2904. EXPECT_EQ(file1.filename, "hello.txt");
  2905. EXPECT_EQ(file1.content_type, "text/plain");
  2906. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2907. auto file2 = file1_values[1];
  2908. EXPECT_EQ(file2.filename, "world.json");
  2909. EXPECT_EQ(file2.content_type, "application/json");
  2910. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2911. }
  2912. })
  2913. .Post("/empty",
  2914. [&](const Request &req, Response &res) {
  2915. EXPECT_EQ(req.body, "");
  2916. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2917. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2918. res.set_content("empty", "text/plain");
  2919. })
  2920. .Post("/empty-no-content-type",
  2921. [&](const Request &req, Response &res) {
  2922. EXPECT_EQ(req.body, "");
  2923. EXPECT_FALSE(req.has_header("Content-Type"));
  2924. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2925. res.set_content("empty-no-content-type", "text/plain");
  2926. })
  2927. .Post("/path-only",
  2928. [&](const Request &req, Response &res) {
  2929. EXPECT_EQ(req.body, "");
  2930. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2931. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2932. res.set_content("path-only", "text/plain");
  2933. })
  2934. .Post("/path-headers-only",
  2935. [&](const Request &req, Response &res) {
  2936. EXPECT_EQ(req.body, "");
  2937. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2938. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2939. EXPECT_EQ("world", req.get_header_value("hello"));
  2940. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2941. res.set_content("path-headers-only", "text/plain");
  2942. })
  2943. .Post("/post-large",
  2944. [&](const Request &req, Response &res) {
  2945. EXPECT_EQ(req.body, LARGE_DATA);
  2946. res.set_content(req.body, "text/plain");
  2947. })
  2948. .Post("/post-loopback",
  2949. [&](const Request &, Response &res,
  2950. ContentReader const &content_reader) {
  2951. std::string body;
  2952. content_reader([&](const char *data, size_t data_length) {
  2953. body.append(data, data_length);
  2954. return true;
  2955. });
  2956. res.set_content(body, "text/plain");
  2957. })
  2958. .Put("/put-loopback",
  2959. [&](const Request &, Response &res,
  2960. ContentReader const &content_reader) {
  2961. std::string body;
  2962. content_reader([&](const char *data, size_t data_length) {
  2963. body.append(data, data_length);
  2964. return true;
  2965. });
  2966. res.set_content(body, "text/plain");
  2967. })
  2968. .Patch("/patch-loopback",
  2969. [&](const Request &, Response &res,
  2970. ContentReader const &content_reader) {
  2971. std::string body;
  2972. content_reader([&](const char *data, size_t data_length) {
  2973. body.append(data, data_length);
  2974. return true;
  2975. });
  2976. res.set_content(body, "text/plain");
  2977. })
  2978. .Put("/empty-no-content-type",
  2979. [&](const Request &req, Response &res) {
  2980. EXPECT_EQ(req.body, "");
  2981. EXPECT_FALSE(req.has_header("Content-Type"));
  2982. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2983. res.set_content("empty-no-content-type", "text/plain");
  2984. })
  2985. .Put("/put",
  2986. [&](const Request &req, Response &res) {
  2987. EXPECT_EQ(req.body, "PUT");
  2988. res.set_content(req.body, "text/plain");
  2989. })
  2990. .Put("/put-large",
  2991. [&](const Request &req, Response &res) {
  2992. EXPECT_EQ(req.body, LARGE_DATA);
  2993. res.set_content(req.body, "text/plain");
  2994. })
  2995. .Patch("/patch",
  2996. [&](const Request &req, Response &res) {
  2997. EXPECT_EQ(req.body, "PATCH");
  2998. res.set_content(req.body, "text/plain");
  2999. })
  3000. .Delete("/delete",
  3001. [&](const Request & /*req*/, Response &res) {
  3002. res.set_content("DELETE", "text/plain");
  3003. })
  3004. .Delete("/delete-body",
  3005. [&](const Request &req, Response &res) {
  3006. EXPECT_EQ(req.body, "content");
  3007. res.set_content(req.body, "text/plain");
  3008. })
  3009. .Options(R"(\*)",
  3010. [&](const Request & /*req*/, Response &res) {
  3011. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3012. })
  3013. .Get("/request-target",
  3014. [&](const Request &req, Response & /*res*/) {
  3015. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3016. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3017. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3018. })
  3019. .Get("/long-query-value",
  3020. [&](const Request &req, Response & /*res*/) {
  3021. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3022. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3023. })
  3024. .Get("/too-long-query-value",
  3025. [&](const Request &req, Response & /*res*/) {
  3026. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3027. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3028. })
  3029. .Get("/array-param",
  3030. [&](const Request &req, Response & /*res*/) {
  3031. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3032. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3033. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3034. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3035. })
  3036. .Post("/validate-no-multiple-headers",
  3037. [&](const Request &req, Response & /*res*/) {
  3038. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3039. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3040. })
  3041. .Post("/content_receiver",
  3042. [&](const Request &req, Response &res,
  3043. const ContentReader &content_reader) {
  3044. if (req.is_multipart_form_data()) {
  3045. std::vector<FormData> items;
  3046. content_reader(
  3047. [&](const FormData &file) {
  3048. items.push_back(file);
  3049. return true;
  3050. },
  3051. [&](const char *data, size_t data_length) {
  3052. items.back().content.append(data, data_length);
  3053. return true;
  3054. });
  3055. EXPECT_EQ(5u, items.size());
  3056. {
  3057. const auto &file = get_file_value(items, "text1");
  3058. EXPECT_TRUE(file.filename.empty());
  3059. EXPECT_EQ("text default", file.content);
  3060. }
  3061. {
  3062. const auto &file = get_file_value(items, "text2");
  3063. EXPECT_TRUE(file.filename.empty());
  3064. EXPECT_EQ("aωb", file.content);
  3065. }
  3066. {
  3067. const auto &file = get_file_value(items, "file1");
  3068. EXPECT_EQ("hello.txt", file.filename);
  3069. EXPECT_EQ("text/plain", file.content_type);
  3070. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3071. }
  3072. {
  3073. const auto &file = get_file_value(items, "file2");
  3074. EXPECT_EQ("world.json", file.filename);
  3075. EXPECT_EQ("application/json", file.content_type);
  3076. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3077. }
  3078. {
  3079. const auto &file = get_file_value(items, "file3");
  3080. EXPECT_TRUE(file.filename.empty());
  3081. EXPECT_EQ("application/octet-stream", file.content_type);
  3082. EXPECT_EQ(0u, file.content.size());
  3083. }
  3084. } else {
  3085. std::string body;
  3086. content_reader([&](const char *data, size_t data_length) {
  3087. EXPECT_EQ(7U, data_length);
  3088. body.append(data, data_length);
  3089. return true;
  3090. });
  3091. EXPECT_EQ(body, "content");
  3092. res.set_content(body, "text/plain");
  3093. }
  3094. })
  3095. .Put("/content_receiver",
  3096. [&](const Request & /*req*/, Response &res,
  3097. const ContentReader &content_reader) {
  3098. std::string body;
  3099. content_reader([&](const char *data, size_t data_length) {
  3100. body.append(data, data_length);
  3101. return true;
  3102. });
  3103. EXPECT_EQ(body, "content");
  3104. res.set_content(body, "text/plain");
  3105. })
  3106. .Patch("/content_receiver",
  3107. [&](const Request & /*req*/, Response &res,
  3108. const ContentReader &content_reader) {
  3109. std::string body;
  3110. content_reader([&](const char *data, size_t data_length) {
  3111. body.append(data, data_length);
  3112. return true;
  3113. });
  3114. EXPECT_EQ(body, "content");
  3115. res.set_content(body, "text/plain");
  3116. })
  3117. .Post("/query-string-and-body",
  3118. [&](const Request &req, Response & /*res*/) {
  3119. ASSERT_TRUE(req.has_param("key"));
  3120. EXPECT_EQ(req.get_param_value("key"), "value");
  3121. EXPECT_EQ(req.body, "content");
  3122. })
  3123. .Get("/last-request",
  3124. [&](const Request &req, Response & /*res*/) {
  3125. EXPECT_EQ("close", req.get_header_value("Connection"));
  3126. })
  3127. .Get(R"(/redirect/(\d+))",
  3128. [&](const Request &req, Response &res) {
  3129. auto num = std::stoi(req.matches[1]) + 1;
  3130. std::string url = "/redirect/" + std::to_string(num);
  3131. res.set_redirect(url);
  3132. })
  3133. .Post("/binary",
  3134. [&](const Request &req, Response &res) {
  3135. EXPECT_EQ(4U, req.body.size());
  3136. EXPECT_EQ("application/octet-stream",
  3137. req.get_header_value("Content-Type"));
  3138. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3139. res.set_content(req.body, "application/octet-stream");
  3140. })
  3141. .Put("/binary",
  3142. [&](const Request &req, Response &res) {
  3143. EXPECT_EQ(4U, req.body.size());
  3144. EXPECT_EQ("application/octet-stream",
  3145. req.get_header_value("Content-Type"));
  3146. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3147. res.set_content(req.body, "application/octet-stream");
  3148. })
  3149. .Patch("/binary",
  3150. [&](const Request &req, Response &res) {
  3151. EXPECT_EQ(4U, req.body.size());
  3152. EXPECT_EQ("application/octet-stream",
  3153. req.get_header_value("Content-Type"));
  3154. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3155. res.set_content(req.body, "application/octet-stream");
  3156. })
  3157. .Delete("/binary",
  3158. [&](const Request &req, Response &res) {
  3159. EXPECT_EQ(4U, req.body.size());
  3160. EXPECT_EQ("application/octet-stream",
  3161. req.get_header_value("Content-Type"));
  3162. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3163. res.set_content(req.body, "application/octet-stream");
  3164. })
  3165. .Get("/issue1772",
  3166. [&](const Request & /*req*/, Response &res) {
  3167. res.status = 401;
  3168. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3169. })
  3170. .Delete("/issue609",
  3171. [](const httplib::Request &, httplib::Response &res,
  3172. const httplib::ContentReader &) {
  3173. res.set_content("ok", "text/plain");
  3174. })
  3175. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3176. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3177. .Get("/compress",
  3178. [&](const Request & /*req*/, Response &res) {
  3179. res.set_content(
  3180. "12345678901234567890123456789012345678901234567890123456789"
  3181. "01234567890123456789012345678901234567890",
  3182. "text/plain");
  3183. })
  3184. .Get("/nocompress",
  3185. [&](const Request & /*req*/, Response &res) {
  3186. res.set_content(
  3187. "12345678901234567890123456789012345678901234567890123456789"
  3188. "01234567890123456789012345678901234567890",
  3189. "application/octet-stream");
  3190. })
  3191. .Post("/compress-multipart",
  3192. [&](const Request &req, Response & /*res*/) {
  3193. EXPECT_EQ(2u, req.form.fields.size());
  3194. ASSERT_TRUE(!req.form.has_field("???"));
  3195. {
  3196. const auto &text = req.form.get_field("key1");
  3197. EXPECT_EQ("test", text);
  3198. }
  3199. {
  3200. const auto &text = req.form.get_field("key2");
  3201. EXPECT_EQ("--abcdefg123", text);
  3202. }
  3203. })
  3204. #endif
  3205. ;
  3206. persons_["john"] = "programmer";
  3207. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3208. svr_.wait_until_ready();
  3209. }
  3210. virtual void TearDown() {
  3211. svr_.stop();
  3212. if (!request_threads_.empty()) {
  3213. std::this_thread::sleep_for(std::chrono::seconds(1));
  3214. for (auto &t : request_threads_) {
  3215. t.join();
  3216. }
  3217. }
  3218. t_.join();
  3219. }
  3220. map<string, string> persons_;
  3221. #ifdef CPPHTTPLIB_SSL_ENABLED
  3222. SSLClient cli_;
  3223. SSLServer svr_;
  3224. #else
  3225. Client cli_;
  3226. Server svr_;
  3227. #endif
  3228. thread t_;
  3229. std::vector<thread> request_threads_;
  3230. };
  3231. TEST_F(ServerTest, GetMethod200) {
  3232. auto res = cli_.Get("/hi");
  3233. ASSERT_TRUE(res);
  3234. EXPECT_EQ("HTTP/1.1", res->version);
  3235. EXPECT_EQ(StatusCode::OK_200, res->status);
  3236. EXPECT_EQ("OK", res->reason);
  3237. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3238. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3239. EXPECT_EQ("Hello World!", res->body);
  3240. }
  3241. TEST_F(ServerTest, GetEmptyFile) {
  3242. auto res = cli_.Get("/empty_file");
  3243. ASSERT_TRUE(res);
  3244. EXPECT_EQ(StatusCode::OK_200, res->status);
  3245. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3246. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3247. EXPECT_EQ("", res->body);
  3248. }
  3249. TEST_F(ServerTest, GetFileContent) {
  3250. auto res = cli_.Get("/file_content");
  3251. ASSERT_TRUE(res);
  3252. EXPECT_EQ(StatusCode::OK_200, res->status);
  3253. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3254. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3255. EXPECT_EQ("test.html", res->body);
  3256. }
  3257. TEST_F(ServerTest, GetFileContentWithRange) {
  3258. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3259. ASSERT_TRUE(res);
  3260. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3261. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3262. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3263. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3264. EXPECT_EQ("est", res->body);
  3265. }
  3266. TEST_F(ServerTest, GetFileContentWithContentType) {
  3267. auto res = cli_.Get("/file_content_with_content_type");
  3268. ASSERT_TRUE(res);
  3269. EXPECT_EQ(StatusCode::OK_200, res->status);
  3270. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3271. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3272. EXPECT_EQ("file\n", res->body);
  3273. }
  3274. TEST_F(ServerTest, GetInvalidFileContent) {
  3275. auto res = cli_.Get("/invalid_file_content");
  3276. ASSERT_TRUE(res);
  3277. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3278. }
  3279. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3280. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3281. ASSERT_TRUE(res);
  3282. EXPECT_EQ("HTTP/1.1", res->version);
  3283. EXPECT_EQ(StatusCode::OK_200, res->status);
  3284. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3285. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3286. EXPECT_EQ("Hello World!", res->body);
  3287. }
  3288. TEST_F(ServerTest, GetMethod302) {
  3289. auto res = cli_.Get("/");
  3290. ASSERT_TRUE(res);
  3291. EXPECT_EQ(StatusCode::Found_302, res->status);
  3292. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3293. }
  3294. TEST_F(ServerTest, GetMethod302Redirect) {
  3295. cli_.set_follow_location(true);
  3296. auto res = cli_.Get("/");
  3297. ASSERT_TRUE(res);
  3298. EXPECT_EQ(StatusCode::OK_200, res->status);
  3299. EXPECT_EQ("Hello World!", res->body);
  3300. EXPECT_EQ("/hi", res->location);
  3301. }
  3302. TEST_F(ServerTest, GetMethod404) {
  3303. auto res = cli_.Get("/invalid");
  3304. ASSERT_TRUE(res);
  3305. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3306. }
  3307. TEST_F(ServerTest, HeadMethod200) {
  3308. auto res = cli_.Head("/hi");
  3309. ASSERT_TRUE(res);
  3310. EXPECT_EQ(StatusCode::OK_200, res->status);
  3311. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3312. EXPECT_TRUE(res->body.empty());
  3313. }
  3314. TEST_F(ServerTest, HeadMethod200Static) {
  3315. auto res = cli_.Head("/mount/dir/index.html");
  3316. ASSERT_TRUE(res);
  3317. EXPECT_EQ(StatusCode::OK_200, res->status);
  3318. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3319. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3320. EXPECT_TRUE(res->body.empty());
  3321. }
  3322. TEST_F(ServerTest, HeadMethod404) {
  3323. auto res = cli_.Head("/invalid");
  3324. ASSERT_TRUE(res);
  3325. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3326. EXPECT_TRUE(res->body.empty());
  3327. }
  3328. TEST_F(ServerTest, GetMethodPersonJohn) {
  3329. auto res = cli_.Get("/person/john");
  3330. ASSERT_TRUE(res);
  3331. EXPECT_EQ(StatusCode::OK_200, res->status);
  3332. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3333. EXPECT_EQ("programmer", res->body);
  3334. }
  3335. TEST_F(ServerTest, PostMethod1) {
  3336. auto res = cli_.Get("/person/john1");
  3337. ASSERT_TRUE(res);
  3338. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3339. res = cli_.Post("/person", "name=john1&note=coder",
  3340. "application/x-www-form-urlencoded");
  3341. ASSERT_TRUE(res);
  3342. ASSERT_EQ(StatusCode::OK_200, res->status);
  3343. res = cli_.Get("/person/john1");
  3344. ASSERT_TRUE(res);
  3345. ASSERT_EQ(StatusCode::OK_200, res->status);
  3346. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3347. ASSERT_EQ("coder", res->body);
  3348. }
  3349. TEST_F(ServerTest, PostMethod2) {
  3350. auto res = cli_.Get("/person/john2");
  3351. ASSERT_TRUE(res);
  3352. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3353. Params params;
  3354. params.emplace("name", "john2");
  3355. params.emplace("note", "coder");
  3356. res = cli_.Post("/person", params);
  3357. ASSERT_TRUE(res);
  3358. ASSERT_EQ(StatusCode::OK_200, res->status);
  3359. res = cli_.Get("/person/john2");
  3360. ASSERT_TRUE(res);
  3361. ASSERT_EQ(StatusCode::OK_200, res->status);
  3362. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3363. ASSERT_EQ("coder", res->body);
  3364. }
  3365. TEST_F(ServerTest, PutMethod3) {
  3366. auto res = cli_.Get("/person/john3");
  3367. ASSERT_TRUE(res);
  3368. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3369. Params params;
  3370. params.emplace("name", "john3");
  3371. params.emplace("note", "coder");
  3372. res = cli_.Put("/person", params);
  3373. ASSERT_TRUE(res);
  3374. ASSERT_EQ(StatusCode::OK_200, res->status);
  3375. res = cli_.Get("/person/john3");
  3376. ASSERT_TRUE(res);
  3377. ASSERT_EQ(StatusCode::OK_200, res->status);
  3378. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3379. ASSERT_EQ("coder", res->body);
  3380. }
  3381. TEST_F(ServerTest, DeleteMethod1) {
  3382. auto res = cli_.Get("/person/john4");
  3383. ASSERT_TRUE(res);
  3384. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3385. Params params;
  3386. params.emplace("name", "john4");
  3387. params.emplace("note", "coder");
  3388. res = cli_.Post("/person", params);
  3389. ASSERT_TRUE(res);
  3390. ASSERT_EQ(StatusCode::OK_200, res->status);
  3391. res = cli_.Get("/person/john4");
  3392. ASSERT_TRUE(res);
  3393. ASSERT_EQ(StatusCode::OK_200, res->status);
  3394. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3395. ASSERT_EQ("coder", res->body);
  3396. Params delete_params;
  3397. delete_params.emplace("name", "john4");
  3398. res = cli_.Delete("/person", delete_params);
  3399. ASSERT_TRUE(res);
  3400. ASSERT_EQ(StatusCode::OK_200, res->status);
  3401. ASSERT_EQ("DELETED", res->body);
  3402. res = cli_.Get("/person/john4");
  3403. ASSERT_TRUE(res);
  3404. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3405. }
  3406. TEST_F(ServerTest, DeleteMethod2) {
  3407. auto res = cli_.Get("/person/john5");
  3408. ASSERT_TRUE(res);
  3409. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3410. Params params;
  3411. params.emplace("name", "john5");
  3412. params.emplace("note", "developer");
  3413. res = cli_.Post("/person", params);
  3414. ASSERT_TRUE(res);
  3415. ASSERT_EQ(StatusCode::OK_200, res->status);
  3416. res = cli_.Get("/person/john5");
  3417. ASSERT_TRUE(res);
  3418. ASSERT_EQ(StatusCode::OK_200, res->status);
  3419. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3420. ASSERT_EQ("developer", res->body);
  3421. Params delete_params;
  3422. delete_params.emplace("name", "john5");
  3423. Headers headers;
  3424. headers.emplace("Custom-Header", "test-value");
  3425. res = cli_.Delete("/person", headers, delete_params);
  3426. ASSERT_TRUE(res);
  3427. ASSERT_EQ(StatusCode::OK_200, res->status);
  3428. ASSERT_EQ("DELETED", res->body);
  3429. res = cli_.Get("/person/john5");
  3430. ASSERT_TRUE(res);
  3431. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3432. }
  3433. TEST_F(ServerTest, DeleteMethod3) {
  3434. auto res = cli_.Get("/person/john6");
  3435. ASSERT_TRUE(res);
  3436. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3437. Params params;
  3438. params.emplace("name", "john6");
  3439. params.emplace("note", "tester");
  3440. res = cli_.Post("/person", params);
  3441. ASSERT_TRUE(res);
  3442. ASSERT_EQ(StatusCode::OK_200, res->status);
  3443. res = cli_.Get("/person/john6");
  3444. ASSERT_TRUE(res);
  3445. ASSERT_EQ(StatusCode::OK_200, res->status);
  3446. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3447. ASSERT_EQ("tester", res->body);
  3448. Params delete_params;
  3449. delete_params.emplace("name", "john6");
  3450. Headers headers;
  3451. headers.emplace("Custom-Header", "test-value");
  3452. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3453. ASSERT_TRUE(res);
  3454. ASSERT_EQ(StatusCode::OK_200, res->status);
  3455. ASSERT_EQ("DELETED", res->body);
  3456. res = cli_.Get("/person/john6");
  3457. ASSERT_TRUE(res);
  3458. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3459. }
  3460. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3461. Params params;
  3462. params.emplace("json", JSON_DATA);
  3463. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3464. ASSERT_TRUE(res);
  3465. ASSERT_EQ(StatusCode::OK_200, res->status);
  3466. ASSERT_EQ(JSON_DATA, res->body);
  3467. }
  3468. TEST_F(ServerTest, PostEmptyContent) {
  3469. auto res = cli_.Post("/empty", "", "text/plain");
  3470. ASSERT_TRUE(res);
  3471. ASSERT_EQ(StatusCode::OK_200, res->status);
  3472. ASSERT_EQ("empty", res->body);
  3473. }
  3474. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3475. auto res = cli_.Post("/empty-no-content-type");
  3476. ASSERT_TRUE(res);
  3477. ASSERT_EQ(StatusCode::OK_200, res->status);
  3478. ASSERT_EQ("empty-no-content-type", res->body);
  3479. }
  3480. TEST_F(ServerTest, PostPathOnly) {
  3481. auto res = cli_.Post("/path-only");
  3482. ASSERT_TRUE(res);
  3483. ASSERT_EQ(StatusCode::OK_200, res->status);
  3484. ASSERT_EQ("path-only", res->body);
  3485. }
  3486. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3487. auto res = cli_.Post("/path-headers-only",
  3488. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3489. ASSERT_TRUE(res);
  3490. ASSERT_EQ(StatusCode::OK_200, res->status);
  3491. ASSERT_EQ("path-headers-only", res->body);
  3492. }
  3493. TEST_F(ServerTest, PostLarge) {
  3494. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3495. ASSERT_TRUE(res);
  3496. ASSERT_EQ(StatusCode::OK_200, res->status);
  3497. EXPECT_EQ(LARGE_DATA, res->body);
  3498. }
  3499. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3500. auto res = cli_.Put("/empty-no-content-type");
  3501. ASSERT_TRUE(res);
  3502. ASSERT_EQ(StatusCode::OK_200, res->status);
  3503. ASSERT_EQ("empty-no-content-type", res->body);
  3504. }
  3505. TEST_F(ServerTest, GetMethodDir) {
  3506. auto res = cli_.Get("/dir/");
  3507. ASSERT_TRUE(res);
  3508. EXPECT_EQ(StatusCode::OK_200, res->status);
  3509. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3510. auto body = R"(<html>
  3511. <head>
  3512. </head>
  3513. <body>
  3514. <a href="/dir/test.html">Test</a>
  3515. <a href="/hi">hi</a>
  3516. </body>
  3517. </html>
  3518. )";
  3519. EXPECT_EQ(body, res->body);
  3520. }
  3521. TEST_F(ServerTest, GetMethodDirTest) {
  3522. auto res = cli_.Get("/dir/test.html");
  3523. ASSERT_TRUE(res);
  3524. EXPECT_EQ(StatusCode::OK_200, res->status);
  3525. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3526. EXPECT_EQ("test.html", res->body);
  3527. }
  3528. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3529. auto res = cli_.Get("/dir/../dir/test.html");
  3530. ASSERT_TRUE(res);
  3531. EXPECT_EQ(StatusCode::OK_200, res->status);
  3532. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3533. EXPECT_EQ("test.html", res->body);
  3534. }
  3535. TEST_F(ServerTest, GetMethodInvalidPath) {
  3536. auto res = cli_.Get("/dir/../test.html");
  3537. ASSERT_TRUE(res);
  3538. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3539. }
  3540. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3541. auto res = cli_.Get("/../www/dir/test.html");
  3542. ASSERT_TRUE(res);
  3543. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3544. }
  3545. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3546. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3547. ASSERT_TRUE(res);
  3548. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3549. }
  3550. TEST_F(ServerTest, GetMethodDirMountTest) {
  3551. auto res = cli_.Get("/mount/dir/test.html");
  3552. ASSERT_TRUE(res);
  3553. EXPECT_EQ(StatusCode::OK_200, res->status);
  3554. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3555. EXPECT_EQ("test.html", res->body);
  3556. }
  3557. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3558. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3559. ASSERT_TRUE(res);
  3560. EXPECT_EQ(StatusCode::OK_200, res->status);
  3561. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3562. EXPECT_EQ("test.html", res->body);
  3563. }
  3564. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3565. auto res = cli_.Get("/mount/dir/../test.html");
  3566. ASSERT_TRUE(res);
  3567. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3568. }
  3569. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3570. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3571. ASSERT_TRUE(res);
  3572. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3573. }
  3574. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3575. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3576. ASSERT_TRUE(res);
  3577. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3578. }
  3579. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3580. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3581. ASSERT_TRUE(res);
  3582. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3583. }
  3584. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3585. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3586. ASSERT_TRUE(res);
  3587. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3588. }
  3589. TEST_F(ServerTest, PostMethod303) {
  3590. auto res = cli_.Post("/1", "body", "text/plain");
  3591. ASSERT_TRUE(res);
  3592. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3593. EXPECT_EQ("/2", res->get_header_value("Location"));
  3594. }
  3595. TEST_F(ServerTest, PostMethod303Redirect) {
  3596. cli_.set_follow_location(true);
  3597. auto res = cli_.Post("/1", "body", "text/plain");
  3598. ASSERT_TRUE(res);
  3599. EXPECT_EQ(StatusCode::OK_200, res->status);
  3600. EXPECT_EQ("redirected.", res->body);
  3601. EXPECT_EQ("/2", res->location);
  3602. }
  3603. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3604. auto res = cli_.Get("/dir/test.abcde");
  3605. ASSERT_TRUE(res);
  3606. EXPECT_EQ(StatusCode::OK_200, res->status);
  3607. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3608. EXPECT_EQ("abcde", res->body);
  3609. }
  3610. TEST_F(ServerTest, StaticFileRange) {
  3611. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3612. ASSERT_TRUE(res);
  3613. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3614. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3615. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3616. EXPECT_EQ(true, res->has_header("Content-Range"));
  3617. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3618. EXPECT_EQ(std::string("cd"), res->body);
  3619. }
  3620. TEST_F(ServerTest, StaticFileRanges) {
  3621. auto res =
  3622. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3623. ASSERT_TRUE(res);
  3624. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3625. EXPECT_TRUE(
  3626. res->get_header_value("Content-Type")
  3627. .find(
  3628. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3629. 0);
  3630. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3631. }
  3632. TEST_F(ServerTest, StaticFileRangeHead) {
  3633. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3634. ASSERT_TRUE(res);
  3635. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3636. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3637. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3638. EXPECT_EQ(true, res->has_header("Content-Range"));
  3639. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3640. }
  3641. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3642. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3643. ASSERT_TRUE(res);
  3644. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3645. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3646. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3647. EXPECT_EQ(true, res->has_header("Content-Range"));
  3648. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3649. res->get_header_value("Content-Range"));
  3650. EXPECT_EQ("LAST\n", res->body);
  3651. }
  3652. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3653. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3654. ASSERT_TRUE(res);
  3655. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3656. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3657. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3658. EXPECT_EQ(true, res->has_header("Content-Range"));
  3659. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3660. }
  3661. TEST_F(ServerTest, StaticFileBigFile) {
  3662. auto res = cli_.Get("/dir/1MB.txt");
  3663. ASSERT_TRUE(res);
  3664. EXPECT_EQ(StatusCode::OK_200, res->status);
  3665. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3666. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3667. }
  3668. TEST_F(ServerTest, InvalidBaseDirMount) {
  3669. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3670. }
  3671. TEST_F(ServerTest, Binary) {
  3672. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3673. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3674. "application/octet-stream");
  3675. ASSERT_TRUE(res);
  3676. ASSERT_EQ(StatusCode::OK_200, res->status);
  3677. ASSERT_EQ(4U, res->body.size());
  3678. res = cli_.Put("/binary", binary.data(), binary.size(),
  3679. "application/octet-stream");
  3680. ASSERT_TRUE(res);
  3681. ASSERT_EQ(StatusCode::OK_200, res->status);
  3682. ASSERT_EQ(4U, res->body.size());
  3683. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3684. "application/octet-stream");
  3685. ASSERT_TRUE(res);
  3686. ASSERT_EQ(StatusCode::OK_200, res->status);
  3687. ASSERT_EQ(4U, res->body.size());
  3688. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3689. "application/octet-stream");
  3690. ASSERT_TRUE(res);
  3691. ASSERT_EQ(StatusCode::OK_200, res->status);
  3692. ASSERT_EQ(4U, res->body.size());
  3693. }
  3694. TEST_F(ServerTest, BinaryString) {
  3695. auto binary = std::string("\x00\x01\x02\x03", 4);
  3696. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3697. ASSERT_TRUE(res);
  3698. ASSERT_EQ(StatusCode::OK_200, res->status);
  3699. ASSERT_EQ(4U, res->body.size());
  3700. res = cli_.Put("/binary", binary, "application/octet-stream");
  3701. ASSERT_TRUE(res);
  3702. ASSERT_EQ(StatusCode::OK_200, res->status);
  3703. ASSERT_EQ(4U, res->body.size());
  3704. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3705. ASSERT_TRUE(res);
  3706. ASSERT_EQ(StatusCode::OK_200, res->status);
  3707. ASSERT_EQ(4U, res->body.size());
  3708. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3709. ASSERT_TRUE(res);
  3710. ASSERT_EQ(StatusCode::OK_200, res->status);
  3711. ASSERT_EQ(4U, res->body.size());
  3712. }
  3713. TEST_F(ServerTest, EmptyRequest) {
  3714. auto res = cli_.Get("");
  3715. ASSERT_TRUE(!res);
  3716. EXPECT_EQ(Error::Connection, res.error());
  3717. }
  3718. TEST_F(ServerTest, LongRequest) {
  3719. std::string request;
  3720. for (size_t i = 0; i < 545; i++) {
  3721. request += "/TooLongRequest";
  3722. }
  3723. request += "OK";
  3724. auto res = cli_.Get(request.c_str());
  3725. ASSERT_TRUE(res);
  3726. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3727. }
  3728. TEST_F(ServerTest, TooLongRequest) {
  3729. std::string request;
  3730. for (size_t i = 0; i < 546; i++) {
  3731. request += "/TooLongRequest";
  3732. }
  3733. request += "_NG";
  3734. auto start = std::chrono::high_resolution_clock::now();
  3735. cli_.set_keep_alive(true);
  3736. auto res = cli_.Get(request.c_str());
  3737. auto end = std::chrono::high_resolution_clock::now();
  3738. auto elapsed =
  3739. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3740. .count();
  3741. ASSERT_TRUE(res);
  3742. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3743. EXPECT_LE(elapsed, 1000);
  3744. EXPECT_EQ("close", res->get_header_value("Connection"));
  3745. EXPECT_FALSE(cli_.is_socket_open());
  3746. }
  3747. TEST_F(ServerTest, AlmostTooLongRequest) {
  3748. // test for #2046 - URI length check shouldn't include other content on req
  3749. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3750. // leading /, space, HTTP/1.1)
  3751. std::string request =
  3752. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3753. auto res = cli_.Get(request.c_str());
  3754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3755. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3756. }
  3757. TEST_F(ServerTest, LongHeader) {
  3758. Request req;
  3759. req.method = "GET";
  3760. req.path = "/hi";
  3761. std::string host_and_port;
  3762. host_and_port += HOST;
  3763. host_and_port += ":";
  3764. host_and_port += std::to_string(PORT);
  3765. req.headers.emplace("Host", host_and_port.c_str());
  3766. req.headers.emplace("Accept", "*/*");
  3767. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3768. req.headers.emplace(
  3769. "Header-Name",
  3770. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3771. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3772. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3773. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3774. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3775. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3776. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3777. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3778. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3779. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3780. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3781. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3782. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3783. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3784. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3785. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3786. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3787. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3788. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3789. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3790. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3791. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3792. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3793. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3794. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3795. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3796. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3797. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3798. "@@@@@@@@@@@@@@@@");
  3799. auto res = std::make_shared<Response>();
  3800. auto error = Error::Success;
  3801. auto ret = cli_.send(req, *res, error);
  3802. ASSERT_TRUE(ret);
  3803. EXPECT_EQ(StatusCode::OK_200, res->status);
  3804. }
  3805. TEST_F(ServerTest, LongQueryValue) {
  3806. auto start = std::chrono::high_resolution_clock::now();
  3807. cli_.set_keep_alive(true);
  3808. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3809. auto end = std::chrono::high_resolution_clock::now();
  3810. auto elapsed =
  3811. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3812. .count();
  3813. ASSERT_TRUE(res);
  3814. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3815. EXPECT_LE(elapsed, 1000);
  3816. EXPECT_EQ("close", res->get_header_value("Connection"));
  3817. EXPECT_FALSE(cli_.is_socket_open());
  3818. }
  3819. TEST_F(ServerTest, TooLongQueryValue) {
  3820. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3821. ASSERT_FALSE(res);
  3822. EXPECT_EQ(Error::Read, res.error());
  3823. }
  3824. TEST_F(ServerTest, TooLongHeader) {
  3825. Request req;
  3826. req.method = "GET";
  3827. req.path = "/hi";
  3828. std::string host_and_port;
  3829. host_and_port += HOST;
  3830. host_and_port += ":";
  3831. host_and_port += std::to_string(PORT);
  3832. req.headers.emplace("Host", host_and_port.c_str());
  3833. req.headers.emplace("Accept", "*/*");
  3834. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3835. req.headers.emplace(
  3836. "Header-Name",
  3837. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3838. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3839. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3840. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3841. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3842. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3843. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3844. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3845. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3846. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3847. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3848. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3849. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3850. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3851. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3852. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3853. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3854. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3855. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3856. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3857. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3858. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3859. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3860. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3861. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3862. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3863. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3864. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3865. "@@@@@@@@@@@@@@@@@");
  3866. auto res = std::make_shared<Response>();
  3867. auto error = Error::Success;
  3868. auto ret = cli_.send(req, *res, error);
  3869. ASSERT_TRUE(ret);
  3870. EXPECT_EQ(StatusCode::OK_200, res->status);
  3871. }
  3872. TEST_F(ServerTest, HeaderCountAtLimit) {
  3873. // Test with headers just under the 100 limit
  3874. httplib::Headers headers;
  3875. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3876. // This should keep us just under the 100 header limit
  3877. for (int i = 0; i < 95; i++) {
  3878. std::string name = "X-Test-Header-" + std::to_string(i);
  3879. std::string value = "value" + std::to_string(i);
  3880. headers.emplace(name, value);
  3881. }
  3882. // This should work fine as we're under the limit
  3883. auto res = cli_.Get("/hi", headers);
  3884. EXPECT_TRUE(res);
  3885. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3886. }
  3887. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3888. // Test with many headers to exceed the 100 limit
  3889. httplib::Headers headers;
  3890. // Add 150 headers to definitely exceed the 100 limit
  3891. for (int i = 0; i < 150; i++) {
  3892. std::string name = "X-Test-Header-" + std::to_string(i);
  3893. std::string value = "value" + std::to_string(i);
  3894. headers.emplace(name, value);
  3895. }
  3896. // This should fail due to exceeding header count limit
  3897. cli_.set_keep_alive(true);
  3898. auto res = cli_.Get("/hi", headers);
  3899. // The server should respond with 400 Bad Request
  3900. ASSERT_TRUE(res);
  3901. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3902. EXPECT_EQ("close", res->get_header_value("Connection"));
  3903. EXPECT_FALSE(cli_.is_socket_open());
  3904. }
  3905. TEST_F(ServerTest, PercentEncoding) {
  3906. auto res = cli_.Get("/e%6edwith%");
  3907. ASSERT_TRUE(res);
  3908. EXPECT_EQ(StatusCode::OK_200, res->status);
  3909. }
  3910. TEST_F(ServerTest, PercentEncodingUnicode) {
  3911. auto res = cli_.Get("/e%u006edwith%");
  3912. ASSERT_TRUE(res);
  3913. EXPECT_EQ(StatusCode::OK_200, res->status);
  3914. }
  3915. TEST_F(ServerTest, InvalidPercentEncoding) {
  3916. auto res = cli_.Get("/%endwith%");
  3917. ASSERT_TRUE(res);
  3918. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3919. }
  3920. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3921. auto res = cli_.Get("/%uendwith%");
  3922. ASSERT_TRUE(res);
  3923. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3924. }
  3925. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3926. auto res = cli_.Get("/hello?aaa=bbb%");
  3927. ASSERT_TRUE(res);
  3928. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3929. }
  3930. TEST_F(ServerTest, PlusSignEncoding) {
  3931. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3932. ASSERT_TRUE(res);
  3933. EXPECT_EQ(StatusCode::OK_200, res->status);
  3934. EXPECT_EQ("a +b", res->body);
  3935. }
  3936. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3937. // This test simulates a potential DoS attack using many headers
  3938. // to verify our security fix prevents memory exhaustion
  3939. httplib::Headers attack_headers;
  3940. // Attempt to add many headers like an attacker would (200 headers to far
  3941. // exceed limit)
  3942. for (int i = 0; i < 200; i++) {
  3943. std::string name = "X-Attack-Header-" + std::to_string(i);
  3944. std::string value = "attack_payload_" + std::to_string(i);
  3945. attack_headers.emplace(name, value);
  3946. }
  3947. // Try to POST with excessive headers
  3948. cli_.set_keep_alive(true);
  3949. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3950. // Should either fail or return 400 Bad Request due to security limit
  3951. if (res) {
  3952. // If we get a response, it should be 400 Bad Request
  3953. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3954. } else {
  3955. // Request failed, which is the expected behavior for DoS protection
  3956. EXPECT_FALSE(res);
  3957. }
  3958. EXPECT_EQ("close", res->get_header_value("Connection"));
  3959. EXPECT_FALSE(cli_.is_socket_open());
  3960. }
  3961. TEST_F(ServerTest, MultipartFormData) {
  3962. UploadFormDataItems items = {
  3963. {"text1", "text default", "", ""},
  3964. {"text2", "aωb", "", ""},
  3965. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3966. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3967. {"file3", "", "", "application/octet-stream"},
  3968. {"file4", "", "", " application/json tmp-string "}};
  3969. auto res = cli_.Post("/multipart", items);
  3970. ASSERT_TRUE(res);
  3971. EXPECT_EQ(StatusCode::OK_200, res->status);
  3972. }
  3973. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3974. UploadFormDataItems items = {
  3975. {"text", "default text", "", ""},
  3976. {"multi_text1", "aaaaa", "", ""},
  3977. {"multi_text1", "bbbbb", "", ""},
  3978. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3979. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3980. "application/json"},
  3981. };
  3982. auto res = cli_.Post("/multipart/multi_file_values", items);
  3983. ASSERT_TRUE(res);
  3984. EXPECT_EQ(StatusCode::OK_200, res->status);
  3985. }
  3986. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3987. auto res = cli_.Get("/hi");
  3988. ASSERT_TRUE(res);
  3989. EXPECT_EQ(StatusCode::OK_200, res->status);
  3990. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3991. EXPECT_EQ("Hello World!", res->body);
  3992. }
  3993. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3994. Request req;
  3995. req.method = "POST";
  3996. req.path = "/chunked";
  3997. std::string host_and_port;
  3998. host_and_port += HOST;
  3999. host_and_port += ":";
  4000. host_and_port += std::to_string(PORT);
  4001. req.headers.emplace("Host", host_and_port.c_str());
  4002. req.headers.emplace("Accept", "*/*");
  4003. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4004. req.headers.emplace("Content-Type", "text/plain");
  4005. req.headers.emplace("Content-Length", "0");
  4006. req.headers.emplace(
  4007. "Transfer-Encoding",
  4008. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4009. // Client does not chunk, so make a chunked body manually.
  4010. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4011. auto res = std::make_shared<Response>();
  4012. auto error = Error::Success;
  4013. auto ret = cli_.send(req, *res, error);
  4014. ASSERT_TRUE(ret);
  4015. EXPECT_EQ(StatusCode::OK_200, res->status);
  4016. }
  4017. TEST_F(ServerTest, GetStreamed2) {
  4018. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4019. ASSERT_TRUE(res);
  4020. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4021. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4022. EXPECT_EQ(true, res->has_header("Content-Range"));
  4023. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4024. EXPECT_EQ(std::string("ab"), res->body);
  4025. }
  4026. TEST_F(ServerTest, GetStreamed) {
  4027. auto res = cli_.Get("/streamed");
  4028. ASSERT_TRUE(res);
  4029. EXPECT_EQ(StatusCode::OK_200, res->status);
  4030. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4031. EXPECT_EQ(std::string("aaabbb"), res->body);
  4032. }
  4033. TEST_F(ServerTest, GetStreamedWithRange1) {
  4034. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4035. ASSERT_TRUE(res);
  4036. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4037. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4038. EXPECT_EQ(true, res->has_header("Content-Range"));
  4039. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4040. EXPECT_EQ(std::string("def"), res->body);
  4041. }
  4042. TEST_F(ServerTest, GetStreamedWithRange2) {
  4043. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4044. ASSERT_TRUE(res);
  4045. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4046. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4047. EXPECT_EQ(true, res->has_header("Content-Range"));
  4048. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4049. EXPECT_EQ(std::string("bcdefg"), res->body);
  4050. }
  4051. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4052. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4053. ASSERT_TRUE(res);
  4054. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4055. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4056. EXPECT_EQ(true, res->has_header("Content-Range"));
  4057. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4058. EXPECT_EQ(std::string("efg"), res->body);
  4059. }
  4060. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4061. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4062. ASSERT_TRUE(res);
  4063. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4064. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4065. EXPECT_EQ(false, res->has_header("Content-Range"));
  4066. EXPECT_EQ(0U, res->body.size());
  4067. }
  4068. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4069. auto res = cli_.Get("/streamed-with-range",
  4070. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4071. "92233720368547758079223372036854775807"}});
  4072. ASSERT_TRUE(res);
  4073. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4074. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4075. EXPECT_EQ(false, res->has_header("Content-Range"));
  4076. EXPECT_EQ(0U, res->body.size());
  4077. }
  4078. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4079. auto res = cli_.Get(
  4080. "/with-range",
  4081. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4082. {"Accept-Encoding", ""}});
  4083. ASSERT_TRUE(res);
  4084. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4085. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4086. EXPECT_EQ(true, res->has_header("Content-Range"));
  4087. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4088. EXPECT_EQ(std::string("abcdefg"), res->body);
  4089. }
  4090. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4091. auto res = cli_.Get("/with-range", {
  4092. {"Range", "bytes=0-"},
  4093. {"Accept-Encoding", ""},
  4094. });
  4095. ASSERT_TRUE(res);
  4096. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4097. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4098. EXPECT_EQ(true, res->has_header("Content-Range"));
  4099. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4100. EXPECT_EQ(std::string("abcdefg"), res->body);
  4101. }
  4102. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4103. auto res =
  4104. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4105. ASSERT_TRUE(res);
  4106. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4107. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4108. EXPECT_EQ(false, res->has_header("Content-Range"));
  4109. EXPECT_EQ(267U, res->body.size());
  4110. // Check that both range contents are present
  4111. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4112. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4113. // Check that Content-Range headers are present for both ranges
  4114. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4115. std::string::npos);
  4116. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4117. std::string::npos);
  4118. }
  4119. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4120. Ranges ranges;
  4121. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4122. ranges.emplace_back(0, -1);
  4123. }
  4124. auto res =
  4125. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4126. ASSERT_TRUE(res);
  4127. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4128. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4129. EXPECT_EQ(false, res->has_header("Content-Range"));
  4130. EXPECT_EQ(0U, res->body.size());
  4131. }
  4132. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4133. auto res =
  4134. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4135. ASSERT_TRUE(res);
  4136. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4137. EXPECT_EQ(5U, res->body.size());
  4138. // Check that overlapping ranges are coalesced into a single range
  4139. EXPECT_EQ("bcdef", res->body);
  4140. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4141. // Should be single range, not multipart
  4142. EXPECT_TRUE(res->has_header("Content-Range"));
  4143. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4144. }
  4145. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4146. auto res =
  4147. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4148. ASSERT_TRUE(res);
  4149. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4150. EXPECT_EQ(268U, res->body.size());
  4151. // Check that both range contents are present
  4152. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4153. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4154. // Check that Content-Range headers are present for both ranges
  4155. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4156. std::string::npos);
  4157. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4158. std::string::npos);
  4159. }
  4160. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4161. auto res =
  4162. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4163. ASSERT_TRUE(res);
  4164. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4165. EXPECT_EQ(269U, res->body.size());
  4166. // Check that both duplicate range contents are present
  4167. size_t first_abc = res->body.find("abc\r\n");
  4168. EXPECT_TRUE(first_abc != std::string::npos);
  4169. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4170. EXPECT_TRUE(second_abc != std::string::npos);
  4171. // Check that Content-Range headers are present for both ranges
  4172. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4173. EXPECT_TRUE(first_range != std::string::npos);
  4174. size_t second_range =
  4175. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4176. EXPECT_TRUE(second_range != std::string::npos);
  4177. }
  4178. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4179. auto res = cli_.Get("/streamed-with-range?error",
  4180. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4181. ASSERT_TRUE(res);
  4182. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4183. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4184. EXPECT_EQ(false, res->has_header("Content-Range"));
  4185. EXPECT_EQ(0U, res->body.size());
  4186. }
  4187. TEST_F(ServerTest, GetStreamedEndless) {
  4188. uint64_t offset = 0;
  4189. auto res = cli_.Get("/streamed-cancel",
  4190. [&](const char * /*data*/, uint64_t data_length) {
  4191. if (offset < 100) {
  4192. offset += data_length;
  4193. return true;
  4194. }
  4195. return false;
  4196. });
  4197. ASSERT_TRUE(!res);
  4198. EXPECT_EQ(Error::Canceled, res.error());
  4199. }
  4200. TEST_F(ServerTest, ClientStop) {
  4201. std::atomic_size_t count{4};
  4202. std::vector<std::thread> threads;
  4203. for (auto i = count.load(); i != 0; --i) {
  4204. threads.emplace_back([&]() {
  4205. auto res = cli_.Get("/streamed-cancel",
  4206. [&](const char *, uint64_t) { return true; });
  4207. --count;
  4208. ASSERT_TRUE(!res);
  4209. EXPECT_TRUE(res.error() == Error::Canceled ||
  4210. res.error() == Error::Read || res.error() == Error::Write);
  4211. });
  4212. }
  4213. std::this_thread::sleep_for(std::chrono::seconds(2));
  4214. while (count != 0) {
  4215. cli_.stop();
  4216. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4217. }
  4218. for (auto &t : threads) {
  4219. t.join();
  4220. }
  4221. }
  4222. TEST_F(ServerTest, GetWithRange1) {
  4223. auto res = cli_.Get("/with-range", {
  4224. make_range_header({{3, 5}}),
  4225. {"Accept-Encoding", ""},
  4226. });
  4227. ASSERT_TRUE(res);
  4228. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4229. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4230. EXPECT_EQ(true, res->has_header("Content-Range"));
  4231. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4232. EXPECT_EQ(std::string("def"), res->body);
  4233. }
  4234. TEST_F(ServerTest, GetWithRange2) {
  4235. auto res = cli_.Get("/with-range", {
  4236. make_range_header({{1, -1}}),
  4237. {"Accept-Encoding", ""},
  4238. });
  4239. ASSERT_TRUE(res);
  4240. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4241. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4242. EXPECT_EQ(true, res->has_header("Content-Range"));
  4243. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4244. EXPECT_EQ(std::string("bcdefg"), res->body);
  4245. }
  4246. TEST_F(ServerTest, GetWithRange3) {
  4247. auto res = cli_.Get("/with-range", {
  4248. make_range_header({{0, 0}}),
  4249. {"Accept-Encoding", ""},
  4250. });
  4251. ASSERT_TRUE(res);
  4252. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4253. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4254. EXPECT_EQ(true, res->has_header("Content-Range"));
  4255. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4256. EXPECT_EQ(std::string("a"), res->body);
  4257. }
  4258. TEST_F(ServerTest, GetWithRange4) {
  4259. auto res = cli_.Get("/with-range", {
  4260. make_range_header({{-1, 2}}),
  4261. {"Accept-Encoding", ""},
  4262. });
  4263. ASSERT_TRUE(res);
  4264. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4265. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4266. EXPECT_EQ(true, res->has_header("Content-Range"));
  4267. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4268. EXPECT_EQ(std::string("fg"), res->body);
  4269. }
  4270. TEST_F(ServerTest, GetWithRange5) {
  4271. auto res = cli_.Get("/with-range", {
  4272. make_range_header({{0, 5}}),
  4273. {"Accept-Encoding", ""},
  4274. });
  4275. ASSERT_TRUE(res);
  4276. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4277. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4278. EXPECT_EQ(true, res->has_header("Content-Range"));
  4279. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4280. EXPECT_EQ(std::string("abcdef"), res->body);
  4281. }
  4282. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4283. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4284. ASSERT_TRUE(res);
  4285. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4286. }
  4287. TEST_F(ServerTest, GetWithRangeMultipart) {
  4288. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4289. ASSERT_TRUE(res);
  4290. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4291. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4292. EXPECT_EQ(false, res->has_header("Content-Range"));
  4293. EXPECT_EQ(267U, res->body.size());
  4294. }
  4295. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4296. auto res =
  4297. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4298. ASSERT_TRUE(res);
  4299. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4300. }
  4301. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4302. auto res = cli_.Get("/with-range-customized-response",
  4303. {{make_range_header({{1, 2}})}});
  4304. ASSERT_TRUE(res);
  4305. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4306. EXPECT_EQ(true, res->has_header("Content-Length"));
  4307. EXPECT_EQ(false, res->has_header("Content-Range"));
  4308. EXPECT_EQ(JSON_DATA, res->body);
  4309. }
  4310. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4311. auto res = cli_.Get("/with-range-customized-response",
  4312. {{make_range_header({{1, 2}, {4, 5}})}});
  4313. ASSERT_TRUE(res);
  4314. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4315. EXPECT_EQ(true, res->has_header("Content-Length"));
  4316. EXPECT_EQ(false, res->has_header("Content-Range"));
  4317. EXPECT_EQ(JSON_DATA, res->body);
  4318. }
  4319. TEST_F(ServerTest, Issue1772) {
  4320. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4321. ASSERT_TRUE(res);
  4322. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4323. }
  4324. TEST_F(ServerTest, Issue609) {
  4325. auto res = cli_.Delete("/issue609");
  4326. ASSERT_TRUE(res);
  4327. EXPECT_EQ(StatusCode::OK_200, res->status);
  4328. EXPECT_EQ(std::string("ok"), res->body);
  4329. }
  4330. TEST_F(ServerTest, GetStreamedChunked) {
  4331. auto res = cli_.Get("/streamed-chunked");
  4332. ASSERT_TRUE(res);
  4333. EXPECT_EQ(StatusCode::OK_200, res->status);
  4334. EXPECT_EQ(std::string("123456789"), res->body);
  4335. }
  4336. TEST_F(ServerTest, GetStreamedChunked2) {
  4337. auto res = cli_.Get("/streamed-chunked2");
  4338. ASSERT_TRUE(res);
  4339. EXPECT_EQ(StatusCode::OK_200, res->status);
  4340. EXPECT_EQ(std::string("123456789"), res->body);
  4341. }
  4342. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4343. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4344. ASSERT_TRUE(res);
  4345. EXPECT_EQ(StatusCode::OK_200, res->status);
  4346. EXPECT_EQ(std::string("123456789"), res->body);
  4347. EXPECT_TRUE(res->has_header("Trailer"));
  4348. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4349. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4350. // Trailers are now stored separately from headers (security fix)
  4351. EXPECT_EQ(2U, res->trailers.size());
  4352. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4353. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4354. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4355. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4356. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4357. // Verify trailers are NOT in headers (security verification)
  4358. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4359. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4360. }
  4361. TEST_F(ServerTest, LargeChunkedPost) {
  4362. Request req;
  4363. req.method = "POST";
  4364. req.path = "/large-chunked";
  4365. std::string host_and_port;
  4366. host_and_port += HOST;
  4367. host_and_port += ":";
  4368. host_and_port += std::to_string(PORT);
  4369. req.headers.emplace("Host", host_and_port.c_str());
  4370. req.headers.emplace("Accept", "*/*");
  4371. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4372. req.headers.emplace("Content-Type", "text/plain");
  4373. req.headers.emplace("Content-Length", "0");
  4374. req.headers.emplace("Transfer-Encoding", "chunked");
  4375. std::string long_string(30 * 1024u, 'a');
  4376. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4377. // Attempt to make a large enough post to exceed OS buffers, to test that
  4378. // the server handles short reads if the full chunk data isn't available.
  4379. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4380. auto res = std::make_shared<Response>();
  4381. auto error = Error::Success;
  4382. auto ret = cli_.send(req, *res, error);
  4383. ASSERT_TRUE(ret);
  4384. EXPECT_EQ(StatusCode::OK_200, res->status);
  4385. }
  4386. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4387. auto res = cli_.Get("/remote_addr");
  4388. ASSERT_TRUE(res);
  4389. EXPECT_EQ(StatusCode::OK_200, res->status);
  4390. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4391. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4392. }
  4393. TEST_F(ServerTest, GetMethodLocalAddr) {
  4394. auto res = cli_.Get("/local_addr");
  4395. ASSERT_TRUE(res);
  4396. EXPECT_EQ(StatusCode::OK_200, res->status);
  4397. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4398. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4399. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4400. }
  4401. TEST_F(ServerTest, HTTPResponseSplitting) {
  4402. auto res = cli_.Get("/http_response_splitting");
  4403. ASSERT_TRUE(res);
  4404. EXPECT_EQ(StatusCode::OK_200, res->status);
  4405. }
  4406. TEST_F(ServerTest, SlowRequest) {
  4407. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4408. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4409. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4410. }
  4411. #if 0
  4412. TEST_F(ServerTest, SlowPost) {
  4413. char buffer[64 * 1024];
  4414. memset(buffer, 0x42, sizeof(buffer));
  4415. auto res = cli_.Post(
  4416. "/slowpost", 64 * 1024 * 1024,
  4417. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4418. auto ret = sink.write(buffer, sizeof(buffer));
  4419. EXPECT_TRUE(ret);
  4420. return true;
  4421. },
  4422. "text/plain");
  4423. ASSERT_TRUE(res);
  4424. EXPECT_EQ(StatusCode::OK_200, res->status);
  4425. }
  4426. TEST_F(ServerTest, SlowPostFail) {
  4427. char buffer[64 * 1024];
  4428. memset(buffer, 0x42, sizeof(buffer));
  4429. cli_.set_write_timeout(std::chrono::seconds(0));
  4430. auto res = cli_.Post(
  4431. "/slowpost", 64 * 1024 * 1024,
  4432. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4433. sink.write(buffer, sizeof(buffer));
  4434. return true;
  4435. },
  4436. "text/plain");
  4437. ASSERT_TRUE(!res);
  4438. EXPECT_EQ(Error::Write, res.error());
  4439. }
  4440. #endif
  4441. TEST_F(ServerTest, Put) {
  4442. auto res = cli_.Put("/put", "PUT", "text/plain");
  4443. ASSERT_TRUE(res);
  4444. EXPECT_EQ(StatusCode::OK_200, res->status);
  4445. EXPECT_EQ("PUT", res->body);
  4446. }
  4447. TEST_F(ServerTest, PutWithContentProvider) {
  4448. auto res = cli_.Put(
  4449. "/put", 3,
  4450. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4451. sink.os << "PUT";
  4452. return true;
  4453. },
  4454. "text/plain");
  4455. ASSERT_TRUE(res);
  4456. EXPECT_EQ(StatusCode::OK_200, res->status);
  4457. EXPECT_EQ("PUT", res->body);
  4458. }
  4459. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4460. auto res = cli_.Post(
  4461. "/post", 42,
  4462. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4463. return false;
  4464. },
  4465. "text/plain");
  4466. ASSERT_TRUE(!res);
  4467. EXPECT_EQ(Error::Canceled, res.error());
  4468. }
  4469. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4470. auto res = cli_.Put(
  4471. "/put",
  4472. [](size_t /*offset*/, DataSink &sink) {
  4473. sink.os << "PUT";
  4474. sink.done();
  4475. return true;
  4476. },
  4477. "text/plain");
  4478. ASSERT_TRUE(res);
  4479. EXPECT_EQ(StatusCode::OK_200, res->status);
  4480. EXPECT_EQ("PUT", res->body);
  4481. }
  4482. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4483. auto res = cli_.Post(
  4484. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4485. "text/plain");
  4486. ASSERT_TRUE(!res);
  4487. EXPECT_EQ(Error::Canceled, res.error());
  4488. }
  4489. TEST_F(ServerTest, PostLoopBack) {
  4490. std::string body;
  4491. auto res = cli_.Post(
  4492. "/post-loopback", 9,
  4493. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4494. EXPECT_EQ(9u, length);
  4495. sink.write("123", 3);
  4496. sink.write("456", 3);
  4497. sink.write("789", 3);
  4498. return true;
  4499. },
  4500. "text/plain",
  4501. [&body](const char *data, size_t data_length) {
  4502. body.append(data, data_length);
  4503. return true;
  4504. });
  4505. ASSERT_TRUE(res);
  4506. EXPECT_EQ(StatusCode::OK_200, res->status);
  4507. EXPECT_EQ("123456789", body);
  4508. }
  4509. TEST_F(ServerTest, PutLoopBack) {
  4510. std::string body;
  4511. auto res = cli_.Put(
  4512. "/put-loopback", 9,
  4513. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4514. EXPECT_EQ(9u, length);
  4515. sink.write("123", 3);
  4516. sink.write("456", 3);
  4517. sink.write("789", 3);
  4518. return true;
  4519. },
  4520. "text/plain",
  4521. [&body](const char *data, size_t data_length) {
  4522. body.append(data, data_length);
  4523. return true;
  4524. });
  4525. ASSERT_TRUE(res);
  4526. EXPECT_EQ(StatusCode::OK_200, res->status);
  4527. EXPECT_EQ("123456789", body);
  4528. }
  4529. TEST_F(ServerTest, PatchLoopBack) {
  4530. std::string body;
  4531. auto res = cli_.Patch(
  4532. "/patch-loopback", 9,
  4533. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4534. EXPECT_EQ(9u, length);
  4535. sink.write("123", 3);
  4536. sink.write("456", 3);
  4537. sink.write("789", 3);
  4538. return true;
  4539. },
  4540. "text/plain",
  4541. [&body](const char *data, size_t data_length) {
  4542. body.append(data, data_length);
  4543. return true;
  4544. });
  4545. ASSERT_TRUE(res);
  4546. EXPECT_EQ(StatusCode::OK_200, res->status);
  4547. EXPECT_EQ("123456789", body);
  4548. }
  4549. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4550. std::string body;
  4551. auto res = cli_.Post(
  4552. "/post-loopback",
  4553. [](size_t /*offset*/, DataSink &sink) {
  4554. sink.write("123", 3);
  4555. sink.write("456", 3);
  4556. sink.write("789", 3);
  4557. sink.done();
  4558. return true;
  4559. },
  4560. "text/plain",
  4561. [&body](const char *data, size_t data_length) {
  4562. body.append(data, data_length);
  4563. return true;
  4564. });
  4565. ASSERT_TRUE(res);
  4566. EXPECT_EQ(StatusCode::OK_200, res->status);
  4567. EXPECT_EQ("123456789", body);
  4568. }
  4569. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4570. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4571. cli_.set_compress(true);
  4572. auto res = cli_.Put(
  4573. "/put", 3,
  4574. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4575. sink.os << "PUT";
  4576. return true;
  4577. },
  4578. "text/plain");
  4579. ASSERT_TRUE(res);
  4580. EXPECT_EQ(StatusCode::OK_200, res->status);
  4581. EXPECT_EQ("PUT", res->body);
  4582. }
  4583. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4584. cli_.set_compress(true);
  4585. auto res = cli_.Post(
  4586. "/post", 42,
  4587. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4588. return false;
  4589. },
  4590. "text/plain");
  4591. ASSERT_TRUE(!res);
  4592. EXPECT_EQ(Error::Canceled, res.error());
  4593. }
  4594. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4595. cli_.set_compress(true);
  4596. auto res = cli_.Put(
  4597. "/put",
  4598. [](size_t /*offset*/, DataSink &sink) {
  4599. sink.os << "PUT";
  4600. sink.done();
  4601. return true;
  4602. },
  4603. "text/plain");
  4604. ASSERT_TRUE(res);
  4605. EXPECT_EQ(StatusCode::OK_200, res->status);
  4606. EXPECT_EQ("PUT", res->body);
  4607. }
  4608. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4609. cli_.set_compress(true);
  4610. auto res = cli_.Post(
  4611. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4612. "text/plain");
  4613. ASSERT_TRUE(!res);
  4614. EXPECT_EQ(Error::Canceled, res.error());
  4615. }
  4616. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4617. cli_.set_compress(true);
  4618. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4619. ASSERT_TRUE(res);
  4620. EXPECT_EQ(StatusCode::OK_200, res->status);
  4621. EXPECT_EQ(LARGE_DATA, res->body);
  4622. }
  4623. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4624. #ifdef CPPHTTPLIB_SSL_ENABLED
  4625. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4626. Client cli(s.c_str());
  4627. cli.enable_server_certificate_verification(false);
  4628. #else
  4629. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4630. Client cli(s.c_str());
  4631. #endif
  4632. cli.set_compress(true);
  4633. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4634. ASSERT_TRUE(res);
  4635. EXPECT_EQ(StatusCode::OK_200, res->status);
  4636. EXPECT_EQ(LARGE_DATA, res->body);
  4637. // The compressed size should be less than a 10th of the original. May vary
  4638. // depending on the zlib library.
  4639. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4640. static_cast<uint64_t>(10 * 1024 * 1024));
  4641. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4642. }
  4643. TEST_F(ServerTest, PutContentWithDeflate) {
  4644. cli_.set_compress(false);
  4645. Headers headers;
  4646. headers.emplace("Content-Encoding", "deflate");
  4647. // PUT in deflate format:
  4648. auto res = cli_.Put("/put", headers,
  4649. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4650. ASSERT_TRUE(res);
  4651. EXPECT_EQ(StatusCode::OK_200, res->status);
  4652. EXPECT_EQ("PUT", res->body);
  4653. }
  4654. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4655. Headers headers;
  4656. headers.emplace("Accept-Encoding", "gzip, deflate");
  4657. auto res = cli_.Get("/streamed-chunked", headers);
  4658. ASSERT_TRUE(res);
  4659. EXPECT_EQ(StatusCode::OK_200, res->status);
  4660. EXPECT_EQ(std::string("123456789"), res->body);
  4661. }
  4662. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4663. Headers headers;
  4664. headers.emplace("Accept-Encoding", "gzip, deflate");
  4665. auto res = cli_.Get("/streamed-chunked2", headers);
  4666. ASSERT_TRUE(res);
  4667. EXPECT_EQ(StatusCode::OK_200, res->status);
  4668. EXPECT_EQ(std::string("123456789"), res->body);
  4669. }
  4670. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4671. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4672. ASSERT_TRUE(res);
  4673. EXPECT_EQ(StatusCode::OK_200, res->status);
  4674. }
  4675. TEST(GzipDecompressor, ChunkedDecompression) {
  4676. std::string data;
  4677. for (size_t i = 0; i < 32 * 1024; ++i) {
  4678. data.push_back(static_cast<char>('a' + i % 26));
  4679. }
  4680. std::string compressed_data;
  4681. {
  4682. httplib::detail::gzip_compressor compressor;
  4683. bool result = compressor.compress(
  4684. data.data(), data.size(),
  4685. /*last=*/true,
  4686. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4687. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4688. compressed_data_size);
  4689. return true;
  4690. });
  4691. ASSERT_TRUE(result);
  4692. }
  4693. std::string decompressed_data;
  4694. {
  4695. httplib::detail::gzip_decompressor decompressor;
  4696. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4697. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4698. size_t chunk_size = 130;
  4699. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4700. chunk_begin += chunk_size) {
  4701. size_t current_chunk_size =
  4702. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4703. bool result = decompressor.decompress(
  4704. compressed_data.data() + chunk_begin, current_chunk_size,
  4705. [&](const char *decompressed_data_chunk,
  4706. size_t decompressed_data_chunk_size) {
  4707. decompressed_data.insert(decompressed_data.size(),
  4708. decompressed_data_chunk,
  4709. decompressed_data_chunk_size);
  4710. return true;
  4711. });
  4712. ASSERT_TRUE(result);
  4713. }
  4714. }
  4715. ASSERT_EQ(data, decompressed_data);
  4716. }
  4717. TEST(GzipDecompressor, DeflateDecompression) {
  4718. std::string original_text = "Raw deflate without gzip";
  4719. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4720. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4721. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4722. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4723. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4724. std::string decompressed_data;
  4725. {
  4726. httplib::detail::gzip_decompressor decompressor;
  4727. bool result = decompressor.decompress(
  4728. compressed_data.data(), compressed_data.size(),
  4729. [&](const char *decompressed_data_chunk,
  4730. size_t decompressed_data_chunk_size) {
  4731. decompressed_data.insert(decompressed_data.size(),
  4732. decompressed_data_chunk,
  4733. decompressed_data_chunk_size);
  4734. return true;
  4735. });
  4736. ASSERT_TRUE(result);
  4737. }
  4738. ASSERT_EQ(original_text, decompressed_data);
  4739. }
  4740. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4741. std::string original_text = "Raw deflate without gzip";
  4742. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4743. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4744. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4745. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4746. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4747. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4748. std::string decompressed_data;
  4749. {
  4750. httplib::detail::gzip_decompressor decompressor;
  4751. bool result = decompressor.decompress(
  4752. compressed_data.data(), compressed_data.size(),
  4753. [&](const char *decompressed_data_chunk,
  4754. size_t decompressed_data_chunk_size) {
  4755. decompressed_data.insert(decompressed_data.size(),
  4756. decompressed_data_chunk,
  4757. decompressed_data_chunk_size);
  4758. return true;
  4759. });
  4760. ASSERT_TRUE(result);
  4761. }
  4762. ASSERT_EQ(original_text, decompressed_data);
  4763. }
  4764. #ifdef _WIN32
  4765. TEST(GzipDecompressor, LargeRandomData) {
  4766. // prepare large random data that is difficult to be compressed and is
  4767. // expected to have large size even when compressed
  4768. std::random_device seed_gen;
  4769. std::mt19937 random(seed_gen());
  4770. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4771. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4772. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4773. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4774. // compress data over 4GiB
  4775. std::string compressed_data;
  4776. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4777. httplib::detail::gzip_compressor compressor;
  4778. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4779. data.size() * sizeof(std::uint32_t), true,
  4780. [&](const char *data, size_t size) {
  4781. compressed_data.insert(
  4782. compressed_data.size(), data, size);
  4783. return true;
  4784. });
  4785. ASSERT_TRUE(result);
  4786. // FIXME: compressed data size is expected to be greater than 4GiB,
  4787. // but there is no guarantee
  4788. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4789. // decompress data over 4GiB
  4790. std::string decompressed_data;
  4791. decompressed_data.reserve(data_size);
  4792. httplib::detail::gzip_decompressor decompressor;
  4793. result = decompressor.decompress(
  4794. compressed_data.data(), compressed_data.size(),
  4795. [&](const char *data, size_t size) {
  4796. decompressed_data.insert(decompressed_data.size(), data, size);
  4797. return true;
  4798. });
  4799. ASSERT_TRUE(result);
  4800. // compare
  4801. ASSERT_EQ(data_size, decompressed_data.size());
  4802. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4803. 0);
  4804. }
  4805. #endif
  4806. #endif
  4807. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4808. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4809. Headers headers;
  4810. headers.emplace("Accept-Encoding", "br");
  4811. auto res = cli_.Get("/streamed-chunked", headers);
  4812. ASSERT_TRUE(res);
  4813. EXPECT_EQ(StatusCode::OK_200, res->status);
  4814. EXPECT_EQ(std::string("123456789"), res->body);
  4815. }
  4816. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4817. Headers headers;
  4818. headers.emplace("Accept-Encoding", "br");
  4819. auto res = cli_.Get("/streamed-chunked2", headers);
  4820. ASSERT_TRUE(res);
  4821. EXPECT_EQ(StatusCode::OK_200, res->status);
  4822. EXPECT_EQ(std::string("123456789"), res->body);
  4823. }
  4824. #endif
  4825. TEST_F(ServerTest, Patch) {
  4826. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4827. ASSERT_TRUE(res);
  4828. EXPECT_EQ(StatusCode::OK_200, res->status);
  4829. EXPECT_EQ("PATCH", res->body);
  4830. }
  4831. TEST_F(ServerTest, Delete) {
  4832. auto res = cli_.Delete("/delete");
  4833. ASSERT_TRUE(res);
  4834. EXPECT_EQ(StatusCode::OK_200, res->status);
  4835. EXPECT_EQ("DELETE", res->body);
  4836. }
  4837. TEST_F(ServerTest, DeleteContentReceiver) {
  4838. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4839. ASSERT_TRUE(res);
  4840. EXPECT_EQ(StatusCode::OK_200, res->status);
  4841. EXPECT_EQ("content", res->body);
  4842. }
  4843. TEST_F(ServerTest, Options) {
  4844. auto res = cli_.Options("*");
  4845. ASSERT_TRUE(res);
  4846. EXPECT_EQ(StatusCode::OK_200, res->status);
  4847. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4848. EXPECT_TRUE(res->body.empty());
  4849. }
  4850. TEST_F(ServerTest, URL) {
  4851. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4852. ASSERT_TRUE(res);
  4853. EXPECT_EQ(StatusCode::OK_200, res->status);
  4854. }
  4855. TEST_F(ServerTest, ArrayParam) {
  4856. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4857. ASSERT_TRUE(res);
  4858. EXPECT_EQ(StatusCode::OK_200, res->status);
  4859. }
  4860. TEST_F(ServerTest, NoMultipleHeaders) {
  4861. Headers headers = {{"Content-Length", "5"}};
  4862. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4863. "text/plain");
  4864. ASSERT_TRUE(res);
  4865. EXPECT_EQ(StatusCode::OK_200, res->status);
  4866. }
  4867. TEST_F(ServerTest, PostContentReceiver) {
  4868. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4869. ASSERT_TRUE(res);
  4870. ASSERT_EQ(StatusCode::OK_200, res->status);
  4871. ASSERT_EQ("content", res->body);
  4872. }
  4873. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4874. UploadFormDataItems items = {
  4875. {"text1", "text default", "", ""},
  4876. {"text2", "aωb", "", ""},
  4877. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4878. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4879. {"file3", "", "", "application/octet-stream"},
  4880. };
  4881. auto res = cli_.Post("/content_receiver", items);
  4882. ASSERT_TRUE(res);
  4883. EXPECT_EQ(StatusCode::OK_200, res->status);
  4884. }
  4885. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4886. UploadFormDataItems items = {
  4887. {"text1", "text default", "", ""},
  4888. {"text2", "aωb", "", ""},
  4889. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4890. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4891. {"file3", "", "", "application/octet-stream"},
  4892. };
  4893. auto boundary = std::string("+++++");
  4894. std::string body;
  4895. for (const auto &item : items) {
  4896. body += "--" + boundary + "\r\n";
  4897. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4898. if (!item.filename.empty()) {
  4899. body += "; filename=\"" + item.filename + "\"";
  4900. }
  4901. body += "\r\n";
  4902. if (!item.content_type.empty()) {
  4903. body += "Content-Type: " + item.content_type + "\r\n";
  4904. }
  4905. body += "\r\n";
  4906. body += item.content + "\r\n";
  4907. }
  4908. body += "--" + boundary + "--\r\n";
  4909. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4910. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4911. ASSERT_TRUE(res);
  4912. EXPECT_EQ(StatusCode::OK_200, res->status);
  4913. }
  4914. TEST_F(ServerTest, PostContentReceiverGzip) {
  4915. cli_.set_compress(true);
  4916. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4917. ASSERT_TRUE(res);
  4918. ASSERT_EQ(StatusCode::OK_200, res->status);
  4919. ASSERT_EQ("content", res->body);
  4920. }
  4921. TEST_F(ServerTest, PutContentReceiver) {
  4922. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4923. ASSERT_TRUE(res);
  4924. ASSERT_EQ(StatusCode::OK_200, res->status);
  4925. ASSERT_EQ("content", res->body);
  4926. }
  4927. TEST_F(ServerTest, PatchContentReceiver) {
  4928. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4929. ASSERT_TRUE(res);
  4930. ASSERT_EQ(StatusCode::OK_200, res->status);
  4931. ASSERT_EQ("content", res->body);
  4932. }
  4933. template <typename ClientType>
  4934. void TestWithHeadersAndContentReceiver(
  4935. ClientType &cli,
  4936. std::function<Result(ClientType &, const std::string &, const Headers &,
  4937. const std::string &, const std::string &,
  4938. ContentReceiver, DownloadProgress)>
  4939. request_func) {
  4940. Headers headers;
  4941. headers.emplace("X-Custom-Header", "test-value");
  4942. std::string received_body;
  4943. auto res = request_func(
  4944. cli, "/content_receiver", headers, "content", "application/json",
  4945. [&](const char *data, size_t data_length) {
  4946. received_body.append(data, data_length);
  4947. return true;
  4948. },
  4949. nullptr);
  4950. ASSERT_TRUE(res);
  4951. EXPECT_EQ(StatusCode::OK_200, res->status);
  4952. EXPECT_EQ("content", received_body);
  4953. }
  4954. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4955. #ifdef CPPHTTPLIB_SSL_ENABLED
  4956. using ClientT = SSLClient;
  4957. #else
  4958. using ClientT = Client;
  4959. #endif
  4960. TestWithHeadersAndContentReceiver<ClientT>(
  4961. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4962. const std::string &body, const std::string &content_type,
  4963. ContentReceiver receiver, DownloadProgress progress) {
  4964. return cli.Post(path, headers, body, content_type, receiver, progress);
  4965. });
  4966. }
  4967. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4968. #ifdef CPPHTTPLIB_SSL_ENABLED
  4969. using ClientT = SSLClient;
  4970. #else
  4971. using ClientT = Client;
  4972. #endif
  4973. TestWithHeadersAndContentReceiver<ClientT>(
  4974. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4975. const std::string &body, const std::string &content_type,
  4976. ContentReceiver receiver, DownloadProgress progress) {
  4977. return cli.Put(path, headers, body, content_type, receiver, progress);
  4978. });
  4979. }
  4980. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4981. #ifdef CPPHTTPLIB_SSL_ENABLED
  4982. using ClientT = SSLClient;
  4983. #else
  4984. using ClientT = Client;
  4985. #endif
  4986. TestWithHeadersAndContentReceiver<ClientT>(
  4987. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4988. const std::string &body, const std::string &content_type,
  4989. ContentReceiver receiver, DownloadProgress progress) {
  4990. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4991. });
  4992. }
  4993. template <typename ClientType>
  4994. void TestWithHeadersAndContentReceiverWithProgress(
  4995. ClientType &cli,
  4996. std::function<Result(ClientType &, const std::string &, const Headers &,
  4997. const std::string &, const std::string &,
  4998. ContentReceiver, DownloadProgress)>
  4999. request_func) {
  5000. Headers headers;
  5001. headers.emplace("X-Test-Header", "progress-test");
  5002. std::string received_body;
  5003. auto progress_called = false;
  5004. auto res = request_func(
  5005. cli, "/content_receiver", headers, "content", "text/plain",
  5006. [&](const char *data, size_t data_length) {
  5007. received_body.append(data, data_length);
  5008. return true;
  5009. },
  5010. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5011. progress_called = true;
  5012. return true;
  5013. });
  5014. ASSERT_TRUE(res);
  5015. EXPECT_EQ(StatusCode::OK_200, res->status);
  5016. EXPECT_EQ("content", received_body);
  5017. EXPECT_TRUE(progress_called);
  5018. }
  5019. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5020. #ifdef CPPHTTPLIB_SSL_ENABLED
  5021. using ClientT = SSLClient;
  5022. #else
  5023. using ClientT = Client;
  5024. #endif
  5025. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5026. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5027. const std::string &body, const std::string &content_type,
  5028. ContentReceiver receiver, DownloadProgress progress) {
  5029. return cli.Post(path, headers, body, content_type, receiver, progress);
  5030. });
  5031. }
  5032. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5033. #ifdef CPPHTTPLIB_SSL_ENABLED
  5034. using ClientT = SSLClient;
  5035. #else
  5036. using ClientT = Client;
  5037. #endif
  5038. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5039. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5040. const std::string &body, const std::string &content_type,
  5041. ContentReceiver receiver, DownloadProgress progress) {
  5042. return cli.Put(path, headers, body, content_type, receiver, progress);
  5043. });
  5044. }
  5045. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5046. #ifdef CPPHTTPLIB_SSL_ENABLED
  5047. using ClientT = SSLClient;
  5048. #else
  5049. using ClientT = Client;
  5050. #endif
  5051. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5052. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5053. const std::string &body, const std::string &content_type,
  5054. ContentReceiver receiver, DownloadProgress progress) {
  5055. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5056. });
  5057. }
  5058. template <typename ClientType>
  5059. void TestWithHeadersAndContentReceiverError(
  5060. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5061. const Headers &, const std::string &,
  5062. const std::string &, ContentReceiver)>
  5063. request_func) {
  5064. Headers headers;
  5065. headers.emplace("X-Error-Test", "true");
  5066. std::string received_body;
  5067. auto receiver_failed = false;
  5068. auto res =
  5069. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5070. [&](const char *data, size_t data_length) {
  5071. received_body.append(data, data_length);
  5072. receiver_failed = true;
  5073. return false;
  5074. });
  5075. ASSERT_FALSE(res);
  5076. EXPECT_TRUE(receiver_failed);
  5077. }
  5078. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5079. #ifdef CPPHTTPLIB_SSL_ENABLED
  5080. using ClientT = SSLClient;
  5081. #else
  5082. using ClientT = Client;
  5083. #endif
  5084. TestWithHeadersAndContentReceiverError<ClientT>(
  5085. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5086. const std::string &body, const std::string &content_type,
  5087. ContentReceiver receiver) {
  5088. return cli.Post(path, headers, body, content_type, receiver);
  5089. });
  5090. }
  5091. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5092. #ifdef CPPHTTPLIB_SSL_ENABLED
  5093. using ClientT = SSLClient;
  5094. #else
  5095. using ClientT = Client;
  5096. #endif
  5097. TestWithHeadersAndContentReceiverError<ClientT>(
  5098. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5099. const std::string &body, const std::string &content_type,
  5100. ContentReceiver receiver) {
  5101. return cli.Put(path, headers, body, content_type, receiver);
  5102. });
  5103. }
  5104. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5105. #ifdef CPPHTTPLIB_SSL_ENABLED
  5106. using ClientT = SSLClient;
  5107. #else
  5108. using ClientT = Client;
  5109. #endif
  5110. TestWithHeadersAndContentReceiverError<ClientT>(
  5111. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5112. const std::string &body, const std::string &content_type,
  5113. ContentReceiver receiver) {
  5114. return cli.Patch(path, headers, body, content_type, receiver);
  5115. });
  5116. }
  5117. TEST_F(ServerTest, PostQueryStringAndBody) {
  5118. auto res =
  5119. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5120. ASSERT_TRUE(res);
  5121. ASSERT_EQ(StatusCode::OK_200, res->status);
  5122. }
  5123. TEST_F(ServerTest, HTTP2Magic) {
  5124. Request req;
  5125. req.method = "PRI";
  5126. req.path = "*";
  5127. req.body = "SM";
  5128. auto res = std::make_shared<Response>();
  5129. auto error = Error::Success;
  5130. auto ret = cli_.send(req, *res, error);
  5131. ASSERT_TRUE(ret);
  5132. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5133. }
  5134. TEST_F(ServerTest, KeepAlive) {
  5135. auto res = cli_.Get("/hi");
  5136. ASSERT_TRUE(res);
  5137. EXPECT_EQ(StatusCode::OK_200, res->status);
  5138. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5139. EXPECT_EQ("Hello World!", res->body);
  5140. res = cli_.Get("/hi");
  5141. ASSERT_TRUE(res);
  5142. EXPECT_EQ(StatusCode::OK_200, res->status);
  5143. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5144. EXPECT_EQ("Hello World!", res->body);
  5145. res = cli_.Get("/hi");
  5146. ASSERT_TRUE(res);
  5147. EXPECT_EQ(StatusCode::OK_200, res->status);
  5148. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5149. EXPECT_EQ("Hello World!", res->body);
  5150. res = cli_.Get("/not-exist");
  5151. ASSERT_TRUE(res);
  5152. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5153. res = cli_.Post("/empty", "", "text/plain");
  5154. ASSERT_TRUE(res);
  5155. EXPECT_EQ(StatusCode::OK_200, res->status);
  5156. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5157. EXPECT_EQ("empty", res->body);
  5158. EXPECT_EQ("close", res->get_header_value("Connection"));
  5159. res = cli_.Post(
  5160. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5161. "text/plain");
  5162. ASSERT_TRUE(res);
  5163. EXPECT_EQ(StatusCode::OK_200, res->status);
  5164. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5165. EXPECT_EQ("empty", res->body);
  5166. cli_.set_keep_alive(false);
  5167. res = cli_.Get("/last-request");
  5168. ASSERT_TRUE(res);
  5169. EXPECT_EQ(StatusCode::OK_200, res->status);
  5170. EXPECT_EQ("close", res->get_header_value("Connection"));
  5171. }
  5172. TEST_F(ServerTest, TooManyRedirect) {
  5173. cli_.set_follow_location(true);
  5174. auto res = cli_.Get("/redirect/0");
  5175. ASSERT_TRUE(!res);
  5176. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5177. }
  5178. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5179. Request req;
  5180. req.method = "FOOBAR";
  5181. req.path = "/hi";
  5182. cli_.set_keep_alive(true);
  5183. auto res = cli_.send(req);
  5184. ASSERT_TRUE(res);
  5185. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5186. EXPECT_EQ("close", res->get_header_value("Connection"));
  5187. EXPECT_FALSE(cli_.is_socket_open());
  5188. }
  5189. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5190. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5191. TEST_F(ServerTest, Gzip) {
  5192. Headers headers;
  5193. headers.emplace("Accept-Encoding", "gzip, deflate");
  5194. auto res = cli_.Get("/compress", headers);
  5195. ASSERT_TRUE(res);
  5196. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5197. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5198. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5199. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5200. "7890123456789012345678901234567890",
  5201. res->body);
  5202. EXPECT_EQ(StatusCode::OK_200, res->status);
  5203. }
  5204. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5205. Headers headers;
  5206. headers.emplace("Accept-Encoding", "");
  5207. auto res = cli_.Get("/compress", headers);
  5208. ASSERT_TRUE(res);
  5209. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5210. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5211. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5212. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5213. "7890123456789012345678901234567890",
  5214. res->body);
  5215. EXPECT_EQ(StatusCode::OK_200, res->status);
  5216. }
  5217. TEST_F(ServerTest, GzipWithContentReceiver) {
  5218. Headers headers;
  5219. headers.emplace("Accept-Encoding", "gzip, deflate");
  5220. std::string body;
  5221. auto res = cli_.Get("/compress", headers,
  5222. [&](const char *data, uint64_t data_length) {
  5223. EXPECT_EQ(100U, data_length);
  5224. body.append(data, data_length);
  5225. return true;
  5226. });
  5227. ASSERT_TRUE(res);
  5228. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5229. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5230. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5231. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5232. "7890123456789012345678901234567890",
  5233. body);
  5234. EXPECT_EQ(StatusCode::OK_200, res->status);
  5235. }
  5236. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5237. Headers headers;
  5238. headers.emplace("Accept-Encoding", "gzip, deflate");
  5239. cli_.set_decompress(false);
  5240. auto res = cli_.Get("/compress", headers);
  5241. ASSERT_TRUE(res);
  5242. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5243. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5244. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5245. EXPECT_EQ(33U, res->body.size());
  5246. EXPECT_EQ(StatusCode::OK_200, res->status);
  5247. }
  5248. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5249. Headers headers;
  5250. headers.emplace("Accept-Encoding", "");
  5251. std::string body;
  5252. auto res = cli_.Get("/compress", headers,
  5253. [&](const char *data, uint64_t data_length) {
  5254. EXPECT_EQ(100U, data_length);
  5255. body.append(data, data_length);
  5256. return true;
  5257. });
  5258. ASSERT_TRUE(res);
  5259. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5260. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5261. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5262. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5263. "7890123456789012345678901234567890",
  5264. body);
  5265. EXPECT_EQ(StatusCode::OK_200, res->status);
  5266. }
  5267. TEST_F(ServerTest, NoGzip) {
  5268. Headers headers;
  5269. headers.emplace("Accept-Encoding", "gzip, deflate");
  5270. auto res = cli_.Get("/nocompress", headers);
  5271. ASSERT_TRUE(res);
  5272. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5273. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5274. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5275. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5276. "7890123456789012345678901234567890",
  5277. res->body);
  5278. EXPECT_EQ(StatusCode::OK_200, res->status);
  5279. }
  5280. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5281. Headers headers;
  5282. headers.emplace("Accept-Encoding", "gzip, deflate");
  5283. std::string body;
  5284. auto res = cli_.Get("/nocompress", headers,
  5285. [&](const char *data, uint64_t data_length) {
  5286. EXPECT_EQ(100U, data_length);
  5287. body.append(data, data_length);
  5288. return true;
  5289. });
  5290. ASSERT_TRUE(res);
  5291. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5292. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5293. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5294. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5295. "7890123456789012345678901234567890",
  5296. body);
  5297. EXPECT_EQ(StatusCode::OK_200, res->status);
  5298. }
  5299. TEST_F(ServerTest, MultipartFormDataGzip) {
  5300. UploadFormDataItems items = {
  5301. {"key1", "test", "", ""},
  5302. {"key2", "--abcdefg123", "", ""},
  5303. };
  5304. cli_.set_compress(true);
  5305. auto res = cli_.Post("/compress-multipart", items);
  5306. ASSERT_TRUE(res);
  5307. EXPECT_EQ(StatusCode::OK_200, res->status);
  5308. }
  5309. #endif
  5310. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5311. TEST_F(ServerTest, Brotli) {
  5312. Headers headers;
  5313. headers.emplace("Accept-Encoding", "br");
  5314. auto res = cli_.Get("/compress", headers);
  5315. ASSERT_TRUE(res);
  5316. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5317. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5318. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5319. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5320. "7890123456789012345678901234567890",
  5321. res->body);
  5322. EXPECT_EQ(StatusCode::OK_200, res->status);
  5323. }
  5324. #endif
  5325. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5326. TEST_F(ServerTest, Zstd) {
  5327. Headers headers;
  5328. headers.emplace("Accept-Encoding", "zstd");
  5329. auto res = cli_.Get("/compress", headers);
  5330. ASSERT_TRUE(res);
  5331. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5332. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5333. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5334. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5335. "7890123456789012345678901234567890",
  5336. res->body);
  5337. EXPECT_EQ(StatusCode::OK_200, res->status);
  5338. }
  5339. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5340. Headers headers;
  5341. headers.emplace("Accept-Encoding", "");
  5342. auto res = cli_.Get("/compress", headers);
  5343. ASSERT_TRUE(res);
  5344. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5345. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5346. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5347. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5348. "7890123456789012345678901234567890",
  5349. res->body);
  5350. EXPECT_EQ(StatusCode::OK_200, res->status);
  5351. }
  5352. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5353. Headers headers;
  5354. headers.emplace("Accept-Encoding", "zstd");
  5355. std::string body;
  5356. auto res = cli_.Get("/compress", headers,
  5357. [&](const char *data, uint64_t data_length) {
  5358. EXPECT_EQ(100U, data_length);
  5359. body.append(data, data_length);
  5360. return true;
  5361. });
  5362. ASSERT_TRUE(res);
  5363. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5364. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5365. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5366. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5367. "7890123456789012345678901234567890",
  5368. body);
  5369. EXPECT_EQ(StatusCode::OK_200, res->status);
  5370. }
  5371. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5372. Headers headers;
  5373. headers.emplace("Accept-Encoding", "zstd");
  5374. cli_.set_decompress(false);
  5375. auto res = cli_.Get("/compress", headers);
  5376. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5377. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5378. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5379. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5380. ASSERT_TRUE(res);
  5381. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5382. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5383. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5384. EXPECT_EQ(StatusCode::OK_200, res->status);
  5385. ASSERT_EQ(26U, res->body.size());
  5386. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5387. 0);
  5388. }
  5389. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5390. Headers headers;
  5391. headers.emplace("Accept-Encoding", "");
  5392. std::string body;
  5393. auto res = cli_.Get("/compress", headers,
  5394. [&](const char *data, uint64_t data_length) {
  5395. EXPECT_EQ(100U, data_length);
  5396. body.append(data, data_length);
  5397. return true;
  5398. });
  5399. ASSERT_TRUE(res);
  5400. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5401. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5402. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5403. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5404. "7890123456789012345678901234567890",
  5405. body);
  5406. EXPECT_EQ(StatusCode::OK_200, res->status);
  5407. }
  5408. TEST_F(ServerTest, NoZstd) {
  5409. Headers headers;
  5410. headers.emplace("Accept-Encoding", "zstd");
  5411. auto res = cli_.Get("/nocompress", headers);
  5412. ASSERT_TRUE(res);
  5413. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5414. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5415. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5416. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5417. "7890123456789012345678901234567890",
  5418. res->body);
  5419. EXPECT_EQ(StatusCode::OK_200, res->status);
  5420. }
  5421. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5422. Headers headers;
  5423. headers.emplace("Accept-Encoding", "zstd");
  5424. std::string body;
  5425. auto res = cli_.Get("/nocompress", headers,
  5426. [&](const char *data, uint64_t data_length) {
  5427. EXPECT_EQ(100U, data_length);
  5428. body.append(data, data_length);
  5429. return true;
  5430. });
  5431. ASSERT_TRUE(res);
  5432. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5433. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5434. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5435. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5436. "7890123456789012345678901234567890",
  5437. body);
  5438. EXPECT_EQ(StatusCode::OK_200, res->status);
  5439. }
  5440. // TODO: How to enable zstd ??
  5441. TEST_F(ServerTest, MultipartFormDataZstd) {
  5442. UploadFormDataItems items = {
  5443. {"key1", "test", "", ""},
  5444. {"key2", "--abcdefg123", "", ""},
  5445. };
  5446. Headers headers;
  5447. headers.emplace("Accept-Encoding", "zstd");
  5448. cli_.set_compress(true);
  5449. auto res = cli_.Post("/compress-multipart", headers, items);
  5450. ASSERT_TRUE(res);
  5451. EXPECT_EQ(StatusCode::OK_200, res->status);
  5452. }
  5453. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5454. Headers headers;
  5455. headers.emplace("Accept-Encoding", "zstd");
  5456. cli_.set_compress(true);
  5457. auto res = cli_.Put(
  5458. "/put", headers, 3,
  5459. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5460. sink.os << "PUT";
  5461. return true;
  5462. },
  5463. "text/plain");
  5464. ASSERT_TRUE(res);
  5465. EXPECT_EQ(StatusCode::OK_200, res->status);
  5466. EXPECT_EQ("PUT", res->body);
  5467. }
  5468. // Pre-compression logging tests
  5469. TEST_F(ServerTest, PreCompressionLogging) {
  5470. // Test data for compression (matches the actual /compress endpoint content)
  5471. const std::string test_content =
  5472. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5473. "3456789012345678901234567890";
  5474. // Variables to capture logging data
  5475. std::string pre_compression_body;
  5476. std::string pre_compression_content_type;
  5477. std::string pre_compression_content_encoding;
  5478. std::string post_compression_body;
  5479. std::string post_compression_content_type;
  5480. std::string post_compression_content_encoding;
  5481. // Set up pre-compression logger
  5482. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5483. const Response &res) {
  5484. pre_compression_body = res.body;
  5485. pre_compression_content_type = res.get_header_value("Content-Type");
  5486. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5487. });
  5488. // Set up post-compression logger
  5489. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5490. post_compression_body = res.body;
  5491. post_compression_content_type = res.get_header_value("Content-Type");
  5492. post_compression_content_encoding =
  5493. res.get_header_value("Content-Encoding");
  5494. });
  5495. // Test with gzip compression
  5496. Headers headers;
  5497. headers.emplace("Accept-Encoding", "gzip");
  5498. auto res = cli_.Get("/compress", headers);
  5499. // Verify response was compressed
  5500. ASSERT_TRUE(res);
  5501. EXPECT_EQ(StatusCode::OK_200, res->status);
  5502. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5503. // Verify pre-compression logger captured uncompressed content
  5504. EXPECT_EQ(test_content, pre_compression_body);
  5505. EXPECT_EQ("text/plain", pre_compression_content_type);
  5506. EXPECT_TRUE(pre_compression_content_encoding
  5507. .empty()); // No encoding header before compression
  5508. // Verify post-compression logger captured compressed content
  5509. EXPECT_NE(test_content,
  5510. post_compression_body); // Should be different after compression
  5511. EXPECT_EQ("text/plain", post_compression_content_type);
  5512. EXPECT_EQ("gzip", post_compression_content_encoding);
  5513. // Verify compressed content is smaller
  5514. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5515. }
  5516. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5517. const std::string test_content =
  5518. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5519. "3456789012345678901234567890";
  5520. std::string pre_compression_body;
  5521. std::string post_compression_body;
  5522. svr_.set_pre_compression_logger(
  5523. [&](const Request & /*req*/, const Response &res) {
  5524. pre_compression_body = res.body;
  5525. });
  5526. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5527. post_compression_body = res.body;
  5528. });
  5529. Headers headers;
  5530. headers.emplace("Accept-Encoding", "br");
  5531. auto res = cli_.Get("/compress", headers);
  5532. ASSERT_TRUE(res);
  5533. EXPECT_EQ(StatusCode::OK_200, res->status);
  5534. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5535. // Verify pre-compression content is uncompressed
  5536. EXPECT_EQ(test_content, pre_compression_body);
  5537. // Verify post-compression content is compressed
  5538. EXPECT_NE(test_content, post_compression_body);
  5539. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5540. }
  5541. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5542. const std::string test_content =
  5543. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5544. "3456789012345678901234567890";
  5545. std::string pre_compression_body;
  5546. std::string post_compression_body;
  5547. svr_.set_pre_compression_logger(
  5548. [&](const Request & /*req*/, const Response &res) {
  5549. pre_compression_body = res.body;
  5550. });
  5551. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5552. post_compression_body = res.body;
  5553. });
  5554. // Request without compression (use /nocompress endpoint)
  5555. Headers headers;
  5556. auto res = cli_.Get("/nocompress", headers);
  5557. ASSERT_TRUE(res);
  5558. EXPECT_EQ(StatusCode::OK_200, res->status);
  5559. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5560. // Pre-compression logger should not be called when no compression is applied
  5561. EXPECT_TRUE(
  5562. pre_compression_body.empty()); // Pre-compression logger not called
  5563. EXPECT_EQ(
  5564. test_content,
  5565. post_compression_body); // Post-compression logger captures final content
  5566. }
  5567. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5568. const std::string test_content =
  5569. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5570. "3456789012345678901234567890";
  5571. std::string pre_compression_body;
  5572. bool pre_logger_called = false;
  5573. // Set only pre-compression logger
  5574. svr_.set_pre_compression_logger(
  5575. [&](const Request & /*req*/, const Response &res) {
  5576. pre_compression_body = res.body;
  5577. pre_logger_called = true;
  5578. });
  5579. Headers headers;
  5580. headers.emplace("Accept-Encoding", "gzip");
  5581. auto res = cli_.Get("/compress", headers);
  5582. ASSERT_TRUE(res);
  5583. EXPECT_EQ(StatusCode::OK_200, res->status);
  5584. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5585. // Verify pre-compression logger was called
  5586. EXPECT_TRUE(pre_logger_called);
  5587. EXPECT_EQ(test_content, pre_compression_body);
  5588. }
  5589. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5590. {
  5591. // Test with Expect: 100-continue header - success case
  5592. // Server returns 100 Continue, client sends body, server returns 200 OK
  5593. Request req;
  5594. req.method = "POST";
  5595. req.path = "/post-large";
  5596. req.set_header("Expect", "100-continue");
  5597. req.body = LARGE_DATA;
  5598. Response res;
  5599. auto error = Error::Success;
  5600. cli_.set_keep_alive(true);
  5601. auto ret = cli_.send(req, res, error);
  5602. EXPECT_TRUE(ret);
  5603. EXPECT_EQ(StatusCode::OK_200, res.status);
  5604. EXPECT_EQ(LARGE_DATA, res.body);
  5605. }
  5606. {
  5607. // Test with Expect: 100-continue header - error case
  5608. // Client should not send the body when server returns an error
  5609. Request req;
  5610. req.method = "POST";
  5611. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5612. req.set_header("Expect", "100-continue");
  5613. req.body = LARGE_DATA;
  5614. Response res;
  5615. auto error = Error::Success;
  5616. auto start = std::chrono::high_resolution_clock::now();
  5617. cli_.set_keep_alive(true);
  5618. auto ret = cli_.send(req, res, error);
  5619. auto end = std::chrono::high_resolution_clock::now();
  5620. auto elapsed =
  5621. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5622. .count();
  5623. // With Expect: 100-continue, request completes successfully but with error
  5624. EXPECT_TRUE(ret);
  5625. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5626. EXPECT_EQ("close", res.get_header_value("Connection"));
  5627. EXPECT_FALSE(cli_.is_socket_open());
  5628. EXPECT_LE(elapsed, 200);
  5629. }
  5630. {
  5631. // Send an extra GET request to ensure error recovery without hanging
  5632. Request req;
  5633. req.method = "GET";
  5634. req.path = "/hi";
  5635. auto start = std::chrono::high_resolution_clock::now();
  5636. auto res = cli_.send(req);
  5637. auto end = std::chrono::high_resolution_clock::now();
  5638. auto elapsed =
  5639. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5640. .count();
  5641. ASSERT_TRUE(res);
  5642. EXPECT_EQ(StatusCode::OK_200, res->status);
  5643. EXPECT_EQ("Hello World!", res->body);
  5644. EXPECT_LE(elapsed, 500);
  5645. }
  5646. }
  5647. TEST(ZstdDecompressor, ChunkedDecompression) {
  5648. std::string data;
  5649. for (size_t i = 0; i < 32 * 1024; ++i) {
  5650. data.push_back(static_cast<char>('a' + i % 26));
  5651. }
  5652. std::string compressed_data;
  5653. {
  5654. httplib::detail::zstd_compressor compressor;
  5655. bool result = compressor.compress(
  5656. data.data(), data.size(),
  5657. /*last=*/true,
  5658. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5659. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5660. compressed_data_size);
  5661. return true;
  5662. });
  5663. ASSERT_TRUE(result);
  5664. }
  5665. std::string decompressed_data;
  5666. {
  5667. httplib::detail::zstd_decompressor decompressor;
  5668. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5669. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5670. size_t chunk_size = 130;
  5671. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5672. chunk_begin += chunk_size) {
  5673. size_t current_chunk_size =
  5674. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5675. bool result = decompressor.decompress(
  5676. compressed_data.data() + chunk_begin, current_chunk_size,
  5677. [&](const char *decompressed_data_chunk,
  5678. size_t decompressed_data_chunk_size) {
  5679. decompressed_data.insert(decompressed_data.size(),
  5680. decompressed_data_chunk,
  5681. decompressed_data_chunk_size);
  5682. return true;
  5683. });
  5684. ASSERT_TRUE(result);
  5685. }
  5686. }
  5687. ASSERT_EQ(data, decompressed_data);
  5688. }
  5689. TEST(ZstdDecompressor, Decompress) {
  5690. std::string original_text = "Compressed with ZSTD";
  5691. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5692. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5693. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5694. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5695. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5696. std::string decompressed_data;
  5697. {
  5698. httplib::detail::zstd_decompressor decompressor;
  5699. bool result = decompressor.decompress(
  5700. compressed_data.data(), compressed_data.size(),
  5701. [&](const char *decompressed_data_chunk,
  5702. size_t decompressed_data_chunk_size) {
  5703. decompressed_data.insert(decompressed_data.size(),
  5704. decompressed_data_chunk,
  5705. decompressed_data_chunk_size);
  5706. return true;
  5707. });
  5708. ASSERT_TRUE(result);
  5709. }
  5710. ASSERT_EQ(original_text, decompressed_data);
  5711. }
  5712. #endif
  5713. // Sends a raw request to a server listening at HOST:PORT.
  5714. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5715. std::string *resp = nullptr) {
  5716. auto error = Error::Success;
  5717. auto client_sock = detail::create_client_socket(
  5718. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5719. /*connection_timeout_sec=*/5, 0,
  5720. /*read_timeout_sec=*/5, 0,
  5721. /*write_timeout_sec=*/5, 0, std::string(), error);
  5722. if (client_sock == INVALID_SOCKET) { return false; }
  5723. auto ret = detail::process_client_socket(
  5724. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5725. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5726. if (req.size() !=
  5727. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5728. return false;
  5729. }
  5730. char buf[512];
  5731. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5732. while (line_reader.getline()) {
  5733. if (resp) { *resp += line_reader.ptr(); }
  5734. }
  5735. return true;
  5736. });
  5737. detail::close_socket(client_sock);
  5738. return ret;
  5739. }
  5740. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5741. Server svr;
  5742. std::string header_value;
  5743. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5744. header_value = req.get_header_value("foo");
  5745. res.set_content("ok", "text/plain");
  5746. });
  5747. thread t = thread([&] { svr.listen(HOST, PORT); });
  5748. auto se = detail::scope_exit([&] {
  5749. svr.stop();
  5750. t.join();
  5751. ASSERT_FALSE(svr.is_running());
  5752. });
  5753. svr.wait_until_ready();
  5754. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5755. // like characters are not treated the same - use vertical tab and escape.
  5756. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5757. "foo: \t \v bar \x1B\t \r\n"
  5758. "Connection: close\r\n"
  5759. "\r\n";
  5760. std::string res;
  5761. ASSERT_TRUE(send_request(5, req, &res));
  5762. EXPECT_EQ(header_value, "");
  5763. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5764. }
  5765. // Sends a raw request and verifies that there isn't a crash or exception.
  5766. static void test_raw_request(const std::string &req,
  5767. std::string *out = nullptr) {
  5768. Server svr;
  5769. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5770. res.set_content("ok", "text/plain");
  5771. });
  5772. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5773. res.set_content("ok", "text/plain");
  5774. });
  5775. svr.Get("/header_field_value_check",
  5776. [&](const Request & /*req*/, Response &res) {
  5777. res.set_content("ok", "text/plain");
  5778. });
  5779. // Server read timeout must be longer than the client read timeout for the
  5780. // bug to reproduce, probably to force the server to process a request
  5781. // without a trailing blank line.
  5782. const time_t client_read_timeout_sec = 1;
  5783. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5784. bool listen_thread_ok = false;
  5785. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5786. auto se = detail::scope_exit([&] {
  5787. svr.stop();
  5788. t.join();
  5789. ASSERT_FALSE(svr.is_running());
  5790. EXPECT_TRUE(listen_thread_ok);
  5791. });
  5792. svr.wait_until_ready();
  5793. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5794. }
  5795. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5796. // A certain header line causes an exception if the header property is parsed
  5797. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5798. test_raw_request(
  5799. "GET /hi HTTP/1.1\r\n"
  5800. " : "
  5801. " "
  5802. " ");
  5803. }
  5804. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5805. // A certain header line causes an exception if the header property *name* is
  5806. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5807. // greedy matcher and requires backtracking when there are a lot of ":"
  5808. // characters.
  5809. // This occurs with libc++ but not libstdc++.
  5810. test_raw_request(
  5811. "GET /hi HTTP/1.1\r\n"
  5812. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5813. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5814. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5815. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5816. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5817. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5818. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5819. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5820. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5821. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5822. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5823. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5824. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5825. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5826. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5827. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5828. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5829. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5830. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5831. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5832. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5833. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5834. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5835. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5836. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5837. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5838. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5839. "&&&%%%");
  5840. }
  5841. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5842. // Make sure this doesn't crash the server.
  5843. // In a previous version of the header line regex, the "\r" rendered the line
  5844. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5845. // a new position where the leading white space ended and the field value
  5846. // began.
  5847. // The crash occurs with libc++ but not libstdc++.
  5848. test_raw_request("GET /hi HTTP/1.1\r\n"
  5849. "a:" +
  5850. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5851. "\r\n"
  5852. "\r\n");
  5853. }
  5854. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5855. std::string out;
  5856. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5857. "Content-Type: text/plain\r\n"
  5858. "Transfer-Encoding: chunked\r\n"
  5859. "\r\n"
  5860. "nothex\r\n",
  5861. &out);
  5862. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5863. }
  5864. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5865. std::string out;
  5866. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5867. "Content-Type: text/plain\r\n"
  5868. "Transfer-Encoding: chunked\r\n"
  5869. "\r\n"
  5870. "3\r\n"
  5871. "xyz\r\n"
  5872. "NaN\r\n",
  5873. &out);
  5874. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5875. }
  5876. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5877. std::string out;
  5878. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5879. "Content-Type: text/plain\r\n"
  5880. "Transfer-Encoding: chunked\r\n"
  5881. "\r\n"
  5882. // Length is too large for 64 bits.
  5883. "1ffffffffffffffff\r\n"
  5884. "xyz\r\n",
  5885. &out);
  5886. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5887. }
  5888. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5889. test_raw_request("GET /hi HTTP/1.1\r\n"
  5890. "Content-Type: text/plain\r\n\r");
  5891. }
  5892. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5893. std::string out;
  5894. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5895. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5896. }
  5897. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  5898. Server svr;
  5899. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  5900. EXPECT_TRUE(!req.remote_addr.empty());
  5901. });
  5902. thread t = thread([&] { svr.listen(HOST, PORT); });
  5903. auto se = detail::scope_exit([&] {
  5904. svr.stop();
  5905. t.join();
  5906. ASSERT_FALSE(svr.is_running());
  5907. });
  5908. svr.wait_until_ready();
  5909. // Send an invalid request line to trigger Bad Request
  5910. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  5911. std::string out;
  5912. ASSERT_TRUE(send_request(5, bad_req, &out));
  5913. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5914. }
  5915. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5916. std::string out;
  5917. std::string request(
  5918. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5919. test_raw_request(request, &out);
  5920. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5921. }
  5922. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5923. std::string out;
  5924. std::string request(
  5925. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5926. test_raw_request(request, &out);
  5927. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5928. }
  5929. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5930. std::string out;
  5931. std::string request(
  5932. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5933. test_raw_request(request, &out);
  5934. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5935. }
  5936. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5937. std::string out;
  5938. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5939. "Test: \r\n\r\n",
  5940. &out);
  5941. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5942. }
  5943. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5944. Server svr;
  5945. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5946. res.set_header("Cache-Control", "no-cache");
  5947. res.set_chunked_content_provider(
  5948. "text/event-stream", [](size_t offset, DataSink &sink) {
  5949. std::string s = "data:";
  5950. s += std::to_string(offset);
  5951. s += "\n\n";
  5952. auto ret = sink.write(s.data(), s.size());
  5953. EXPECT_TRUE(ret);
  5954. std::this_thread::sleep_for(std::chrono::seconds(1));
  5955. return true;
  5956. });
  5957. });
  5958. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5959. svr.wait_until_ready();
  5960. Client client(HOST, PORT);
  5961. const Headers headers = {{"Accept", "text/event-stream"}};
  5962. auto get_thread = std::thread([&client, &headers]() {
  5963. auto res = client.Get(
  5964. "/events", headers,
  5965. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5966. });
  5967. auto se = detail::scope_exit([&] {
  5968. svr.stop();
  5969. get_thread.join();
  5970. listen_thread.join();
  5971. ASSERT_FALSE(svr.is_running());
  5972. });
  5973. // Give GET time to get a few messages.
  5974. std::this_thread::sleep_for(std::chrono::seconds(2));
  5975. }
  5976. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5977. httplib::Server svr;
  5978. svr.Post("/hi",
  5979. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5980. res.status = StatusCode::OK_200;
  5981. });
  5982. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5983. svr.wait_until_ready();
  5984. Client cli(HOST, PORT);
  5985. auto res = cli.Post("/hi", "data", "text/plain");
  5986. ASSERT_TRUE(res);
  5987. EXPECT_EQ(StatusCode::OK_200, res->status);
  5988. svr.stop();
  5989. thread.join();
  5990. ASSERT_FALSE(svr.is_running());
  5991. res = cli.Post("/hi", "data", "text/plain");
  5992. ASSERT_FALSE(res);
  5993. }
  5994. TEST(ServerStopTest, ListenFailure) {
  5995. Server svr;
  5996. auto t = thread([&]() {
  5997. auto ret = svr.listen("????", PORT);
  5998. EXPECT_FALSE(ret);
  5999. });
  6000. svr.wait_until_ready();
  6001. svr.stop();
  6002. t.join();
  6003. }
  6004. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6005. TEST(ServerStopTest, Decommision) {
  6006. Server svr;
  6007. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6008. for (int i = 0; i < 4; i++) {
  6009. auto is_even = !(i % 2);
  6010. std::thread t{[&] {
  6011. try {
  6012. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6013. if (is_even) {
  6014. throw std::runtime_error("Some thing that happens to go wrong.");
  6015. }
  6016. svr.listen(HOST, PORT);
  6017. } catch (...) { svr.decommission(); }
  6018. }};
  6019. svr.wait_until_ready();
  6020. // Server is up
  6021. {
  6022. Client cli(HOST, PORT);
  6023. auto res = cli.Get("/hi");
  6024. if (is_even) {
  6025. EXPECT_FALSE(res);
  6026. } else {
  6027. EXPECT_TRUE(res);
  6028. EXPECT_EQ("hi...", res->body);
  6029. }
  6030. }
  6031. svr.stop();
  6032. t.join();
  6033. // Server is down...
  6034. {
  6035. Client cli(HOST, PORT);
  6036. auto res = cli.Get("/hi");
  6037. EXPECT_FALSE(res);
  6038. }
  6039. }
  6040. }
  6041. #endif
  6042. // Helper function for string body upload progress tests
  6043. template <typename SetupHandler, typename ClientCall>
  6044. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6045. ClientCall &&client_call,
  6046. const string &body) {
  6047. Server svr;
  6048. setup_handler(svr);
  6049. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6050. auto se = detail::scope_exit([&] {
  6051. svr.stop();
  6052. t.join();
  6053. });
  6054. svr.wait_until_ready();
  6055. Client cli(HOST, PORT);
  6056. vector<uint64_t> progress_values;
  6057. bool progress_called = false;
  6058. auto res =
  6059. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6060. progress_values.push_back(current);
  6061. progress_called = true;
  6062. return true;
  6063. });
  6064. ASSERT_TRUE(res);
  6065. EXPECT_EQ(200, res->status);
  6066. EXPECT_TRUE(progress_called);
  6067. }
  6068. TEST(UploadProgressTest, PostStringBodyBasic) {
  6069. TestStringBodyUploadProgress(
  6070. [](Server &svr) {
  6071. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6072. res.set_content("received", "text/plain");
  6073. });
  6074. },
  6075. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6076. return cli.Post("/test", body, "text/plain", progress_callback);
  6077. },
  6078. "test data for upload progress");
  6079. }
  6080. TEST(UploadProgressTest, PutStringBodyBasic) {
  6081. TestStringBodyUploadProgress(
  6082. [](Server &svr) {
  6083. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6084. res.set_content("put received", "text/plain");
  6085. });
  6086. },
  6087. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6088. return cli.Put("/test", body, "text/plain", progress_callback);
  6089. },
  6090. "put test data for upload progress");
  6091. }
  6092. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6093. TestStringBodyUploadProgress(
  6094. [](Server &svr) {
  6095. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6096. res.set_content("patch received", "text/plain");
  6097. });
  6098. },
  6099. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6100. return cli.Patch("/test", body, "text/plain", progress_callback);
  6101. },
  6102. "patch test data for upload progress");
  6103. }
  6104. // Helper function for content provider upload progress tests
  6105. template <typename SetupHandler, typename ClientCall>
  6106. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6107. ClientCall &&client_call) {
  6108. Server svr;
  6109. setup_handler(svr);
  6110. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6111. auto se = detail::scope_exit([&] {
  6112. svr.stop();
  6113. t.join();
  6114. });
  6115. svr.wait_until_ready();
  6116. Client cli(HOST, PORT);
  6117. vector<uint64_t> progress_values;
  6118. auto res =
  6119. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6120. progress_values.push_back(current);
  6121. return true;
  6122. });
  6123. ASSERT_TRUE(res);
  6124. EXPECT_EQ(200, res->status);
  6125. EXPECT_FALSE(progress_values.empty());
  6126. }
  6127. TEST(UploadProgressTest, PostContentProviderProgress) {
  6128. TestContentProviderUploadProgress(
  6129. [](Server &svr) {
  6130. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6131. res.set_content("provider received", "text/plain");
  6132. });
  6133. },
  6134. [](Client &cli, UploadProgress progress_callback) {
  6135. return cli.Post(
  6136. "/test", 10,
  6137. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6138. sink.os << "test data";
  6139. return true;
  6140. },
  6141. "text/plain", progress_callback);
  6142. });
  6143. }
  6144. // Helper function for multipart upload progress tests
  6145. template <typename SetupHandler, typename ClientCall>
  6146. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6147. ClientCall &&client_call,
  6148. const string &endpoint) {
  6149. Server svr;
  6150. setup_handler(svr);
  6151. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6152. auto se = detail::scope_exit([&] {
  6153. svr.stop();
  6154. t.join();
  6155. });
  6156. svr.wait_until_ready();
  6157. Client cli(HOST, PORT);
  6158. vector<uint64_t> progress_values;
  6159. UploadFormDataItems items = {
  6160. {"field1", "value1", "", ""},
  6161. {"field2", "longer value for progress tracking test", "", ""},
  6162. {"file1", "file content data for upload progress", "test.txt",
  6163. "text/plain"}};
  6164. auto res = client_call(cli, endpoint, items,
  6165. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6166. progress_values.push_back(current);
  6167. return true;
  6168. });
  6169. ASSERT_TRUE(res);
  6170. EXPECT_EQ(200, res->status);
  6171. EXPECT_FALSE(progress_values.empty());
  6172. }
  6173. TEST(UploadProgressTest, PostMultipartProgress) {
  6174. TestMultipartUploadProgress(
  6175. [](Server &svr) {
  6176. svr.Post("/multipart", [](const Request &req, Response &res) {
  6177. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6178. res.set_content("multipart received", "text/plain");
  6179. });
  6180. },
  6181. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6182. UploadProgress progress_callback) {
  6183. return cli.Post(endpoint, items, progress_callback);
  6184. },
  6185. "/multipart");
  6186. }
  6187. // Helper function for basic download progress tests
  6188. template <typename SetupHandler, typename ClientCall>
  6189. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6190. ClientCall &&client_call, const string &endpoint,
  6191. size_t expected_content_size) {
  6192. Server svr;
  6193. setup_handler(svr);
  6194. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6195. auto se = detail::scope_exit([&] {
  6196. svr.stop();
  6197. t.join();
  6198. });
  6199. svr.wait_until_ready();
  6200. Client cli(HOST, PORT);
  6201. vector<uint64_t> progress_values;
  6202. auto res = client_call(cli, endpoint,
  6203. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6204. progress_values.push_back(current);
  6205. return true;
  6206. });
  6207. ASSERT_TRUE(res);
  6208. EXPECT_EQ(200, res->status);
  6209. EXPECT_FALSE(progress_values.empty());
  6210. EXPECT_EQ(expected_content_size, res->body.size());
  6211. }
  6212. TEST(DownloadProgressTest, GetBasic) {
  6213. TestBasicDownloadProgress(
  6214. [](Server &svr) {
  6215. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6216. string content(1000, 'D');
  6217. res.set_content(content, "text/plain");
  6218. });
  6219. },
  6220. [](Client &cli, const string &endpoint,
  6221. DownloadProgress progress_callback) {
  6222. return cli.Get(endpoint, progress_callback);
  6223. },
  6224. "/download", 1000u);
  6225. }
  6226. // Helper function for content receiver download progress tests
  6227. template <typename SetupHandler, typename ClientCall>
  6228. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6229. ClientCall &&client_call,
  6230. const string &endpoint,
  6231. size_t expected_content_size) {
  6232. Server svr;
  6233. setup_handler(svr);
  6234. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6235. auto se = detail::scope_exit([&] {
  6236. svr.stop();
  6237. t.join();
  6238. });
  6239. svr.wait_until_ready();
  6240. Client cli(HOST, PORT);
  6241. vector<uint64_t> progress_values;
  6242. string received_body;
  6243. auto res = client_call(
  6244. cli, endpoint,
  6245. [&](const char *data, size_t data_length) -> bool {
  6246. received_body.append(data, data_length);
  6247. return true;
  6248. },
  6249. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6250. progress_values.push_back(current);
  6251. return true;
  6252. });
  6253. ASSERT_TRUE(res);
  6254. EXPECT_EQ(200, res->status);
  6255. EXPECT_FALSE(progress_values.empty());
  6256. EXPECT_EQ(expected_content_size, received_body.size());
  6257. EXPECT_TRUE(res->body.empty());
  6258. }
  6259. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6260. TestContentReceiverDownloadProgress(
  6261. [](Server &svr) {
  6262. svr.Get("/download-receiver",
  6263. [](const Request & /*req*/, Response &res) {
  6264. string content(2000, 'R');
  6265. res.set_content(content, "text/plain");
  6266. });
  6267. },
  6268. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6269. DownloadProgress progress_callback) {
  6270. return cli.Get(endpoint, content_receiver, progress_callback);
  6271. },
  6272. "/download-receiver", 2000u);
  6273. }
  6274. TEST(StreamingTest, NoContentLengthStreaming) {
  6275. Server svr;
  6276. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6277. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6278. if (offset < 6) {
  6279. sink.os << (offset < 3 ? "a" : "b");
  6280. } else {
  6281. sink.done();
  6282. }
  6283. return true;
  6284. });
  6285. });
  6286. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6287. auto listen_se = detail::scope_exit([&] {
  6288. svr.stop();
  6289. listen_thread.join();
  6290. ASSERT_FALSE(svr.is_running());
  6291. });
  6292. svr.wait_until_ready();
  6293. Client client(HOST, PORT);
  6294. auto get_thread = std::thread([&client]() {
  6295. std::string s;
  6296. auto res =
  6297. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6298. s += std::string(data, len);
  6299. return true;
  6300. });
  6301. ASSERT_TRUE(res);
  6302. EXPECT_EQ(StatusCode::OK_200, res->status);
  6303. EXPECT_EQ("aaabbb", s);
  6304. });
  6305. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6306. // Give GET time to get a few messages.
  6307. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6308. }
  6309. TEST(MountTest, Unmount) {
  6310. Server svr;
  6311. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6312. auto se = detail::scope_exit([&] {
  6313. svr.stop();
  6314. listen_thread.join();
  6315. ASSERT_FALSE(svr.is_running());
  6316. });
  6317. svr.wait_until_ready();
  6318. Client cli("localhost", PORT);
  6319. svr.set_mount_point("/mount2", "./www2");
  6320. auto res = cli.Get("/");
  6321. ASSERT_TRUE(res);
  6322. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6323. res = cli.Get("/mount2/dir/test.html");
  6324. ASSERT_TRUE(res);
  6325. EXPECT_EQ(StatusCode::OK_200, res->status);
  6326. svr.set_mount_point("/", "./www");
  6327. res = cli.Get("/dir/");
  6328. ASSERT_TRUE(res);
  6329. EXPECT_EQ(StatusCode::OK_200, res->status);
  6330. svr.remove_mount_point("/");
  6331. res = cli.Get("/dir/");
  6332. ASSERT_TRUE(res);
  6333. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6334. svr.remove_mount_point("/mount2");
  6335. res = cli.Get("/mount2/dir/test.html");
  6336. ASSERT_TRUE(res);
  6337. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6338. }
  6339. TEST(MountTest, Redicect) {
  6340. Server svr;
  6341. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6342. auto se = detail::scope_exit([&] {
  6343. svr.stop();
  6344. listen_thread.join();
  6345. ASSERT_FALSE(svr.is_running());
  6346. });
  6347. svr.set_mount_point("/", "./www");
  6348. svr.wait_until_ready();
  6349. Client cli("localhost", PORT);
  6350. auto res = cli.Get("/dir/");
  6351. ASSERT_TRUE(res);
  6352. EXPECT_EQ(StatusCode::OK_200, res->status);
  6353. res = cli.Get("/dir");
  6354. ASSERT_TRUE(res);
  6355. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6356. res = cli.Get("/file");
  6357. ASSERT_TRUE(res);
  6358. EXPECT_EQ(StatusCode::OK_200, res->status);
  6359. res = cli.Get("/file/");
  6360. ASSERT_TRUE(res);
  6361. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6362. cli.set_follow_location(true);
  6363. res = cli.Get("/dir");
  6364. ASSERT_TRUE(res);
  6365. EXPECT_EQ(StatusCode::OK_200, res->status);
  6366. }
  6367. TEST(MountTest, MultibytesPathName) {
  6368. Server svr;
  6369. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6370. auto se = detail::scope_exit([&] {
  6371. svr.stop();
  6372. listen_thread.join();
  6373. ASSERT_FALSE(svr.is_running());
  6374. });
  6375. svr.set_mount_point("/", "./www");
  6376. svr.wait_until_ready();
  6377. Client cli("localhost", PORT);
  6378. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6379. ASSERT_TRUE(res);
  6380. EXPECT_EQ(StatusCode::OK_200, res->status);
  6381. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6382. }
  6383. TEST(KeepAliveTest, ReadTimeout) {
  6384. Server svr;
  6385. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6386. std::this_thread::sleep_for(std::chrono::seconds(2));
  6387. res.set_content("a", "text/plain");
  6388. });
  6389. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6390. res.set_content("b", "text/plain");
  6391. });
  6392. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6393. auto se = detail::scope_exit([&] {
  6394. svr.stop();
  6395. listen_thread.join();
  6396. ASSERT_FALSE(svr.is_running());
  6397. });
  6398. svr.wait_until_ready();
  6399. Client cli("localhost", PORT);
  6400. cli.set_keep_alive(true);
  6401. cli.set_read_timeout(std::chrono::seconds(1));
  6402. auto resa = cli.Get("/a");
  6403. ASSERT_FALSE(resa);
  6404. EXPECT_EQ(Error::Read, resa.error());
  6405. auto resb = cli.Get("/b");
  6406. ASSERT_TRUE(resb);
  6407. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6408. EXPECT_EQ("b", resb->body);
  6409. }
  6410. TEST(KeepAliveTest, MaxCount) {
  6411. size_t keep_alive_max_count = 3;
  6412. Server svr;
  6413. svr.set_keep_alive_max_count(keep_alive_max_count);
  6414. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6415. res.set_content("Hello World!", "text/plain");
  6416. });
  6417. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6418. auto se = detail::scope_exit([&] {
  6419. svr.stop();
  6420. listen_thread.join();
  6421. ASSERT_FALSE(svr.is_running());
  6422. });
  6423. svr.wait_until_ready();
  6424. Client cli(HOST, PORT);
  6425. cli.set_keep_alive(true);
  6426. for (size_t i = 0; i < 5; i++) {
  6427. auto result = cli.Get("/hi");
  6428. ASSERT_TRUE(result);
  6429. EXPECT_EQ(StatusCode::OK_200, result->status);
  6430. if (i == keep_alive_max_count - 1) {
  6431. EXPECT_EQ("close", result->get_header_value("Connection"));
  6432. } else {
  6433. EXPECT_FALSE(result->has_header("Connection"));
  6434. }
  6435. }
  6436. }
  6437. TEST(KeepAliveTest, Issue1041) {
  6438. Server svr;
  6439. svr.set_keep_alive_timeout(3);
  6440. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6441. res.set_content("Hello World!", "text/plain");
  6442. });
  6443. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6444. auto se = detail::scope_exit([&] {
  6445. svr.stop();
  6446. listen_thread.join();
  6447. ASSERT_FALSE(svr.is_running());
  6448. });
  6449. svr.wait_until_ready();
  6450. Client cli(HOST, PORT);
  6451. cli.set_keep_alive(true);
  6452. auto result = cli.Get("/hi");
  6453. ASSERT_TRUE(result);
  6454. EXPECT_EQ(StatusCode::OK_200, result->status);
  6455. std::this_thread::sleep_for(std::chrono::seconds(5));
  6456. result = cli.Get("/hi");
  6457. ASSERT_TRUE(result);
  6458. EXPECT_EQ(StatusCode::OK_200, result->status);
  6459. }
  6460. TEST(KeepAliveTest, Issue1959) {
  6461. Server svr;
  6462. svr.set_keep_alive_timeout(5);
  6463. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6464. res.set_content("a", "text/plain");
  6465. });
  6466. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6467. auto se = detail::scope_exit([&] {
  6468. if (!svr.is_running()) return;
  6469. svr.stop();
  6470. listen_thread.join();
  6471. ASSERT_FALSE(svr.is_running());
  6472. });
  6473. svr.wait_until_ready();
  6474. Client cli("localhost", PORT);
  6475. cli.set_keep_alive(true);
  6476. using namespace std::chrono;
  6477. auto start = steady_clock::now();
  6478. cli.Get("/a");
  6479. svr.stop();
  6480. listen_thread.join();
  6481. auto end = steady_clock::now();
  6482. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6483. EXPECT_LT(elapsed, 5000);
  6484. }
  6485. #ifdef CPPHTTPLIB_SSL_ENABLED
  6486. TEST(KeepAliveTest, SSLClientReconnection) {
  6487. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6488. ASSERT_TRUE(svr.is_valid());
  6489. svr.set_keep_alive_timeout(1);
  6490. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6491. res.set_content("Hello World!", "text/plain");
  6492. });
  6493. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6494. auto se = detail::scope_exit([&] {
  6495. svr.stop();
  6496. listen_thread.join();
  6497. ASSERT_FALSE(svr.is_running());
  6498. });
  6499. svr.wait_until_ready();
  6500. SSLClient cli(HOST, PORT);
  6501. cli.enable_server_certificate_verification(false);
  6502. cli.set_keep_alive(true);
  6503. auto result = cli.Get("/hi");
  6504. ASSERT_TRUE(result);
  6505. EXPECT_EQ(StatusCode::OK_200, result->status);
  6506. result = cli.Get("/hi");
  6507. ASSERT_TRUE(result);
  6508. EXPECT_EQ(StatusCode::OK_200, result->status);
  6509. std::this_thread::sleep_for(std::chrono::seconds(2));
  6510. // Recoonect
  6511. result = cli.Get("/hi");
  6512. ASSERT_TRUE(result);
  6513. EXPECT_EQ(StatusCode::OK_200, result->status);
  6514. result = cli.Get("/hi");
  6515. ASSERT_TRUE(result);
  6516. EXPECT_EQ(StatusCode::OK_200, result->status);
  6517. }
  6518. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6519. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6520. ASSERT_TRUE(svr.is_valid());
  6521. svr.set_keep_alive_timeout(1);
  6522. std::string content = "reconnect";
  6523. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6524. res.set_content("Hello World!", "text/plain");
  6525. });
  6526. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6527. auto se = detail::scope_exit([&] {
  6528. svr.stop();
  6529. listen_thread.join();
  6530. ASSERT_FALSE(svr.is_running());
  6531. });
  6532. svr.wait_until_ready();
  6533. SSLClient cli(HOST, PORT);
  6534. cli.enable_server_certificate_verification(false);
  6535. cli.set_keep_alive(true);
  6536. auto result = cli.Post(
  6537. "/hi", content.size(),
  6538. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6539. sink.write(content.c_str(), content.size());
  6540. return true;
  6541. },
  6542. "text/plain");
  6543. ASSERT_TRUE(result);
  6544. EXPECT_EQ(200, result->status);
  6545. std::this_thread::sleep_for(std::chrono::seconds(2));
  6546. // Recoonect
  6547. result = cli.Post(
  6548. "/hi", content.size(),
  6549. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6550. sink.write(content.c_str(), content.size());
  6551. return true;
  6552. },
  6553. "text/plain");
  6554. ASSERT_TRUE(result);
  6555. EXPECT_EQ(200, result->status);
  6556. result = cli.Post(
  6557. "/hi", content.size(),
  6558. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6559. sink.write(content.c_str(), content.size());
  6560. return true;
  6561. },
  6562. "text/plain");
  6563. ASSERT_TRUE(result);
  6564. EXPECT_EQ(200, result->status);
  6565. }
  6566. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6567. using namespace httplib::tls;
  6568. {
  6569. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6570. ASSERT_TRUE(svr.is_valid());
  6571. svr.Get("/sni", [&](const Request &req, Response &res) {
  6572. std::string expected = req.sni();
  6573. EXPECT_EQ(expected, req.get_param_value("expected"));
  6574. res.set_content("ok", "text/plain");
  6575. });
  6576. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6577. auto se = detail::scope_exit([&] {
  6578. svr.stop();
  6579. listen_thread.join();
  6580. ASSERT_FALSE(svr.is_running());
  6581. });
  6582. svr.wait_until_ready();
  6583. {
  6584. SSLClient cli("localhost", PORT);
  6585. cli.enable_server_certificate_verification(false);
  6586. auto res = cli.Get("/sni?expected=localhost");
  6587. ASSERT_TRUE(res);
  6588. }
  6589. {
  6590. SSLClient cli("::1", PORT);
  6591. cli.enable_server_certificate_verification(false);
  6592. auto res = cli.Get("/sni?expected=");
  6593. // NOTE: This may fail if the server is listening on IPv4 only
  6594. // (e.g., when localhost resolves to 127.0.0.1 only)
  6595. if (res) {
  6596. EXPECT_EQ(StatusCode::OK_200, res->status);
  6597. } else {
  6598. EXPECT_EQ(Error::Connection, res.error());
  6599. }
  6600. }
  6601. }
  6602. }
  6603. #endif
  6604. TEST(ClientProblemDetectionTest, ContentProvider) {
  6605. Server svr;
  6606. size_t content_length = 1024 * 1024;
  6607. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6608. res.set_content_provider(
  6609. content_length, "text/plain",
  6610. [&](size_t offset, size_t length, DataSink &sink) {
  6611. auto out_len = std::min(length, static_cast<size_t>(1024));
  6612. std::string out(out_len, '@');
  6613. sink.write(out.data(), out_len);
  6614. return offset < 4096;
  6615. },
  6616. [](bool success) { ASSERT_FALSE(success); });
  6617. });
  6618. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6619. res.set_content_provider(
  6620. 0, "text/plain",
  6621. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6622. EXPECT_TRUE(false);
  6623. return true;
  6624. },
  6625. [](bool success) { ASSERT_FALSE(success); });
  6626. });
  6627. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6628. auto se = detail::scope_exit([&] {
  6629. svr.stop();
  6630. listen_thread.join();
  6631. ASSERT_FALSE(svr.is_running());
  6632. });
  6633. svr.wait_until_ready();
  6634. Client cli("localhost", PORT);
  6635. {
  6636. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6637. size_t /*data_length*/) { return false; });
  6638. ASSERT_FALSE(res);
  6639. }
  6640. {
  6641. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6642. size_t /*data_length*/) { return false; });
  6643. ASSERT_TRUE(res);
  6644. }
  6645. }
  6646. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6647. Server svr;
  6648. svr.set_error_handler([](Request const &, Response &res) -> void {
  6649. res.set_chunked_content_provider(
  6650. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6651. sink.os << "hello";
  6652. sink.os << "world";
  6653. sink.done();
  6654. return true;
  6655. });
  6656. });
  6657. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6658. auto se = detail::scope_exit([&] {
  6659. svr.stop();
  6660. listen_thread.join();
  6661. ASSERT_FALSE(svr.is_running());
  6662. });
  6663. svr.wait_until_ready();
  6664. Client cli("localhost", PORT);
  6665. auto res = cli.Get("/");
  6666. ASSERT_TRUE(res);
  6667. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6668. EXPECT_EQ("helloworld", res->body);
  6669. }
  6670. TEST(LongPollingTest, ClientCloseDetection) {
  6671. Server svr;
  6672. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6673. res.set_chunked_content_provider(
  6674. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6675. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6676. sink.os << "hello";
  6677. auto count = 10;
  6678. while (count > 0 && sink.is_writable()) {
  6679. this_thread::sleep_for(chrono::milliseconds(10));
  6680. count--;
  6681. }
  6682. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6683. return true;
  6684. });
  6685. });
  6686. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6687. auto se = detail::scope_exit([&] {
  6688. svr.stop();
  6689. listen_thread.join();
  6690. ASSERT_FALSE(svr.is_running());
  6691. });
  6692. svr.wait_until_ready();
  6693. Client cli("localhost", PORT);
  6694. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6695. EXPECT_EQ("hello", string(data, data_length));
  6696. return false; // close the socket immediately.
  6697. });
  6698. ASSERT_FALSE(res);
  6699. }
  6700. TEST(GetWithParametersTest, GetWithParameters) {
  6701. Server svr;
  6702. svr.Get("/", [&](const Request &req, Response &) {
  6703. EXPECT_EQ("world", req.get_param_value("hello"));
  6704. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6705. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6706. });
  6707. svr.Get("/params", [&](const Request &req, Response &) {
  6708. EXPECT_EQ("world", req.get_param_value("hello"));
  6709. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6710. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6711. });
  6712. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6713. EXPECT_EQ("resource-id", req.matches[1]);
  6714. EXPECT_EQ("foo", req.get_param_value("param1"));
  6715. EXPECT_EQ("bar", req.get_param_value("param2"));
  6716. });
  6717. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6718. EXPECT_EQ("user-id", req.path_params.at("id"));
  6719. EXPECT_EQ("foo", req.get_param_value("param1"));
  6720. EXPECT_EQ("bar", req.get_param_value("param2"));
  6721. });
  6722. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6723. auto se = detail::scope_exit([&] {
  6724. svr.stop();
  6725. listen_thread.join();
  6726. ASSERT_FALSE(svr.is_running());
  6727. });
  6728. svr.wait_until_ready();
  6729. {
  6730. Client cli(HOST, PORT);
  6731. Params params;
  6732. params.emplace("hello", "world");
  6733. params.emplace("hello2", "world2");
  6734. params.emplace("hello3", "world3");
  6735. auto res = cli.Get("/", params, Headers{});
  6736. ASSERT_TRUE(res);
  6737. EXPECT_EQ(StatusCode::OK_200, res->status);
  6738. }
  6739. {
  6740. Client cli(HOST, PORT);
  6741. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6742. ASSERT_TRUE(res);
  6743. EXPECT_EQ(StatusCode::OK_200, res->status);
  6744. }
  6745. {
  6746. Client cli(HOST, PORT);
  6747. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6748. ASSERT_TRUE(res);
  6749. EXPECT_EQ(StatusCode::OK_200, res->status);
  6750. }
  6751. {
  6752. Client cli(HOST, PORT);
  6753. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6754. ASSERT_TRUE(res);
  6755. EXPECT_EQ(StatusCode::OK_200, res->status);
  6756. }
  6757. }
  6758. TEST(GetWithParametersTest, GetWithParameters2) {
  6759. Server svr;
  6760. svr.Get("/", [&](const Request &req, Response &res) {
  6761. auto text = req.get_param_value("hello");
  6762. res.set_content(text, "text/plain");
  6763. });
  6764. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6765. auto se = detail::scope_exit([&] {
  6766. svr.stop();
  6767. listen_thread.join();
  6768. ASSERT_FALSE(svr.is_running());
  6769. });
  6770. svr.wait_until_ready();
  6771. Client cli("localhost", PORT);
  6772. Params params;
  6773. params.emplace("hello", "world");
  6774. std::string body;
  6775. auto res = cli.Get("/", params, Headers{},
  6776. [&](const char *data, size_t data_length) {
  6777. body.append(data, data_length);
  6778. return true;
  6779. });
  6780. ASSERT_TRUE(res);
  6781. EXPECT_EQ(StatusCode::OK_200, res->status);
  6782. EXPECT_EQ("world", body);
  6783. }
  6784. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6785. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6786. auto host = "httpcan.org";
  6787. auto path = std::string{"/range/32"};
  6788. #else
  6789. auto host = "nghttp2.org";
  6790. auto path = std::string{"/httpbin/range/32"};
  6791. #endif
  6792. #ifdef CPPHTTPLIB_SSL_ENABLED
  6793. SSLClient cli(host);
  6794. #else
  6795. Client cli(host);
  6796. #endif
  6797. cli.set_default_headers({make_range_header({{1, 10}})});
  6798. cli.set_connection_timeout(5);
  6799. {
  6800. auto res = cli.Get(path);
  6801. ASSERT_TRUE(res);
  6802. EXPECT_EQ("bcdefghijk", res->body);
  6803. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6804. }
  6805. {
  6806. auto res = cli.Get(path);
  6807. ASSERT_TRUE(res);
  6808. EXPECT_EQ("bcdefghijk", res->body);
  6809. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6810. }
  6811. }
  6812. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6813. Server svr;
  6814. svr.set_default_headers({{"Hello", "World"}});
  6815. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6816. res.set_content("ok", "text/plain");
  6817. });
  6818. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6819. auto se = detail::scope_exit([&] {
  6820. svr.stop();
  6821. listen_thread.join();
  6822. ASSERT_FALSE(svr.is_running());
  6823. });
  6824. svr.wait_until_ready();
  6825. Client cli("localhost", PORT);
  6826. auto res = cli.Get("/");
  6827. ASSERT_TRUE(res);
  6828. EXPECT_EQ(StatusCode::OK_200, res->status);
  6829. EXPECT_EQ("ok", res->body);
  6830. EXPECT_EQ("World", res->get_header_value("Hello"));
  6831. }
  6832. #ifdef CPPHTTPLIB_SSL_ENABLED
  6833. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6834. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6835. ASSERT_TRUE(svr.is_valid());
  6836. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6837. std::this_thread::sleep_for(std::chrono::seconds(2));
  6838. res.set_content("a", "text/plain");
  6839. });
  6840. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6841. res.set_content("b", "text/plain");
  6842. });
  6843. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6844. auto se = detail::scope_exit([&] {
  6845. svr.stop();
  6846. listen_thread.join();
  6847. ASSERT_FALSE(svr.is_running());
  6848. });
  6849. svr.wait_until_ready();
  6850. SSLClient cli("localhost", PORT);
  6851. cli.enable_server_certificate_verification(false);
  6852. cli.set_keep_alive(true);
  6853. cli.set_read_timeout(std::chrono::seconds(1));
  6854. auto resa = cli.Get("/a");
  6855. ASSERT_TRUE(!resa);
  6856. EXPECT_EQ(Error::Read, resa.error());
  6857. auto resb = cli.Get("/b");
  6858. ASSERT_TRUE(resb);
  6859. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6860. EXPECT_EQ("b", resb->body);
  6861. }
  6862. #endif
  6863. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6864. protected:
  6865. ServerTestWithAI_PASSIVE()
  6866. : cli_(HOST, PORT)
  6867. #ifdef CPPHTTPLIB_SSL_ENABLED
  6868. ,
  6869. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6870. #endif
  6871. {
  6872. #ifdef CPPHTTPLIB_SSL_ENABLED
  6873. cli_.enable_server_certificate_verification(false);
  6874. #endif
  6875. }
  6876. virtual void SetUp() {
  6877. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6878. res.set_content("Hello World!", "text/plain");
  6879. });
  6880. t_ = thread(
  6881. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6882. svr_.wait_until_ready();
  6883. }
  6884. virtual void TearDown() {
  6885. svr_.stop();
  6886. t_.join();
  6887. }
  6888. #ifdef CPPHTTPLIB_SSL_ENABLED
  6889. SSLClient cli_;
  6890. SSLServer svr_;
  6891. #else
  6892. Client cli_;
  6893. Server svr_;
  6894. #endif
  6895. thread t_;
  6896. };
  6897. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6898. auto res = cli_.Get("/hi");
  6899. ASSERT_TRUE(res);
  6900. EXPECT_EQ(StatusCode::OK_200, res->status);
  6901. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6902. EXPECT_EQ("Hello World!", res->body);
  6903. }
  6904. class ServerUpDownTest : public ::testing::Test {
  6905. protected:
  6906. ServerUpDownTest() : cli_(HOST, PORT) {}
  6907. virtual void SetUp() {
  6908. t_ = thread([&]() {
  6909. svr_.bind_to_any_port(HOST);
  6910. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6911. ASSERT_TRUE(svr_.listen_after_bind());
  6912. });
  6913. svr_.wait_until_ready();
  6914. }
  6915. virtual void TearDown() {
  6916. svr_.stop();
  6917. t_.join();
  6918. }
  6919. Client cli_;
  6920. Server svr_;
  6921. thread t_;
  6922. };
  6923. TEST_F(ServerUpDownTest, QuickStartStop) {
  6924. // Should not crash, especially when run with
  6925. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6926. }
  6927. class PayloadMaxLengthTest : public ::testing::Test {
  6928. protected:
  6929. PayloadMaxLengthTest()
  6930. : cli_(HOST, PORT)
  6931. #ifdef CPPHTTPLIB_SSL_ENABLED
  6932. ,
  6933. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6934. #endif
  6935. {
  6936. #ifdef CPPHTTPLIB_SSL_ENABLED
  6937. cli_.enable_server_certificate_verification(false);
  6938. #endif
  6939. }
  6940. virtual void SetUp() {
  6941. svr_.set_payload_max_length(8);
  6942. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6943. res.set_content("test", "text/plain");
  6944. });
  6945. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6946. svr_.wait_until_ready();
  6947. }
  6948. virtual void TearDown() {
  6949. svr_.stop();
  6950. t_.join();
  6951. }
  6952. #ifdef CPPHTTPLIB_SSL_ENABLED
  6953. SSLClient cli_;
  6954. SSLServer svr_;
  6955. #else
  6956. Client cli_;
  6957. Server svr_;
  6958. #endif
  6959. thread t_;
  6960. };
  6961. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6962. auto res = cli_.Post("/test", "123456789", "text/plain");
  6963. ASSERT_TRUE(res);
  6964. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6965. res = cli_.Post("/test", "12345678", "text/plain");
  6966. ASSERT_TRUE(res);
  6967. EXPECT_EQ(StatusCode::OK_200, res->status);
  6968. }
  6969. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  6970. // Test chunked encoding with payload exceeding the 8-byte limit
  6971. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  6972. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  6973. ASSERT_TRUE(res);
  6974. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6975. }
  6976. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  6977. // Test chunked encoding with payload within the 8-byte limit
  6978. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  6979. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  6980. ASSERT_TRUE(res);
  6981. EXPECT_EQ(StatusCode::OK_200, res->status);
  6982. }
  6983. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  6984. // Test using send_request to send chunked data exceeding payload limit
  6985. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  6986. "Host: " +
  6987. std::string(HOST) + ":" + std::to_string(PORT) +
  6988. "\r\n"
  6989. "Transfer-Encoding: chunked\r\n"
  6990. "Connection: close\r\n"
  6991. "\r\n"
  6992. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  6993. "0123456789\r\n"
  6994. "0\r\n" // End chunk
  6995. "\r\n";
  6996. std::string response;
  6997. bool result = send_request(1, chunked_request, &response);
  6998. if (!result) {
  6999. // If send_request fails, it might be because the server closed the
  7000. // connection due to payload limit enforcement, which is acceptable
  7001. SUCCEED()
  7002. << "Server rejected oversized chunked request (connection closed)";
  7003. } else {
  7004. // If we got a response, check if it's an error response or connection was
  7005. // closed early Short response length indicates connection was closed due to
  7006. // payload limit
  7007. if (response.length() <= 10) {
  7008. SUCCEED() << "Server closed connection for oversized chunked request";
  7009. } else {
  7010. // Check for error status codes
  7011. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7012. response.find("Payload Too Large") != std::string::npos ||
  7013. response.find("400") != std::string::npos);
  7014. }
  7015. }
  7016. }
  7017. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7018. // Test request without Content-Length header exceeding payload limit
  7019. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7020. "Host: " +
  7021. std::string(HOST) + ":" +
  7022. std::to_string(PORT) +
  7023. "\r\n"
  7024. "Connection: close\r\n"
  7025. "\r\n";
  7026. // Add payload exceeding the 8-byte limit
  7027. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7028. request_without_content_length += large_payload;
  7029. std::string response;
  7030. bool result = send_request(1, request_without_content_length, &response);
  7031. if (!result) {
  7032. // If send_request fails, server likely closed connection due to payload
  7033. // limit
  7034. SUCCEED() << "Server rejected oversized request without Content-Length "
  7035. "(connection closed)";
  7036. } else {
  7037. // Check if server responded with error or closed connection early
  7038. if (response.length() <= 10) {
  7039. SUCCEED() << "Server closed connection for oversized request without "
  7040. "Content-Length";
  7041. } else {
  7042. // Check for error status codes
  7043. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7044. response.find("Payload Too Large") != std::string::npos ||
  7045. response.find("400") != std::string::npos);
  7046. }
  7047. }
  7048. }
  7049. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7050. // Test request without Content-Length header within payload limit
  7051. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7052. "Host: " +
  7053. std::string(HOST) + ":" +
  7054. std::to_string(PORT) +
  7055. "\r\n"
  7056. "Connection: close\r\n"
  7057. "\r\n";
  7058. // Add payload within the 8-byte limit
  7059. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7060. request_without_content_length += small_payload;
  7061. std::string response;
  7062. bool result = send_request(1, request_without_content_length, &response);
  7063. // For requests without Content-Length, the server may have different behavior
  7064. // The key is that it should not reject due to payload limit for small
  7065. // payloads
  7066. if (result) {
  7067. // Check for any HTTP response (success or error, but not connection closed)
  7068. if (response.length() > 10) {
  7069. SUCCEED()
  7070. << "Server processed request without Content-Length within limit";
  7071. } else {
  7072. // Short response might indicate connection closed, which is acceptable
  7073. SUCCEED() << "Server closed connection for request without "
  7074. "Content-Length (acceptable behavior)";
  7075. }
  7076. } else {
  7077. // Connection failure might be due to protocol requirements
  7078. SUCCEED() << "Connection issue with request without Content-Length "
  7079. "(environment-specific)";
  7080. }
  7081. }
  7082. class LargePayloadMaxLengthTest : public ::testing::Test {
  7083. protected:
  7084. LargePayloadMaxLengthTest()
  7085. : cli_(HOST, PORT)
  7086. #ifdef CPPHTTPLIB_SSL_ENABLED
  7087. ,
  7088. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7089. #endif
  7090. {
  7091. #ifdef CPPHTTPLIB_SSL_ENABLED
  7092. cli_.enable_server_certificate_verification(false);
  7093. #endif
  7094. }
  7095. virtual void SetUp() {
  7096. // Set 10MB payload limit
  7097. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7098. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7099. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7100. res.set_content("Large payload test", "text/plain");
  7101. });
  7102. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7103. svr_.wait_until_ready();
  7104. }
  7105. virtual void TearDown() {
  7106. svr_.stop();
  7107. t_.join();
  7108. }
  7109. #ifdef CPPHTTPLIB_SSL_ENABLED
  7110. SSLClient cli_;
  7111. SSLServer svr_;
  7112. #else
  7113. Client cli_;
  7114. Server svr_;
  7115. #endif
  7116. thread t_;
  7117. };
  7118. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7119. // Test chunked encoding with payload within 10MB limit
  7120. std::string medium_payload(5 * 1024 * 1024,
  7121. 'A'); // 5MB payload, within 10MB limit
  7122. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7123. ASSERT_TRUE(res);
  7124. EXPECT_EQ(StatusCode::OK_200, res->status);
  7125. }
  7126. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7127. // Test chunked encoding with payload exceeding 10MB limit
  7128. std::string large_payload(12 * 1024 * 1024,
  7129. 'B'); // 12MB payload, exceeds 10MB limit
  7130. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7131. // Server may either return 413 or close the connection
  7132. if (res) {
  7133. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7134. } else {
  7135. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7136. }
  7137. }
  7138. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7139. // Test request without Content-Length header within 10MB limit
  7140. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7141. "Host: " +
  7142. std::string(HOST) + ":" +
  7143. std::to_string(PORT) +
  7144. "\r\n"
  7145. "Connection: close\r\n"
  7146. "\r\n";
  7147. // Add 1MB payload (within 10MB limit)
  7148. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7149. request_without_content_length += medium_payload;
  7150. std::string response;
  7151. bool result = send_request(5, request_without_content_length, &response);
  7152. if (result) {
  7153. // Should get a proper HTTP response for payloads within limit
  7154. if (response.length() > 10) {
  7155. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7156. "10MB limit";
  7157. } else {
  7158. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7159. "Content-Length)";
  7160. }
  7161. } else {
  7162. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7163. }
  7164. }
  7165. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7166. // Test request without Content-Length header exceeding 10MB limit
  7167. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7168. "Host: " +
  7169. std::string(HOST) + ":" +
  7170. std::to_string(PORT) +
  7171. "\r\n"
  7172. "Connection: close\r\n"
  7173. "\r\n";
  7174. // Add 12MB payload (exceeds 10MB limit)
  7175. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7176. request_without_content_length += large_payload;
  7177. std::string response;
  7178. bool result = send_request(10, request_without_content_length, &response);
  7179. if (!result) {
  7180. // Server should close connection due to payload limit
  7181. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7182. "(connection closed)";
  7183. } else {
  7184. // Check for error response
  7185. if (response.length() <= 10) {
  7186. SUCCEED()
  7187. << "Server closed connection for 12MB request exceeding 10MB limit";
  7188. } else {
  7189. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7190. response.find("Payload Too Large") != std::string::npos ||
  7191. response.find("400") != std::string::npos);
  7192. }
  7193. }
  7194. }
  7195. // Regression test for DoS vulnerability: a malicious server sending a response
  7196. // without Content-Length header must not cause unbounded memory consumption on
  7197. // the client side. The client should stop reading after a reasonable limit,
  7198. // similar to the server-side set_payload_max_length protection.
  7199. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7200. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7201. #ifndef _WIN32
  7202. signal(SIGPIPE, SIG_IGN);
  7203. #endif
  7204. auto server_thread = std::thread([] {
  7205. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7206. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7207. default_socket_options(srv);
  7208. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7209. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7210. sockaddr_in addr{};
  7211. addr.sin_family = AF_INET;
  7212. addr.sin_port = htons(PORT + 2);
  7213. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7214. int opt = 1;
  7215. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7216. #ifdef _WIN32
  7217. reinterpret_cast<const char *>(&opt),
  7218. #else
  7219. &opt,
  7220. #endif
  7221. sizeof(opt));
  7222. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7223. ::listen(srv, 1);
  7224. sockaddr_in cli_addr{};
  7225. socklen_t cli_len = sizeof(cli_addr);
  7226. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7227. if (cli != INVALID_SOCKET) {
  7228. char buf[4096];
  7229. ::recv(cli, buf, sizeof(buf), 0);
  7230. // Malicious response: no Content-Length, no chunked encoding
  7231. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7232. "Connection: close\r\n"
  7233. "\r\n";
  7234. ::send(cli,
  7235. #ifdef _WIN32
  7236. static_cast<const char *>(response_header.c_str()),
  7237. static_cast<int>(response_header.size()),
  7238. #else
  7239. response_header.c_str(), response_header.size(),
  7240. #endif
  7241. 0);
  7242. // Send 10MB of data
  7243. std::string chunk(64 * 1024, 'A');
  7244. size_t total_sent = 0;
  7245. while (total_sent < MALICIOUS_DATA_SIZE) {
  7246. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7247. auto sent = ::send(cli,
  7248. #ifdef _WIN32
  7249. static_cast<const char *>(chunk.c_str()),
  7250. static_cast<int>(to_send),
  7251. #else
  7252. chunk.c_str(), to_send,
  7253. #endif
  7254. 0);
  7255. if (sent <= 0) break;
  7256. total_sent += static_cast<size_t>(sent);
  7257. }
  7258. detail::close_socket(cli);
  7259. }
  7260. detail::close_socket(srv);
  7261. });
  7262. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7263. size_t total_read = 0;
  7264. {
  7265. Client cli("127.0.0.1", PORT + 2);
  7266. cli.set_read_timeout(5, 0);
  7267. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7268. auto stream = cli.open_stream("GET", "/malicious");
  7269. ASSERT_TRUE(stream.is_valid());
  7270. char buffer[64 * 1024];
  7271. ssize_t n;
  7272. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7273. total_read += static_cast<size_t>(n);
  7274. }
  7275. } // StreamHandle and Client destroyed here, closing the socket
  7276. server_thread.join();
  7277. // With set_payload_max_length, the client must stop reading before consuming
  7278. // all 10MB. The read loop should be cut off at or near the configured limit.
  7279. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7280. << "Client read " << total_read << " bytes, exceeding the configured "
  7281. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7282. }
  7283. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7284. // the entire response body without truncation.
  7285. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7286. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7287. #ifndef _WIN32
  7288. signal(SIGPIPE, SIG_IGN);
  7289. #endif
  7290. auto server_thread = std::thread([] {
  7291. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7292. default_socket_options(srv);
  7293. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7294. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7295. sockaddr_in addr{};
  7296. addr.sin_family = AF_INET;
  7297. addr.sin_port = htons(PORT + 2);
  7298. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7299. int opt = 1;
  7300. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7301. #ifdef _WIN32
  7302. reinterpret_cast<const char *>(&opt),
  7303. #else
  7304. &opt,
  7305. #endif
  7306. sizeof(opt));
  7307. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7308. ::listen(srv, 1);
  7309. sockaddr_in cli_addr{};
  7310. socklen_t cli_len = sizeof(cli_addr);
  7311. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7312. if (cli != INVALID_SOCKET) {
  7313. char buf[4096];
  7314. ::recv(cli, buf, sizeof(buf), 0);
  7315. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7316. "Connection: close\r\n"
  7317. "\r\n";
  7318. ::send(cli,
  7319. #ifdef _WIN32
  7320. static_cast<const char *>(response_header.c_str()),
  7321. static_cast<int>(response_header.size()),
  7322. #else
  7323. response_header.c_str(), response_header.size(),
  7324. #endif
  7325. 0);
  7326. std::string chunk(64 * 1024, 'A');
  7327. size_t total_sent = 0;
  7328. while (total_sent < DATA_SIZE) {
  7329. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7330. auto sent = ::send(cli,
  7331. #ifdef _WIN32
  7332. static_cast<const char *>(chunk.c_str()),
  7333. static_cast<int>(to_send),
  7334. #else
  7335. chunk.c_str(), to_send,
  7336. #endif
  7337. 0);
  7338. if (sent <= 0) break;
  7339. total_sent += static_cast<size_t>(sent);
  7340. }
  7341. #ifdef _WIN32
  7342. ::shutdown(cli, SD_SEND);
  7343. #else
  7344. ::shutdown(cli, SHUT_WR);
  7345. #endif
  7346. // Drain until the client closes its end, ensuring all data is delivered
  7347. char drain[1024];
  7348. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7349. detail::close_socket(cli);
  7350. }
  7351. detail::close_socket(srv);
  7352. });
  7353. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7354. size_t total_read = 0;
  7355. {
  7356. Client cli("127.0.0.1", PORT + 2);
  7357. cli.set_read_timeout(5, 0);
  7358. cli.set_payload_max_length(0); // 0 means no limit
  7359. auto stream = cli.open_stream("GET", "/data");
  7360. ASSERT_TRUE(stream.is_valid());
  7361. char buffer[64 * 1024];
  7362. ssize_t n;
  7363. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7364. total_read += static_cast<size_t>(n);
  7365. }
  7366. }
  7367. server_thread.join();
  7368. EXPECT_EQ(total_read, DATA_SIZE)
  7369. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7370. << " bytes without truncation, but only read " << total_read << " bytes.";
  7371. }
  7372. // Verify that content_receiver bypasses the default payload_max_length,
  7373. // allowing streaming downloads larger than 100MB without requiring an explicit
  7374. // set_payload_max_length call.
  7375. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  7376. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7377. #ifndef _WIN32
  7378. signal(SIGPIPE, SIG_IGN);
  7379. #endif
  7380. auto server_thread = std::thread([] {
  7381. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7382. default_socket_options(srv);
  7383. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7384. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7385. sockaddr_in addr{};
  7386. addr.sin_family = AF_INET;
  7387. addr.sin_port = htons(PORT + 2);
  7388. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7389. int opt = 1;
  7390. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7391. #ifdef _WIN32
  7392. reinterpret_cast<const char *>(&opt),
  7393. #else
  7394. &opt,
  7395. #endif
  7396. sizeof(opt));
  7397. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7398. ::listen(srv, 1);
  7399. sockaddr_in cli_addr{};
  7400. socklen_t cli_len = sizeof(cli_addr);
  7401. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7402. if (cli != INVALID_SOCKET) {
  7403. char buf[4096];
  7404. ::recv(cli, buf, sizeof(buf), 0);
  7405. // Response with Content-Length larger than default 100MB limit
  7406. auto content_length = std::to_string(DATA_SIZE);
  7407. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7408. "Content-Length: " +
  7409. content_length +
  7410. "\r\n"
  7411. "Connection: close\r\n"
  7412. "\r\n";
  7413. ::send(cli,
  7414. #ifdef _WIN32
  7415. static_cast<const char *>(response_header.c_str()),
  7416. static_cast<int>(response_header.size()),
  7417. #else
  7418. response_header.c_str(), response_header.size(),
  7419. #endif
  7420. 0);
  7421. std::string chunk(64 * 1024, 'A');
  7422. size_t total_sent = 0;
  7423. while (total_sent < DATA_SIZE) {
  7424. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7425. auto sent = ::send(cli,
  7426. #ifdef _WIN32
  7427. static_cast<const char *>(chunk.c_str()),
  7428. static_cast<int>(to_send),
  7429. #else
  7430. chunk.c_str(), to_send,
  7431. #endif
  7432. 0);
  7433. if (sent <= 0) break;
  7434. total_sent += static_cast<size_t>(sent);
  7435. }
  7436. detail::close_socket(cli);
  7437. }
  7438. detail::close_socket(srv);
  7439. });
  7440. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7441. size_t total_received = 0;
  7442. {
  7443. Client cli("127.0.0.1", PORT + 2);
  7444. cli.set_read_timeout(10, 0);
  7445. // Do NOT call set_payload_max_length — use the default 100MB limit
  7446. auto res =
  7447. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7448. total_received += data_length;
  7449. return true;
  7450. });
  7451. ASSERT_TRUE(res);
  7452. EXPECT_EQ(StatusCode::OK_200, res->status);
  7453. }
  7454. server_thread.join();
  7455. EXPECT_EQ(total_received, DATA_SIZE)
  7456. << "With content_receiver, the client should read all " << DATA_SIZE
  7457. << " bytes despite the default 100MB payload_max_length, but only read "
  7458. << total_received << " bytes.";
  7459. }
  7460. // Verify that an explicit set_payload_max_length smaller than the response is
  7461. // enforced even when a content_receiver is used.
  7462. TEST(ClientVulnerabilityTest,
  7463. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  7464. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7465. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  7466. #ifndef _WIN32
  7467. signal(SIGPIPE, SIG_IGN);
  7468. #endif
  7469. auto server_thread = std::thread([] {
  7470. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7471. default_socket_options(srv);
  7472. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7473. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7474. sockaddr_in addr{};
  7475. addr.sin_family = AF_INET;
  7476. addr.sin_port = htons(PORT + 2);
  7477. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7478. int opt = 1;
  7479. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7480. #ifdef _WIN32
  7481. reinterpret_cast<const char *>(&opt),
  7482. #else
  7483. &opt,
  7484. #endif
  7485. sizeof(opt));
  7486. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7487. ::listen(srv, 1);
  7488. sockaddr_in cli_addr{};
  7489. socklen_t cli_len = sizeof(cli_addr);
  7490. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7491. if (cli != INVALID_SOCKET) {
  7492. char buf[4096];
  7493. ::recv(cli, buf, sizeof(buf), 0);
  7494. auto content_length = std::to_string(DATA_SIZE);
  7495. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7496. "Content-Length: " +
  7497. content_length +
  7498. "\r\n"
  7499. "Connection: close\r\n"
  7500. "\r\n";
  7501. ::send(cli,
  7502. #ifdef _WIN32
  7503. static_cast<const char *>(response_header.c_str()),
  7504. static_cast<int>(response_header.size()),
  7505. #else
  7506. response_header.c_str(), response_header.size(),
  7507. #endif
  7508. 0);
  7509. std::string chunk(64 * 1024, 'A');
  7510. size_t total_sent = 0;
  7511. while (total_sent < DATA_SIZE) {
  7512. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7513. auto sent = ::send(cli,
  7514. #ifdef _WIN32
  7515. static_cast<const char *>(chunk.c_str()),
  7516. static_cast<int>(to_send),
  7517. #else
  7518. chunk.c_str(), to_send,
  7519. #endif
  7520. 0);
  7521. if (sent <= 0) break;
  7522. total_sent += static_cast<size_t>(sent);
  7523. }
  7524. detail::close_socket(cli);
  7525. }
  7526. detail::close_socket(srv);
  7527. });
  7528. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7529. size_t total_received = 0;
  7530. {
  7531. Client cli("127.0.0.1", PORT + 2);
  7532. cli.set_read_timeout(10, 0);
  7533. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  7534. auto res =
  7535. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7536. total_received += data_length;
  7537. return true;
  7538. });
  7539. // Should fail because 200MB exceeds the explicit 150MB limit
  7540. EXPECT_FALSE(res);
  7541. }
  7542. server_thread.join();
  7543. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  7544. << "Client with content_receiver should respect the explicit "
  7545. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  7546. << total_received << " bytes.";
  7547. }
  7548. // Verify that an explicit set_payload_max_length larger than the response
  7549. // allows the content_receiver to read all data successfully.
  7550. TEST(ClientVulnerabilityTest,
  7551. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  7552. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7553. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  7554. #ifndef _WIN32
  7555. signal(SIGPIPE, SIG_IGN);
  7556. #endif
  7557. auto server_thread = std::thread([] {
  7558. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7559. default_socket_options(srv);
  7560. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7561. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7562. sockaddr_in addr{};
  7563. addr.sin_family = AF_INET;
  7564. addr.sin_port = htons(PORT + 2);
  7565. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7566. int opt = 1;
  7567. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7568. #ifdef _WIN32
  7569. reinterpret_cast<const char *>(&opt),
  7570. #else
  7571. &opt,
  7572. #endif
  7573. sizeof(opt));
  7574. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7575. ::listen(srv, 1);
  7576. sockaddr_in cli_addr{};
  7577. socklen_t cli_len = sizeof(cli_addr);
  7578. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7579. if (cli != INVALID_SOCKET) {
  7580. char buf[4096];
  7581. ::recv(cli, buf, sizeof(buf), 0);
  7582. auto content_length = std::to_string(DATA_SIZE);
  7583. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7584. "Content-Length: " +
  7585. content_length +
  7586. "\r\n"
  7587. "Connection: close\r\n"
  7588. "\r\n";
  7589. ::send(cli,
  7590. #ifdef _WIN32
  7591. static_cast<const char *>(response_header.c_str()),
  7592. static_cast<int>(response_header.size()),
  7593. #else
  7594. response_header.c_str(), response_header.size(),
  7595. #endif
  7596. 0);
  7597. std::string chunk(64 * 1024, 'A');
  7598. size_t total_sent = 0;
  7599. while (total_sent < DATA_SIZE) {
  7600. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7601. auto sent = ::send(cli,
  7602. #ifdef _WIN32
  7603. static_cast<const char *>(chunk.c_str()),
  7604. static_cast<int>(to_send),
  7605. #else
  7606. chunk.c_str(), to_send,
  7607. #endif
  7608. 0);
  7609. if (sent <= 0) break;
  7610. total_sent += static_cast<size_t>(sent);
  7611. }
  7612. #ifdef _WIN32
  7613. ::shutdown(cli, SD_SEND);
  7614. #else
  7615. ::shutdown(cli, SHUT_WR);
  7616. #endif
  7617. char drain[1024];
  7618. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7619. detail::close_socket(cli);
  7620. }
  7621. detail::close_socket(srv);
  7622. });
  7623. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7624. size_t total_received = 0;
  7625. {
  7626. Client cli("127.0.0.1", PORT + 2);
  7627. cli.set_read_timeout(10, 0);
  7628. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  7629. auto res =
  7630. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7631. total_received += data_length;
  7632. return true;
  7633. });
  7634. ASSERT_TRUE(res);
  7635. EXPECT_EQ(StatusCode::OK_200, res->status);
  7636. }
  7637. server_thread.join();
  7638. EXPECT_EQ(total_received, DATA_SIZE)
  7639. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  7640. << " bytes (larger than " << DATA_SIZE
  7641. << " bytes response), content_receiver should read all data, but only "
  7642. "read "
  7643. << total_received << " bytes.";
  7644. }
  7645. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  7646. // Regression test for "zip bomb" attack on the client side: a malicious server
  7647. // sends a small gzip-compressed response that decompresses to a huge payload.
  7648. // The client must enforce payload_max_length on the decompressed size.
  7649. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  7650. constexpr size_t DECOMPRESSED_SIZE =
  7651. 10 * 1024 * 1024; // 10MB after decompression
  7652. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7653. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  7654. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  7655. std::string compressed;
  7656. {
  7657. httplib::detail::gzip_compressor compressor;
  7658. bool ok =
  7659. compressor.compress(uncompressed.data(), uncompressed.size(),
  7660. /*last=*/true, [&](const char *buf, size_t len) {
  7661. compressed.append(buf, len);
  7662. return true;
  7663. });
  7664. ASSERT_TRUE(ok);
  7665. }
  7666. // Sanity: compressed data should be much smaller than the decompressed size
  7667. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  7668. #ifndef _WIN32
  7669. signal(SIGPIPE, SIG_IGN);
  7670. #endif
  7671. // Set up the listening socket in the main thread so the server is guaranteed
  7672. // to be ready before the client connects (eliminates race condition).
  7673. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7674. default_socket_options(srv);
  7675. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7676. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7677. sockaddr_in addr{};
  7678. addr.sin_family = AF_INET;
  7679. addr.sin_port = htons(PORT + 3);
  7680. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7681. int opt = 1;
  7682. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7683. #ifdef _WIN32
  7684. reinterpret_cast<const char *>(&opt),
  7685. #else
  7686. &opt,
  7687. #endif
  7688. sizeof(opt));
  7689. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  7690. ASSERT_EQ(0, ::listen(srv, 1));
  7691. auto server_thread = std::thread([&compressed, srv] {
  7692. sockaddr_in cli_addr{};
  7693. socklen_t cli_len = sizeof(cli_addr);
  7694. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7695. if (cli != INVALID_SOCKET) {
  7696. char buf[4096];
  7697. ::recv(cli, buf, sizeof(buf), 0);
  7698. // Malicious response: gzip-compressed body, no Content-Length
  7699. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7700. "Content-Encoding: gzip\r\n"
  7701. "Connection: close\r\n"
  7702. "\r\n";
  7703. ::send(cli,
  7704. #ifdef _WIN32
  7705. static_cast<const char *>(response_header.c_str()),
  7706. static_cast<int>(response_header.size()),
  7707. #else
  7708. response_header.c_str(), response_header.size(),
  7709. #endif
  7710. 0);
  7711. // Send the compressed payload (small on the wire, huge when decompressed)
  7712. size_t total_sent = 0;
  7713. while (total_sent < compressed.size()) {
  7714. auto to_send = std::min(compressed.size() - total_sent,
  7715. static_cast<size_t>(64 * 1024));
  7716. auto sent =
  7717. ::send(cli,
  7718. #ifdef _WIN32
  7719. static_cast<const char *>(compressed.c_str() + total_sent),
  7720. static_cast<int>(to_send),
  7721. #else
  7722. compressed.c_str() + total_sent, to_send,
  7723. #endif
  7724. 0);
  7725. if (sent <= 0) break;
  7726. total_sent += static_cast<size_t>(sent);
  7727. }
  7728. detail::close_socket(cli);
  7729. }
  7730. });
  7731. auto se = detail::scope_exit([&] {
  7732. detail::close_socket(srv);
  7733. server_thread.join();
  7734. });
  7735. size_t total_decompressed = 0;
  7736. {
  7737. Client cli("127.0.0.1", PORT + 3);
  7738. cli.set_read_timeout(5, 0);
  7739. cli.set_decompress(true);
  7740. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7741. auto stream = cli.open_stream("GET", "/zipbomb");
  7742. ASSERT_TRUE(stream.is_valid());
  7743. char buffer[64 * 1024];
  7744. ssize_t n;
  7745. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7746. total_decompressed += static_cast<size_t>(n);
  7747. }
  7748. }
  7749. // The decompressed size must be capped by payload_max_length. Without
  7750. // protection, the client would decompress the full 10MB from a tiny
  7751. // compressed payload, enabling a zip bomb DoS attack.
  7752. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  7753. << "Client decompressed " << total_decompressed
  7754. << " bytes from a gzip response. The decompressed size should be "
  7755. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  7756. }
  7757. #endif
  7758. TEST(HostAndPortPropertiesTest, NoSSL) {
  7759. httplib::Client cli("www.google.com", 1234);
  7760. ASSERT_EQ("www.google.com", cli.host());
  7761. ASSERT_EQ(1234, cli.port());
  7762. }
  7763. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7764. httplib::Client cli("www.google.com:1234");
  7765. ASSERT_EQ("www.google.com", cli.host());
  7766. ASSERT_EQ(1234, cli.port());
  7767. }
  7768. #ifdef CPPHTTPLIB_SSL_ENABLED
  7769. TEST(HostAndPortPropertiesTest, SSL) {
  7770. httplib::SSLClient cli("www.google.com");
  7771. ASSERT_EQ("www.google.com", cli.host());
  7772. ASSERT_EQ(443, cli.port());
  7773. }
  7774. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  7775. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  7776. std::string cert;
  7777. read_file(CA_CERT_FILE, cert);
  7778. httplib::SSLClient httplib_client("www.google.com");
  7779. // Load CA store first time
  7780. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  7781. // Load CA store second time (update)
  7782. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  7783. // Verify client is still valid and can make connections
  7784. httplib_client.enable_server_certificate_verification(true);
  7785. auto res = httplib_client.Get("/");
  7786. ASSERT_TRUE(res);
  7787. // Google may return 200 or 301 depending on various factors
  7788. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  7789. res->status == StatusCode::MovedPermanently_301);
  7790. }
  7791. TEST(SSLClientTest, ServerNameIndication_Online) {
  7792. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7793. auto host = "httpcan.org";
  7794. auto path = std::string{"/get"};
  7795. #else
  7796. auto host = "nghttp2.org";
  7797. auto path = std::string{"/httpbin/get"};
  7798. #endif
  7799. SSLClient cli(host, 443);
  7800. auto res = cli.Get(path);
  7801. ASSERT_TRUE(res);
  7802. ASSERT_EQ(StatusCode::OK_200, res->status);
  7803. }
  7804. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  7805. // Use a site that will cause SSL verification failure due to self-signed cert
  7806. SSLClient cli("self-signed.badssl.com", 443);
  7807. cli.enable_server_certificate_verification(true);
  7808. auto res = cli.Get("/");
  7809. ASSERT_TRUE(!res);
  7810. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7811. // Verify backend error is captured for SSLServerVerification
  7812. // This occurs when certificate verification fails
  7813. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  7814. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  7815. EXPECT_NE(0UL, res.ssl_backend_error());
  7816. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7817. // For OpenSSL, ssl_error is 0 for verification errors
  7818. EXPECT_EQ(0, res.ssl_error());
  7819. #if !defined(_WIN32) || \
  7820. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  7821. // On non-Windows or when Windows Schannel is disabled, the error comes
  7822. // from OpenSSL's verification
  7823. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  7824. res.ssl_backend_error());
  7825. #endif
  7826. #endif
  7827. }
  7828. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  7829. // Use a site where hostname doesn't match the certificate
  7830. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  7831. SSLClient cli("wrong.host.badssl.com", 443);
  7832. cli.enable_server_certificate_verification(true);
  7833. cli.enable_server_hostname_verification(true);
  7834. auto res = cli.Get("/");
  7835. ASSERT_TRUE(!res);
  7836. // The error type depends on when hostname verification occurs:
  7837. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  7838. // - Mbed TLS: SSLServerVerification (during handshake)
  7839. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  7840. res.error() == Error::SSLServerVerification);
  7841. // Verify backend error is captured for hostname verification failure
  7842. EXPECT_NE(0UL, res.ssl_backend_error());
  7843. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7844. // For OpenSSL, ssl_error is 0 for verification errors
  7845. EXPECT_EQ(0, res.ssl_error());
  7846. #if !defined(_WIN32) || \
  7847. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  7848. // On non-Windows or when Windows Schannel is disabled, the error comes
  7849. // from OpenSSL's hostname verification
  7850. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  7851. res.ssl_backend_error());
  7852. #endif
  7853. #endif
  7854. }
  7855. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  7856. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  7857. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  7858. SSLClient cli("www.google.com", 443);
  7859. cli.enable_server_certificate_verification(true);
  7860. auto res = cli.Get("/");
  7861. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  7862. }
  7863. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  7864. SSLClient cli("www.google.com", 443);
  7865. cli.enable_server_certificate_verification(true);
  7866. cli.enable_windows_certificate_verification(false);
  7867. auto res = cli.Get("/");
  7868. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  7869. }
  7870. #endif
  7871. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  7872. Client cli("https://google.com");
  7873. auto res = cli.Get("/");
  7874. ASSERT_TRUE(res);
  7875. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7876. }
  7877. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  7878. SSLClient cli("google.com");
  7879. cli.set_ca_cert_path(CA_CERT_FILE);
  7880. auto res = cli.Get("/");
  7881. ASSERT_TRUE(res);
  7882. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7883. }
  7884. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  7885. SSLClient cli("google.com");
  7886. cli.enable_server_certificate_verification(true);
  7887. cli.set_ca_cert_path("hello");
  7888. auto res = cli.Get("/");
  7889. ASSERT_TRUE(!res);
  7890. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  7891. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  7892. // should be set
  7893. EXPECT_EQ(0, res.ssl_error());
  7894. // Verify backend error is captured for SSLLoadingCerts
  7895. // This error occurs when loading CA certificates fails
  7896. EXPECT_NE(0UL, res.ssl_backend_error());
  7897. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7898. // OpenSSL specific error codes:
  7899. // > openssl errstr 0x80000002
  7900. // error:80000002:system library::No such file or directory
  7901. // > openssl errstr 0xA000126
  7902. // error:0A000126:SSL routines::unexpected eof while reading
  7903. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  7904. res.ssl_backend_error() == 0xA000126);
  7905. #endif
  7906. }
  7907. TEST(SSLClientTest, ServerCertificateVerification4) {
  7908. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7909. ASSERT_TRUE(svr.is_valid());
  7910. svr.Get("/test", [&](const Request &, Response &res) {
  7911. res.set_content("test", "text/plain");
  7912. svr.stop();
  7913. ASSERT_TRUE(true);
  7914. });
  7915. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7916. auto se = detail::scope_exit([&] {
  7917. t.join();
  7918. ASSERT_FALSE(svr.is_running());
  7919. });
  7920. svr.wait_until_ready();
  7921. SSLClient cli("127.0.0.1", PORT);
  7922. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7923. cli.enable_server_certificate_verification(true);
  7924. cli.set_connection_timeout(30);
  7925. auto res = cli.Get("/test");
  7926. ASSERT_TRUE(res);
  7927. ASSERT_EQ(StatusCode::OK_200, res->status);
  7928. }
  7929. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  7930. std::string cert;
  7931. read_file(CA_CERT_FILE, cert);
  7932. SSLClient cli("google.com");
  7933. cli.load_ca_cert_store(cert.data(), cert.size());
  7934. const auto res = cli.Get("/");
  7935. ASSERT_TRUE(res);
  7936. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7937. }
  7938. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  7939. // clang-format off
  7940. static constexpr char cert[] =
  7941. "GlobalSign Root CA\n"
  7942. "==================\n"
  7943. "-----BEGIN CERTIFICATE-----\n"
  7944. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  7945. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  7946. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  7947. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  7948. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  7949. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  7950. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  7951. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  7952. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  7953. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  7954. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  7955. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  7956. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  7957. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  7958. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  7959. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  7960. "-----END CERTIFICATE-----\n";
  7961. // clang-format on
  7962. SSLClient cli("google.com");
  7963. cli.load_ca_cert_store(cert, sizeof(cert));
  7964. const auto res = cli.Get("/");
  7965. ASSERT_TRUE(res);
  7966. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7967. }
  7968. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  7969. SSLClient cli("www.youtube.com");
  7970. cli.set_ca_cert_path(CA_CERT_FILE);
  7971. cli.enable_server_certificate_verification(true);
  7972. cli.set_follow_location(true);
  7973. auto res = cli.Get("/");
  7974. ASSERT_TRUE(res);
  7975. ASSERT_EQ(StatusCode::OK_200, res->status);
  7976. }
  7977. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  7978. SSLClient cli("wWw.YouTube.Com");
  7979. cli.set_ca_cert_path(CA_CERT_FILE);
  7980. cli.enable_server_certificate_verification(true);
  7981. cli.enable_server_hostname_verification(true);
  7982. cli.set_follow_location(true);
  7983. auto res = cli.Get("/");
  7984. ASSERT_TRUE(res);
  7985. ASSERT_EQ(StatusCode::OK_200, res->status);
  7986. }
  7987. TEST(SSLClientTest, HostNameMatchCase_Online) {
  7988. SSLClient cli("gOoGlE.COm");
  7989. cli.enable_server_certificate_verification(true);
  7990. cli.enable_server_hostname_verification(true);
  7991. cli.set_follow_location(true);
  7992. auto res = cli.Get("/");
  7993. ASSERT_TRUE(res);
  7994. ASSERT_EQ(StatusCode::OK_200, res->status);
  7995. }
  7996. TEST(SSLClientTest, Issue2004_Online) {
  7997. Client client("https://google.com");
  7998. client.set_follow_location(true);
  7999. auto res = client.Get("/");
  8000. ASSERT_TRUE(res);
  8001. ASSERT_EQ(StatusCode::OK_200, res->status);
  8002. auto body = res->body;
  8003. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8004. }
  8005. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8006. // Create SSLClient with invalid cert/key to make is_valid() return false
  8007. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8008. "nonexistent_key.pem");
  8009. // is_valid() should be false due to cert loading failure
  8010. ASSERT_FALSE(cli.is_valid());
  8011. auto res = cli.Get("/");
  8012. ASSERT_FALSE(res);
  8013. EXPECT_EQ(Error::SSLConnection, res.error());
  8014. }
  8015. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8016. // Test for Issue #2251: SSL error not properly reported when client cert
  8017. // and key paths are swapped or mismatched
  8018. // This simulates the scenario where user accidentally swaps the cert and key
  8019. // files
  8020. // Using client cert file as private key and vice versa (completely wrong)
  8021. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8022. // Should fail validation due to cert/key mismatch
  8023. ASSERT_FALSE(cli.is_valid());
  8024. // Attempt to make a request should fail with proper error
  8025. auto res = cli.Get("/");
  8026. ASSERT_FALSE(res);
  8027. EXPECT_EQ(Error::SSLConnection, res.error());
  8028. // SSL error should be recorded in the Result object (this is the key fix for
  8029. // Issue #2251)
  8030. auto backend_error = res.ssl_backend_error();
  8031. EXPECT_NE(0u, backend_error);
  8032. }
  8033. // Tests cert/key mismatch detection at the TLS context level
  8034. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8035. // Test that using mismatched cert/key causes connection failure.
  8036. // We verify this at the SSLClient level rather than through internal
  8037. // TLS API functions.
  8038. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8039. cli.enable_server_certificate_verification(false);
  8040. cli.set_connection_timeout(2);
  8041. // The mismatch should cause a connection or handshake error
  8042. auto res = cli.Get("/test");
  8043. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8044. // Either way, the request should fail
  8045. EXPECT_FALSE(res);
  8046. }
  8047. #endif
  8048. #if 0
  8049. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8050. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8051. ASSERT_TRUE(cli != nullptr);
  8052. cli->set_address_family(AF_INET6);
  8053. cli->set_interface("en0");
  8054. auto res = cli->Get("/get");
  8055. ASSERT_TRUE(res);
  8056. ASSERT_EQ(StatusCode::OK_200, res->status);
  8057. }
  8058. #endif
  8059. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8060. #ifdef CPPHTTPLIB_SSL_ENABLED
  8061. void ClientCertPresent(
  8062. const std::string &client_cert_file,
  8063. const std::string &client_private_key_file,
  8064. const std::string &client_encrypted_private_key_pass = std::string()) {
  8065. using namespace httplib::tls;
  8066. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8067. CLIENT_CA_CERT_DIR);
  8068. ASSERT_TRUE(svr.is_valid());
  8069. svr.Get("/test", [&](const Request &req, Response &res) {
  8070. res.set_content("test", "text/plain");
  8071. auto cert = req.peer_cert();
  8072. ASSERT_TRUE(static_cast<bool>(cert));
  8073. std::string common_name = cert.subject_cn();
  8074. EXPECT_EQ("Common Name", common_name);
  8075. });
  8076. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8077. auto se = detail::scope_exit([&] {
  8078. svr.stop();
  8079. t.join();
  8080. ASSERT_FALSE(svr.is_running());
  8081. });
  8082. svr.wait_until_ready();
  8083. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8084. client_encrypted_private_key_pass);
  8085. cli.enable_server_certificate_verification(false);
  8086. cli.set_connection_timeout(30);
  8087. auto res = cli.Get("/test");
  8088. ASSERT_TRUE(res);
  8089. ASSERT_EQ(StatusCode::OK_200, res->status);
  8090. }
  8091. TEST(SSLClientServerTest, ClientCertPresent) {
  8092. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8093. }
  8094. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8095. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8096. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8097. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8098. }
  8099. // PEM memory-based constructor tests (works with all TLS backends)
  8100. void PemMemoryClientCertPresent(
  8101. const std::string &client_cert_file,
  8102. const std::string &client_private_key_file,
  8103. const std::string &client_encrypted_private_key_pass = std::string()) {
  8104. // Read PEM files into memory
  8105. std::string server_cert_pem, server_key_pem;
  8106. std::string client_ca_pem;
  8107. std::string client_cert_pem, client_key_pem;
  8108. read_file(SERVER_CERT_FILE, server_cert_pem);
  8109. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8110. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8111. read_file(client_cert_file, client_cert_pem);
  8112. read_file(client_private_key_file, client_key_pem);
  8113. // Create server with PEM memory
  8114. SSLServer::PemMemory server_pem = {
  8115. server_cert_pem.c_str(),
  8116. server_cert_pem.size(),
  8117. server_key_pem.c_str(),
  8118. server_key_pem.size(),
  8119. client_ca_pem.c_str(),
  8120. client_ca_pem.size(),
  8121. nullptr // no password for server key
  8122. };
  8123. SSLServer svr(server_pem);
  8124. ASSERT_TRUE(svr.is_valid());
  8125. svr.Get("/test", [&](const Request &, Response &res) {
  8126. res.set_content("test", "text/plain");
  8127. });
  8128. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8129. auto se = detail::scope_exit([&] {
  8130. svr.stop();
  8131. t.join();
  8132. ASSERT_FALSE(svr.is_running());
  8133. });
  8134. svr.wait_until_ready();
  8135. // Create client with PEM memory
  8136. const char *password = client_encrypted_private_key_pass.empty()
  8137. ? nullptr
  8138. : client_encrypted_private_key_pass.c_str();
  8139. SSLClient::PemMemory client_pem = {
  8140. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8141. client_key_pem.size(), password};
  8142. SSLClient cli(HOST, PORT, client_pem);
  8143. cli.enable_server_certificate_verification(false);
  8144. cli.set_connection_timeout(30);
  8145. auto res = cli.Get("/test");
  8146. ASSERT_TRUE(res);
  8147. ASSERT_EQ(StatusCode::OK_200, res->status);
  8148. }
  8149. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8150. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8151. }
  8152. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8153. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8154. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8155. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8156. }
  8157. TEST(SSLClientServerTest, ClientCertMissing) {
  8158. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8159. CLIENT_CA_CERT_DIR);
  8160. ASSERT_TRUE(svr.is_valid());
  8161. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8162. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8163. auto se = detail::scope_exit([&] {
  8164. svr.stop();
  8165. t.join();
  8166. ASSERT_FALSE(svr.is_running());
  8167. });
  8168. svr.wait_until_ready();
  8169. SSLClient cli(HOST, PORT);
  8170. cli.set_connection_timeout(30);
  8171. auto res = cli.Get("/test");
  8172. ASSERT_TRUE(!res);
  8173. // When client cert is missing and server requires it, connection fails
  8174. // Error type depends on backend implementation
  8175. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8176. res.error() == Error::SSLConnection);
  8177. // Verify backend error is captured
  8178. // Note: This test may have different error codes depending on the exact
  8179. // verification failure
  8180. EXPECT_NE(0UL, res.ssl_backend_error());
  8181. }
  8182. TEST(SSLClientServerTest, TrustDirOptional) {
  8183. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8184. ASSERT_TRUE(svr.is_valid());
  8185. svr.Get("/test", [&](const Request &, Response &res) {
  8186. res.set_content("test", "text/plain");
  8187. });
  8188. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8189. auto se = detail::scope_exit([&] {
  8190. svr.stop();
  8191. t.join();
  8192. ASSERT_FALSE(svr.is_running());
  8193. });
  8194. svr.wait_until_ready();
  8195. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8196. cli.enable_server_certificate_verification(false);
  8197. cli.set_connection_timeout(30);
  8198. auto res = cli.Get("/test");
  8199. ASSERT_TRUE(res);
  8200. ASSERT_EQ(StatusCode::OK_200, res->status);
  8201. }
  8202. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8203. class NoListenSSLServer : public SSLServer {
  8204. public:
  8205. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8206. const char *client_ca_cert_file_path,
  8207. const char *client_ca_cert_dir_path = nullptr)
  8208. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8209. client_ca_cert_dir_path),
  8210. stop_(false) {}
  8211. std::atomic_bool stop_;
  8212. private:
  8213. bool process_and_close_socket(socket_t /*sock*/) override {
  8214. // Don't create SSL context
  8215. while (!stop_.load()) {
  8216. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8217. }
  8218. return true;
  8219. }
  8220. };
  8221. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8222. CLIENT_CA_CERT_FILE);
  8223. ASSERT_TRUE(svr.is_valid());
  8224. svr.Get("/test", [&](const Request &, Response &res) {
  8225. res.set_content("test", "text/plain");
  8226. });
  8227. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8228. auto se = detail::scope_exit([&] {
  8229. svr.stop_ = true;
  8230. svr.stop();
  8231. t.join();
  8232. ASSERT_FALSE(svr.is_running());
  8233. });
  8234. svr.wait_until_ready();
  8235. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8236. cli.enable_server_certificate_verification(false);
  8237. cli.set_connection_timeout(1);
  8238. auto res = cli.Get("/test");
  8239. ASSERT_TRUE(!res);
  8240. EXPECT_EQ(Error::SSLConnection, res.error());
  8241. // Timeout results in WantRead error code (maps to backend-specific value)
  8242. EXPECT_NE(0, res.ssl_error());
  8243. }
  8244. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8245. // Test SSLServer with client certificate verification using the standard
  8246. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8247. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8248. CLIENT_CA_CERT_DIR);
  8249. ASSERT_TRUE(svr.is_valid());
  8250. svr.Get("/test", [&](const Request &req, Response &res) {
  8251. res.set_content("test", "text/plain");
  8252. auto cert = req.peer_cert();
  8253. ASSERT_TRUE(static_cast<bool>(cert));
  8254. auto common_name = cert.subject_cn();
  8255. EXPECT_EQ("Common Name", common_name);
  8256. });
  8257. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8258. auto se = detail::scope_exit([&] {
  8259. svr.stop();
  8260. t.join();
  8261. ASSERT_FALSE(svr.is_running());
  8262. });
  8263. svr.wait_until_ready();
  8264. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8265. cli.enable_server_certificate_verification(false);
  8266. cli.set_connection_timeout(30);
  8267. auto res = cli.Get("/test");
  8268. ASSERT_TRUE(res);
  8269. ASSERT_EQ(StatusCode::OK_200, res->status);
  8270. }
  8271. // Test verify_hostname for both OpenSSL and MbedTLS backends
  8272. // Verifies that wildcard matching and exact matching work consistently
  8273. TEST(SSLClientServerTest, TlsVerifyHostname) {
  8274. using namespace httplib::tls;
  8275. // We need a running server to test against
  8276. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8277. ASSERT_TRUE(svr.is_valid());
  8278. svr.Get("/test", [](const Request &, Response &res) {
  8279. res.set_content("ok", "text/plain");
  8280. });
  8281. thread t([&]() { svr.listen(HOST, PORT); });
  8282. auto se = detail::scope_exit([&] {
  8283. svr.stop();
  8284. t.join();
  8285. });
  8286. svr.wait_until_ready();
  8287. bool verify_callback_called = false;
  8288. bool verify_result_wrong = false;
  8289. SSLClient cli(HOST, PORT);
  8290. cli.enable_server_certificate_verification(true);
  8291. cli.set_ca_cert_path(CA_CERT_FILE);
  8292. cli.set_connection_timeout(5);
  8293. // Note: Test certificate has CN="Common Name", not "localhost"
  8294. bool verify_result_cn = false;
  8295. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8296. verify_callback_called = true;
  8297. if (!ctx.cert) return false;
  8298. // Test 1: "Common Name" should match (our test server cert CN)
  8299. verify_result_cn = ctx.check_hostname("Common Name");
  8300. // Test 2: wrong hostname should not match
  8301. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  8302. return true; // Accept for the purpose of this test
  8303. });
  8304. auto res = cli.Get("/test");
  8305. // The request may succeed or fail depending on cert configuration
  8306. // but the callback should have been called
  8307. ASSERT_TRUE(verify_callback_called)
  8308. << "Verify callback should have been called";
  8309. // CN="Common Name" should match our test certificate
  8310. EXPECT_TRUE(verify_result_cn)
  8311. << "verify_hostname should match 'Common Name' (certificate CN)";
  8312. // Wrong hostname should not match
  8313. EXPECT_FALSE(verify_result_wrong)
  8314. << "verify_hostname should not match 'wronghost.example.com'";
  8315. }
  8316. #endif
  8317. // mbedTLS-specific callback constructor test
  8318. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8319. #ifdef CPPHTTPLIB_SSL_ENABLED
  8320. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8321. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8322. ASSERT_TRUE(svr.is_valid());
  8323. // Set up a handler to verify client certificate is present
  8324. bool client_cert_verified = false;
  8325. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8326. // Verify that client certificate was provided
  8327. client_cert_verified = true;
  8328. res.set_content("success", "text/plain");
  8329. });
  8330. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8331. auto se = detail::scope_exit([&] {
  8332. svr.stop();
  8333. t.join();
  8334. ASSERT_FALSE(svr.is_running());
  8335. });
  8336. svr.wait_until_ready();
  8337. // Client with certificate
  8338. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8339. cli.enable_server_certificate_verification(false);
  8340. cli.set_connection_timeout(30);
  8341. auto res = cli.Get("/test");
  8342. ASSERT_TRUE(res);
  8343. ASSERT_EQ(StatusCode::OK_200, res->status);
  8344. ASSERT_TRUE(client_cert_verified);
  8345. EXPECT_EQ("success", res->body);
  8346. }
  8347. #endif
  8348. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  8349. // backends
  8350. #ifdef CPPHTTPLIB_SSL_ENABLED
  8351. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  8352. using namespace httplib::tls;
  8353. // Test that when client CA cert file is provided,
  8354. // the server properly requests and validates client certificates
  8355. // Create a server with client authentication
  8356. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8357. ASSERT_TRUE(svr.is_valid());
  8358. bool handler_called = false;
  8359. svr.Get("/test", [&](const Request &req, Response &res) {
  8360. handler_called = true;
  8361. // Verify that a client certificate was provided
  8362. auto cert = req.peer_cert();
  8363. ASSERT_TRUE(static_cast<bool>(cert));
  8364. // Get the issuer name
  8365. std::string issuer_str = cert.issuer_name();
  8366. ASSERT_FALSE(issuer_str.empty());
  8367. // The client certificate should be issued by our test CA
  8368. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  8369. res.set_content("authenticated", "text/plain");
  8370. });
  8371. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8372. auto se = detail::scope_exit([&] {
  8373. svr.stop();
  8374. t.join();
  8375. ASSERT_FALSE(svr.is_running());
  8376. });
  8377. svr.wait_until_ready();
  8378. // Connect with a client certificate issued by the CA
  8379. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8380. cli.enable_server_certificate_verification(false);
  8381. cli.set_connection_timeout(30);
  8382. auto res = cli.Get("/test");
  8383. ASSERT_TRUE(res);
  8384. ASSERT_EQ(StatusCode::OK_200, res->status);
  8385. ASSERT_TRUE(handler_called);
  8386. EXPECT_EQ("authenticated", res->body);
  8387. }
  8388. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  8389. using namespace httplib::tls;
  8390. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8391. ASSERT_TRUE(svr.is_valid());
  8392. svr.Get("/test", [](const Request &, Response &res) {
  8393. res.set_content("ok", "text/plain");
  8394. });
  8395. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8396. auto se = detail::scope_exit([&] {
  8397. svr.stop();
  8398. t.join();
  8399. });
  8400. svr.wait_until_ready();
  8401. SSLClient cli(HOST, PORT);
  8402. cli.enable_server_certificate_verification(false);
  8403. cli.set_connection_timeout(30);
  8404. bool cert_checked = false;
  8405. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8406. if (ctx.cert) {
  8407. auto sans = ctx.sans();
  8408. // Test certificate may or may not have SANs - just verify the API
  8409. // works If SANs exist, verify the types are valid
  8410. for (const auto &san : sans) {
  8411. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  8412. san.type == SanType::EMAIL || san.type == SanType::URI ||
  8413. san.type == SanType::OTHER);
  8414. EXPECT_FALSE(san.value.empty());
  8415. }
  8416. cert_checked = true;
  8417. }
  8418. return true;
  8419. });
  8420. auto res = cli.Get("/test");
  8421. ASSERT_TRUE(res);
  8422. EXPECT_TRUE(cert_checked);
  8423. }
  8424. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  8425. using namespace httplib::tls;
  8426. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8427. ASSERT_TRUE(svr.is_valid());
  8428. svr.Get("/test", [](const Request &, Response &res) {
  8429. res.set_content("ok", "text/plain");
  8430. });
  8431. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8432. auto se = detail::scope_exit([&] {
  8433. svr.stop();
  8434. t.join();
  8435. });
  8436. svr.wait_until_ready();
  8437. SSLClient cli(HOST, PORT);
  8438. cli.enable_server_certificate_verification(false);
  8439. cli.set_connection_timeout(30);
  8440. bool validity_checked = false;
  8441. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8442. if (ctx.cert) {
  8443. time_t not_before = 0, not_after = 0;
  8444. bool result = ctx.validity(not_before, not_after);
  8445. EXPECT_TRUE(result);
  8446. // Verify that not_before < now < not_after for a valid cert
  8447. time_t now = time(nullptr);
  8448. EXPECT_LT(not_before, now);
  8449. EXPECT_GT(not_after, now);
  8450. validity_checked = true;
  8451. }
  8452. return true;
  8453. });
  8454. auto res = cli.Get("/test");
  8455. ASSERT_TRUE(res);
  8456. EXPECT_TRUE(validity_checked);
  8457. }
  8458. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  8459. using namespace httplib::tls;
  8460. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8461. ASSERT_TRUE(svr.is_valid());
  8462. svr.Get("/test", [](const Request &, Response &res) {
  8463. res.set_content("ok", "text/plain");
  8464. });
  8465. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8466. auto se = detail::scope_exit([&] {
  8467. svr.stop();
  8468. t.join();
  8469. });
  8470. svr.wait_until_ready();
  8471. SSLClient cli(HOST, PORT);
  8472. cli.enable_server_certificate_verification(false);
  8473. cli.set_connection_timeout(30);
  8474. bool serial_checked = false;
  8475. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8476. if (ctx.cert) {
  8477. std::string serial = ctx.serial();
  8478. EXPECT_FALSE(serial.empty());
  8479. // Serial should be a hex string
  8480. for (char c : serial) {
  8481. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  8482. (c >= 'a' && c <= 'f'));
  8483. }
  8484. serial_checked = true;
  8485. }
  8486. return true;
  8487. });
  8488. auto res = cli.Get("/test");
  8489. ASSERT_TRUE(res);
  8490. EXPECT_TRUE(serial_checked);
  8491. }
  8492. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  8493. // Test 1: Valid CA file - no error should be recorded
  8494. {
  8495. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8496. CLIENT_CA_CERT_FILE);
  8497. ASSERT_TRUE(svr.is_valid());
  8498. // With valid setup, last_ssl_error should be 0
  8499. EXPECT_EQ(0, svr.ssl_last_error());
  8500. }
  8501. // Test 2: Invalid CA file content
  8502. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  8503. {
  8504. // Create a temporary file with completely invalid content
  8505. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  8506. {
  8507. std::ofstream ofs(temp_invalid_ca);
  8508. ofs << "This is not a certificate file at all\n";
  8509. ofs << "Just plain text content\n";
  8510. }
  8511. // Create server with invalid CA file
  8512. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  8513. // Clean up temporary file
  8514. std::remove(temp_invalid_ca);
  8515. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  8516. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  8517. // Note: SSL_CTX_load_verify_locations typically fails first,
  8518. // but our error handling code path is still exercised
  8519. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  8520. }
  8521. }
  8522. TEST(VerifyCallbackTest, VerifyContextFields) {
  8523. using namespace httplib::tls;
  8524. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8525. ASSERT_TRUE(svr.is_valid());
  8526. svr.Get("/test", [](const Request &, Response &res) {
  8527. res.set_content("ok", "text/plain");
  8528. });
  8529. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8530. auto se = detail::scope_exit([&] {
  8531. svr.stop();
  8532. t.join();
  8533. });
  8534. svr.wait_until_ready();
  8535. SSLClient cli(HOST, PORT);
  8536. cli.enable_server_certificate_verification(false);
  8537. cli.set_connection_timeout(30);
  8538. int callback_count = 0;
  8539. bool saw_leaf_cert = false;
  8540. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8541. if (ctx.cert) {
  8542. callback_count++;
  8543. // We should see at least one certificate (the leaf)
  8544. std::string cn = ctx.subject_cn();
  8545. if (!cn.empty()) { saw_leaf_cert = true; }
  8546. // Verify context fields are populated
  8547. EXPECT_NE(ctx.session, nullptr);
  8548. EXPECT_GE(ctx.depth, 0);
  8549. }
  8550. return true;
  8551. });
  8552. auto res = cli.Get("/test");
  8553. ASSERT_TRUE(res);
  8554. EXPECT_GT(callback_count, 0);
  8555. EXPECT_TRUE(saw_leaf_cert);
  8556. }
  8557. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  8558. using httplib::tls::TlsError;
  8559. // Test that verify_error_to_string returns empty for success
  8560. std::string success_str = TlsError::verify_error_to_string(0);
  8561. EXPECT_TRUE(success_str.empty());
  8562. // Test that verify_error_to_string returns non-empty for error codes
  8563. // Using a common error code (certificate expired)
  8564. std::string error_str =
  8565. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  8566. EXPECT_FALSE(error_str.empty());
  8567. }
  8568. TEST(SessionVerifierTest, CertificateAccepted) {
  8569. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8570. ASSERT_TRUE(svr.is_valid());
  8571. svr.Get("/test", [](const Request &, Response &res) {
  8572. res.set_content("ok", "text/plain");
  8573. });
  8574. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8575. auto se = detail::scope_exit([&] {
  8576. svr.stop();
  8577. t.join();
  8578. });
  8579. svr.wait_until_ready();
  8580. SSLClient cli(HOST, PORT);
  8581. cli.enable_server_certificate_verification(false);
  8582. cli.set_connection_timeout(30);
  8583. bool callback_called = false;
  8584. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8585. EXPECT_NE(session, nullptr);
  8586. callback_called = true;
  8587. return SSLVerifierResponse::CertificateAccepted;
  8588. });
  8589. auto res = cli.Get("/test");
  8590. ASSERT_TRUE(res);
  8591. EXPECT_EQ(200, res->status);
  8592. EXPECT_TRUE(callback_called);
  8593. }
  8594. TEST(SessionVerifierTest, CertificateRejected) {
  8595. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8596. ASSERT_TRUE(svr.is_valid());
  8597. svr.Get("/test", [](const Request &, Response &res) {
  8598. res.set_content("ok", "text/plain");
  8599. });
  8600. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8601. auto se = detail::scope_exit([&] {
  8602. svr.stop();
  8603. t.join();
  8604. });
  8605. svr.wait_until_ready();
  8606. SSLClient cli(HOST, PORT);
  8607. cli.enable_server_certificate_verification(false);
  8608. cli.set_connection_timeout(30);
  8609. bool callback_called = false;
  8610. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8611. EXPECT_NE(session, nullptr);
  8612. callback_called = true;
  8613. return SSLVerifierResponse::CertificateRejected;
  8614. });
  8615. auto res = cli.Get("/test");
  8616. EXPECT_FALSE(res);
  8617. EXPECT_TRUE(callback_called);
  8618. }
  8619. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  8620. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8621. ASSERT_TRUE(svr.is_valid());
  8622. svr.Get("/test", [](const Request &, Response &res) {
  8623. res.set_content("ok", "text/plain");
  8624. });
  8625. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8626. auto se = detail::scope_exit([&] {
  8627. svr.stop();
  8628. t.join();
  8629. });
  8630. svr.wait_until_ready();
  8631. // NoDecisionMade with verification disabled should succeed (no default check)
  8632. SSLClient cli(HOST, PORT);
  8633. cli.enable_server_certificate_verification(false);
  8634. cli.set_connection_timeout(30);
  8635. bool callback_called = false;
  8636. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8637. EXPECT_NE(session, nullptr);
  8638. callback_called = true;
  8639. return SSLVerifierResponse::NoDecisionMade;
  8640. });
  8641. auto res = cli.Get("/test");
  8642. ASSERT_TRUE(res);
  8643. EXPECT_EQ(200, res->status);
  8644. EXPECT_TRUE(callback_called);
  8645. }
  8646. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  8647. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8648. ASSERT_TRUE(svr.is_valid());
  8649. svr.Get("/test", [](const Request &, Response &res) {
  8650. res.set_content("ok", "text/plain");
  8651. });
  8652. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8653. auto se = detail::scope_exit([&] {
  8654. svr.stop();
  8655. t.join();
  8656. });
  8657. svr.wait_until_ready();
  8658. // NoDecisionMade with verification enabled should fail (self-signed cert).
  8659. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  8660. // so we only check that the request fails, not whether the callback was
  8661. // called.
  8662. SSLClient cli(HOST, PORT);
  8663. cli.enable_server_certificate_verification(true);
  8664. cli.set_connection_timeout(30);
  8665. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8666. EXPECT_NE(session, nullptr);
  8667. return SSLVerifierResponse::NoDecisionMade;
  8668. });
  8669. auto res = cli.Get("/test");
  8670. EXPECT_FALSE(res);
  8671. }
  8672. TEST(SSLClientServerTest, ClientCAListFromPem) {
  8673. // Test SSL server using PemMemory constructor with client CA certificates
  8674. // Read PEM files
  8675. std::string server_cert_pem, server_key_pem, client_ca_pem;
  8676. read_file(SERVER_CERT_FILE, server_cert_pem);
  8677. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8678. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8679. // Create SSLServer with PemMemory constructor including client CA
  8680. SSLServer::PemMemory server_pem = {
  8681. server_cert_pem.c_str(),
  8682. server_cert_pem.size(),
  8683. server_key_pem.c_str(),
  8684. server_key_pem.size(),
  8685. client_ca_pem.c_str(),
  8686. client_ca_pem.size(),
  8687. nullptr // no password for server key
  8688. };
  8689. SSLServer svr(server_pem);
  8690. ASSERT_TRUE(svr.is_valid());
  8691. // No SSL error should be recorded for valid setup
  8692. EXPECT_EQ(0, svr.ssl_last_error());
  8693. // Set up server endpoints
  8694. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  8695. res.set_content("ok", "text/plain");
  8696. });
  8697. // Start server in a thread
  8698. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  8699. svr.wait_until_ready();
  8700. // Connect with client certificate (using constructor with paths)
  8701. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8702. cli.enable_server_certificate_verification(false);
  8703. auto res = cli.Get("/test-pem-ca");
  8704. ASSERT_TRUE(res);
  8705. EXPECT_EQ(200, res->status);
  8706. EXPECT_EQ("ok", res->body);
  8707. svr.stop();
  8708. server_thread.join();
  8709. }
  8710. #endif
  8711. #ifdef _WIN32
  8712. TEST(CleanupTest, WSACleanup) {
  8713. int ret = WSACleanup();
  8714. ASSERT_EQ(0, ret);
  8715. }
  8716. #endif
  8717. #ifndef CPPHTTPLIB_SSL_ENABLED
  8718. TEST(NoSSLSupport, SimpleInterface) {
  8719. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  8720. }
  8721. #endif
  8722. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8723. TEST(InvalidScheme, SimpleInterface) {
  8724. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  8725. }
  8726. #endif
  8727. TEST(NoScheme, SimpleInterface) {
  8728. Client cli("yahoo.com:80");
  8729. ASSERT_TRUE(cli.is_valid());
  8730. }
  8731. TEST(SendAPI, SimpleInterface_Online) {
  8732. Client cli("http://yahoo.com");
  8733. Request req;
  8734. req.method = "GET";
  8735. req.path = "/";
  8736. auto res = cli.send(req);
  8737. ASSERT_TRUE(res);
  8738. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8739. }
  8740. TEST(SendAPI, WithParamsInRequest) {
  8741. Server svr;
  8742. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  8743. EXPECT_TRUE(req.has_param("test"));
  8744. EXPECT_EQ("test_value", req.get_param_value("test"));
  8745. });
  8746. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  8747. auto se = detail::scope_exit([&] {
  8748. svr.stop();
  8749. t.join();
  8750. ASSERT_FALSE(svr.is_running());
  8751. });
  8752. svr.wait_until_ready();
  8753. Client cli(HOST, PORT);
  8754. {
  8755. Request req;
  8756. req.method = "GET";
  8757. req.path = "/";
  8758. req.params.emplace("test", "test_value");
  8759. auto res = cli.send(req);
  8760. ASSERT_TRUE(res);
  8761. }
  8762. {
  8763. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  8764. ASSERT_TRUE(res);
  8765. }
  8766. }
  8767. TEST(ClientImplMethods, GetSocketTest) {
  8768. httplib::Server svr;
  8769. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  8770. res.status = StatusCode::OK_200;
  8771. });
  8772. auto port = svr.bind_to_any_port("127.0.0.1");
  8773. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  8774. auto se = detail::scope_exit([&] {
  8775. svr.stop();
  8776. thread.join();
  8777. ASSERT_FALSE(svr.is_running());
  8778. });
  8779. svr.wait_until_ready();
  8780. {
  8781. httplib::Client cli("127.0.0.1", port);
  8782. cli.set_keep_alive(true);
  8783. // Use the behavior of cpp-httplib of opening the connection
  8784. // only when the first request happens. If that changes,
  8785. // this test would be obsolete.
  8786. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  8787. // This also implicitly tests the server. But other tests would fail much
  8788. // earlier than this one to be considered.
  8789. auto res = cli.Get("/");
  8790. ASSERT_TRUE(res);
  8791. EXPECT_EQ(StatusCode::OK_200, res->status);
  8792. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  8793. }
  8794. }
  8795. // Disabled due to out-of-memory problem on GitHub Actions
  8796. #ifdef _WIN64
  8797. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  8798. // allocate content size larger than 2GB in memory
  8799. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  8800. char *content = (char *)malloc(content_size);
  8801. ASSERT_TRUE(content);
  8802. Server svr;
  8803. svr.Get("/foo",
  8804. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  8805. res.set_content(content, content_size, "application/octet-stream");
  8806. });
  8807. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8808. auto se = detail::scope_exit([&] {
  8809. svr.stop();
  8810. listen_thread.join();
  8811. if (content) free(content);
  8812. ASSERT_FALSE(svr.is_running());
  8813. });
  8814. svr.wait_until_ready();
  8815. Client cli(HOST, PORT);
  8816. auto res = cli.Get("/foo");
  8817. ASSERT_TRUE(res);
  8818. EXPECT_EQ(StatusCode::OK_200, res->status);
  8819. EXPECT_EQ(content_size, res->body.length());
  8820. }
  8821. #endif
  8822. #ifdef CPPHTTPLIB_SSL_ENABLED
  8823. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  8824. Client cli("http://yahoo.com");
  8825. auto res = cli.Get("/");
  8826. ASSERT_TRUE(res);
  8827. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8828. cli.set_follow_location(true);
  8829. res = cli.Get("/");
  8830. ASSERT_TRUE(res);
  8831. EXPECT_EQ(StatusCode::OK_200, res->status);
  8832. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8833. }
  8834. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  8835. Client cli("https://yahoo.com");
  8836. auto res = cli.Get("/");
  8837. ASSERT_TRUE(res);
  8838. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8839. cli.set_follow_location(true);
  8840. res = cli.Get("/");
  8841. ASSERT_TRUE(res);
  8842. EXPECT_EQ(StatusCode::OK_200, res->status);
  8843. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8844. }
  8845. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  8846. Client cli("https://yahoo.com");
  8847. auto res = cli.Get("/");
  8848. ASSERT_TRUE(res);
  8849. ASSERT_FALSE(!res);
  8850. ASSERT_TRUE(res);
  8851. ASSERT_FALSE(res == nullptr);
  8852. ASSERT_TRUE(res != nullptr);
  8853. EXPECT_EQ(Error::Success, res.error());
  8854. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  8855. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  8856. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8857. cli.set_follow_location(true);
  8858. res = cli.Get("/");
  8859. ASSERT_TRUE(res);
  8860. EXPECT_EQ(Error::Success, res.error());
  8861. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  8862. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  8863. EXPECT_EQ(StatusCode::OK_200, res->status);
  8864. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8865. }
  8866. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8867. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  8868. Client cli("https://cdnjs.cloudflare.com");
  8869. auto res =
  8870. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  8871. ASSERT_TRUE(res);
  8872. EXPECT_EQ(StatusCode::OK_200, res->status);
  8873. EXPECT_EQ(287630U, res->body.size());
  8874. EXPECT_EQ("application/javascript; charset=utf-8",
  8875. res->get_header_value("Content-Type"));
  8876. }
  8877. #endif
  8878. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  8879. #undef REDIR_HOST // Silence compiler warning
  8880. #define REDIR_HOST "https://httpbingo.org"
  8881. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  8882. Client cli(REDIR_HOST);
  8883. cli.set_follow_location(true);
  8884. auto res =
  8885. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  8886. ASSERT_TRUE(res);
  8887. EXPECT_EQ(StatusCode::OK_200, res->status);
  8888. }
  8889. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  8890. Client cli(REDIR_HOST);
  8891. cli.set_follow_location(true);
  8892. Params params;
  8893. params.emplace("url", "http://example.com");
  8894. params.emplace("status_code", "302");
  8895. auto res = cli.Get(REDIR_PATH, params, Headers{});
  8896. ASSERT_TRUE(res);
  8897. EXPECT_EQ(StatusCode::OK_200, res->status);
  8898. }
  8899. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  8900. Client cli(REDIR_HOST);
  8901. cli.set_follow_location(true);
  8902. Params params;
  8903. params.emplace("url", "http://example.com");
  8904. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  8905. ASSERT_TRUE(res);
  8906. EXPECT_EQ(StatusCode::OK_200, res->status);
  8907. }
  8908. TEST(HttpToHttpsRedirectTest, CertFile) {
  8909. auto ssl_port = PORT + 1;
  8910. Server svr;
  8911. ASSERT_TRUE(svr.is_valid());
  8912. svr.Get("/index", [&](const Request &, Response &res) {
  8913. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  8914. "/index");
  8915. svr.stop();
  8916. });
  8917. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8918. ASSERT_TRUE(ssl_svr.is_valid());
  8919. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  8920. res.set_content("test", "text/plain");
  8921. ssl_svr.stop();
  8922. });
  8923. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8924. thread t2 =
  8925. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  8926. auto se = detail::scope_exit([&] {
  8927. t2.join();
  8928. t.join();
  8929. ASSERT_FALSE(svr.is_running());
  8930. });
  8931. svr.wait_until_ready();
  8932. ssl_svr.wait_until_ready();
  8933. Client cli("127.0.0.1", PORT);
  8934. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8935. cli.enable_server_certificate_verification(true);
  8936. cli.set_follow_location(true);
  8937. cli.set_connection_timeout(30);
  8938. auto res = cli.Get("/index");
  8939. ASSERT_TRUE(res);
  8940. ASSERT_EQ(StatusCode::OK_200, res->status);
  8941. }
  8942. TEST(SSLClientRedirectTest, CertFile) {
  8943. auto ssl_port = PORT + 1;
  8944. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8945. ASSERT_TRUE(ssl_svr1.is_valid());
  8946. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  8947. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  8948. "/index");
  8949. ssl_svr1.stop();
  8950. });
  8951. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8952. ASSERT_TRUE(ssl_svr2.is_valid());
  8953. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  8954. res.set_content("test", "text/plain");
  8955. ssl_svr2.stop();
  8956. });
  8957. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  8958. thread t2 =
  8959. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  8960. auto se = detail::scope_exit([&] {
  8961. t2.join();
  8962. t.join();
  8963. ASSERT_FALSE(ssl_svr1.is_running());
  8964. });
  8965. ssl_svr1.wait_until_ready();
  8966. ssl_svr2.wait_until_ready();
  8967. SSLClient cli("127.0.0.1", PORT);
  8968. std::string cert;
  8969. read_file(SERVER_CERT2_FILE, cert);
  8970. cli.load_ca_cert_store(cert.c_str(), cert.size());
  8971. cli.enable_server_certificate_verification(true);
  8972. cli.set_follow_location(true);
  8973. cli.set_connection_timeout(30);
  8974. auto res = cli.Get("/index");
  8975. ASSERT_TRUE(res);
  8976. ASSERT_EQ(StatusCode::OK_200, res->status);
  8977. }
  8978. #endif
  8979. #ifdef CPPHTTPLIB_SSL_ENABLED
  8980. // Test that set_ca_cert_store() skips system certs (consistent with
  8981. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  8982. // should be trusted - system certs should NOT be loaded.
  8983. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  8984. // Load a specific cert that is NOT a system CA cert
  8985. std::string cert;
  8986. read_file(SERVER_CERT2_FILE, cert);
  8987. SSLClient cli("google.com");
  8988. cli.load_ca_cert_store(cert.c_str(), cert.size());
  8989. cli.enable_server_certificate_verification(true);
  8990. // This should FAIL because:
  8991. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  8992. // 2. System certs should NOT be loaded when custom store is set
  8993. // If system certs WERE loaded, this would succeed
  8994. auto res = cli.Get("/");
  8995. ASSERT_FALSE(res);
  8996. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8997. }
  8998. TEST(MultipartFormDataTest, LargeData) {
  8999. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9000. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9001. const ContentReader &content_reader) {
  9002. if (req.is_multipart_form_data()) {
  9003. std::vector<FormData> items;
  9004. content_reader(
  9005. [&](const FormData &file) {
  9006. items.push_back(file);
  9007. return true;
  9008. },
  9009. [&](const char *data, size_t data_length) {
  9010. items.back().content.append(data, data_length);
  9011. return true;
  9012. });
  9013. EXPECT_TRUE(std::string(items[0].name) == "document");
  9014. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9015. EXPECT_TRUE(items[0].filename == "2MB_data");
  9016. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9017. EXPECT_TRUE(items[1].name == "hello");
  9018. EXPECT_TRUE(items[1].content == "world");
  9019. EXPECT_TRUE(items[1].filename == "");
  9020. EXPECT_TRUE(items[1].content_type == "");
  9021. } else {
  9022. std::string body;
  9023. content_reader([&](const char *data, size_t data_length) {
  9024. body.append(data, data_length);
  9025. return true;
  9026. });
  9027. }
  9028. });
  9029. auto port = svr.bind_to_any_port(HOST);
  9030. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9031. auto se = detail::scope_exit([&] {
  9032. svr.stop();
  9033. t.join();
  9034. ASSERT_FALSE(svr.is_running());
  9035. });
  9036. svr.wait_until_ready();
  9037. {
  9038. std::string data(1024 * 1024 * 2, '.');
  9039. std::stringstream buffer;
  9040. buffer << data;
  9041. SSLClient cli(HOST, port);
  9042. cli.enable_server_certificate_verification(false);
  9043. UploadFormDataItems items{
  9044. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9045. {"hello", "world", "", ""},
  9046. };
  9047. auto res = cli.Post("/post", items);
  9048. ASSERT_TRUE(res);
  9049. ASSERT_EQ(StatusCode::OK_200, res->status);
  9050. }
  9051. }
  9052. TEST(MultipartFormDataTest, DataProviderItems) {
  9053. std::random_device seed_gen;
  9054. std::mt19937 random(seed_gen());
  9055. std::string rand1;
  9056. rand1.resize(1000);
  9057. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9058. std::string rand2;
  9059. rand2.resize(3000);
  9060. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9061. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9062. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9063. const ContentReader &content_reader) {
  9064. ASSERT_FALSE(req.is_multipart_form_data());
  9065. std::string body;
  9066. content_reader([&](const char *data, size_t data_length) {
  9067. body.append(data, data_length);
  9068. return true;
  9069. });
  9070. EXPECT_EQ(body, "");
  9071. });
  9072. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9073. const ContentReader &content_reader) {
  9074. ASSERT_TRUE(req.is_multipart_form_data());
  9075. std::vector<FormData> items;
  9076. content_reader(
  9077. [&](const FormData &file) {
  9078. items.push_back(file);
  9079. return true;
  9080. },
  9081. [&](const char *data, size_t data_length) {
  9082. items.back().content.append(data, data_length);
  9083. return true;
  9084. });
  9085. ASSERT_TRUE(items.size() == 2);
  9086. EXPECT_EQ(std::string(items[0].name), "name1");
  9087. EXPECT_EQ(items[0].content, "Testing123");
  9088. EXPECT_EQ(items[0].filename, "filename1");
  9089. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9090. EXPECT_EQ(items[1].name, "name2");
  9091. EXPECT_EQ(items[1].content, "Testing456");
  9092. EXPECT_EQ(items[1].filename, "");
  9093. EXPECT_EQ(items[1].content_type, "");
  9094. });
  9095. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9096. const ContentReader &content_reader) {
  9097. ASSERT_TRUE(req.is_multipart_form_data());
  9098. std::vector<FormData> items;
  9099. content_reader(
  9100. [&](const FormData &file) {
  9101. items.push_back(file);
  9102. return true;
  9103. },
  9104. [&](const char *data, size_t data_length) {
  9105. items.back().content.append(data, data_length);
  9106. return true;
  9107. });
  9108. ASSERT_TRUE(items.size() == 2);
  9109. EXPECT_EQ(items[0].name, "name3");
  9110. EXPECT_EQ(items[0].content, rand1);
  9111. EXPECT_EQ(items[0].filename, "filename3");
  9112. EXPECT_EQ(items[0].content_type, "");
  9113. EXPECT_EQ(items[1].name, "name4");
  9114. EXPECT_EQ(items[1].content, rand2);
  9115. EXPECT_EQ(items[1].filename, "filename4");
  9116. EXPECT_EQ(items[1].content_type, "");
  9117. });
  9118. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9119. const ContentReader &content_reader) {
  9120. ASSERT_TRUE(req.is_multipart_form_data());
  9121. std::vector<FormData> items;
  9122. content_reader(
  9123. [&](const FormData &file) {
  9124. items.push_back(file);
  9125. return true;
  9126. },
  9127. [&](const char *data, size_t data_length) {
  9128. items.back().content.append(data, data_length);
  9129. return true;
  9130. });
  9131. ASSERT_TRUE(items.size() == 4);
  9132. EXPECT_EQ(std::string(items[0].name), "name1");
  9133. EXPECT_EQ(items[0].content, "Testing123");
  9134. EXPECT_EQ(items[0].filename, "filename1");
  9135. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9136. EXPECT_EQ(items[1].name, "name2");
  9137. EXPECT_EQ(items[1].content, "Testing456");
  9138. EXPECT_EQ(items[1].filename, "");
  9139. EXPECT_EQ(items[1].content_type, "");
  9140. EXPECT_EQ(items[2].name, "name3");
  9141. EXPECT_EQ(items[2].content, rand1);
  9142. EXPECT_EQ(items[2].filename, "filename3");
  9143. EXPECT_EQ(items[2].content_type, "");
  9144. EXPECT_EQ(items[3].name, "name4");
  9145. EXPECT_EQ(items[3].content, rand2);
  9146. EXPECT_EQ(items[3].filename, "filename4");
  9147. EXPECT_EQ(items[3].content_type, "");
  9148. });
  9149. auto port = svr.bind_to_any_port("localhost");
  9150. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9151. auto se = detail::scope_exit([&] {
  9152. svr.stop();
  9153. t.join();
  9154. ASSERT_FALSE(svr.is_running());
  9155. });
  9156. svr.wait_until_ready();
  9157. {
  9158. SSLClient cli("localhost", port);
  9159. cli.enable_server_certificate_verification(false);
  9160. UploadFormDataItems items{
  9161. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9162. {"name2", "Testing456", "", ""}, // not a file
  9163. };
  9164. {
  9165. auto res = cli.Post("/post-none", {}, {}, {});
  9166. ASSERT_TRUE(res);
  9167. ASSERT_EQ(StatusCode::OK_200, res->status);
  9168. }
  9169. FormDataProviderItems providers;
  9170. {
  9171. auto res =
  9172. cli.Post("/post-items", {}, items, providers); // empty providers
  9173. ASSERT_TRUE(res);
  9174. ASSERT_EQ(StatusCode::OK_200, res->status);
  9175. }
  9176. providers.push_back({"name3",
  9177. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9178. // test the offset is given correctly at each step
  9179. if (!offset)
  9180. sink.os.write(rand1.data(), 30);
  9181. else if (offset == 30)
  9182. sink.os.write(rand1.data() + 30, 300);
  9183. else if (offset == 330)
  9184. sink.os.write(rand1.data() + 330, 670);
  9185. else if (offset == rand1.size())
  9186. sink.done();
  9187. return true;
  9188. },
  9189. "filename3",
  9190. {}});
  9191. providers.push_back({"name4",
  9192. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9193. // test the offset is given correctly at each step
  9194. if (!offset)
  9195. sink.os.write(rand2.data(), 2000);
  9196. else if (offset == 2000)
  9197. sink.os.write(rand2.data() + 2000, 1);
  9198. else if (offset == 2001)
  9199. sink.os.write(rand2.data() + 2001, 999);
  9200. else if (offset == rand2.size())
  9201. sink.done();
  9202. return true;
  9203. },
  9204. "filename4",
  9205. {}});
  9206. {
  9207. auto res = cli.Post("/post-providers", {}, {}, providers);
  9208. ASSERT_TRUE(res);
  9209. ASSERT_EQ(StatusCode::OK_200, res->status);
  9210. }
  9211. {
  9212. auto res = cli.Post("/post-both", {}, items, providers);
  9213. ASSERT_TRUE(res);
  9214. ASSERT_EQ(StatusCode::OK_200, res->status);
  9215. }
  9216. }
  9217. }
  9218. TEST(MultipartFormDataTest, BadHeader) {
  9219. Server svr;
  9220. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9221. res.set_content("ok", "text/plain");
  9222. });
  9223. thread t = thread([&] { svr.listen(HOST, PORT); });
  9224. auto se = detail::scope_exit([&] {
  9225. svr.stop();
  9226. t.join();
  9227. ASSERT_FALSE(svr.is_running());
  9228. });
  9229. svr.wait_until_ready();
  9230. const std::string body =
  9231. "This is the preamble. It is to be ignored, though it\r\n"
  9232. "is a handy place for composition agents to include an\r\n"
  9233. "explanatory note to non-MIME conformant readers.\r\n"
  9234. "\r\n"
  9235. "\r\n"
  9236. "--simple boundary\r\n"
  9237. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9238. ": BAD...\r\n"
  9239. "\r\n"
  9240. "value1\r\n"
  9241. "--simple boundary\r\n"
  9242. "Content-Disposition: form-data; name=\"field2\"; "
  9243. "filename=\"example.txt\"\r\n"
  9244. "\r\n"
  9245. "value2\r\n"
  9246. "--simple boundary--\r\n"
  9247. "This is the epilogue. It is also to be ignored.\r\n";
  9248. std::string content_type =
  9249. R"(multipart/form-data; boundary="simple boundary")";
  9250. Client cli(HOST, PORT);
  9251. auto res = cli.Post("/post", body, content_type.c_str());
  9252. ASSERT_TRUE(res);
  9253. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9254. }
  9255. TEST(MultipartFormDataTest, WithPreamble) {
  9256. Server svr;
  9257. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9258. res.set_content("ok", "text/plain");
  9259. });
  9260. thread t = thread([&] { svr.listen(HOST, PORT); });
  9261. auto se = detail::scope_exit([&] {
  9262. svr.stop();
  9263. t.join();
  9264. ASSERT_FALSE(svr.is_running());
  9265. });
  9266. svr.wait_until_ready();
  9267. const std::string body =
  9268. "This is the preamble. It is to be ignored, though it\r\n"
  9269. "is a handy place for composition agents to include an\r\n"
  9270. "explanatory note to non-MIME conformant readers.\r\n"
  9271. "\r\n"
  9272. "\r\n"
  9273. "--simple boundary\r\n"
  9274. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9275. "\r\n"
  9276. "value1\r\n"
  9277. "--simple boundary\r\n"
  9278. "Content-Disposition: form-data; name=\"field2\"; "
  9279. "filename=\"example.txt\"\r\n"
  9280. "\r\n"
  9281. "value2\r\n"
  9282. "--simple boundary--\r\n"
  9283. "This is the epilogue. It is also to be ignored.\r\n";
  9284. std::string content_type =
  9285. R"(multipart/form-data; boundary="simple boundary")";
  9286. Client cli(HOST, PORT);
  9287. auto res = cli.Post("/post", body, content_type.c_str());
  9288. ASSERT_TRUE(res);
  9289. EXPECT_EQ(StatusCode::OK_200, res->status);
  9290. }
  9291. TEST(MultipartFormDataTest, PostCustomBoundary) {
  9292. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9293. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  9294. const ContentReader &content_reader) {
  9295. if (req.is_multipart_form_data()) {
  9296. std::vector<FormData> items;
  9297. content_reader(
  9298. [&](const FormData &file) {
  9299. items.push_back(file);
  9300. return true;
  9301. },
  9302. [&](const char *data, size_t data_length) {
  9303. items.back().content.append(data, data_length);
  9304. return true;
  9305. });
  9306. EXPECT_TRUE(std::string(items[0].name) == "document");
  9307. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9308. EXPECT_TRUE(items[0].filename == "2MB_data");
  9309. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9310. EXPECT_TRUE(items[1].name == "hello");
  9311. EXPECT_TRUE(items[1].content == "world");
  9312. EXPECT_TRUE(items[1].filename == "");
  9313. EXPECT_TRUE(items[1].content_type == "");
  9314. } else {
  9315. std::string body;
  9316. content_reader([&](const char *data, size_t data_length) {
  9317. body.append(data, data_length);
  9318. return true;
  9319. });
  9320. }
  9321. });
  9322. auto port = svr.bind_to_any_port("localhost");
  9323. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9324. auto se = detail::scope_exit([&] {
  9325. svr.stop();
  9326. t.join();
  9327. ASSERT_FALSE(svr.is_running());
  9328. });
  9329. svr.wait_until_ready();
  9330. {
  9331. std::string data(1024 * 1024 * 2, '.');
  9332. std::stringstream buffer;
  9333. buffer << data;
  9334. SSLClient cli("localhost", port);
  9335. cli.enable_server_certificate_verification(false);
  9336. UploadFormDataItems items{
  9337. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9338. {"hello", "world", "", ""},
  9339. };
  9340. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9341. ASSERT_TRUE(res);
  9342. ASSERT_EQ(StatusCode::OK_200, res->status);
  9343. }
  9344. }
  9345. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9346. std::string data(1024 * 1024 * 2, '&');
  9347. std::stringstream buffer;
  9348. buffer << data;
  9349. Client cli("https://localhost:8080");
  9350. UploadFormDataItems items{
  9351. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9352. {"hello", "world", "", ""},
  9353. };
  9354. for (const char &c : " \t\r\n") {
  9355. auto res =
  9356. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9357. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9358. ASSERT_FALSE(res);
  9359. }
  9360. }
  9361. TEST(MultipartFormDataTest, PutFormData) {
  9362. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9363. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9364. const ContentReader &content_reader) {
  9365. if (req.is_multipart_form_data()) {
  9366. std::vector<FormData> items;
  9367. content_reader(
  9368. [&](const FormData &file) {
  9369. items.push_back(file);
  9370. return true;
  9371. },
  9372. [&](const char *data, size_t data_length) {
  9373. items.back().content.append(data, data_length);
  9374. return true;
  9375. });
  9376. EXPECT_TRUE(std::string(items[0].name) == "document");
  9377. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9378. EXPECT_TRUE(items[0].filename == "2MB_data");
  9379. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9380. EXPECT_TRUE(items[1].name == "hello");
  9381. EXPECT_TRUE(items[1].content == "world");
  9382. EXPECT_TRUE(items[1].filename == "");
  9383. EXPECT_TRUE(items[1].content_type == "");
  9384. } else {
  9385. std::string body;
  9386. content_reader([&](const char *data, size_t data_length) {
  9387. body.append(data, data_length);
  9388. return true;
  9389. });
  9390. }
  9391. });
  9392. auto port = svr.bind_to_any_port("localhost");
  9393. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9394. auto se = detail::scope_exit([&] {
  9395. svr.stop();
  9396. t.join();
  9397. ASSERT_FALSE(svr.is_running());
  9398. });
  9399. svr.wait_until_ready();
  9400. {
  9401. std::string data(1024 * 1024 * 2, '&');
  9402. std::stringstream buffer;
  9403. buffer << data;
  9404. SSLClient cli("localhost", port);
  9405. cli.enable_server_certificate_verification(false);
  9406. UploadFormDataItems items{
  9407. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9408. {"hello", "world", "", ""},
  9409. };
  9410. auto res = cli.Put("/put", items);
  9411. ASSERT_TRUE(res);
  9412. ASSERT_EQ(StatusCode::OK_200, res->status);
  9413. }
  9414. }
  9415. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  9416. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9417. svr.Put("/put_customboundary",
  9418. [&](const Request &req, const Response & /*res*/,
  9419. const ContentReader &content_reader) {
  9420. if (req.is_multipart_form_data()) {
  9421. std::vector<FormData> items;
  9422. content_reader(
  9423. [&](const FormData &file) {
  9424. items.push_back(file);
  9425. return true;
  9426. },
  9427. [&](const char *data, size_t data_length) {
  9428. items.back().content.append(data, data_length);
  9429. return true;
  9430. });
  9431. EXPECT_TRUE(std::string(items[0].name) == "document");
  9432. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9433. EXPECT_TRUE(items[0].filename == "2MB_data");
  9434. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9435. EXPECT_TRUE(items[1].name == "hello");
  9436. EXPECT_TRUE(items[1].content == "world");
  9437. EXPECT_TRUE(items[1].filename == "");
  9438. EXPECT_TRUE(items[1].content_type == "");
  9439. } else {
  9440. std::string body;
  9441. content_reader([&](const char *data, size_t data_length) {
  9442. body.append(data, data_length);
  9443. return true;
  9444. });
  9445. }
  9446. });
  9447. auto port = svr.bind_to_any_port("localhost");
  9448. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9449. auto se = detail::scope_exit([&] {
  9450. svr.stop();
  9451. t.join();
  9452. ASSERT_FALSE(svr.is_running());
  9453. });
  9454. svr.wait_until_ready();
  9455. {
  9456. std::string data(1024 * 1024 * 2, '&');
  9457. std::stringstream buffer;
  9458. buffer << data;
  9459. SSLClient cli("localhost", port);
  9460. cli.enable_server_certificate_verification(false);
  9461. UploadFormDataItems items{
  9462. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9463. {"hello", "world", "", ""},
  9464. };
  9465. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  9466. ASSERT_TRUE(res);
  9467. ASSERT_EQ(StatusCode::OK_200, res->status);
  9468. }
  9469. }
  9470. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  9471. std::string data(1024 * 1024 * 2, '&');
  9472. std::stringstream buffer;
  9473. buffer << data;
  9474. Client cli("https://localhost:8080");
  9475. cli.enable_server_certificate_verification(false);
  9476. UploadFormDataItems items{
  9477. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9478. {"hello", "world", "", ""},
  9479. };
  9480. for (const char &c : " \t\r\n") {
  9481. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  9482. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9483. ASSERT_FALSE(res);
  9484. }
  9485. }
  9486. TEST(MultipartFormDataTest, AlternateFilename) {
  9487. auto handled = false;
  9488. Server svr;
  9489. svr.Post("/test", [&](const Request &req, Response &res) {
  9490. ASSERT_EQ(2u, req.form.files.size());
  9491. ASSERT_EQ(1u, req.form.fields.size());
  9492. // Test files
  9493. const auto &file1 = req.form.get_file("file1");
  9494. ASSERT_EQ("file1", file1.name);
  9495. ASSERT_EQ("A.txt", file1.filename);
  9496. ASSERT_EQ("text/plain", file1.content_type);
  9497. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  9498. const auto &file2 = req.form.get_file("file2");
  9499. ASSERT_EQ("file2", file2.name);
  9500. ASSERT_EQ("a.html", file2.filename);
  9501. ASSERT_EQ("text/html", file2.content_type);
  9502. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  9503. file2.content);
  9504. // Test text field
  9505. const auto &text = req.form.get_field("text");
  9506. ASSERT_EQ("text default", text);
  9507. res.set_content("ok", "text/plain");
  9508. handled = true;
  9509. });
  9510. thread t = thread([&] { svr.listen(HOST, PORT); });
  9511. auto se = detail::scope_exit([&] {
  9512. svr.stop();
  9513. t.join();
  9514. ASSERT_FALSE(svr.is_running());
  9515. ASSERT_TRUE(handled);
  9516. });
  9517. svr.wait_until_ready();
  9518. auto req = "POST /test HTTP/1.1\r\n"
  9519. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9520. "Content-Length: 399\r\n"
  9521. "\r\n"
  9522. "----------\r\n"
  9523. "Content-Disposition: form-data; name=\"text\"\r\n"
  9524. "\r\n"
  9525. "text default\r\n"
  9526. "----------\r\n"
  9527. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  9528. "filename=\"a.txt\"; name=\"file1\"\r\n"
  9529. "Content-Type: text/plain\r\n"
  9530. "\r\n"
  9531. "Content of a.txt.\r\n"
  9532. "\r\n"
  9533. "----------\r\n"
  9534. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  9535. "\"a.html\"\r\n"
  9536. "Content-Type: text/html\r\n"
  9537. "\r\n"
  9538. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  9539. "\r\n"
  9540. "------------\r\n";
  9541. ASSERT_TRUE(send_request(1, req));
  9542. }
  9543. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  9544. auto handled = false;
  9545. Server svr;
  9546. svr.Post("/test", [&](const Request &req, Response &) {
  9547. ASSERT_EQ(2u, req.form.fields.size());
  9548. const auto &text1 = req.form.get_field("text1");
  9549. ASSERT_EQ("text1", text1);
  9550. const auto &text2 = req.form.get_field("text2");
  9551. ASSERT_EQ("text2", text2);
  9552. handled = true;
  9553. });
  9554. thread t = thread([&] { svr.listen(HOST, PORT); });
  9555. auto se = detail::scope_exit([&] {
  9556. svr.stop();
  9557. t.join();
  9558. ASSERT_FALSE(svr.is_running());
  9559. ASSERT_TRUE(handled);
  9560. });
  9561. svr.wait_until_ready();
  9562. auto req = "POST /test HTTP/1.1\r\n"
  9563. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9564. "Content-Length: 146\r\n"
  9565. "\r\n----------\r\n"
  9566. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9567. "\r\n"
  9568. "text1"
  9569. "\r\n----------\r\n"
  9570. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9571. "\r\n"
  9572. "text2"
  9573. "\r\n------------";
  9574. std::string response;
  9575. ASSERT_TRUE(send_request(1, req, &response));
  9576. ASSERT_EQ("200", response.substr(9, 3));
  9577. }
  9578. TEST(MultipartFormDataTest, ContentLength) {
  9579. auto handled = false;
  9580. Server svr;
  9581. svr.Post("/test", [&](const Request &req, Response &) {
  9582. ASSERT_EQ(2u, req.form.fields.size());
  9583. const auto &text1 = req.form.get_field("text1");
  9584. ASSERT_EQ("text1", text1);
  9585. const auto &text2 = req.form.get_field("text2");
  9586. ASSERT_EQ("text2", text2);
  9587. handled = true;
  9588. });
  9589. thread t = thread([&] { svr.listen(HOST, PORT); });
  9590. auto se = detail::scope_exit([&] {
  9591. svr.stop();
  9592. t.join();
  9593. ASSERT_FALSE(svr.is_running());
  9594. ASSERT_TRUE(handled);
  9595. });
  9596. svr.wait_until_ready();
  9597. auto req = "POST /test HTTP/1.1\r\n"
  9598. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9599. "Content-Length: 167\r\n"
  9600. "\r\n----------\r\n"
  9601. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9602. "Content-Length: 5\r\n"
  9603. "\r\n"
  9604. "text1"
  9605. "\r\n----------\r\n"
  9606. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9607. "\r\n"
  9608. "text2"
  9609. "\r\n------------\r\n";
  9610. std::string response;
  9611. ASSERT_TRUE(send_request(1, req, &response));
  9612. ASSERT_EQ("200", response.substr(9, 3));
  9613. }
  9614. TEST(MultipartFormDataTest, AccessPartHeaders) {
  9615. auto handled = false;
  9616. Server svr;
  9617. svr.Post("/test", [&](const Request &req, Response &) {
  9618. ASSERT_EQ(2u, req.form.fields.size());
  9619. const auto &text1 = req.form.get_field("text1");
  9620. ASSERT_EQ("text1", text1);
  9621. // TODO: Add header access for text fields if needed
  9622. const auto &text2 = req.form.get_field("text2");
  9623. ASSERT_EQ("text2", text2);
  9624. // TODO: Header access for text fields needs to be implemented
  9625. // auto &headers = it->second.headers;
  9626. // ASSERT_EQ(3U, headers.size());
  9627. // auto custom_header = headers.find("x-whatever");
  9628. // ASSERT_TRUE(custom_header != headers.end());
  9629. // ASSERT_NE("customvalue", custom_header->second);
  9630. // ASSERT_EQ("CustomValue", custom_header->second);
  9631. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  9632. handled = true;
  9633. });
  9634. thread t = thread([&] { svr.listen(HOST, PORT); });
  9635. auto se = detail::scope_exit([&] {
  9636. svr.stop();
  9637. t.join();
  9638. ASSERT_FALSE(svr.is_running());
  9639. ASSERT_TRUE(handled);
  9640. });
  9641. svr.wait_until_ready();
  9642. auto req = "POST /test HTTP/1.1\r\n"
  9643. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9644. "Content-Length: 232\r\n"
  9645. "\r\n----------\r\n"
  9646. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9647. "Content-Length: 5\r\n"
  9648. "X-Test: 1\r\n"
  9649. "\r\n"
  9650. "text1"
  9651. "\r\n----------\r\n"
  9652. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9653. "Content-Type: text/plain\r\n"
  9654. "X-Whatever: CustomValue\r\n"
  9655. "\r\n"
  9656. "text2"
  9657. "\r\n------------\r\n"
  9658. "That should be disregarded. Not even read";
  9659. std::string response;
  9660. ASSERT_TRUE(send_request(1, req, &response));
  9661. ASSERT_EQ("200", response.substr(9, 3));
  9662. }
  9663. TEST(MultipartFormDataTest, LargeHeader) {
  9664. auto handled = false;
  9665. Server svr;
  9666. svr.Post("/test", [&](const Request &req, Response &) {
  9667. ASSERT_EQ(1u, req.form.fields.size());
  9668. const auto &text = req.form.get_field("name1");
  9669. ASSERT_EQ("text1", text);
  9670. handled = true;
  9671. });
  9672. thread t = thread([&] { svr.listen(HOST, PORT); });
  9673. auto se = detail::scope_exit([&] {
  9674. svr.stop();
  9675. t.join();
  9676. ASSERT_FALSE(svr.is_running());
  9677. ASSERT_TRUE(handled);
  9678. });
  9679. svr.wait_until_ready();
  9680. auto boundary = std::string("cpp-httplib-multipart-data");
  9681. std::string content = "--" + boundary +
  9682. "\r\n"
  9683. "Content-Disposition: form-data; name=\"name1\"\r\n"
  9684. "\r\n"
  9685. "text1\r\n"
  9686. "--" +
  9687. boundary + "--\r\n";
  9688. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  9689. "Content-Type: multipart/form-data;boundary=" +
  9690. boundary +
  9691. "\r\n"
  9692. "Content-Length: " +
  9693. std::to_string(content.size()) +
  9694. "\r\n"
  9695. "Dummy-Header: ";
  9696. std::string header_suffix = "\r\n"
  9697. "\r\n";
  9698. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  9699. size_t header_dummy_size =
  9700. read_buff_size -
  9701. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  9702. auto header_dummy = std::string(header_dummy_size, '@');
  9703. auto req = header_prefix + header_dummy + header_suffix + content;
  9704. std::string response;
  9705. ASSERT_TRUE(send_request(1, req, &response));
  9706. ASSERT_EQ("200", response.substr(9, 3));
  9707. }
  9708. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  9709. static constexpr unsigned int number_of_tasks{1000000};
  9710. std::atomic_uint count{0};
  9711. std::unique_ptr<TaskQueue> task_queue{
  9712. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  9713. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  9714. auto queued = task_queue->enqueue(
  9715. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  9716. EXPECT_TRUE(queued);
  9717. }
  9718. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  9719. task_queue->shutdown();
  9720. #else
  9721. EXPECT_NO_THROW(task_queue->shutdown());
  9722. #endif
  9723. EXPECT_EQ(number_of_tasks, count.load());
  9724. }
  9725. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  9726. static constexpr unsigned int number_of_tasks{1000000};
  9727. static constexpr unsigned int qlimit{2};
  9728. unsigned int queued_count{0};
  9729. std::atomic_uint count{0};
  9730. std::unique_ptr<TaskQueue> task_queue{
  9731. new ThreadPool{/*num_threads=*/1, qlimit}};
  9732. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  9733. if (task_queue->enqueue(
  9734. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  9735. queued_count++;
  9736. }
  9737. }
  9738. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  9739. task_queue->shutdown();
  9740. #else
  9741. EXPECT_NO_THROW(task_queue->shutdown());
  9742. #endif
  9743. EXPECT_EQ(queued_count, count.load());
  9744. EXPECT_TRUE(queued_count <= number_of_tasks);
  9745. EXPECT_TRUE(queued_count >= qlimit);
  9746. }
  9747. TEST(TaskQueueTest, MaxQueuedRequests) {
  9748. static constexpr unsigned int qlimit{3};
  9749. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  9750. std::condition_variable sem_cv;
  9751. std::mutex sem_mtx;
  9752. int credits = 0;
  9753. bool queued;
  9754. /* Fill up the queue with tasks that will block until we give them credits to
  9755. * complete. */
  9756. for (unsigned int n = 0; n <= qlimit;) {
  9757. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  9758. std::unique_lock<std::mutex> lock(sem_mtx);
  9759. while (credits <= 0) {
  9760. sem_cv.wait(lock);
  9761. }
  9762. /* Consume the credit and signal the test code if they are all gone. */
  9763. if (--credits == 0) { sem_cv.notify_one(); }
  9764. });
  9765. if (n < qlimit) {
  9766. /* The first qlimit enqueues must succeed. */
  9767. EXPECT_TRUE(queued);
  9768. } else {
  9769. /* The last one will succeed only when the worker thread
  9770. * starts and dequeues the first blocking task. Although
  9771. * not necessary for the correctness of this test, we sleep for
  9772. * a short while to avoid busy waiting. */
  9773. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  9774. }
  9775. if (queued) { n++; }
  9776. }
  9777. /* Further enqueues must fail since the queue is full. */
  9778. for (auto i = 0; i < 4; i++) {
  9779. queued = task_queue->enqueue([] {});
  9780. EXPECT_FALSE(queued);
  9781. }
  9782. /* Give the credits to allow the previous tasks to complete. */
  9783. {
  9784. std::unique_lock<std::mutex> lock(sem_mtx);
  9785. credits += qlimit + 1;
  9786. }
  9787. sem_cv.notify_all();
  9788. /* Wait for all the credits to be consumed. */
  9789. {
  9790. std::unique_lock<std::mutex> lock(sem_mtx);
  9791. while (credits > 0) {
  9792. sem_cv.wait(lock);
  9793. }
  9794. }
  9795. /* Check that we are able again to enqueue at least qlimit tasks. */
  9796. for (unsigned int i = 0; i < qlimit; i++) {
  9797. queued = task_queue->enqueue([] {});
  9798. EXPECT_TRUE(queued);
  9799. }
  9800. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  9801. task_queue->shutdown();
  9802. #else
  9803. EXPECT_NO_THROW(task_queue->shutdown());
  9804. #endif
  9805. }
  9806. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  9807. Server svr;
  9808. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9809. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  9810. });
  9811. svr.Get("/hello", [](const Request &req, Response &res) {
  9812. res.set_content(req.get_param_value("key"), "text/plain");
  9813. });
  9814. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9815. auto se = detail::scope_exit([&] {
  9816. svr.stop();
  9817. thread.join();
  9818. ASSERT_FALSE(svr.is_running());
  9819. });
  9820. svr.wait_until_ready();
  9821. {
  9822. Client cli(HOST, PORT);
  9823. cli.set_follow_location(true);
  9824. auto res = cli.Get("/");
  9825. ASSERT_TRUE(res);
  9826. EXPECT_EQ(StatusCode::OK_200, res->status);
  9827. EXPECT_EQ("val&key2=val2", res->body);
  9828. }
  9829. }
  9830. #endif
  9831. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  9832. Server svr;
  9833. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9834. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  9835. });
  9836. svr.Get("/hello", [](const Request &req, Response &res) {
  9837. res.set_content(req.get_param_value("key"), "text/plain");
  9838. });
  9839. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9840. auto se = detail::scope_exit([&] {
  9841. svr.stop();
  9842. thread.join();
  9843. ASSERT_FALSE(svr.is_running());
  9844. });
  9845. svr.wait_until_ready();
  9846. {
  9847. Client cli(HOST, PORT);
  9848. cli.set_follow_location(true);
  9849. auto res = cli.Get("/");
  9850. ASSERT_TRUE(res);
  9851. EXPECT_EQ(StatusCode::OK_200, res->status);
  9852. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  9853. }
  9854. }
  9855. #ifdef CPPHTTPLIB_SSL_ENABLED
  9856. TEST(RedirectTest, Issue2185_Online) {
  9857. SSLClient client("github.com");
  9858. client.set_follow_location(true);
  9859. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  9860. "Coollab-Windows.zip");
  9861. ASSERT_TRUE(res);
  9862. EXPECT_EQ(StatusCode::OK_200, res->status);
  9863. EXPECT_EQ(9920427U, res->body.size());
  9864. }
  9865. #endif
  9866. TEST(VulnerabilityTest, CRLFInjection) {
  9867. Server svr;
  9868. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  9869. res.set_content("Hello 1", "text/plain");
  9870. });
  9871. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  9872. res.set_content("Hello 2", "text/plain");
  9873. });
  9874. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  9875. res.set_content("Hello 3", "text/plain");
  9876. });
  9877. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  9878. res.set_content("Hello 4", "text/plain");
  9879. });
  9880. svr.set_logger([](const Request &req, const Response & /*res*/) {
  9881. for (const auto &x : req.headers) {
  9882. auto key = x.first;
  9883. EXPECT_STRNE("evil", key.c_str());
  9884. }
  9885. });
  9886. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9887. auto se = detail::scope_exit([&] {
  9888. svr.stop();
  9889. thread.join();
  9890. ASSERT_FALSE(svr.is_running());
  9891. });
  9892. svr.wait_until_ready();
  9893. {
  9894. Client cli(HOST, PORT);
  9895. cli.Post("/test1", "A=B",
  9896. "application/x-www-form-urlencoded\r\nevil: hello1");
  9897. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  9898. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  9899. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  9900. }
  9901. }
  9902. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  9903. auto server_thread = std::thread([] {
  9904. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9905. default_socket_options(srv);
  9906. sockaddr_in addr{};
  9907. addr.sin_family = AF_INET;
  9908. addr.sin_port = htons(PORT + 1);
  9909. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9910. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9911. ::listen(srv, 1);
  9912. sockaddr_in cli_addr{};
  9913. socklen_t cli_len = sizeof(cli_addr);
  9914. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9915. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  9916. std::string buf_all;
  9917. char buf[2048];
  9918. ssize_t n;
  9919. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  9920. buf_all.append(buf, static_cast<size_t>(n));
  9921. size_t pos;
  9922. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  9923. auto request_block = buf_all.substr(0, pos + 4); // include separator
  9924. auto e = request_block.find("\r\n");
  9925. if (e != std::string::npos) {
  9926. auto request_line = request_block.substr(0, e);
  9927. std::string msg =
  9928. "CRLF injection detected in request line: '" + request_line + "'";
  9929. EXPECT_FALSE(true) << msg;
  9930. }
  9931. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  9932. ::send(cli,
  9933. #ifdef _WIN32
  9934. static_cast<const char *>(resp.c_str()),
  9935. static_cast<int>(resp.size()),
  9936. #else
  9937. resp.c_str(), resp.size(),
  9938. #endif
  9939. 0);
  9940. buf_all.erase(0, pos + 4);
  9941. }
  9942. }
  9943. detail::close_socket(cli);
  9944. detail::close_socket(srv);
  9945. });
  9946. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9947. auto cli = Client("127.0.0.1", PORT + 1);
  9948. auto headers = Headers{
  9949. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  9950. {"Connection", "keep-alive"}};
  9951. auto res = cli.Get("/hi", headers);
  9952. EXPECT_FALSE(res);
  9953. EXPECT_EQ(Error::InvalidHeaders, res.error());
  9954. server_thread.join();
  9955. }
  9956. TEST(PathParamsTest, StaticMatch) {
  9957. const auto pattern = "/users/all";
  9958. detail::PathParamsMatcher matcher(pattern);
  9959. Request request;
  9960. request.path = "/users/all";
  9961. ASSERT_TRUE(matcher.match(request));
  9962. std::unordered_map<std::string, std::string> expected_params = {};
  9963. EXPECT_EQ(request.path_params, expected_params);
  9964. }
  9965. TEST(PathParamsTest, StaticMismatch) {
  9966. const auto pattern = "/users/all";
  9967. detail::PathParamsMatcher matcher(pattern);
  9968. Request request;
  9969. request.path = "/users/1";
  9970. ASSERT_FALSE(matcher.match(request));
  9971. }
  9972. TEST(PathParamsTest, SingleParamInTheMiddle) {
  9973. const auto pattern = "/users/:id/subscriptions";
  9974. detail::PathParamsMatcher matcher(pattern);
  9975. Request request;
  9976. request.path = "/users/42/subscriptions";
  9977. ASSERT_TRUE(matcher.match(request));
  9978. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  9979. EXPECT_EQ(request.path_params, expected_params);
  9980. }
  9981. TEST(PathParamsTest, SingleParamInTheEnd) {
  9982. const auto pattern = "/users/:id";
  9983. detail::PathParamsMatcher matcher(pattern);
  9984. Request request;
  9985. request.path = "/users/24";
  9986. ASSERT_TRUE(matcher.match(request));
  9987. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  9988. EXPECT_EQ(request.path_params, expected_params);
  9989. }
  9990. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  9991. const auto pattern = "/users/:id/";
  9992. detail::PathParamsMatcher matcher(pattern);
  9993. Request request;
  9994. request.path = "/users/42/";
  9995. ASSERT_TRUE(matcher.match(request));
  9996. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  9997. EXPECT_EQ(request.path_params, expected_params);
  9998. }
  9999. TEST(PathParamsTest, EmptyParam) {
  10000. const auto pattern = "/users/:id/";
  10001. detail::PathParamsMatcher matcher(pattern);
  10002. Request request;
  10003. request.path = "/users//";
  10004. ASSERT_TRUE(matcher.match(request));
  10005. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10006. EXPECT_EQ(request.path_params, expected_params);
  10007. }
  10008. TEST(PathParamsTest, FragmentMismatch) {
  10009. const auto pattern = "/users/:id/";
  10010. detail::PathParamsMatcher matcher(pattern);
  10011. Request request;
  10012. request.path = "/admins/24/";
  10013. ASSERT_FALSE(matcher.match(request));
  10014. }
  10015. TEST(PathParamsTest, ExtraFragments) {
  10016. const auto pattern = "/users/:id";
  10017. detail::PathParamsMatcher matcher(pattern);
  10018. Request request;
  10019. request.path = "/users/42/subscriptions";
  10020. ASSERT_FALSE(matcher.match(request));
  10021. }
  10022. TEST(PathParamsTest, MissingTrailingParam) {
  10023. const auto pattern = "/users/:id";
  10024. detail::PathParamsMatcher matcher(pattern);
  10025. Request request;
  10026. request.path = "/users";
  10027. ASSERT_FALSE(matcher.match(request));
  10028. }
  10029. TEST(PathParamsTest, MissingParamInTheMiddle) {
  10030. const auto pattern = "/users/:id/subscriptions";
  10031. detail::PathParamsMatcher matcher(pattern);
  10032. Request request;
  10033. request.path = "/users/subscriptions";
  10034. ASSERT_FALSE(matcher.match(request));
  10035. }
  10036. TEST(PathParamsTest, MultipleParams) {
  10037. const auto pattern = "/users/:userid/subscriptions/:subid";
  10038. detail::PathParamsMatcher matcher(pattern);
  10039. Request request;
  10040. request.path = "/users/42/subscriptions/2";
  10041. ASSERT_TRUE(matcher.match(request));
  10042. std::unordered_map<std::string, std::string> expected_params = {
  10043. {"userid", "42"}, {"subid", "2"}};
  10044. EXPECT_EQ(request.path_params, expected_params);
  10045. }
  10046. TEST(PathParamsTest, SequenceOfParams) {
  10047. const auto pattern = "/values/:x/:y/:z";
  10048. detail::PathParamsMatcher matcher(pattern);
  10049. Request request;
  10050. request.path = "/values/1/2/3";
  10051. ASSERT_TRUE(matcher.match(request));
  10052. std::unordered_map<std::string, std::string> expected_params = {
  10053. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  10054. EXPECT_EQ(request.path_params, expected_params);
  10055. }
  10056. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  10057. const auto pattern = "/prefix:suffix";
  10058. detail::PathParamsMatcher matcher(pattern);
  10059. Request request;
  10060. request.path = "/prefix:suffix";
  10061. ASSERT_TRUE(matcher.match(request));
  10062. const std::unordered_map<std::string, std::string> expected_params = {};
  10063. EXPECT_EQ(request.path_params, expected_params);
  10064. }
  10065. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  10066. // If ipv6 regex working, regex match codepath is taken.
  10067. // else port will default to 80 in Client impl
  10068. int clientImplMagicPort = 80;
  10069. int port = 4321;
  10070. // above ports must be different to avoid false negative
  10071. EXPECT_NE(clientImplMagicPort, port);
  10072. std::string ipV6TestURL = "http://[ff06::c3]";
  10073. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  10074. CLIENT_PRIVATE_KEY_FILE);
  10075. EXPECT_EQ(cli.port(), port);
  10076. }
  10077. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  10078. auto file_path = "./www/dir/index.html";
  10079. auto dir_path = "./www/dir";
  10080. detail::FileStat stat_file(file_path);
  10081. EXPECT_TRUE(stat_file.is_file());
  10082. EXPECT_FALSE(stat_file.is_dir());
  10083. detail::FileStat stat_dir(dir_path);
  10084. EXPECT_FALSE(stat_dir.is_file());
  10085. EXPECT_TRUE(stat_dir.is_dir());
  10086. }
  10087. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  10088. // IPv4 with default HTTP port (80)
  10089. EXPECT_EQ("example.com",
  10090. detail::make_host_and_port_string("example.com", 80, false));
  10091. // IPv4 with default HTTPS port (443)
  10092. EXPECT_EQ("example.com",
  10093. detail::make_host_and_port_string("example.com", 443, true));
  10094. // IPv4 with non-default HTTP port
  10095. EXPECT_EQ("example.com:8080",
  10096. detail::make_host_and_port_string("example.com", 8080, false));
  10097. // IPv4 with non-default HTTPS port
  10098. EXPECT_EQ("example.com:8443",
  10099. detail::make_host_and_port_string("example.com", 8443, true));
  10100. // IPv6 with default HTTP port (80)
  10101. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  10102. // IPv6 with default HTTPS port (443)
  10103. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  10104. // IPv6 with non-default HTTP port
  10105. EXPECT_EQ("[::1]:8080",
  10106. detail::make_host_and_port_string("::1", 8080, false));
  10107. // IPv6 with non-default HTTPS port
  10108. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  10109. // IPv6 full address with default port
  10110. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  10111. detail::make_host_and_port_string(
  10112. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  10113. // IPv6 full address with non-default port
  10114. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  10115. detail::make_host_and_port_string(
  10116. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  10117. // IPv6 localhost with non-default port
  10118. EXPECT_EQ("[::1]:3000",
  10119. detail::make_host_and_port_string("::1", 3000, false));
  10120. // IPv6 with zone ID (link-local address) with default port
  10121. EXPECT_EQ("[fe80::1%eth0]",
  10122. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  10123. // IPv6 with zone ID (link-local address) with non-default port
  10124. EXPECT_EQ("[fe80::1%eth0]:8080",
  10125. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  10126. // Edge case: Port 443 with is_ssl=false (should add port)
  10127. EXPECT_EQ("example.com:443",
  10128. detail::make_host_and_port_string("example.com", 443, false));
  10129. // Edge case: Port 80 with is_ssl=true (should add port)
  10130. EXPECT_EQ("example.com:80",
  10131. detail::make_host_and_port_string("example.com", 80, true));
  10132. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  10133. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  10134. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  10135. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  10136. // Security fix: Already bracketed IPv6 should not get double brackets
  10137. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  10138. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  10139. EXPECT_EQ("[::1]:8080",
  10140. detail::make_host_and_port_string("[::1]", 8080, false));
  10141. EXPECT_EQ("[2001:db8::1]:8080",
  10142. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  10143. EXPECT_EQ("[fe80::1%eth0]",
  10144. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  10145. EXPECT_EQ("[fe80::1%eth0]:8080",
  10146. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  10147. // Edge case: Empty host (should return as-is)
  10148. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  10149. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  10150. // This is a known limitation but shouldn't crash
  10151. EXPECT_EQ("[host:name]",
  10152. detail::make_host_and_port_string("host:name", 80, false));
  10153. // Port number edge cases (no validation, but should not crash)
  10154. EXPECT_EQ("example.com:0",
  10155. detail::make_host_and_port_string("example.com", 0, false));
  10156. EXPECT_EQ("example.com:-1",
  10157. detail::make_host_and_port_string("example.com", -1, false));
  10158. EXPECT_EQ("example.com:65535",
  10159. detail::make_host_and_port_string("example.com", 65535, false));
  10160. EXPECT_EQ("example.com:65536",
  10161. detail::make_host_and_port_string("example.com", 65536, false));
  10162. }
  10163. #ifdef CPPHTTPLIB_SSL_ENABLED
  10164. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  10165. httplib::SSLClient cli("roblox.com", 443);
  10166. cli.set_follow_location(true);
  10167. auto res = cli.Get("/");
  10168. ASSERT_TRUE(res);
  10169. EXPECT_EQ(StatusCode::OK_200, res->status);
  10170. }
  10171. #endif
  10172. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  10173. Server svr;
  10174. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10175. EXPECT_EQ(res.status, 400);
  10176. });
  10177. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10178. auto se = detail::scope_exit([&] {
  10179. svr.stop();
  10180. thread.join();
  10181. ASSERT_FALSE(svr.is_running());
  10182. });
  10183. svr.wait_until_ready();
  10184. Client cli(HOST, PORT);
  10185. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  10186. }
  10187. TEST(InvalidHeaderCharsTest, is_field_name) {
  10188. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  10189. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  10190. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  10191. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  10192. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  10193. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  10194. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  10195. EXPECT_FALSE(detail::fields::is_field_name(""));
  10196. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  10197. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  10198. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  10199. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  10200. }
  10201. TEST(InvalidHeaderCharsTest, is_field_value) {
  10202. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  10203. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  10204. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  10205. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  10206. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  10207. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  10208. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  10209. EXPECT_TRUE(detail::fields::is_field_value(""));
  10210. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  10211. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  10212. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  10213. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  10214. EXPECT_TRUE(detail::fields::is_field_value("0"));
  10215. }
  10216. TEST(InvalidHeaderCharsTest, OnServer) {
  10217. Server svr;
  10218. svr.Get("/test_name", [&](const Request &req, Response &res) {
  10219. std::string header = "Not Set";
  10220. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10221. res.set_header(header, "value");
  10222. res.set_content("Page Content Page Content", "text/plain");
  10223. });
  10224. svr.Get("/test_value", [&](const Request &req, Response &res) {
  10225. std::string header = "Not Set";
  10226. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10227. res.set_header("X-Test", header);
  10228. res.set_content("Page Content Page Content", "text/plain");
  10229. });
  10230. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10231. auto se = detail::scope_exit([&] {
  10232. svr.stop();
  10233. thread.join();
  10234. ASSERT_FALSE(svr.is_running());
  10235. });
  10236. svr.wait_until_ready();
  10237. Client cli(HOST, PORT);
  10238. {
  10239. auto res = cli.Get(
  10240. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10241. ASSERT_TRUE(res);
  10242. EXPECT_EQ("Page Content Page Content", res->body);
  10243. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10244. }
  10245. {
  10246. auto res = cli.Get(
  10247. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10248. ASSERT_TRUE(res);
  10249. EXPECT_EQ("Page Content Page Content", res->body);
  10250. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10251. }
  10252. }
  10253. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  10254. auto handled = false;
  10255. Server svr;
  10256. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10257. thread t = thread([&] { svr.listen(HOST, PORT); });
  10258. auto se = detail::scope_exit([&] {
  10259. svr.stop();
  10260. t.join();
  10261. ASSERT_FALSE(svr.is_running());
  10262. ASSERT_FALSE(handled);
  10263. });
  10264. svr.wait_until_ready();
  10265. auto req = "POST /test HTTP/1.1\r\n"
  10266. "Content-Length: x\r\n"
  10267. "\r\n";
  10268. std::string response;
  10269. ASSERT_TRUE(send_request(1, req, &response));
  10270. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10271. response.substr(0, response.find("\r\n")));
  10272. }
  10273. #ifndef _WIN32
  10274. TEST(Expect100ContinueTest, ServerClosesConnection) {
  10275. static constexpr char reject[] = "Unauthorized";
  10276. static constexpr char accept[] = "Upload accepted";
  10277. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  10278. Server svr;
  10279. svr.set_expect_100_continue_handler(
  10280. [](const Request & /*req*/, Response &res) {
  10281. res.status = StatusCode::Unauthorized_401;
  10282. res.set_content(reject, "text/plain");
  10283. return res.status;
  10284. });
  10285. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  10286. res.set_content(accept, "text/plain");
  10287. });
  10288. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10289. auto se = detail::scope_exit([&] {
  10290. svr.stop();
  10291. thread.join();
  10292. ASSERT_FALSE(svr.is_running());
  10293. });
  10294. svr.wait_until_ready();
  10295. {
  10296. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  10297. curl_easy_init(), &curl_easy_cleanup};
  10298. ASSERT_NE(curl, nullptr);
  10299. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  10300. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  10301. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  10302. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  10303. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  10304. &curl_slist_free_all};
  10305. ASSERT_NE(list, nullptr);
  10306. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  10307. struct read_data {
  10308. size_t read_size;
  10309. size_t total_size;
  10310. } data = {0, total_size};
  10311. using read_callback_t =
  10312. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10313. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  10314. void *userdata) -> size_t {
  10315. read_data *data = (read_data *)userdata;
  10316. if (!userdata || data->read_size >= data->total_size) { return 0; }
  10317. std::fill_n(ptr, size * nmemb, 'A');
  10318. data->read_size += size * nmemb;
  10319. return size * nmemb;
  10320. };
  10321. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  10322. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  10323. std::vector<char> buffer;
  10324. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  10325. using write_callback_t =
  10326. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10327. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  10328. void *userdata) -> size_t {
  10329. std::vector<char> *buffer = (std::vector<char> *)userdata;
  10330. buffer->reserve(buffer->size() + size * nmemb + 1);
  10331. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  10332. return size * nmemb;
  10333. };
  10334. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  10335. {
  10336. const auto res = curl_easy_perform(curl.get());
  10337. ASSERT_EQ(res, CURLE_OK);
  10338. }
  10339. {
  10340. auto response_code = long{};
  10341. const auto res =
  10342. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  10343. ASSERT_EQ(res, CURLE_OK);
  10344. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  10345. }
  10346. {
  10347. auto dl = curl_off_t{};
  10348. const auto res =
  10349. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  10350. ASSERT_EQ(res, CURLE_OK);
  10351. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  10352. }
  10353. {
  10354. buffer.push_back('\0');
  10355. ASSERT_STRCASEEQ(buffer.data(), reject);
  10356. }
  10357. }
  10358. }
  10359. #endif
  10360. template <typename S, typename C>
  10361. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  10362. svr.Get("/stream", [&](const Request &, Response &res) {
  10363. auto data = new std::string("01234567890123456789");
  10364. res.set_content_provider(
  10365. data->size(), "text/plain",
  10366. [&, data](size_t offset, size_t length, DataSink &sink) {
  10367. const size_t DATA_CHUNK_SIZE = 4;
  10368. const auto &d = *data;
  10369. std::this_thread::sleep_for(std::chrono::seconds(1));
  10370. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  10371. return true;
  10372. },
  10373. [data](bool success) {
  10374. EXPECT_FALSE(success);
  10375. delete data;
  10376. });
  10377. });
  10378. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  10379. auto i = new size_t(0);
  10380. res.set_content_provider(
  10381. "text/plain",
  10382. [i](size_t, DataSink &sink) {
  10383. if (*i < 5) {
  10384. std::this_thread::sleep_for(std::chrono::seconds(1));
  10385. sink.write("abcd", 4);
  10386. (*i)++;
  10387. } else {
  10388. sink.done();
  10389. }
  10390. return true;
  10391. },
  10392. [i](bool success) {
  10393. EXPECT_FALSE(success);
  10394. delete i;
  10395. });
  10396. });
  10397. svr.Get("/chunked", [&](const Request &, Response &res) {
  10398. auto i = new size_t(0);
  10399. res.set_chunked_content_provider(
  10400. "text/plain",
  10401. [i](size_t, DataSink &sink) {
  10402. if (*i < 5) {
  10403. std::this_thread::sleep_for(std::chrono::seconds(1));
  10404. sink.os << "abcd";
  10405. (*i)++;
  10406. } else {
  10407. sink.done();
  10408. }
  10409. return true;
  10410. },
  10411. [i](bool success) {
  10412. EXPECT_FALSE(success);
  10413. delete i;
  10414. });
  10415. });
  10416. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10417. auto se = detail::scope_exit([&] {
  10418. svr.stop();
  10419. listen_thread.join();
  10420. ASSERT_FALSE(svr.is_running());
  10421. });
  10422. svr.wait_until_ready();
  10423. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  10424. {
  10425. auto start = std::chrono::steady_clock::now();
  10426. auto res = cli.Get("/stream");
  10427. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10428. std::chrono::steady_clock::now() - start)
  10429. .count();
  10430. ASSERT_FALSE(res);
  10431. EXPECT_EQ(Error::Read, res.error());
  10432. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10433. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10434. }
  10435. {
  10436. auto start = std::chrono::steady_clock::now();
  10437. auto res = cli.Get("/stream_without_length");
  10438. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10439. std::chrono::steady_clock::now() - start)
  10440. .count();
  10441. ASSERT_FALSE(res);
  10442. EXPECT_EQ(Error::Read, res.error());
  10443. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10444. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10445. }
  10446. {
  10447. auto start = std::chrono::steady_clock::now();
  10448. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  10449. EXPECT_EQ("abcd", string(data, data_length));
  10450. return true;
  10451. });
  10452. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10453. std::chrono::steady_clock::now() - start)
  10454. .count();
  10455. ASSERT_FALSE(res);
  10456. EXPECT_EQ(Error::Read, res.error());
  10457. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10458. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10459. }
  10460. }
  10461. TEST(MaxTimeoutTest, ContentStream) {
  10462. time_t timeout = 2000;
  10463. time_t threshold = 200;
  10464. Server svr;
  10465. Client cli("localhost", PORT);
  10466. max_timeout_test(svr, cli, timeout, threshold);
  10467. }
  10468. #ifdef CPPHTTPLIB_SSL_ENABLED
  10469. TEST(MaxTimeoutTest, ContentStreamSSL) {
  10470. time_t timeout = 2000;
  10471. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  10472. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10473. SSLClient cli("localhost", PORT);
  10474. cli.enable_server_certificate_verification(false);
  10475. max_timeout_test(svr, cli, timeout, threshold);
  10476. }
  10477. #endif
  10478. class EventDispatcher {
  10479. public:
  10480. EventDispatcher() {}
  10481. bool wait_event(DataSink *sink) {
  10482. unique_lock<mutex> lk(m_);
  10483. int id = id_;
  10484. // Wait with timeout to prevent hanging if client disconnects
  10485. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  10486. [&] { return cid_ == id; })) {
  10487. return false; // Timeout occurred
  10488. }
  10489. sink->write(message_.data(), message_.size());
  10490. return true;
  10491. }
  10492. void send_event(const string &message) {
  10493. lock_guard<mutex> lk(m_);
  10494. cid_ = id_++;
  10495. message_ = message;
  10496. cv_.notify_all();
  10497. }
  10498. private:
  10499. mutex m_;
  10500. condition_variable cv_;
  10501. atomic_int id_{0};
  10502. atomic_int cid_{-1};
  10503. string message_;
  10504. };
  10505. TEST(ClientInThreadTest, Issue2068) {
  10506. EventDispatcher ed;
  10507. Server svr;
  10508. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  10509. res.set_chunked_content_provider("text/event-stream",
  10510. [&](size_t /*offset*/, DataSink &sink) {
  10511. return ed.wait_event(&sink);
  10512. });
  10513. });
  10514. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10515. svr.wait_until_ready();
  10516. thread event_thread([&] {
  10517. int id = 0;
  10518. while (svr.is_running()) {
  10519. this_thread::sleep_for(chrono::milliseconds(500));
  10520. std::stringstream ss;
  10521. ss << "data: " << id << "\n\n";
  10522. ed.send_event(ss.str());
  10523. id++;
  10524. }
  10525. });
  10526. auto se = detail::scope_exit([&] {
  10527. svr.stop();
  10528. listen_thread.join();
  10529. event_thread.join();
  10530. ASSERT_FALSE(svr.is_running());
  10531. });
  10532. {
  10533. auto client = detail::make_unique<Client>(HOST, PORT);
  10534. client->set_read_timeout(std::chrono::minutes(10));
  10535. std::atomic<bool> stop{false};
  10536. std::thread t([&] {
  10537. client->Get("/event1",
  10538. [&](const char *, size_t) -> bool { return !stop; });
  10539. });
  10540. std::this_thread::sleep_for(std::chrono::seconds(2));
  10541. stop = true;
  10542. client->stop();
  10543. t.join();
  10544. // Reset client after thread has finished
  10545. client.reset();
  10546. }
  10547. }
  10548. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  10549. Server svr;
  10550. svr.Get("/", [](const Request &req, Response &res) {
  10551. EXPECT_EQ(2U, req.trailers.size());
  10552. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  10553. // Denied
  10554. EXPECT_FALSE(req.has_trailer("Content-Length"));
  10555. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  10556. // Accepted
  10557. EXPECT_TRUE(req.has_trailer("X-Hello"));
  10558. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  10559. EXPECT_TRUE(req.has_trailer("X-World"));
  10560. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  10561. res.set_content("ok", "text/plain");
  10562. });
  10563. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10564. auto se = detail::scope_exit([&] {
  10565. svr.stop();
  10566. t.join();
  10567. ASSERT_FALSE(svr.is_running());
  10568. });
  10569. svr.wait_until_ready();
  10570. const std::string req = "GET / HTTP/1.1\r\n"
  10571. "Transfer-Encoding: chunked\r\n"
  10572. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  10573. "\r\n"
  10574. "0\r\n"
  10575. "Content-Length: 10\r\n"
  10576. "Host: internal.local\r\n"
  10577. "Content-Type: malicious/content\r\n"
  10578. "Cookie: any\r\n"
  10579. "Set-Cookie: any\r\n"
  10580. "X-Forwarded-For: attacker.com\r\n"
  10581. "X-Real-Ip: 1.1.1.1\r\n"
  10582. "X-Hello: hello\r\n"
  10583. "X-World: world\r\n"
  10584. "\r\n";
  10585. std::string res;
  10586. ASSERT_TRUE(send_request(1, req, &res));
  10587. }
  10588. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  10589. Server svr;
  10590. std::string observed_remote_addr;
  10591. std::string observed_xff;
  10592. svr.Get("/ip", [&](const Request &req, Response &res) {
  10593. observed_remote_addr = req.remote_addr;
  10594. observed_xff = req.get_header_value("X-Forwarded-For");
  10595. res.set_content("ok", "text/plain");
  10596. });
  10597. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10598. auto se = detail::scope_exit([&] {
  10599. svr.stop();
  10600. t.join();
  10601. ASSERT_FALSE(svr.is_running());
  10602. });
  10603. svr.wait_until_ready();
  10604. Client cli(HOST, PORT);
  10605. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  10606. ASSERT_TRUE(res);
  10607. EXPECT_EQ(StatusCode::OK_200, res->status);
  10608. EXPECT_EQ(observed_xff, "203.0.113.66");
  10609. EXPECT_TRUE(observed_remote_addr == "::1" ||
  10610. observed_remote_addr == "127.0.0.1");
  10611. }
  10612. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  10613. Server svr;
  10614. svr.set_trusted_proxies({"203.0.113.66"});
  10615. std::string observed_remote_addr;
  10616. std::string observed_xff;
  10617. svr.Get("/ip", [&](const Request &req, Response &res) {
  10618. observed_remote_addr = req.remote_addr;
  10619. observed_xff = req.get_header_value("X-Forwarded-For");
  10620. res.set_content("ok", "text/plain");
  10621. });
  10622. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10623. auto se = detail::scope_exit([&] {
  10624. svr.stop();
  10625. t.join();
  10626. ASSERT_FALSE(svr.is_running());
  10627. });
  10628. svr.wait_until_ready();
  10629. Client cli(HOST, PORT);
  10630. auto res = cli.Get("/ip");
  10631. ASSERT_TRUE(res);
  10632. EXPECT_EQ(StatusCode::OK_200, res->status);
  10633. EXPECT_EQ(observed_xff, "");
  10634. EXPECT_TRUE(observed_remote_addr == "::1" ||
  10635. observed_remote_addr == "127.0.0.1");
  10636. }
  10637. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  10638. Server svr;
  10639. svr.set_trusted_proxies({"203.0.113.66"});
  10640. std::string observed_remote_addr;
  10641. std::string observed_xff;
  10642. svr.Get("/ip", [&](const Request &req, Response &res) {
  10643. observed_remote_addr = req.remote_addr;
  10644. observed_xff = req.get_header_value("X-Forwarded-For");
  10645. res.set_content("ok", "text/plain");
  10646. });
  10647. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10648. auto se = detail::scope_exit([&] {
  10649. svr.stop();
  10650. t.join();
  10651. ASSERT_FALSE(svr.is_running());
  10652. });
  10653. svr.wait_until_ready();
  10654. Client cli(HOST, PORT);
  10655. auto res =
  10656. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  10657. ASSERT_TRUE(res);
  10658. EXPECT_EQ(StatusCode::OK_200, res->status);
  10659. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  10660. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10661. }
  10662. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  10663. Server svr;
  10664. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  10665. std::string observed_remote_addr;
  10666. std::string observed_xff;
  10667. svr.Get("/ip", [&](const Request &req, Response &res) {
  10668. observed_remote_addr = req.remote_addr;
  10669. observed_xff = req.get_header_value("X-Forwarded-For");
  10670. res.set_content("ok", "text/plain");
  10671. });
  10672. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10673. auto se = detail::scope_exit([&] {
  10674. svr.stop();
  10675. t.join();
  10676. ASSERT_FALSE(svr.is_running());
  10677. });
  10678. svr.wait_until_ready();
  10679. Client cli(HOST, PORT);
  10680. auto res = cli.Get(
  10681. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  10682. ASSERT_TRUE(res);
  10683. EXPECT_EQ(StatusCode::OK_200, res->status);
  10684. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  10685. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10686. }
  10687. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  10688. Server svr;
  10689. svr.set_trusted_proxies({"192.0.2.45"});
  10690. std::string observed_remote_addr;
  10691. std::string observed_xff;
  10692. svr.Get("/ip", [&](const Request &req, Response &res) {
  10693. observed_remote_addr = req.remote_addr;
  10694. observed_xff = req.get_header_value("X-Forwarded-For");
  10695. res.set_content("ok", "text/plain");
  10696. });
  10697. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10698. auto se = detail::scope_exit([&] {
  10699. svr.stop();
  10700. t.join();
  10701. ASSERT_FALSE(svr.is_running());
  10702. });
  10703. svr.wait_until_ready();
  10704. Client cli(HOST, PORT);
  10705. auto res =
  10706. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  10707. ASSERT_TRUE(res);
  10708. EXPECT_EQ(StatusCode::OK_200, res->status);
  10709. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  10710. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10711. }
  10712. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  10713. Server svr;
  10714. svr.set_trusted_proxies({"192.0.2.45"});
  10715. std::string observed_remote_addr;
  10716. std::string observed_xff;
  10717. svr.Get("/ip", [&](const Request &req, Response &res) {
  10718. observed_remote_addr = req.remote_addr;
  10719. observed_xff = req.get_header_value("X-Forwarded-For");
  10720. res.set_content("ok", "text/plain");
  10721. });
  10722. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10723. auto se = detail::scope_exit([&] {
  10724. svr.stop();
  10725. t.join();
  10726. ASSERT_FALSE(svr.is_running());
  10727. });
  10728. svr.wait_until_ready();
  10729. Client cli(HOST, PORT);
  10730. auto res = cli.Get(
  10731. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  10732. ASSERT_TRUE(res);
  10733. EXPECT_EQ(StatusCode::OK_200, res->status);
  10734. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  10735. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  10736. }
  10737. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  10738. Server svr;
  10739. svr.set_trusted_proxies({"192.0.2.45"});
  10740. std::string observed_remote_addr;
  10741. std::string observed_xff;
  10742. svr.Get("/ip", [&](const Request &req, Response &res) {
  10743. observed_remote_addr = req.remote_addr;
  10744. observed_xff = req.get_header_value("X-Forwarded-For");
  10745. res.set_content("ok", "text/plain");
  10746. });
  10747. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10748. auto se = detail::scope_exit([&] {
  10749. svr.stop();
  10750. t.join();
  10751. ASSERT_FALSE(svr.is_running());
  10752. });
  10753. svr.wait_until_ready();
  10754. std::string raw_req =
  10755. "GET /ip HTTP/1.1\r\n"
  10756. "Host: localhost\r\n"
  10757. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  10758. "Connection: close\r\n"
  10759. "\r\n";
  10760. std::string out;
  10761. ASSERT_TRUE(send_request(5, raw_req, &out));
  10762. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10763. // Header parser trims surrounding whitespace of the header value
  10764. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  10765. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  10766. }
  10767. #ifndef _WIN32
  10768. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  10769. Server svr;
  10770. svr.Post("/post", [&](const Request &req, Response &res) {
  10771. res.set_content(req.body, "text/plain");
  10772. });
  10773. svr.Put("/put", [&](const Request &req, Response &res) {
  10774. res.set_content(req.body, "text/plain");
  10775. });
  10776. svr.Patch("/patch", [&](const Request &req, Response &res) {
  10777. res.set_content(req.body, "text/plain");
  10778. });
  10779. svr.Delete("/delete", [&](const Request &req, Response &res) {
  10780. res.set_content(req.body, "text/plain");
  10781. });
  10782. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10783. auto se = detail::scope_exit([&] {
  10784. svr.stop();
  10785. t.join();
  10786. ASSERT_FALSE(svr.is_running());
  10787. });
  10788. svr.wait_until_ready();
  10789. std::string resp;
  10790. // POST without Content-Length
  10791. ASSERT_TRUE(send_request(5,
  10792. "POST /post HTTP/1.1\r\n"
  10793. "Host: localhost\r\n"
  10794. "Connection: close\r\n"
  10795. "\r\n",
  10796. &resp));
  10797. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10798. // PUT without Content-Length
  10799. resp.clear();
  10800. ASSERT_TRUE(send_request(5,
  10801. "PUT /put HTTP/1.1\r\n"
  10802. "Host: localhost\r\n"
  10803. "Connection: close\r\n"
  10804. "\r\n",
  10805. &resp));
  10806. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10807. // PATCH without Content-Length
  10808. resp.clear();
  10809. ASSERT_TRUE(send_request(5,
  10810. "PATCH /patch HTTP/1.1\r\n"
  10811. "Host: localhost\r\n"
  10812. "Connection: close\r\n"
  10813. "\r\n",
  10814. &resp));
  10815. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10816. // DELETE without Content-Length
  10817. resp.clear();
  10818. ASSERT_TRUE(send_request(5,
  10819. "DELETE /delete HTTP/1.1\r\n"
  10820. "Host: localhost\r\n"
  10821. "Connection: close\r\n"
  10822. "\r\n",
  10823. &resp));
  10824. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10825. }
  10826. #endif
  10827. //==============================================================================
  10828. // open_stream() Tests
  10829. //==============================================================================
  10830. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  10831. std::string result;
  10832. char buf[8192];
  10833. ssize_t n;
  10834. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10835. result.append(buf, static_cast<size_t>(n));
  10836. }
  10837. return result;
  10838. }
  10839. // Mock stream for unit tests
  10840. class MockStream : public Stream {
  10841. public:
  10842. std::string data;
  10843. size_t pos = 0;
  10844. ssize_t error_after = -1; // -1 = no error
  10845. explicit MockStream(const std::string &d, ssize_t err = -1)
  10846. : data(d), error_after(err) {}
  10847. bool is_readable() const override { return true; }
  10848. bool wait_readable() const override { return true; }
  10849. bool wait_writable() const override { return true; }
  10850. ssize_t read(char *ptr, size_t size) override {
  10851. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  10852. if (pos >= data.size()) return 0;
  10853. size_t limit =
  10854. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  10855. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  10856. std::memcpy(ptr, data.data() + pos, to_read);
  10857. pos += to_read;
  10858. return static_cast<ssize_t>(to_read);
  10859. }
  10860. ssize_t write(const char *, size_t) override { return -1; }
  10861. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  10862. ip = "127.0.0.1";
  10863. port = 0;
  10864. }
  10865. void get_local_ip_and_port(std::string &ip, int &port) const override {
  10866. ip = "127.0.0.1";
  10867. port = 0;
  10868. }
  10869. socket_t socket() const override { return INVALID_SOCKET; }
  10870. time_t duration() const override { return 0; }
  10871. };
  10872. TEST(StreamHandleTest, Basic) {
  10873. ClientImpl::StreamHandle handle;
  10874. EXPECT_FALSE(handle.is_valid());
  10875. handle.response = detail::make_unique<Response>();
  10876. handle.error = Error::Connection;
  10877. EXPECT_FALSE(handle.is_valid());
  10878. handle.error = Error::Success;
  10879. EXPECT_TRUE(handle.is_valid());
  10880. }
  10881. TEST(BodyReaderTest, Basic) {
  10882. MockStream stream("Hello, World!");
  10883. detail::BodyReader reader;
  10884. reader.stream = &stream;
  10885. reader.content_length = 13;
  10886. char buf[32];
  10887. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  10888. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  10889. EXPECT_TRUE(reader.eof);
  10890. }
  10891. TEST(BodyReaderTest, NoStream) {
  10892. detail::BodyReader reader;
  10893. char buf[32];
  10894. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  10895. EXPECT_EQ(Error::Connection, reader.last_error);
  10896. }
  10897. TEST(BodyReaderTest, Error) {
  10898. MockStream stream("Hello, World!", 5);
  10899. detail::BodyReader reader;
  10900. reader.stream = &stream;
  10901. reader.content_length = 13;
  10902. char buf[32];
  10903. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  10904. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  10905. EXPECT_EQ(Error::Read, reader.last_error);
  10906. }
  10907. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  10908. // Mock-based StreamHandle tests relying on private internals are removed.
  10909. class OpenStreamTest : public ::testing::Test {
  10910. protected:
  10911. void SetUp() override {
  10912. svr_.Get("/hello", [](const Request &, Response &res) {
  10913. res.set_content("Hello World!", "text/plain");
  10914. });
  10915. svr_.Get("/large", [](const Request &, Response &res) {
  10916. res.set_content(std::string(10000, 'X'), "text/plain");
  10917. });
  10918. svr_.Get("/chunked", [](const Request &, Response &res) {
  10919. res.set_chunked_content_provider("text/plain",
  10920. [](size_t offset, DataSink &sink) {
  10921. if (offset < 15) {
  10922. sink.write("chunk", 5);
  10923. return true;
  10924. }
  10925. sink.done();
  10926. return true;
  10927. });
  10928. });
  10929. svr_.Get("/compressible", [](const Request &, Response &res) {
  10930. res.set_chunked_content_provider("text/plain", [](size_t offset,
  10931. DataSink &sink) {
  10932. if (offset < 100 * 1024) {
  10933. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  10934. sink.write(chunk.data(), chunk.size());
  10935. return true;
  10936. }
  10937. sink.done();
  10938. return true;
  10939. });
  10940. });
  10941. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  10942. [](const Request & /*req*/, Response &res) {
  10943. auto i = new int(0);
  10944. res.set_header("Trailer", "Content-Length, X-Allowed");
  10945. res.set_chunked_content_provider(
  10946. "text/plain",
  10947. [i](size_t /*offset*/, DataSink &sink) {
  10948. switch (*i) {
  10949. case 0: sink.os << "123"; break;
  10950. case 1: sink.os << "456"; break;
  10951. case 2: sink.os << "789"; break;
  10952. case 3: {
  10953. sink.done_with_trailer(
  10954. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  10955. } break;
  10956. }
  10957. (*i)++;
  10958. return true;
  10959. },
  10960. [i](bool success) {
  10961. EXPECT_TRUE(success);
  10962. delete i;
  10963. });
  10964. });
  10965. // Echo headers endpoint for header-related tests
  10966. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  10967. std::string body;
  10968. for (const auto &h : req.headers) {
  10969. body.append(h.first);
  10970. body.push_back(':');
  10971. body.append(h.second);
  10972. body.push_back('\n');
  10973. }
  10974. res.set_content(body, "text/plain");
  10975. });
  10976. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  10977. std::string body;
  10978. for (const auto &h : req.headers) {
  10979. body.append(h.first);
  10980. body.push_back(':');
  10981. body.append(h.second);
  10982. body.push_back('\n');
  10983. }
  10984. res.set_content(body, "text/plain");
  10985. });
  10986. port_ = svr_.bind_to_any_port("127.0.0.1");
  10987. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  10988. svr_.wait_until_ready();
  10989. }
  10990. void TearDown() override {
  10991. svr_.stop();
  10992. if (thread_.joinable()) thread_.join();
  10993. }
  10994. Server svr_;
  10995. std::thread thread_;
  10996. int port_ = 0;
  10997. };
  10998. TEST_F(OpenStreamTest, Basic) {
  10999. Client cli("127.0.0.1", port_);
  11000. auto handle = cli.open_stream("GET", "/hello");
  11001. EXPECT_TRUE(handle.is_valid());
  11002. EXPECT_EQ("Hello World!", read_all(handle));
  11003. }
  11004. TEST_F(OpenStreamTest, SmallBuffer) {
  11005. Client cli("127.0.0.1", port_);
  11006. auto handle = cli.open_stream("GET", "/hello");
  11007. std::string result;
  11008. char buf[4];
  11009. ssize_t n;
  11010. while ((n = handle.read(buf, sizeof(buf))) > 0)
  11011. result.append(buf, static_cast<size_t>(n));
  11012. EXPECT_EQ("Hello World!", result);
  11013. }
  11014. TEST_F(OpenStreamTest, DefaultHeaders) {
  11015. Client cli("127.0.0.1", port_);
  11016. // open_stream GET should include Host, User-Agent and Accept-Encoding
  11017. {
  11018. auto handle = cli.open_stream("GET", "/echo-headers");
  11019. ASSERT_TRUE(handle.is_valid());
  11020. auto body = read_all(handle);
  11021. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  11022. std::string::npos);
  11023. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  11024. std::string::npos);
  11025. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  11026. }
  11027. // open_stream POST with body and no explicit content_type should NOT add
  11028. // text/plain Content-Type (behavior differs from non-streaming path), but
  11029. // should include Content-Length
  11030. {
  11031. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  11032. ASSERT_TRUE(handle.is_valid());
  11033. auto body = read_all(handle);
  11034. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  11035. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  11036. }
  11037. // open_stream POST with explicit Content-Type should preserve it
  11038. {
  11039. auto handle = cli.open_stream("POST", "/echo-headers", {},
  11040. {{"Content-Type", "application/custom"}},
  11041. "{}", "application/custom");
  11042. ASSERT_TRUE(handle.is_valid());
  11043. auto body = read_all(handle);
  11044. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  11045. }
  11046. // User-specified User-Agent must not be overwritten for stream API
  11047. {
  11048. auto handle = cli.open_stream("GET", "/echo-headers", {},
  11049. {{"User-Agent", "MyAgent/1.2"}});
  11050. ASSERT_TRUE(handle.is_valid());
  11051. auto body = read_all(handle);
  11052. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  11053. }
  11054. }
  11055. TEST_F(OpenStreamTest, Large) {
  11056. Client cli("127.0.0.1", port_);
  11057. auto handle = cli.open_stream("GET", "/large");
  11058. EXPECT_EQ(10000u, read_all(handle).size());
  11059. }
  11060. TEST_F(OpenStreamTest, ConnectionError) {
  11061. Client cli("127.0.0.1", 9999);
  11062. auto handle = cli.open_stream("GET", "/hello");
  11063. EXPECT_FALSE(handle.is_valid());
  11064. }
  11065. TEST_F(OpenStreamTest, Chunked) {
  11066. Client cli("127.0.0.1", port_);
  11067. auto handle = cli.open_stream("GET", "/chunked");
  11068. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11069. "Transfer-Encoding") == "chunked");
  11070. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  11071. }
  11072. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  11073. Client cli("127.0.0.1", port_);
  11074. auto handle =
  11075. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  11076. ASSERT_TRUE(handle.is_valid());
  11077. // Consume body to allow trailers to be received/parsed
  11078. auto body = read_all(handle);
  11079. // Explicitly parse trailers (ensure trailers are available for assertion)
  11080. handle.parse_trailers_if_needed();
  11081. EXPECT_EQ(std::string("123456789"), body);
  11082. // The response should include a Trailer header declaring both names
  11083. ASSERT_TRUE(handle.response);
  11084. EXPECT_TRUE(handle.response->has_header("Trailer"));
  11085. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  11086. handle.response->get_header_value("Trailer"));
  11087. // Prohibited trailer must not be present
  11088. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  11089. // Allowed trailer should be present
  11090. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  11091. EXPECT_EQ(std::string("yes"),
  11092. handle.response->get_trailer_value("X-Allowed"));
  11093. // Verify trailers are NOT present as regular headers
  11094. EXPECT_EQ(std::string(""),
  11095. handle.response->get_header_value("Content-Length"));
  11096. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  11097. }
  11098. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11099. TEST_F(OpenStreamTest, Gzip) {
  11100. Client cli("127.0.0.1", port_);
  11101. auto handle = cli.open_stream("GET", "/compressible", {},
  11102. {{"Accept-Encoding", "gzip"}});
  11103. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  11104. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11105. }
  11106. #endif
  11107. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11108. TEST_F(OpenStreamTest, Brotli) {
  11109. Client cli("127.0.0.1", port_);
  11110. auto handle =
  11111. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  11112. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  11113. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11114. }
  11115. #endif
  11116. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11117. TEST_F(OpenStreamTest, Zstd) {
  11118. Client cli("127.0.0.1", port_);
  11119. auto handle = cli.open_stream("GET", "/compressible", {},
  11120. {{"Accept-Encoding", "zstd"}});
  11121. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  11122. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11123. }
  11124. #endif
  11125. #ifdef CPPHTTPLIB_SSL_ENABLED
  11126. class SSLOpenStreamTest : public ::testing::Test {
  11127. protected:
  11128. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  11129. void SetUp() override {
  11130. svr_.Get("/hello", [](const Request &, Response &res) {
  11131. res.set_content("Hello SSL World!", "text/plain");
  11132. });
  11133. svr_.Get("/chunked", [](const Request &, Response &res) {
  11134. res.set_chunked_content_provider("text/plain",
  11135. [](size_t offset, DataSink &sink) {
  11136. if (offset < 15) {
  11137. sink.write("chunk", 5);
  11138. return true;
  11139. }
  11140. sink.done();
  11141. return true;
  11142. });
  11143. });
  11144. svr_.Post("/echo", [](const Request &req, Response &res) {
  11145. res.set_content(req.body, req.get_header_value("Content-Type"));
  11146. });
  11147. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  11148. std::string body = req.body;
  11149. res.set_chunked_content_provider(
  11150. "text/plain", [body](size_t offset, DataSink &sink) {
  11151. if (offset < body.size()) {
  11152. sink.write(body.data() + offset, body.size() - offset);
  11153. }
  11154. sink.done();
  11155. return true;
  11156. });
  11157. });
  11158. port_ = svr_.bind_to_any_port("127.0.0.1");
  11159. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11160. svr_.wait_until_ready();
  11161. }
  11162. void TearDown() override {
  11163. svr_.stop();
  11164. if (thread_.joinable()) thread_.join();
  11165. }
  11166. SSLServer svr_;
  11167. std::thread thread_;
  11168. int port_ = 0;
  11169. };
  11170. TEST_F(SSLOpenStreamTest, Basic) {
  11171. SSLClient cli("127.0.0.1", port_);
  11172. cli.enable_server_certificate_verification(false);
  11173. auto handle = cli.open_stream("GET", "/hello");
  11174. ASSERT_TRUE(handle.is_valid());
  11175. EXPECT_EQ("Hello SSL World!", read_all(handle));
  11176. }
  11177. TEST_F(SSLOpenStreamTest, Chunked) {
  11178. SSLClient cli("127.0.0.1", port_);
  11179. cli.enable_server_certificate_verification(false);
  11180. auto handle = cli.open_stream("GET", "/chunked");
  11181. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11182. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11183. "Transfer-Encoding") == "chunked");
  11184. auto body = read_all(handle);
  11185. EXPECT_EQ("chunkchunkchunk", body);
  11186. }
  11187. TEST_F(SSLOpenStreamTest, Post) {
  11188. SSLClient cli("127.0.0.1", port_);
  11189. cli.enable_server_certificate_verification(false);
  11190. auto handle =
  11191. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  11192. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11193. EXPECT_EQ(200, handle.response->status);
  11194. auto body = read_all(handle);
  11195. EXPECT_EQ("Hello SSL POST", body);
  11196. }
  11197. TEST_F(SSLOpenStreamTest, PostChunked) {
  11198. SSLClient cli("127.0.0.1", port_);
  11199. cli.enable_server_certificate_verification(false);
  11200. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  11201. "Chunked SSL Data", "text/plain");
  11202. ASSERT_TRUE(handle.is_valid());
  11203. EXPECT_EQ(200, handle.response->status);
  11204. auto body = read_all(handle);
  11205. EXPECT_EQ("Chunked SSL Data", body);
  11206. }
  11207. #endif // CPPHTTPLIB_SSL_ENABLED
  11208. //==============================================================================
  11209. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  11210. // results for various scenarios.
  11211. //==============================================================================
  11212. TEST(ParityTest, GetVsOpenStream) {
  11213. Server svr;
  11214. const std::string path = "/parity";
  11215. const std::string content = "Parity test content: hello world";
  11216. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11217. res.set_content(content, "text/plain");
  11218. });
  11219. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11220. auto se = detail::scope_exit([&] {
  11221. svr.stop();
  11222. t.join();
  11223. ASSERT_FALSE(svr.is_running());
  11224. });
  11225. svr.wait_until_ready();
  11226. Client cli(HOST, PORT);
  11227. // Non-stream path
  11228. auto r1 = cli.Get(path);
  11229. ASSERT_TRUE(r1);
  11230. EXPECT_EQ(StatusCode::OK_200, r1->status);
  11231. // Stream path
  11232. auto h = cli.open_stream("GET", path);
  11233. ASSERT_TRUE(h.is_valid());
  11234. EXPECT_EQ(r1->body, read_all(h));
  11235. }
  11236. // Helper to compress data with provided compressor type T
  11237. template <typename Compressor>
  11238. static std::string compress_payload_for_parity(const std::string &in) {
  11239. std::string out;
  11240. Compressor compressor;
  11241. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  11242. [&](const char *data, size_t n) {
  11243. out.append(data, n);
  11244. return true;
  11245. });
  11246. EXPECT_TRUE(ok);
  11247. return out;
  11248. }
  11249. // Helper function for compression parity tests
  11250. template <typename Compressor>
  11251. static void test_compression_parity(const std::string &original,
  11252. const std::string &path,
  11253. const std::string &encoding) {
  11254. const std::string compressed =
  11255. compress_payload_for_parity<Compressor>(original);
  11256. Server svr;
  11257. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11258. res.set_content(compressed, "application/octet-stream");
  11259. res.set_header("Content-Encoding", encoding);
  11260. });
  11261. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  11262. auto se = detail::scope_exit([&] {
  11263. svr.stop();
  11264. t.join();
  11265. ASSERT_FALSE(svr.is_running());
  11266. });
  11267. svr.wait_until_ready();
  11268. Client cli(HOST, PORT);
  11269. // Non-streaming
  11270. {
  11271. auto res = cli.Get(path);
  11272. ASSERT_TRUE(res);
  11273. EXPECT_EQ(StatusCode::OK_200, res->status);
  11274. EXPECT_EQ(original, res->body);
  11275. }
  11276. // Streaming
  11277. {
  11278. auto h = cli.open_stream("GET", path);
  11279. ASSERT_TRUE(h.is_valid());
  11280. EXPECT_EQ(original, read_all(h));
  11281. }
  11282. }
  11283. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11284. TEST(ParityTest, Gzip) {
  11285. test_compression_parity<detail::gzip_compressor>(
  11286. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  11287. }
  11288. #endif
  11289. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11290. TEST(ParityTest, Brotli) {
  11291. test_compression_parity<detail::brotli_compressor>(
  11292. "Hello, brotli parity test payload", "/parity-br", "br");
  11293. }
  11294. #endif
  11295. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11296. TEST(ParityTest, Zstd) {
  11297. test_compression_parity<detail::zstd_compressor>(
  11298. "Zstandard parity test payload", "/parity-zstd", "zstd");
  11299. }
  11300. #endif
  11301. //==============================================================================
  11302. // New Stream API Tests
  11303. //==============================================================================
  11304. inline std::string read_body(httplib::stream::Result &result) {
  11305. std::string body;
  11306. while (result.next()) {
  11307. body.append(result.data(), result.size());
  11308. }
  11309. return body;
  11310. }
  11311. TEST(ClientConnectionTest, Basic) {
  11312. httplib::ClientConnection conn;
  11313. EXPECT_FALSE(conn.is_open());
  11314. conn.sock = 1;
  11315. EXPECT_TRUE(conn.is_open());
  11316. httplib::ClientConnection conn2(std::move(conn));
  11317. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  11318. conn2.sock = INVALID_SOCKET;
  11319. }
  11320. // Unified test server for all stream::* tests
  11321. class StreamApiTest : public ::testing::Test {
  11322. protected:
  11323. void SetUp() override {
  11324. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11325. res.set_content("Hello World!", "text/plain");
  11326. });
  11327. svr_.Get("/echo-params",
  11328. [](const httplib::Request &req, httplib::Response &res) {
  11329. std::string r;
  11330. for (const auto &p : req.params) {
  11331. if (!r.empty()) r += "&";
  11332. r += p.first + "=" + p.second;
  11333. }
  11334. res.set_content(r, "text/plain");
  11335. });
  11336. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11337. res.set_content(req.body, req.get_header_value("Content-Type"));
  11338. });
  11339. svr_.Post("/echo-headers",
  11340. [](const httplib::Request &req, httplib::Response &res) {
  11341. std::string r;
  11342. for (const auto &h : req.headers)
  11343. r += h.first + ": " + h.second + "\n";
  11344. res.set_content(r, "text/plain");
  11345. });
  11346. svr_.Post("/echo-params",
  11347. [](const httplib::Request &req, httplib::Response &res) {
  11348. std::string r = "params:";
  11349. for (const auto &p : req.params)
  11350. r += p.first + "=" + p.second + ";";
  11351. res.set_content(r + " body:" + req.body, "text/plain");
  11352. });
  11353. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  11354. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  11355. });
  11356. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11357. res.set_content("PUT:" + req.body, "text/plain");
  11358. });
  11359. svr_.Patch("/echo",
  11360. [](const httplib::Request &req, httplib::Response &res) {
  11361. res.set_content("PATCH:" + req.body, "text/plain");
  11362. });
  11363. svr_.Delete(
  11364. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  11365. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  11366. "text/plain");
  11367. });
  11368. svr_.Get("/head-test",
  11369. [](const httplib::Request &, httplib::Response &res) {
  11370. res.set_content("body for HEAD", "text/plain");
  11371. });
  11372. svr_.Options("/options",
  11373. [](const httplib::Request &, httplib::Response &res) {
  11374. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  11375. });
  11376. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  11377. svr_.wait_until_ready();
  11378. }
  11379. void TearDown() override {
  11380. svr_.stop();
  11381. if (thread_.joinable()) thread_.join();
  11382. }
  11383. httplib::Server svr_;
  11384. std::thread thread_;
  11385. };
  11386. // stream::Get tests
  11387. TEST_F(StreamApiTest, GetBasic) {
  11388. httplib::Client cli(HOST, PORT);
  11389. auto result = httplib::stream::Get(cli, "/hello");
  11390. ASSERT_TRUE(result.is_valid());
  11391. EXPECT_EQ(200, result.status());
  11392. EXPECT_EQ("Hello World!", read_body(result));
  11393. }
  11394. TEST_F(StreamApiTest, GetWithParams) {
  11395. httplib::Client cli(HOST, PORT);
  11396. httplib::Params params{{"foo", "bar"}};
  11397. auto result = httplib::stream::Get(cli, "/echo-params", params);
  11398. ASSERT_TRUE(result.is_valid());
  11399. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  11400. }
  11401. TEST_F(StreamApiTest, GetConnectionError) {
  11402. httplib::Client cli(HOST, 9999);
  11403. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  11404. }
  11405. TEST_F(StreamApiTest, Get404) {
  11406. httplib::Client cli(HOST, PORT);
  11407. auto result = httplib::stream::Get(cli, "/nonexistent");
  11408. EXPECT_TRUE(result.is_valid());
  11409. EXPECT_EQ(404, result.status());
  11410. }
  11411. // stream::Post tests
  11412. TEST_F(StreamApiTest, PostBasic) {
  11413. httplib::Client cli(HOST, PORT);
  11414. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  11415. "application/json");
  11416. ASSERT_TRUE(result.is_valid());
  11417. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  11418. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  11419. }
  11420. TEST_F(StreamApiTest, PostWithHeaders) {
  11421. httplib::Client cli(HOST, PORT);
  11422. httplib::Headers headers{{"X-Custom", "value"}};
  11423. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  11424. "text/plain");
  11425. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  11426. }
  11427. TEST_F(StreamApiTest, PostWithParams) {
  11428. httplib::Client cli(HOST, PORT);
  11429. httplib::Params params{{"k", "v"}};
  11430. auto result =
  11431. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  11432. auto body = read_body(result);
  11433. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  11434. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  11435. }
  11436. TEST_F(StreamApiTest, PostLarge) {
  11437. httplib::Client cli(HOST, PORT);
  11438. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  11439. size_t total = 0;
  11440. while (result.next()) {
  11441. total += result.size();
  11442. }
  11443. EXPECT_EQ(100u * 1024u, total);
  11444. }
  11445. // stream::Put/Patch tests
  11446. TEST_F(StreamApiTest, PutAndPatch) {
  11447. httplib::Client cli(HOST, PORT);
  11448. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  11449. EXPECT_EQ("PUT:test", read_body(put));
  11450. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  11451. EXPECT_EQ("PATCH:test", read_body(patch));
  11452. }
  11453. // stream::Delete tests
  11454. TEST_F(StreamApiTest, Delete) {
  11455. httplib::Client cli(HOST, PORT);
  11456. auto del1 = httplib::stream::Delete(cli, "/resource");
  11457. EXPECT_EQ("Deleted", read_body(del1));
  11458. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  11459. EXPECT_EQ("Deleted:data", read_body(del2));
  11460. }
  11461. // stream::Head/Options tests
  11462. TEST_F(StreamApiTest, HeadAndOptions) {
  11463. httplib::Client cli(HOST, PORT);
  11464. auto head = httplib::stream::Head(cli, "/head-test");
  11465. EXPECT_TRUE(head.is_valid());
  11466. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  11467. auto opts = httplib::stream::Options(cli, "/options");
  11468. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  11469. }
  11470. // SSL stream::* tests
  11471. #ifdef CPPHTTPLIB_SSL_ENABLED
  11472. class SSLStreamApiTest : public ::testing::Test {
  11473. protected:
  11474. void SetUp() override {
  11475. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11476. res.set_content("Hello SSL!", "text/plain");
  11477. });
  11478. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11479. res.set_content(req.body, "text/plain");
  11480. });
  11481. port_ = svr_.bind_to_any_port("127.0.0.1");
  11482. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11483. svr_.wait_until_ready();
  11484. }
  11485. void TearDown() override {
  11486. svr_.stop();
  11487. if (thread_.joinable()) thread_.join();
  11488. }
  11489. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  11490. std::thread thread_;
  11491. int port_ = 0;
  11492. };
  11493. TEST_F(SSLStreamApiTest, GetAndPost) {
  11494. httplib::SSLClient cli("127.0.0.1", port_);
  11495. cli.enable_server_certificate_verification(false);
  11496. auto get = httplib::stream::Get(cli, "/hello");
  11497. EXPECT_EQ("Hello SSL!", read_body(get));
  11498. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  11499. EXPECT_EQ("test", read_body(post));
  11500. }
  11501. #endif
  11502. // Tests for Error::Timeout and Error::ConnectionClosed error types
  11503. // These errors are set in SocketStream/SSLSocketStream and propagated through
  11504. // BodyReader
  11505. TEST(ErrorHandlingTest, StreamReadTimeout) {
  11506. // Test that read timeout during streaming is detected
  11507. // Use a large content-length response where server delays mid-stream
  11508. Server svr;
  11509. svr.Get("/slow-stream", [](const Request &, Response &res) {
  11510. // Send a large response with delay in the middle
  11511. res.set_content_provider(
  11512. 1000, // content_length
  11513. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  11514. if (offset < 100) {
  11515. // Send first 100 bytes immediately
  11516. std::string data(100, 'A');
  11517. sink.write(data.c_str(), data.size());
  11518. return true;
  11519. }
  11520. // Then delay longer than client timeout
  11521. std::this_thread::sleep_for(std::chrono::seconds(3));
  11522. std::string data(900, 'B');
  11523. sink.write(data.c_str(), data.size());
  11524. return true;
  11525. });
  11526. });
  11527. auto port = 8091;
  11528. std::thread t([&]() { svr.listen("localhost", port); });
  11529. svr.wait_until_ready();
  11530. Client cli("localhost", port);
  11531. cli.set_read_timeout(1, 0); // 1 second timeout
  11532. auto handle = cli.open_stream("GET", "/slow-stream");
  11533. ASSERT_TRUE(handle.is_valid());
  11534. char buf[256];
  11535. ssize_t total = 0;
  11536. ssize_t n;
  11537. bool got_error = false;
  11538. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11539. total += n;
  11540. }
  11541. if (n < 0) {
  11542. got_error = true;
  11543. // Should be timeout or read error
  11544. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  11545. handle.get_read_error() == Error::Read)
  11546. << "Actual error: " << to_string(handle.get_read_error());
  11547. }
  11548. // Either we got an error, or we got less data than expected
  11549. EXPECT_TRUE(got_error || total < 1000)
  11550. << "Expected timeout but got all " << total << " bytes";
  11551. svr.stop();
  11552. t.join();
  11553. }
  11554. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  11555. // Test connection closed detection via BodyReader
  11556. Server svr;
  11557. std::atomic<bool> close_now{false};
  11558. svr.Get("/will-close", [&](const Request &, Response &res) {
  11559. res.set_content_provider(
  11560. 10000, // Large content_length that we won't fully send
  11561. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  11562. if (offset < 100) {
  11563. std::string data(100, 'X');
  11564. sink.write(data.c_str(), data.size());
  11565. return true;
  11566. }
  11567. // Wait for signal then abort
  11568. while (!close_now) {
  11569. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11570. }
  11571. return false; // Abort - server will close connection
  11572. });
  11573. });
  11574. auto port = 8092;
  11575. std::thread t([&]() { svr.listen("localhost", port); });
  11576. svr.wait_until_ready();
  11577. Client cli("localhost", port);
  11578. auto handle = cli.open_stream("GET", "/will-close");
  11579. ASSERT_TRUE(handle.is_valid());
  11580. char buf[256];
  11581. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  11582. EXPECT_GT(n, 0) << "First read should succeed";
  11583. // Signal server to close
  11584. close_now = true;
  11585. // Keep reading until error or EOF
  11586. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11587. // Keep reading
  11588. }
  11589. // Should get an error since content_length wasn't satisfied
  11590. if (n < 0) {
  11591. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  11592. handle.get_read_error() == Error::Read)
  11593. << "Actual error: " << to_string(handle.get_read_error());
  11594. }
  11595. svr.stop();
  11596. t.join();
  11597. }
  11598. #ifdef CPPHTTPLIB_SSL_ENABLED
  11599. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  11600. // Test that read timeout during SSL streaming is detected
  11601. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11602. svr.Get("/slow-stream", [](const Request &, Response &res) {
  11603. res.set_content_provider(
  11604. 1000, "text/plain",
  11605. [](size_t offset, size_t /*length*/, DataSink &sink) {
  11606. if (offset < 100) {
  11607. std::string data(100, 'A');
  11608. sink.write(data.c_str(), data.size());
  11609. return true;
  11610. }
  11611. std::this_thread::sleep_for(std::chrono::seconds(3));
  11612. std::string data(900, 'B');
  11613. sink.write(data.c_str(), data.size());
  11614. return true;
  11615. });
  11616. });
  11617. auto port = 8093;
  11618. std::thread t([&]() { svr.listen("localhost", port); });
  11619. svr.wait_until_ready();
  11620. SSLClient cli("localhost", port);
  11621. cli.enable_server_certificate_verification(false);
  11622. cli.set_read_timeout(1, 0); // 1 second timeout
  11623. auto handle = cli.open_stream("GET", "/slow-stream");
  11624. ASSERT_TRUE(handle.is_valid());
  11625. char buf[256];
  11626. ssize_t total = 0;
  11627. ssize_t n;
  11628. bool got_error = false;
  11629. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11630. total += n;
  11631. }
  11632. if (n < 0) {
  11633. got_error = true;
  11634. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  11635. handle.get_read_error() == Error::Read)
  11636. << "Actual error: " << to_string(handle.get_read_error());
  11637. }
  11638. EXPECT_TRUE(got_error || total < 1000)
  11639. << "Expected timeout but got all " << total << " bytes";
  11640. svr.stop();
  11641. t.join();
  11642. }
  11643. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  11644. // Test SSL connection closed detection
  11645. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11646. std::atomic<bool> close_now{false};
  11647. svr.Get("/will-close", [&](const Request &, Response &res) {
  11648. res.set_content_provider(
  11649. 10000, "text/plain",
  11650. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  11651. if (offset < 100) {
  11652. std::string data(100, 'X');
  11653. sink.write(data.c_str(), data.size());
  11654. return true;
  11655. }
  11656. while (!close_now) {
  11657. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11658. }
  11659. return false;
  11660. });
  11661. });
  11662. auto port = 8094;
  11663. std::thread t([&]() { svr.listen("localhost", port); });
  11664. svr.wait_until_ready();
  11665. SSLClient cli("localhost", port);
  11666. cli.enable_server_certificate_verification(false);
  11667. auto handle = cli.open_stream("GET", "/will-close");
  11668. ASSERT_TRUE(handle.is_valid());
  11669. char buf[256];
  11670. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  11671. EXPECT_GT(n, 0);
  11672. // Signal server to close
  11673. close_now = true;
  11674. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11675. // Keep reading
  11676. }
  11677. if (n < 0) {
  11678. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  11679. handle.get_read_error() == Error::Read)
  11680. << "Actual error: " << to_string(handle.get_read_error());
  11681. }
  11682. svr.stop();
  11683. t.join();
  11684. }
  11685. #endif
  11686. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  11687. using namespace httplib;
  11688. // Create a test file
  11689. const char *fname = "etag_testfile.txt";
  11690. const char *content = "etag-content";
  11691. {
  11692. std::ofstream ofs(fname);
  11693. ofs << content;
  11694. ASSERT_TRUE(ofs.good());
  11695. }
  11696. Server svr;
  11697. svr.set_mount_point("/static", ".");
  11698. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  11699. svr.wait_until_ready();
  11700. Client cli(HOST, PORT);
  11701. // First request: should get 200 with ETag header
  11702. auto res1 = cli.Get("/static/etag_testfile.txt");
  11703. ASSERT_TRUE(res1);
  11704. ASSERT_EQ(200, res1->status);
  11705. ASSERT_TRUE(res1->has_header("ETag"));
  11706. std::string etag = res1->get_header_value("ETag");
  11707. EXPECT_FALSE(etag.empty());
  11708. // Verify ETag format: W/"hex-hex"
  11709. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  11710. EXPECT_EQ('W', etag[0]);
  11711. EXPECT_EQ('/', etag[1]);
  11712. EXPECT_EQ('"', etag[2]);
  11713. EXPECT_EQ('"', etag.back());
  11714. // Exact match: expect 304 Not Modified
  11715. Headers h2 = {{"If-None-Match", etag}};
  11716. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  11717. ASSERT_TRUE(res2);
  11718. EXPECT_EQ(304, res2->status);
  11719. // Wildcard match: expect 304 Not Modified
  11720. Headers h3 = {{"If-None-Match", "*"}};
  11721. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  11722. ASSERT_TRUE(res3);
  11723. EXPECT_EQ(304, res3->status);
  11724. // Non-matching ETag: expect 200
  11725. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  11726. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  11727. ASSERT_TRUE(res4);
  11728. EXPECT_EQ(200, res4->status);
  11729. // Multiple ETags with one matching: expect 304
  11730. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  11731. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  11732. ASSERT_TRUE(res5);
  11733. EXPECT_EQ(304, res5->status);
  11734. svr.stop();
  11735. t.join();
  11736. std::remove(fname);
  11737. }
  11738. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  11739. using namespace httplib;
  11740. Server svr;
  11741. svr.set_mount_point("/static", ".");
  11742. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11743. svr.wait_until_ready();
  11744. Client cli(HOST, PORT);
  11745. // Send If-None-Match: * to a non-existent file
  11746. Headers h = {{"If-None-Match", "*"}};
  11747. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  11748. ASSERT_TRUE(res);
  11749. EXPECT_EQ(404, res->status);
  11750. svr.stop();
  11751. t.join();
  11752. }
  11753. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  11754. using namespace httplib;
  11755. // Create a test file
  11756. const char *fname = "etag_boundary_testfile.txt";
  11757. const char *content = "boundary-test";
  11758. {
  11759. std::ofstream ofs(fname);
  11760. ofs << content;
  11761. ASSERT_TRUE(ofs.good());
  11762. }
  11763. Server svr;
  11764. svr.set_mount_point("/static", ".");
  11765. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  11766. svr.wait_until_ready();
  11767. Client cli(HOST, PORT);
  11768. // Get the actual ETag
  11769. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  11770. ASSERT_TRUE(res1);
  11771. ASSERT_EQ(200, res1->status);
  11772. ASSERT_TRUE(res1->has_header("ETag"));
  11773. std::string etag = res1->get_header_value("ETag");
  11774. // Test 1: Very long ETag value (longer than actual ETag)
  11775. // Should NOT match and return 200 (not trigger out-of-bounds read)
  11776. Headers h1 = {{"If-None-Match", "W/"
  11777. "\"very-long-etag-value-that-is-much-longer-"
  11778. "than-the-actual-etag-value\""}};
  11779. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  11780. ASSERT_TRUE(res2);
  11781. EXPECT_EQ(200, res2->status); // Should not match
  11782. // Test 2: Long string followed by wildcard
  11783. // Should match on "*" and return 304 (without out-of-bounds read on the long
  11784. // string)
  11785. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  11786. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  11787. ASSERT_TRUE(res3);
  11788. EXPECT_EQ(304, res3->status); // Should match on "*"
  11789. // Test 3: Wildcard followed by long string
  11790. // Should match on "*" immediately and return 304
  11791. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  11792. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  11793. ASSERT_TRUE(res4);
  11794. EXPECT_EQ(304, res4->status); // Should match on "*"
  11795. // Test 4: Multiple long non-matching values
  11796. // Should NOT match and return 200 (test that all comparisons are safe)
  11797. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  11798. "W/\"second-long-non-matching-value\", "
  11799. "W/\"third-long-non-matching-value\""}};
  11800. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  11801. ASSERT_TRUE(res5);
  11802. EXPECT_EQ(200, res5->status); // Should not match
  11803. // Test 5: Single character that is not "*" (edge case)
  11804. Headers h5 = {{"If-None-Match", "X"}};
  11805. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  11806. ASSERT_TRUE(res6);
  11807. EXPECT_EQ(200, res6->status); // Should not match
  11808. svr.stop();
  11809. t.join();
  11810. std::remove(fname);
  11811. }
  11812. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  11813. using namespace httplib;
  11814. // Create a test file
  11815. const char *fname = "ims_testfile.txt";
  11816. const char *content = "if-modified-since-test";
  11817. {
  11818. std::ofstream ofs(fname);
  11819. ofs << content;
  11820. ASSERT_TRUE(ofs.good());
  11821. }
  11822. Server svr;
  11823. svr.set_mount_point("/static", ".");
  11824. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11825. svr.wait_until_ready();
  11826. Client cli(HOST, PORT);
  11827. // First request: should get 200 with Last-Modified header
  11828. auto res1 = cli.Get("/static/ims_testfile.txt");
  11829. ASSERT_TRUE(res1);
  11830. ASSERT_EQ(200, res1->status);
  11831. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11832. std::string last_modified = res1->get_header_value("Last-Modified");
  11833. EXPECT_FALSE(last_modified.empty());
  11834. // If-Modified-Since with same time: expect 304
  11835. Headers h2 = {{"If-Modified-Since", last_modified}};
  11836. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  11837. ASSERT_TRUE(res2);
  11838. EXPECT_EQ(304, res2->status);
  11839. // If-Modified-Since with future time: expect 304
  11840. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  11841. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  11842. ASSERT_TRUE(res3);
  11843. EXPECT_EQ(304, res3->status);
  11844. // If-Modified-Since with past time: expect 200
  11845. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  11846. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  11847. ASSERT_TRUE(res4);
  11848. EXPECT_EQ(200, res4->status);
  11849. // If-None-Match takes precedence over If-Modified-Since
  11850. // (send matching ETag with old If-Modified-Since -> should still be 304)
  11851. ASSERT_TRUE(res1->has_header("ETag"));
  11852. std::string etag = res1->get_header_value("ETag");
  11853. Headers h5 = {{"If-None-Match", etag},
  11854. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  11855. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  11856. ASSERT_TRUE(res5);
  11857. EXPECT_EQ(304, res5->status);
  11858. svr.stop();
  11859. t.join();
  11860. std::remove(fname);
  11861. }
  11862. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  11863. using namespace httplib;
  11864. Server svr;
  11865. // Endpoint that returns compressible content
  11866. svr.Get("/compressible", [](const Request &, Response &res) {
  11867. // Return a large enough body to trigger compression
  11868. std::string body(1000, 'a');
  11869. res.set_content(body, "text/plain");
  11870. });
  11871. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11872. svr.wait_until_ready();
  11873. Client cli(HOST, PORT);
  11874. // Request with gzip support: should get Vary header when compressed
  11875. cli.set_compress(true);
  11876. auto res1 = cli.Get("/compressible");
  11877. ASSERT_TRUE(res1);
  11878. EXPECT_EQ(200, res1->status);
  11879. // If Content-Encoding is set, Vary should also be set
  11880. if (res1->has_header("Content-Encoding")) {
  11881. EXPECT_TRUE(res1->has_header("Vary"));
  11882. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  11883. }
  11884. // Request without Accept-Encoding header: should not have compression
  11885. Headers h_no_compress;
  11886. auto res2 = cli.Get("/compressible", h_no_compress);
  11887. ASSERT_TRUE(res2);
  11888. EXPECT_EQ(200, res2->status);
  11889. // Verify Vary header is present when compression is applied
  11890. // (the exact behavior depends on server configuration)
  11891. svr.stop();
  11892. t.join();
  11893. }
  11894. TEST(ETagTest, IfRangeWithETag) {
  11895. using namespace httplib;
  11896. // Create a test file with known content
  11897. const char *fname = "if_range_testfile.txt";
  11898. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  11899. {
  11900. std::ofstream ofs(fname);
  11901. ofs << content;
  11902. ASSERT_TRUE(ofs.good());
  11903. }
  11904. Server svr;
  11905. svr.set_mount_point("/static", ".");
  11906. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11907. svr.wait_until_ready();
  11908. Client cli(HOST, PORT);
  11909. // First request: get ETag
  11910. auto res1 = cli.Get("/static/if_range_testfile.txt");
  11911. ASSERT_TRUE(res1);
  11912. ASSERT_EQ(200, res1->status);
  11913. ASSERT_TRUE(res1->has_header("ETag"));
  11914. std::string etag = res1->get_header_value("ETag");
  11915. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  11916. // Since our server generates weak ETags (W/"..."), If-Range with our
  11917. // ETag should NOT result in partial content - it should return full content.
  11918. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  11919. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  11920. ASSERT_TRUE(res2);
  11921. // Weak ETag in If-Range -> full content (200), not partial (206)
  11922. EXPECT_EQ(200, res2->status);
  11923. EXPECT_EQ(content, res2->body);
  11924. EXPECT_FALSE(res2->has_header("Content-Range"));
  11925. // Range request with non-matching If-Range (ETag): should get 200 (full
  11926. // content)
  11927. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  11928. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  11929. ASSERT_TRUE(res3);
  11930. EXPECT_EQ(200, res3->status);
  11931. EXPECT_EQ(content, res3->body);
  11932. EXPECT_FALSE(res3->has_header("Content-Range"));
  11933. // Range request with strong ETag (hypothetical - our server doesn't generate
  11934. // strong ETags, but if client sends a strong ETag that doesn't match, it
  11935. // should return full content)
  11936. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  11937. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  11938. ASSERT_TRUE(res4);
  11939. EXPECT_EQ(200, res4->status);
  11940. EXPECT_EQ(content, res4->body);
  11941. EXPECT_FALSE(res4->has_header("Content-Range"));
  11942. svr.stop();
  11943. t.join();
  11944. std::remove(fname);
  11945. }
  11946. TEST(ETagTest, IfRangeWithDate) {
  11947. using namespace httplib;
  11948. // Create a test file
  11949. const char *fname = "if_range_date_testfile.txt";
  11950. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  11951. {
  11952. std::ofstream ofs(fname);
  11953. ofs << content;
  11954. ASSERT_TRUE(ofs.good());
  11955. }
  11956. Server svr;
  11957. svr.set_mount_point("/static", ".");
  11958. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11959. svr.wait_until_ready();
  11960. Client cli(HOST, PORT);
  11961. // First request: get Last-Modified
  11962. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  11963. ASSERT_TRUE(res1);
  11964. ASSERT_EQ(200, res1->status);
  11965. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11966. std::string last_modified = res1->get_header_value("Last-Modified");
  11967. // Range request with matching If-Range (date): should get 206
  11968. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  11969. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  11970. ASSERT_TRUE(res2);
  11971. EXPECT_EQ(206, res2->status);
  11972. EXPECT_EQ("FGHIJ", res2->body);
  11973. // Range request with old If-Range date: should get 200 (full content)
  11974. Headers h3 = {{"Range", "bytes=5-9"},
  11975. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  11976. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  11977. ASSERT_TRUE(res3);
  11978. EXPECT_EQ(200, res3->status);
  11979. EXPECT_EQ(content, res3->body);
  11980. // Range request with future If-Range date: should get 206
  11981. Headers h4 = {{"Range", "bytes=0-4"},
  11982. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  11983. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  11984. ASSERT_TRUE(res4);
  11985. EXPECT_EQ(206, res4->status);
  11986. EXPECT_EQ("ABCDE", res4->body);
  11987. svr.stop();
  11988. t.join();
  11989. std::remove(fname);
  11990. }
  11991. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  11992. using namespace httplib;
  11993. const char *fname = "etag_malformed.txt";
  11994. const char *content = "malformed-etag";
  11995. {
  11996. std::ofstream ofs(fname);
  11997. ofs << content;
  11998. ASSERT_TRUE(ofs.good());
  11999. }
  12000. Server svr;
  12001. svr.set_mount_point("/static", ".");
  12002. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12003. svr.wait_until_ready();
  12004. Client cli(HOST, PORT);
  12005. // baseline: should get 200 and an ETag
  12006. auto res1 = cli.Get("/static/etag_malformed.txt");
  12007. ASSERT_TRUE(res1);
  12008. ASSERT_EQ(200, res1->status);
  12009. ASSERT_TRUE(res1->has_header("ETag"));
  12010. // Malformed ETag value (missing quotes) should be treated as non-matching
  12011. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  12012. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  12013. ASSERT_TRUE(res_bad);
  12014. EXPECT_EQ(200, res_bad->status);
  12015. // Whitespace-only header value should be considered invalid / non-matching
  12016. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  12017. "Host: localhost\r\n"
  12018. "If-None-Match: \r\n"
  12019. "Connection: close\r\n"
  12020. "\r\n";
  12021. std::string out;
  12022. ASSERT_TRUE(send_request(5, raw_req, &out));
  12023. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12024. svr.stop();
  12025. t.join();
  12026. std::remove(fname);
  12027. }
  12028. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  12029. using namespace httplib;
  12030. const char *fname = "ims_invalid_format.txt";
  12031. const char *content = "ims-bad-format";
  12032. {
  12033. std::ofstream ofs(fname);
  12034. ofs << content;
  12035. ASSERT_TRUE(ofs.good());
  12036. }
  12037. Server svr;
  12038. svr.set_mount_point("/static", ".");
  12039. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12040. svr.wait_until_ready();
  12041. Client cli(HOST, PORT);
  12042. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  12043. ASSERT_TRUE(res1);
  12044. ASSERT_EQ(200, res1->status);
  12045. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12046. // If-Modified-Since with invalid format should not result in 304
  12047. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  12048. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  12049. ASSERT_TRUE(res_bad);
  12050. EXPECT_EQ(200, res_bad->status);
  12051. // If-Range with invalid date format should be treated as mismatch -> full
  12052. // content (200)
  12053. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  12054. {"If-Range", "invalid-date"}};
  12055. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  12056. ASSERT_TRUE(res_ifrange);
  12057. EXPECT_EQ(200, res_ifrange->status);
  12058. svr.stop();
  12059. t.join();
  12060. std::remove(fname);
  12061. }
  12062. TEST(ETagTest, IfRangeWithMalformedETag) {
  12063. using namespace httplib;
  12064. const char *fname = "ifrange_malformed.txt";
  12065. const std::string content = "0123456789";
  12066. {
  12067. std::ofstream ofs(fname);
  12068. ofs << content;
  12069. ASSERT_TRUE(ofs.good());
  12070. }
  12071. Server svr;
  12072. svr.set_mount_point("/static", ".");
  12073. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12074. svr.wait_until_ready();
  12075. Client cli(HOST, PORT);
  12076. // First request: get ETag
  12077. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  12078. ASSERT_TRUE(res1);
  12079. ASSERT_EQ(200, res1->status);
  12080. ASSERT_TRUE(res1->has_header("ETag"));
  12081. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  12082. // full content (200)
  12083. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  12084. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  12085. ASSERT_TRUE(res2);
  12086. EXPECT_EQ(200, res2->status);
  12087. EXPECT_EQ(content, res2->body);
  12088. svr.stop();
  12089. t.join();
  12090. std::remove(fname);
  12091. }
  12092. TEST(ETagTest, ExtremeLargeDateValues) {
  12093. using namespace httplib;
  12094. const char *fname = "ims_extreme_date.txt";
  12095. const char *content = "ims-extreme-date";
  12096. {
  12097. std::ofstream ofs(fname);
  12098. ofs << content;
  12099. ASSERT_TRUE(ofs.good());
  12100. }
  12101. Server svr;
  12102. svr.set_mount_point("/static", ".");
  12103. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12104. svr.wait_until_ready();
  12105. Client cli(HOST, PORT);
  12106. auto res1 = cli.Get(std::string("/static/") + fname);
  12107. ASSERT_TRUE(res1);
  12108. ASSERT_EQ(200, res1->status);
  12109. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12110. // Extremely large year that may overflow date parsing routines.
  12111. Headers h_large_date = {
  12112. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12113. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  12114. ASSERT_TRUE(res_bad);
  12115. // Expect server to treat this as invalid/mismatch and return full content
  12116. EXPECT_EQ(200, res_bad->status);
  12117. // If-Range with extremely large date should be treated as mismatch -> full
  12118. // content (200)
  12119. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  12120. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12121. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  12122. ASSERT_TRUE(res_ifrange);
  12123. EXPECT_EQ(200, res_ifrange->status);
  12124. svr.stop();
  12125. t.join();
  12126. std::remove(fname);
  12127. }
  12128. TEST(ETagTest, NegativeFileModificationTime) {
  12129. using namespace httplib;
  12130. const char *fname = "ims_negative_mtime.txt";
  12131. const std::string content = "negative-mtime";
  12132. {
  12133. std::ofstream ofs(fname);
  12134. ofs << content;
  12135. ASSERT_TRUE(ofs.good());
  12136. }
  12137. // Try to set file mtime to a negative value. This may fail on some
  12138. // platforms/filesystems; if it fails, the test will still verify server
  12139. // behaves safely by performing a regular conditional request.
  12140. #if defined(__APPLE__) || defined(__linux__)
  12141. bool set_negative = false;
  12142. do {
  12143. struct timeval times[2];
  12144. // access time: now
  12145. times[0].tv_sec = time(nullptr);
  12146. times[0].tv_usec = 0;
  12147. // modification time: negative (e.g., -1)
  12148. times[1].tv_sec = -1;
  12149. times[1].tv_usec = 0;
  12150. if (utimes(fname, times) == 0) { set_negative = true; }
  12151. } while (0);
  12152. #else
  12153. bool set_negative = false;
  12154. #endif
  12155. Server svr;
  12156. svr.set_mount_point("/static", ".");
  12157. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12158. svr.wait_until_ready();
  12159. Client cli(HOST, PORT);
  12160. auto res1 = cli.Get(std::string("/static/") + fname);
  12161. ASSERT_TRUE(res1);
  12162. ASSERT_EQ(200, res1->status);
  12163. bool has_last_modified = res1->has_header("Last-Modified");
  12164. std::string last_modified;
  12165. if (has_last_modified) {
  12166. last_modified = res1->get_header_value("Last-Modified");
  12167. }
  12168. if (set_negative) {
  12169. // If we successfully set a negative mtime, ensure server returns a
  12170. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  12171. // with an old date and ensure server handles it without crash.
  12172. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  12173. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  12174. ASSERT_TRUE(res2);
  12175. // Behavior may vary; at minimum ensure server responds (200 or 304).
  12176. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  12177. } else {
  12178. // Could not set negative mtime on this platform; fall back to verifying
  12179. // that normal invalid/malformed dates are treated safely (non-304).
  12180. Headers h_bad_date = {
  12181. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12182. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  12183. ASSERT_TRUE(res_bad);
  12184. EXPECT_EQ(200, res_bad->status);
  12185. }
  12186. svr.stop();
  12187. t.join();
  12188. std::remove(fname);
  12189. }
  12190. //==============================================================================
  12191. // SSE Parsing Tests
  12192. //==============================================================================
  12193. class SSEParsingTest : public ::testing::Test {
  12194. protected:
  12195. // Test helper that mimics SSE parsing behavior
  12196. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  12197. int &retry_ms) {
  12198. // Blank line signals end of event
  12199. if (line.empty() || line == "\r") { return true; }
  12200. // Lines starting with ':' are comments (ignored)
  12201. if (!line.empty() && line[0] == ':') { return false; }
  12202. // Find the colon separator
  12203. auto colon_pos = line.find(':');
  12204. if (colon_pos == std::string::npos) {
  12205. // Line with no colon is treated as field name with empty value
  12206. return false;
  12207. }
  12208. std::string field = line.substr(0, colon_pos);
  12209. std::string value;
  12210. // Value starts after colon, skip optional single space
  12211. if (colon_pos + 1 < line.size()) {
  12212. size_t value_start = colon_pos + 1;
  12213. if (line[value_start] == ' ') { value_start++; }
  12214. value = line.substr(value_start);
  12215. // Remove trailing \r if present
  12216. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  12217. }
  12218. // Handle known fields
  12219. if (field == "event") {
  12220. msg.event = value;
  12221. } else if (field == "data") {
  12222. // Multiple data lines are concatenated with newlines
  12223. if (!msg.data.empty()) { msg.data += "\n"; }
  12224. msg.data += value;
  12225. } else if (field == "id") {
  12226. // Empty id is valid (clears the last event ID)
  12227. msg.id = value;
  12228. } else if (field == "retry") {
  12229. // Parse retry interval in milliseconds
  12230. {
  12231. int v = 0;
  12232. auto res =
  12233. detail::from_chars(value.data(), value.data() + value.size(), v);
  12234. if (res.ec == std::errc{}) { retry_ms = v; }
  12235. }
  12236. }
  12237. // Unknown fields are ignored per SSE spec
  12238. return false;
  12239. }
  12240. };
  12241. // Test: Single-line data
  12242. TEST_F(SSEParsingTest, SingleLineData) {
  12243. sse::SSEMessage msg;
  12244. int retry_ms = 3000;
  12245. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  12246. EXPECT_EQ(msg.data, "hello");
  12247. EXPECT_EQ(msg.event, "message");
  12248. // Blank line ends event
  12249. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12250. }
  12251. // Test: Multi-line data
  12252. TEST_F(SSEParsingTest, MultiLineData) {
  12253. sse::SSEMessage msg;
  12254. int retry_ms = 3000;
  12255. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  12256. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  12257. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  12258. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  12259. }
  12260. // Test: Custom event types
  12261. TEST_F(SSEParsingTest, CustomEventType) {
  12262. sse::SSEMessage msg;
  12263. int retry_ms = 3000;
  12264. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  12265. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  12266. EXPECT_EQ(msg.event, "update");
  12267. EXPECT_EQ(msg.data, "payload");
  12268. }
  12269. // Test: Event ID handling
  12270. TEST_F(SSEParsingTest, EventIdHandling) {
  12271. sse::SSEMessage msg;
  12272. int retry_ms = 3000;
  12273. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  12274. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  12275. EXPECT_EQ(msg.id, "12345");
  12276. }
  12277. // Test: Empty event ID (clears last event ID)
  12278. TEST_F(SSEParsingTest, EmptyEventId) {
  12279. sse::SSEMessage msg;
  12280. msg.id = "previous";
  12281. int retry_ms = 3000;
  12282. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  12283. EXPECT_EQ(msg.id, "");
  12284. }
  12285. // Test: Retry field parsing
  12286. TEST_F(SSEParsingTest, RetryFieldParsing) {
  12287. sse::SSEMessage msg;
  12288. int retry_ms = 3000;
  12289. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  12290. EXPECT_EQ(retry_ms, 5000);
  12291. }
  12292. // Test: Invalid retry value
  12293. TEST_F(SSEParsingTest, InvalidRetryValue) {
  12294. sse::SSEMessage msg;
  12295. int retry_ms = 3000;
  12296. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  12297. EXPECT_EQ(retry_ms, 3000); // Unchanged
  12298. }
  12299. // Test: Comments (lines starting with :)
  12300. TEST_F(SSEParsingTest, CommentsIgnored) {
  12301. sse::SSEMessage msg;
  12302. int retry_ms = 3000;
  12303. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  12304. EXPECT_EQ(msg.data, "");
  12305. EXPECT_EQ(msg.event, "message");
  12306. }
  12307. // Test: Colon in value
  12308. TEST_F(SSEParsingTest, ColonInValue) {
  12309. sse::SSEMessage msg;
  12310. int retry_ms = 3000;
  12311. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  12312. EXPECT_EQ(msg.data, "hello:world:test");
  12313. }
  12314. // Test: Line with no colon (field name only)
  12315. TEST_F(SSEParsingTest, FieldNameOnly) {
  12316. sse::SSEMessage msg;
  12317. int retry_ms = 3000;
  12318. // According to SSE spec, this is treated as field name with empty value
  12319. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  12320. // Since we don't recognize "data" without colon, data should be empty
  12321. EXPECT_EQ(msg.data, "");
  12322. }
  12323. // Test: Trailing \r handling
  12324. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  12325. sse::SSEMessage msg;
  12326. int retry_ms = 3000;
  12327. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  12328. EXPECT_EQ(msg.data, "hello");
  12329. }
  12330. // Test: Unknown fields ignored
  12331. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  12332. sse::SSEMessage msg;
  12333. int retry_ms = 3000;
  12334. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  12335. EXPECT_EQ(msg.data, "");
  12336. EXPECT_EQ(msg.event, "message");
  12337. }
  12338. // Test: Space after colon is optional
  12339. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  12340. sse::SSEMessage msg1, msg2;
  12341. int retry_ms = 3000;
  12342. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  12343. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  12344. EXPECT_EQ(msg1.data, "hello");
  12345. EXPECT_EQ(msg2.data, "hello");
  12346. }
  12347. // Test: SSEMessage clear
  12348. TEST_F(SSEParsingTest, MessageClear) {
  12349. sse::SSEMessage msg;
  12350. msg.event = "custom";
  12351. msg.data = "some data";
  12352. msg.id = "123";
  12353. msg.clear();
  12354. EXPECT_EQ(msg.event, "message");
  12355. EXPECT_EQ(msg.data, "");
  12356. EXPECT_EQ(msg.id, "");
  12357. }
  12358. // Test: Complete event parsing
  12359. TEST_F(SSEParsingTest, CompleteEventParsing) {
  12360. sse::SSEMessage msg;
  12361. int retry_ms = 3000;
  12362. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  12363. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  12364. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  12365. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  12366. // Blank line ends event
  12367. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12368. EXPECT_EQ(msg.event, "notification");
  12369. EXPECT_EQ(msg.id, "evt-42");
  12370. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  12371. EXPECT_EQ(retry_ms, 1000);
  12372. }
  12373. //==============================================================================
  12374. // Integration Tests with Server
  12375. //==============================================================================
  12376. class SSEIntegrationTest : public ::testing::Test {
  12377. protected:
  12378. void SetUp() override {
  12379. stop_server_.store(false);
  12380. events_.clear();
  12381. server_ = httplib::detail::make_unique<Server>();
  12382. setup_server();
  12383. start_server();
  12384. }
  12385. void TearDown() override {
  12386. stop_server_.store(true);
  12387. event_cv_.notify_all();
  12388. server_->stop();
  12389. if (server_thread_.joinable()) { server_thread_.join(); }
  12390. }
  12391. void setup_server() {
  12392. // Simple SSE endpoint
  12393. server_->Get("/events", [this](const Request &req, Response &res) {
  12394. auto last_id = req.get_header_value("Last-Event-ID");
  12395. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  12396. res.set_chunked_content_provider(
  12397. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  12398. std::unique_lock<std::mutex> lock(event_mutex_);
  12399. if (event_cv_.wait_for(
  12400. lock, std::chrono::milliseconds(200), [this] {
  12401. return !events_.empty() || stop_server_.load();
  12402. })) {
  12403. if (stop_server_.load()) { return false; }
  12404. if (!events_.empty()) {
  12405. std::string event = events_.front();
  12406. events_.erase(events_.begin());
  12407. sink.write(event.data(), event.size());
  12408. return true;
  12409. }
  12410. }
  12411. return !stop_server_.load();
  12412. });
  12413. });
  12414. // Endpoint that returns error
  12415. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  12416. res.status = 500;
  12417. res.set_content("Internal Server Error", "text/plain");
  12418. });
  12419. // Endpoint for custom event types
  12420. server_->Get("/custom-events", [](const Request &, Response &res) {
  12421. res.set_chunked_content_provider(
  12422. "text/event-stream", [](size_t offset, DataSink &sink) {
  12423. if (offset == 0) {
  12424. std::string event = "event: update\ndata: updated\n\n"
  12425. "event: delete\ndata: deleted\n\n";
  12426. sink.write(event.data(), event.size());
  12427. }
  12428. return false; // End stream after sending
  12429. });
  12430. });
  12431. }
  12432. void start_server() {
  12433. port_ = server_->bind_to_any_port(HOST);
  12434. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  12435. // Wait for server to start
  12436. while (!server_->is_running()) {
  12437. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12438. }
  12439. }
  12440. int get_port() const { return port_; }
  12441. void send_event(const std::string &event) {
  12442. std::lock_guard<std::mutex> lock(event_mutex_);
  12443. events_.push_back(event);
  12444. event_cv_.notify_all();
  12445. }
  12446. std::unique_ptr<Server> server_;
  12447. std::thread server_thread_;
  12448. std::mutex event_mutex_;
  12449. std::condition_variable event_cv_;
  12450. std::vector<std::string> events_;
  12451. std::atomic<bool> stop_server_{false};
  12452. std::string last_received_event_id_;
  12453. int port_ = 0;
  12454. };
  12455. // Test: Successful connection and on_open callback
  12456. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  12457. // Add a simple endpoint that sends one event and closes
  12458. server_->Get("/simple-event", [](const Request &, Response &res) {
  12459. res.set_chunked_content_provider(
  12460. "text/event-stream", [](size_t offset, DataSink &sink) {
  12461. if (offset == 0) {
  12462. std::string event = "data: hello\n\n";
  12463. sink.write(event.data(), event.size());
  12464. }
  12465. return false; // Close stream after sending
  12466. });
  12467. });
  12468. Client client("localhost", get_port());
  12469. sse::SSEClient sse(client, "/simple-event");
  12470. std::atomic<bool> open_called{false};
  12471. std::atomic<bool> message_received{false};
  12472. sse.on_open([&open_called]() { open_called.store(true); });
  12473. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  12474. if (msg.data == "hello") { message_received.store(true); }
  12475. });
  12476. sse.set_reconnect_interval(100);
  12477. sse.set_max_reconnect_attempts(1);
  12478. // Start async
  12479. sse.start_async();
  12480. // Wait for message to be processed
  12481. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12482. sse.stop();
  12483. EXPECT_TRUE(open_called.load());
  12484. EXPECT_TRUE(message_received.load());
  12485. }
  12486. // Test: on_message callback
  12487. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  12488. // Endpoint that sends multiple events then closes
  12489. server_->Get("/multi-event", [](const Request &, Response &res) {
  12490. res.set_chunked_content_provider(
  12491. "text/event-stream", [](size_t offset, DataSink &sink) {
  12492. if (offset == 0) {
  12493. std::string events = "data: message1\n\ndata: message2\n\n";
  12494. sink.write(events.data(), events.size());
  12495. }
  12496. return false;
  12497. });
  12498. });
  12499. Client client("localhost", get_port());
  12500. sse::SSEClient sse(client, "/multi-event");
  12501. std::vector<std::string> received_messages;
  12502. std::mutex messages_mutex;
  12503. sse.on_message([&](const sse::SSEMessage &msg) {
  12504. std::lock_guard<std::mutex> lock(messages_mutex);
  12505. received_messages.push_back(msg.data);
  12506. });
  12507. sse.set_reconnect_interval(100);
  12508. sse.set_max_reconnect_attempts(1);
  12509. sse.start_async();
  12510. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12511. sse.stop();
  12512. std::lock_guard<std::mutex> lock(messages_mutex);
  12513. EXPECT_GE(received_messages.size(), 2u);
  12514. if (received_messages.size() >= 2) {
  12515. EXPECT_EQ(received_messages[0], "message1");
  12516. EXPECT_EQ(received_messages[1], "message2");
  12517. }
  12518. }
  12519. // Test: on_event for specific types
  12520. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  12521. Client client("localhost", get_port());
  12522. sse::SSEClient sse(client, "/custom-events");
  12523. std::atomic<bool> update_received{false};
  12524. std::atomic<bool> delete_received{false};
  12525. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  12526. if (msg.data == "updated") { update_received.store(true); }
  12527. });
  12528. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  12529. if (msg.data == "deleted") { delete_received.store(true); }
  12530. });
  12531. sse.set_max_reconnect_attempts(1);
  12532. sse.start_async();
  12533. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  12534. sse.stop();
  12535. EXPECT_TRUE(update_received.load());
  12536. EXPECT_TRUE(delete_received.load());
  12537. }
  12538. // Test: on_error callback on connection failure
  12539. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  12540. // Connect to a non-existent port
  12541. Client client("localhost", 59999);
  12542. sse::SSEClient sse(client, "/events");
  12543. std::atomic<bool> error_called{false};
  12544. Error received_error = Error::Success;
  12545. sse.on_error([&](Error err) {
  12546. error_called.store(true);
  12547. received_error = err;
  12548. });
  12549. sse.set_reconnect_interval(50);
  12550. sse.set_max_reconnect_attempts(1);
  12551. sse.start_async();
  12552. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12553. sse.stop();
  12554. EXPECT_TRUE(error_called.load());
  12555. EXPECT_NE(received_error, Error::Success);
  12556. }
  12557. // Test: Last-Event-ID header sent on reconnect
  12558. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  12559. // Endpoint that sends event with ID
  12560. server_->Get("/event-with-id", [](const Request &, Response &res) {
  12561. res.set_chunked_content_provider(
  12562. "text/event-stream", [](size_t offset, DataSink &sink) {
  12563. if (offset == 0) {
  12564. std::string event = "id: evt-123\ndata: test\n\n";
  12565. sink.write(event.data(), event.size());
  12566. }
  12567. return false;
  12568. });
  12569. });
  12570. Client client("localhost", get_port());
  12571. sse::SSEClient sse(client, "/event-with-id");
  12572. std::atomic<bool> id_received{false};
  12573. sse.on_message([&](const sse::SSEMessage &msg) {
  12574. if (!msg.id.empty()) { id_received.store(true); }
  12575. });
  12576. sse.set_reconnect_interval(100);
  12577. sse.set_max_reconnect_attempts(1);
  12578. sse.start_async();
  12579. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12580. sse.stop();
  12581. EXPECT_TRUE(id_received.load());
  12582. EXPECT_EQ(sse.last_event_id(), "evt-123");
  12583. }
  12584. // Test: Manual stop
  12585. TEST_F(SSEIntegrationTest, ManualStop) {
  12586. // Endpoint that sends one event and stays open briefly
  12587. std::atomic<bool> handler_running{true};
  12588. server_->Get("/stay-open", [&handler_running](const Request &,
  12589. Response &res) {
  12590. res.set_chunked_content_provider(
  12591. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  12592. if (offset == 0) {
  12593. std::string event = "data: connected\n\n";
  12594. sink.write(event.data(), event.size());
  12595. }
  12596. // Keep connection open while handler_running is true
  12597. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  12598. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  12599. }
  12600. return false;
  12601. });
  12602. });
  12603. Client client("localhost", get_port());
  12604. sse::SSEClient sse(client, "/stay-open");
  12605. std::atomic<bool> connected{false};
  12606. sse.on_open([&connected]() { connected.store(true); });
  12607. sse.set_reconnect_interval(100);
  12608. sse.set_max_reconnect_attempts(1);
  12609. sse.start_async();
  12610. // Wait for connection to establish
  12611. for (int i = 0; i < 20 && !connected.load(); ++i) {
  12612. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  12613. }
  12614. EXPECT_TRUE(connected.load());
  12615. EXPECT_TRUE(sse.is_connected());
  12616. // Signal handler to stop
  12617. handler_running.store(false);
  12618. // Stop SSE client
  12619. sse.stop();
  12620. EXPECT_FALSE(sse.is_connected());
  12621. }
  12622. // Test: SSEClient with custom headers
  12623. TEST_F(SSEIntegrationTest, CustomHeaders) {
  12624. // Setup a server endpoint that checks for custom header
  12625. std::atomic<bool> header_received{false};
  12626. server_->Get("/header-check", [&](const Request &req, Response &res) {
  12627. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  12628. header_received.store(true);
  12629. }
  12630. res.set_chunked_content_provider("text/event-stream",
  12631. [](size_t, DataSink &) { return false; });
  12632. });
  12633. Client client("localhost", get_port());
  12634. Headers headers = {{"X-Custom-Header", "custom-value"}};
  12635. sse::SSEClient sse(client, "/header-check", headers);
  12636. sse.set_max_reconnect_attempts(1);
  12637. sse.start_async();
  12638. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12639. sse.stop();
  12640. EXPECT_TRUE(header_received.load());
  12641. }
  12642. // Test: Reconnect interval configuration
  12643. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  12644. Client client("localhost", get_port());
  12645. sse::SSEClient sse(client, "/events");
  12646. auto &result = sse.set_reconnect_interval(500);
  12647. // Builder pattern should return reference to self
  12648. EXPECT_EQ(&result, &sse);
  12649. }
  12650. // Test: Max reconnect attempts
  12651. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  12652. // Connect to non-existent port to force reconnects
  12653. Client client("localhost", 59998);
  12654. sse::SSEClient sse(client, "/events");
  12655. std::atomic<int> error_count{0};
  12656. sse.on_error([&](Error) { error_count.fetch_add(1); });
  12657. sse.set_reconnect_interval(50);
  12658. sse.set_max_reconnect_attempts(2);
  12659. auto start = std::chrono::steady_clock::now();
  12660. sse.start(); // Blocking call
  12661. auto end = std::chrono::steady_clock::now();
  12662. // Should have stopped after 2 failed attempts
  12663. EXPECT_GE(error_count.load(), 2);
  12664. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  12665. auto duration =
  12666. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  12667. #ifdef _WIN32
  12668. // Windows is much slower for socket connection failures
  12669. EXPECT_LT(duration.count(), 7000);
  12670. #else
  12671. EXPECT_LT(duration.count(), 1000);
  12672. #endif
  12673. }
  12674. // Test: Multi-line data in integration
  12675. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  12676. // Endpoint with multi-line data
  12677. server_->Get("/multiline-data", [](const Request &, Response &res) {
  12678. res.set_chunked_content_provider(
  12679. "text/event-stream", [](size_t offset, DataSink &sink) {
  12680. if (offset == 0) {
  12681. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  12682. sink.write(event.data(), event.size());
  12683. }
  12684. return false;
  12685. });
  12686. });
  12687. Client client("localhost", get_port());
  12688. sse::SSEClient sse(client, "/multiline-data");
  12689. std::string received_data;
  12690. std::mutex data_mutex;
  12691. sse.on_message([&](const sse::SSEMessage &msg) {
  12692. std::lock_guard<std::mutex> lock(data_mutex);
  12693. received_data = msg.data;
  12694. });
  12695. sse.set_reconnect_interval(100);
  12696. sse.set_max_reconnect_attempts(1);
  12697. sse.start_async();
  12698. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12699. sse.stop();
  12700. std::lock_guard<std::mutex> lock(data_mutex);
  12701. EXPECT_EQ(received_data, "line1\nline2\nline3");
  12702. }
  12703. // Test: Auto-reconnect after server disconnection
  12704. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  12705. std::atomic<int> connection_count{0};
  12706. std::atomic<int> message_count{0};
  12707. // Endpoint that sends one event and closes, forcing reconnect
  12708. server_->Get("/reconnect-test",
  12709. [&connection_count](const Request &, Response &res) {
  12710. connection_count.fetch_add(1);
  12711. res.set_chunked_content_provider(
  12712. "text/event-stream", [](size_t offset, DataSink &sink) {
  12713. if (offset == 0) {
  12714. std::string event = "data: hello\n\n";
  12715. sink.write(event.data(), event.size());
  12716. }
  12717. return false; // Close connection after sending
  12718. });
  12719. });
  12720. Client client("localhost", get_port());
  12721. sse::SSEClient sse(client, "/reconnect-test");
  12722. sse.on_message([&message_count](const sse::SSEMessage &) {
  12723. message_count.fetch_add(1);
  12724. });
  12725. sse.set_reconnect_interval(100);
  12726. sse.set_max_reconnect_attempts(3);
  12727. sse.start_async();
  12728. // Wait long enough for multiple reconnects
  12729. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  12730. sse.stop();
  12731. // Should have connected multiple times (initial + reconnects)
  12732. EXPECT_GE(connection_count.load(), 2);
  12733. // Should have received messages from multiple connections
  12734. EXPECT_GE(message_count.load(), 2);
  12735. }
  12736. // Test: Last-Event-ID sent on reconnect
  12737. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  12738. std::atomic<int> connection_count{0};
  12739. std::vector<std::string> received_last_event_ids;
  12740. std::mutex id_mutex;
  12741. // Endpoint that checks Last-Event-ID header and sends event with ID
  12742. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  12743. int conn = connection_count.fetch_add(1);
  12744. // Capture the Last-Event-ID header from each connection
  12745. {
  12746. std::lock_guard<std::mutex> lock(id_mutex);
  12747. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  12748. }
  12749. res.set_chunked_content_provider(
  12750. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  12751. if (offset == 0) {
  12752. std::string event =
  12753. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  12754. sink.write(event.data(), event.size());
  12755. }
  12756. return false;
  12757. });
  12758. });
  12759. Client client("localhost", get_port());
  12760. sse::SSEClient sse(client, "/reconnect-with-id");
  12761. sse.set_reconnect_interval(100);
  12762. sse.set_max_reconnect_attempts(3);
  12763. sse.start_async();
  12764. // Wait for at least 2 connections
  12765. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12766. sse.stop();
  12767. // Verify behavior
  12768. std::lock_guard<std::mutex> lock(id_mutex);
  12769. EXPECT_GE(received_last_event_ids.size(), 2u);
  12770. // First connection should have no Last-Event-ID
  12771. if (!received_last_event_ids.empty()) {
  12772. EXPECT_EQ(received_last_event_ids[0], "");
  12773. }
  12774. // Second connection should have Last-Event-ID from first connection
  12775. if (received_last_event_ids.size() >= 2) {
  12776. EXPECT_EQ(received_last_event_ids[1], "event-0");
  12777. }
  12778. }
  12779. TEST(Issue2318Test, EmptyHostString) {
  12780. {
  12781. httplib::Client cli_empty("", PORT);
  12782. auto res = cli_empty.Get("/");
  12783. ASSERT_FALSE(res);
  12784. EXPECT_EQ(httplib::Error::Connection, res.error());
  12785. }
  12786. {
  12787. httplib::Client cli(" ", PORT);
  12788. auto res = cli.Get("/");
  12789. ASSERT_FALSE(res);
  12790. EXPECT_EQ(httplib::Error::Connection, res.error());
  12791. }
  12792. }
  12793. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12794. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  12795. Server svr;
  12796. // Set a small payload limit (1KB)
  12797. svr.set_payload_max_length(1024);
  12798. svr.Post("/test", [&](const Request &req, Response &res) {
  12799. res.set_content("Body size: " + std::to_string(req.body.size()),
  12800. "text/plain");
  12801. });
  12802. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12803. auto se = detail::scope_exit([&] {
  12804. svr.stop();
  12805. listen_thread.join();
  12806. });
  12807. svr.wait_until_ready();
  12808. // Create data that compresses well but exceeds limit when decompressed
  12809. // 8KB of repeated null bytes compresses to a very small size
  12810. std::string original_data(8 * 1024, '\0');
  12811. // Compress the data using gzip
  12812. std::string compressed_data;
  12813. detail::gzip_compressor compressor;
  12814. compressor.compress(original_data.data(), original_data.size(), true,
  12815. [&](const char *data, size_t size) {
  12816. compressed_data.append(data, size);
  12817. return true;
  12818. });
  12819. // Verify compression worked (compressed should be much smaller)
  12820. ASSERT_LT(compressed_data.size(), original_data.size());
  12821. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  12822. // Send compressed data with Content-Encoding: gzip
  12823. Client cli(HOST, PORT);
  12824. Headers headers = {{"Content-Encoding", "gzip"}};
  12825. auto res =
  12826. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  12827. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  12828. ASSERT_TRUE(res);
  12829. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12830. }
  12831. #endif
  12832. // ============================================================================
  12833. // OpenSSL-Specific Tests
  12834. // ============================================================================
  12835. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12836. X509 *readCertificate(const std::string &strFileName) {
  12837. std::ifstream inStream(strFileName);
  12838. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  12839. std::istreambuf_iterator<char>());
  12840. if (strCertPEM.empty()) return (nullptr);
  12841. BIO *pbCert = BIO_new(BIO_s_mem());
  12842. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  12843. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  12844. BIO_free(pbCert);
  12845. return (pCert);
  12846. }
  12847. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  12848. std::ifstream inStream(strFileName);
  12849. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  12850. std::istreambuf_iterator<char>());
  12851. if (strPrivateKeyPEM.empty()) return (nullptr);
  12852. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  12853. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  12854. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  12855. BIO_free(pbPrivKey);
  12856. return (pPrivateKey);
  12857. }
  12858. TEST(BindServerTest, UpdateCerts) {
  12859. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12860. int port = svr.bind_to_any_port("0.0.0.0");
  12861. ASSERT_TRUE(svr.is_valid());
  12862. ASSERT_TRUE(port > 0);
  12863. X509 *cert = readCertificate(SERVER_CERT_FILE);
  12864. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  12865. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  12866. ASSERT_TRUE(cert != nullptr);
  12867. ASSERT_TRUE(ca_cert != nullptr);
  12868. ASSERT_TRUE(key != nullptr);
  12869. X509_STORE *cert_store = X509_STORE_new();
  12870. X509_STORE_add_cert(cert_store, ca_cert);
  12871. // svr.update_certs(cert, key, cert_store); // deprecated
  12872. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12873. CLIENT_CA_CERT_FILE);
  12874. ASSERT_TRUE(svr.is_valid());
  12875. svr.stop();
  12876. X509_STORE_free(cert_store);
  12877. X509_free(cert);
  12878. X509_free(ca_cert);
  12879. EVP_PKEY_free(key);
  12880. }
  12881. // Test that SSLServer(X509*, EVP_PKEY*, X509_STORE*) constructor sets
  12882. // client CA list correctly for TLS handshake
  12883. TEST(SSLClientServerTest, X509ConstructorSetsClientCAList) {
  12884. X509 *cert = readCertificate(SERVER_CERT_FILE);
  12885. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  12886. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  12887. ASSERT_TRUE(cert != nullptr);
  12888. ASSERT_TRUE(ca_cert != nullptr);
  12889. ASSERT_TRUE(key != nullptr);
  12890. X509_STORE *cert_store = X509_STORE_new();
  12891. X509_STORE_add_cert(cert_store, ca_cert);
  12892. // Use X509-based constructor (deprecated but should still work correctly)
  12893. #pragma GCC diagnostic push
  12894. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  12895. SSLServer svr(cert, key, cert_store);
  12896. #pragma GCC diagnostic pop
  12897. ASSERT_TRUE(svr.is_valid());
  12898. // Verify that client CA list is set in SSL_CTX
  12899. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  12900. ASSERT_TRUE(ssl_ctx != nullptr);
  12901. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  12902. ASSERT_TRUE(ca_list != nullptr);
  12903. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  12904. X509_free(cert);
  12905. X509_free(ca_cert);
  12906. EVP_PKEY_free(key);
  12907. }
  12908. // Test that update_certs() updates client CA list correctly
  12909. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  12910. // Start with file-based constructor
  12911. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12912. ASSERT_TRUE(svr.is_valid());
  12913. // Initially no client CA list should be set
  12914. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  12915. ASSERT_TRUE(ssl_ctx != nullptr);
  12916. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  12917. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  12918. EXPECT_EQ(0, count_before);
  12919. // Now update with client CA (PEM string)
  12920. std::string cert_pem, key_pem, ca_pem;
  12921. read_file(SERVER_CERT_FILE, cert_pem);
  12922. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  12923. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  12924. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  12925. ASSERT_TRUE(svr.is_valid());
  12926. // Now client CA list should be set
  12927. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  12928. ASSERT_TRUE(ca_list_after != nullptr);
  12929. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  12930. }
  12931. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  12932. // Test that the file-path SSLServer constructor properly sets the client CA
  12933. // list that is sent to clients during the TLS handshake (CertificateRequest)
  12934. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12935. ASSERT_TRUE(svr.is_valid());
  12936. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  12937. ASSERT_TRUE(ssl_ctx != nullptr);
  12938. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  12939. ASSERT_TRUE(ca_list != nullptr);
  12940. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  12941. }
  12942. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  12943. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  12944. // prepare large data
  12945. std::random_device seed_gen;
  12946. std::mt19937 random(seed_gen());
  12947. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  12948. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  12949. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  12950. // server
  12951. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12952. ASSERT_TRUE(svr.is_valid());
  12953. svr.Post("/binary", [&](const Request &req, Response &res) {
  12954. EXPECT_EQ(large_size_byte, req.body.size());
  12955. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  12956. res.set_content(req.body, "application/octet-stream");
  12957. });
  12958. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12959. auto se = detail::scope_exit([&] {
  12960. svr.stop();
  12961. listen_thread.join();
  12962. ASSERT_FALSE(svr.is_running());
  12963. });
  12964. svr.wait_until_ready();
  12965. // client POST
  12966. SSLClient cli("localhost", PORT);
  12967. cli.enable_server_certificate_verification(false);
  12968. cli.set_read_timeout(std::chrono::seconds(100));
  12969. cli.set_write_timeout(std::chrono::seconds(100));
  12970. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  12971. large_size_byte, "application/octet-stream");
  12972. // compare
  12973. EXPECT_EQ(StatusCode::OK_200, res->status);
  12974. EXPECT_EQ(large_size_byte, res->body.size());
  12975. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  12976. }
  12977. #endif
  12978. // ============================================================================
  12979. // MbedTLS-Specific Tests
  12980. // ============================================================================
  12981. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  12982. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  12983. using namespace httplib::tls;
  12984. // Track if callback was invoked
  12985. bool callback_invoked = false;
  12986. // The callback receives void* ctx which is actually MbedTlsContext*
  12987. // We can access the mbedtls_ssl_config via the context
  12988. auto setup_callback = [&callback_invoked](void *ctx) {
  12989. callback_invoked = true;
  12990. // Cast to MbedTlsContext* to access the ssl config
  12991. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  12992. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  12993. // Use static variables to hold certificate data (simplified for test)
  12994. static mbedtls_x509_crt own_cert;
  12995. static mbedtls_pk_context own_key;
  12996. static mbedtls_x509_crt ca_chain;
  12997. static bool initialized = false;
  12998. if (!initialized) {
  12999. mbedtls_x509_crt_init(&own_cert);
  13000. mbedtls_pk_init(&own_key);
  13001. mbedtls_x509_crt_init(&ca_chain);
  13002. // Load server certificate
  13003. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  13004. return false;
  13005. }
  13006. // Load server private key
  13007. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  13008. #if MBEDTLS_VERSION_MAJOR >= 3
  13009. ,
  13010. mbedtls_ctr_drbg_random, nullptr
  13011. #endif
  13012. ) != 0) {
  13013. return false;
  13014. }
  13015. // Load CA chain for client verification
  13016. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  13017. return false;
  13018. }
  13019. initialized = true;
  13020. }
  13021. // Configure the SSL config
  13022. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  13023. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  13024. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  13025. // Set minimum TLS version using mbedTLS native API
  13026. #if MBEDTLS_VERSION_MAJOR >= 3
  13027. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  13028. #else
  13029. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  13030. MBEDTLS_SSL_MINOR_VERSION_3);
  13031. #endif
  13032. return true;
  13033. };
  13034. SSLServer svr(setup_callback);
  13035. ASSERT_TRUE(svr.is_valid());
  13036. ASSERT_TRUE(callback_invoked);
  13037. svr.Get("/test", [&](const Request &req, Response &res) {
  13038. res.set_content("test", "text/plain");
  13039. auto cert = req.peer_cert();
  13040. ASSERT_TRUE(static_cast<bool>(cert));
  13041. auto common_name = cert.subject_cn();
  13042. EXPECT_EQ("Common Name", common_name);
  13043. });
  13044. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13045. auto se = detail::scope_exit([&] {
  13046. svr.stop();
  13047. t.join();
  13048. ASSERT_FALSE(svr.is_running());
  13049. });
  13050. svr.wait_until_ready();
  13051. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13052. cli.enable_server_certificate_verification(false);
  13053. cli.set_connection_timeout(30);
  13054. auto res = cli.Get("/test");
  13055. ASSERT_TRUE(res);
  13056. ASSERT_EQ(StatusCode::OK_200, res->status);
  13057. }
  13058. #endif
  13059. // WebSocket Tests
  13060. TEST(WebSocketTest, RSVBitsMustBeZero) {
  13061. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  13062. // defining the meaning of these bits has been negotiated.
  13063. auto make_frame = [](uint8_t first_byte) {
  13064. std::string frame;
  13065. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  13066. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  13067. frame += "Hello";
  13068. return frame;
  13069. };
  13070. // RSV1 set (0x40)
  13071. {
  13072. detail::BufferStream strm;
  13073. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  13074. ws::Opcode opcode;
  13075. std::string payload;
  13076. bool fin;
  13077. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13078. false, 1024));
  13079. }
  13080. // RSV2 set (0x20)
  13081. {
  13082. detail::BufferStream strm;
  13083. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  13084. ws::Opcode opcode;
  13085. std::string payload;
  13086. bool fin;
  13087. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13088. false, 1024));
  13089. }
  13090. // RSV3 set (0x10)
  13091. {
  13092. detail::BufferStream strm;
  13093. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  13094. ws::Opcode opcode;
  13095. std::string payload;
  13096. bool fin;
  13097. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13098. false, 1024));
  13099. }
  13100. // No RSV bits set - should succeed
  13101. {
  13102. detail::BufferStream strm;
  13103. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  13104. ws::Opcode opcode;
  13105. std::string payload;
  13106. bool fin;
  13107. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13108. false, 1024));
  13109. EXPECT_EQ(ws::Opcode::Text, opcode);
  13110. EXPECT_EQ("Hello", payload);
  13111. EXPECT_TRUE(fin);
  13112. }
  13113. }
  13114. TEST(WebSocketTest, ControlFrameValidation) {
  13115. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  13116. // payload length <= 125.
  13117. // Ping with FIN=0 - must be rejected
  13118. {
  13119. detail::BufferStream strm;
  13120. std::string frame;
  13121. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  13122. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13123. strm.write(frame.data(), frame.size());
  13124. ws::Opcode opcode;
  13125. std::string payload;
  13126. bool fin;
  13127. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13128. false, 1024));
  13129. }
  13130. // Close with FIN=0 - must be rejected
  13131. {
  13132. detail::BufferStream strm;
  13133. std::string frame;
  13134. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  13135. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13136. strm.write(frame.data(), frame.size());
  13137. ws::Opcode opcode;
  13138. std::string payload;
  13139. bool fin;
  13140. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13141. false, 1024));
  13142. }
  13143. // Ping with payload_len=126 (extended length) - must be rejected
  13144. {
  13145. detail::BufferStream strm;
  13146. std::string frame;
  13147. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13148. frame += static_cast<char>(126); // payload_len=126 (>125)
  13149. frame += static_cast<char>(0x00); // extended length high byte
  13150. frame += static_cast<char>(126); // extended length low byte
  13151. frame += std::string(126, 'x');
  13152. strm.write(frame.data(), frame.size());
  13153. ws::Opcode opcode;
  13154. std::string payload;
  13155. bool fin;
  13156. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13157. false, 1024));
  13158. }
  13159. // Ping with FIN=1 and payload_len=125 - should succeed
  13160. {
  13161. detail::BufferStream strm;
  13162. std::string frame;
  13163. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13164. frame += static_cast<char>(125); // payload_len=125
  13165. frame += std::string(125, 'x');
  13166. strm.write(frame.data(), frame.size());
  13167. ws::Opcode opcode;
  13168. std::string payload;
  13169. bool fin;
  13170. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13171. false, 1024));
  13172. EXPECT_EQ(ws::Opcode::Ping, opcode);
  13173. EXPECT_EQ(125u, payload.size());
  13174. EXPECT_TRUE(fin);
  13175. }
  13176. }
  13177. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  13178. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  13179. // length MUST be 0.
  13180. // MSB set - must be rejected
  13181. {
  13182. detail::BufferStream strm;
  13183. std::string frame;
  13184. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13185. frame += static_cast<char>(127); // 64-bit extended length
  13186. frame += static_cast<char>(0x80); // MSB set (invalid)
  13187. frame += std::string(7, '\0'); // remaining 7 bytes of length
  13188. strm.write(frame.data(), frame.size());
  13189. ws::Opcode opcode;
  13190. std::string payload;
  13191. bool fin;
  13192. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13193. false, 1024));
  13194. }
  13195. // MSB clear - should pass length parsing (will be rejected by max_len,
  13196. // but that's a different check; use a small length to verify)
  13197. {
  13198. detail::BufferStream strm;
  13199. std::string frame;
  13200. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13201. frame += static_cast<char>(127); // 64-bit extended length
  13202. frame += std::string(7, '\0'); // high bytes = 0
  13203. frame += static_cast<char>(0x03); // length = 3
  13204. frame += "abc";
  13205. strm.write(frame.data(), frame.size());
  13206. ws::Opcode opcode;
  13207. std::string payload;
  13208. bool fin;
  13209. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13210. false, 1024));
  13211. EXPECT_EQ(ws::Opcode::Text, opcode);
  13212. EXPECT_EQ("abc", payload);
  13213. }
  13214. }
  13215. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  13216. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  13217. // Valid UTF-8
  13218. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  13219. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  13220. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  13221. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  13222. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  13223. // Invalid UTF-8
  13224. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  13225. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  13226. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  13227. EXPECT_FALSE(
  13228. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  13229. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  13230. }
  13231. TEST(WebSocketTest, ConnectAndDisconnect) {
  13232. Server svr;
  13233. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  13234. std::string msg;
  13235. while (ws.read(msg)) {}
  13236. });
  13237. auto port = svr.bind_to_any_port(HOST);
  13238. std::thread t([&]() { svr.listen_after_bind(); });
  13239. svr.wait_until_ready();
  13240. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  13241. ASSERT_TRUE(client.connect());
  13242. EXPECT_TRUE(client.is_open());
  13243. client.close();
  13244. EXPECT_FALSE(client.is_open());
  13245. svr.stop();
  13246. t.join();
  13247. }
  13248. TEST(WebSocketTest, ValidURL) {
  13249. ws::WebSocketClient ws1("ws://localhost:8080/path");
  13250. EXPECT_TRUE(ws1.is_valid());
  13251. ws::WebSocketClient ws2("ws://example.com/path");
  13252. EXPECT_TRUE(ws2.is_valid());
  13253. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  13254. EXPECT_TRUE(ws3.is_valid());
  13255. #ifdef CPPHTTPLIB_SSL_ENABLED
  13256. ws::WebSocketClient wss1("wss://example.com/path");
  13257. EXPECT_TRUE(wss1.is_valid());
  13258. ws::WebSocketClient wss2("wss://example.com:443/path");
  13259. EXPECT_TRUE(wss2.is_valid());
  13260. #endif
  13261. }
  13262. TEST(WebSocketTest, InvalidURL) {
  13263. // No scheme
  13264. ws::WebSocketClient ws1("localhost:8080/path");
  13265. EXPECT_FALSE(ws1.is_valid());
  13266. // No path
  13267. ws::WebSocketClient ws2("ws://localhost:8080");
  13268. EXPECT_FALSE(ws2.is_valid());
  13269. // Empty string
  13270. ws::WebSocketClient ws3("");
  13271. EXPECT_FALSE(ws3.is_valid());
  13272. // Missing host
  13273. ws::WebSocketClient ws4("ws://:8080/path");
  13274. EXPECT_FALSE(ws4.is_valid());
  13275. }
  13276. TEST(WebSocketTest, UnsupportedScheme) {
  13277. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13278. ws::WebSocketClient ws1("http://localhost:8080/path");
  13279. EXPECT_FALSE(ws1.is_valid());
  13280. ws::WebSocketClient ws2("https://localhost:8080/path");
  13281. EXPECT_FALSE(ws2.is_valid());
  13282. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  13283. EXPECT_FALSE(ws3.is_valid());
  13284. #else
  13285. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  13286. std::invalid_argument);
  13287. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  13288. std::invalid_argument);
  13289. #endif
  13290. }
  13291. TEST(WebSocketTest, ConnectWhenInvalid) {
  13292. ws::WebSocketClient ws("not a valid url");
  13293. EXPECT_FALSE(ws.is_valid());
  13294. EXPECT_FALSE(ws.connect());
  13295. }
  13296. TEST(WebSocketTest, DefaultPort) {
  13297. ws::WebSocketClient ws1("ws://example.com/path");
  13298. EXPECT_TRUE(ws1.is_valid());
  13299. // ws:// defaults to port 80 (verified by successful parse)
  13300. #ifdef CPPHTTPLIB_SSL_ENABLED
  13301. ws::WebSocketClient ws2("wss://example.com/path");
  13302. EXPECT_TRUE(ws2.is_valid());
  13303. // wss:// defaults to port 443 (verified by successful parse)
  13304. #endif
  13305. }
  13306. TEST(WebSocketTest, IPv6LiteralAddress) {
  13307. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  13308. EXPECT_TRUE(ws1.is_valid());
  13309. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  13310. EXPECT_TRUE(ws2.is_valid());
  13311. }
  13312. TEST(WebSocketTest, ComplexPath) {
  13313. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  13314. EXPECT_TRUE(ws1.is_valid());
  13315. ws::WebSocketClient ws2("ws://localhost:8080/");
  13316. EXPECT_TRUE(ws2.is_valid());
  13317. }
  13318. class WebSocketIntegrationTest : public ::testing::Test {
  13319. protected:
  13320. void SetUp() override {
  13321. server_ = httplib::detail::make_unique<Server>();
  13322. setup_server();
  13323. start_server();
  13324. }
  13325. void TearDown() override {
  13326. server_->stop();
  13327. if (server_thread_.joinable()) { server_thread_.join(); }
  13328. }
  13329. void setup_server() {
  13330. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  13331. std::string msg;
  13332. ws::ReadResult ret;
  13333. while ((ret = ws.read(msg))) {
  13334. if (ret == ws::Binary) {
  13335. ws.send(msg.data(), msg.size());
  13336. } else {
  13337. ws.send(msg);
  13338. }
  13339. }
  13340. });
  13341. server_->WebSocket("/ws-echo-string",
  13342. [](const Request &, ws::WebSocket &ws) {
  13343. std::string msg;
  13344. while (ws.read(msg)) {
  13345. ws.send("echo: " + msg);
  13346. }
  13347. });
  13348. server_->WebSocket(
  13349. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  13350. // Echo back request metadata
  13351. ws.send("path:" + req.path);
  13352. ws.send("header:" + req.get_header_value("X-Test-Header"));
  13353. std::string msg;
  13354. while (ws.read(msg)) {}
  13355. });
  13356. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  13357. std::string msg;
  13358. ws.read(msg); // wait for a message
  13359. ws.close();
  13360. });
  13361. server_->WebSocket("/ws-close-status",
  13362. [](const Request &, ws::WebSocket &ws) {
  13363. std::string msg;
  13364. ws.read(msg); // wait for a message
  13365. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  13366. });
  13367. server_->WebSocket(
  13368. "/ws-subprotocol",
  13369. [](const Request &, ws::WebSocket &ws) {
  13370. std::string msg;
  13371. while (ws.read(msg)) {
  13372. ws.send(msg);
  13373. }
  13374. },
  13375. [](const std::vector<std::string> &protocols) -> std::string {
  13376. for (const auto &p : protocols) {
  13377. if (p == "graphql-ws") { return p; }
  13378. }
  13379. return "";
  13380. });
  13381. }
  13382. void start_server() {
  13383. port_ = server_->bind_to_any_port(HOST);
  13384. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13385. server_->wait_until_ready();
  13386. }
  13387. std::unique_ptr<Server> server_;
  13388. std::thread server_thread_;
  13389. int port_ = 0;
  13390. };
  13391. TEST_F(WebSocketIntegrationTest, TextEcho) {
  13392. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13393. "/ws-echo");
  13394. ASSERT_TRUE(client.connect());
  13395. ASSERT_TRUE(client.is_open());
  13396. ASSERT_TRUE(client.send("Hello WebSocket"));
  13397. std::string msg;
  13398. EXPECT_EQ(ws::Text, client.read(msg));
  13399. EXPECT_EQ("Hello WebSocket", msg);
  13400. client.close();
  13401. }
  13402. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  13403. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13404. "/ws-echo");
  13405. ASSERT_TRUE(client.connect());
  13406. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  13407. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  13408. std::string msg;
  13409. EXPECT_EQ(ws::Binary, client.read(msg));
  13410. EXPECT_EQ(binary_data, msg);
  13411. client.close();
  13412. }
  13413. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  13414. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13415. "/ws-echo");
  13416. ASSERT_TRUE(client.connect());
  13417. for (int i = 0; i < 10; i++) {
  13418. auto text = "message " + std::to_string(i);
  13419. ASSERT_TRUE(client.send(text));
  13420. std::string msg;
  13421. ASSERT_TRUE(client.read(msg));
  13422. EXPECT_EQ(text, msg);
  13423. }
  13424. client.close();
  13425. }
  13426. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  13427. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13428. "/ws-close");
  13429. ASSERT_TRUE(client.connect());
  13430. // Send a message to trigger the server to close
  13431. ASSERT_TRUE(client.send("trigger close"));
  13432. // The server will close, so read should return false
  13433. std::string msg;
  13434. EXPECT_FALSE(client.read(msg));
  13435. EXPECT_FALSE(client.is_open());
  13436. }
  13437. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  13438. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13439. "/ws-echo");
  13440. ASSERT_TRUE(client.connect());
  13441. // 128KB message
  13442. std::string large_data(128 * 1024, 'X');
  13443. ASSERT_TRUE(client.send(large_data));
  13444. std::string msg;
  13445. ASSERT_TRUE(client.read(msg));
  13446. EXPECT_EQ(large_data, msg);
  13447. client.close();
  13448. }
  13449. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  13450. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13451. "/ws-echo");
  13452. ASSERT_TRUE(client.connect());
  13453. const int num_threads = 4;
  13454. std::vector<std::thread> threads;
  13455. std::atomic<int> send_count{0};
  13456. for (int t = 0; t < num_threads; t++) {
  13457. threads.emplace_back([&client, &send_count, t]() {
  13458. for (int i = 0; i < 5; i++) {
  13459. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  13460. if (client.send(text)) { send_count++; }
  13461. }
  13462. });
  13463. }
  13464. for (auto &th : threads) {
  13465. th.join();
  13466. }
  13467. int received = 0;
  13468. std::string msg;
  13469. while (received < send_count.load()) {
  13470. if (!client.read(msg)) { break; }
  13471. received++;
  13472. }
  13473. EXPECT_EQ(send_count.load(), received);
  13474. client.close();
  13475. }
  13476. TEST_F(WebSocketIntegrationTest, ReadString) {
  13477. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13478. "/ws-echo-string");
  13479. ASSERT_TRUE(client.connect());
  13480. ASSERT_TRUE(client.send("hello"));
  13481. std::string msg;
  13482. ASSERT_TRUE(client.read(msg));
  13483. EXPECT_EQ("echo: hello", msg);
  13484. ASSERT_TRUE(client.send("world"));
  13485. ASSERT_TRUE(client.read(msg));
  13486. EXPECT_EQ("echo: world", msg);
  13487. client.close();
  13488. }
  13489. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  13490. Headers headers = {{"X-Test-Header", "test-value"}};
  13491. ws::WebSocketClient client(
  13492. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  13493. ASSERT_TRUE(client.connect());
  13494. std::string msg;
  13495. ASSERT_TRUE(client.read(msg));
  13496. EXPECT_EQ("path:/ws-request-info", msg);
  13497. ASSERT_TRUE(client.read(msg));
  13498. EXPECT_EQ("header:test-value", msg);
  13499. client.close();
  13500. }
  13501. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  13502. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13503. "/ws-echo");
  13504. client.set_read_timeout(1, 0); // 1 second
  13505. ASSERT_TRUE(client.connect());
  13506. // Don't send anything — server echo handler waits for a message,
  13507. // so read() should time out and return false.
  13508. std::string msg;
  13509. EXPECT_FALSE(client.read(msg));
  13510. }
  13511. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  13512. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13513. "/ws-echo");
  13514. client.set_read_timeout(5, 0);
  13515. ASSERT_TRUE(client.connect());
  13516. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  13517. // The server should reject it and close the connection.
  13518. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  13519. client.send(oversized);
  13520. // The server's read() should have failed due to payload limit,
  13521. // so our read() should return false (connection closed).
  13522. std::string msg;
  13523. EXPECT_FALSE(client.read(msg));
  13524. }
  13525. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  13526. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13527. "/ws-echo");
  13528. client.set_read_timeout(10, 0);
  13529. ASSERT_TRUE(client.connect());
  13530. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  13531. // This should succeed.
  13532. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  13533. ASSERT_TRUE(client.send(at_limit));
  13534. std::string msg;
  13535. ASSERT_TRUE(client.read(msg));
  13536. EXPECT_EQ(at_limit.size(), msg.size());
  13537. client.close();
  13538. }
  13539. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  13540. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13541. "/nonexistent");
  13542. EXPECT_FALSE(client.connect());
  13543. EXPECT_FALSE(client.is_open());
  13544. }
  13545. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  13546. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13547. "/ws-echo");
  13548. ASSERT_TRUE(client.connect());
  13549. ASSERT_TRUE(client.send(""));
  13550. std::string msg;
  13551. EXPECT_EQ(ws::Text, client.read(msg));
  13552. EXPECT_EQ("", msg);
  13553. client.close();
  13554. }
  13555. TEST_F(WebSocketIntegrationTest, Reconnect) {
  13556. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13557. "/ws-echo");
  13558. // First connection
  13559. ASSERT_TRUE(client.connect());
  13560. ASSERT_TRUE(client.send("first"));
  13561. std::string msg;
  13562. ASSERT_TRUE(client.read(msg));
  13563. EXPECT_EQ("first", msg);
  13564. client.close();
  13565. EXPECT_FALSE(client.is_open());
  13566. // Reconnect using the same client object
  13567. ASSERT_TRUE(client.connect());
  13568. ASSERT_TRUE(client.is_open());
  13569. ASSERT_TRUE(client.send("second"));
  13570. ASSERT_TRUE(client.read(msg));
  13571. EXPECT_EQ("second", msg);
  13572. client.close();
  13573. }
  13574. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  13575. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13576. "/ws-close-status");
  13577. ASSERT_TRUE(client.connect());
  13578. // Trigger the server to close with GoingAway status
  13579. ASSERT_TRUE(client.send("trigger"));
  13580. // read() should return false after receiving the close frame
  13581. std::string msg;
  13582. EXPECT_FALSE(client.read(msg));
  13583. EXPECT_FALSE(client.is_open());
  13584. }
  13585. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  13586. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13587. "/ws-echo");
  13588. ASSERT_TRUE(client.connect());
  13589. client.close(ws::CloseStatus::GoingAway, "client leaving");
  13590. EXPECT_FALSE(client.is_open());
  13591. }
  13592. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  13593. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  13594. ws::WebSocketClient client(
  13595. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  13596. ASSERT_TRUE(client.connect());
  13597. // Server should have selected graphql-ws
  13598. EXPECT_EQ("graphql-ws", client.subprotocol());
  13599. client.close();
  13600. }
  13601. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  13602. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  13603. ws::WebSocketClient client(
  13604. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  13605. ASSERT_TRUE(client.connect());
  13606. // Server should not have selected any subprotocol
  13607. EXPECT_TRUE(client.subprotocol().empty());
  13608. client.close();
  13609. }
  13610. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  13611. // Connect without requesting any subprotocol
  13612. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13613. "/ws-subprotocol");
  13614. ASSERT_TRUE(client.connect());
  13615. EXPECT_TRUE(client.subprotocol().empty());
  13616. client.close();
  13617. }
  13618. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  13619. Server svr;
  13620. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  13621. if (!req.has_header("Authorization")) {
  13622. res.status = StatusCode::Unauthorized_401;
  13623. res.set_content("Unauthorized", "text/plain");
  13624. return Server::HandlerResponse::Handled;
  13625. }
  13626. return Server::HandlerResponse::Unhandled;
  13627. });
  13628. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  13629. std::string msg;
  13630. while (ws.read(msg)) {
  13631. ws.send(msg);
  13632. }
  13633. });
  13634. auto port = svr.bind_to_any_port("localhost");
  13635. std::thread t([&]() { svr.listen_after_bind(); });
  13636. svr.wait_until_ready();
  13637. // Without Authorization header - should be rejected before upgrade
  13638. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  13639. EXPECT_FALSE(client1.connect());
  13640. // With Authorization header - should succeed
  13641. Headers headers = {{"Authorization", "Bearer token123"}};
  13642. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  13643. headers);
  13644. ASSERT_TRUE(client2.connect());
  13645. ASSERT_TRUE(client2.send("hello"));
  13646. std::string msg;
  13647. ASSERT_TRUE(client2.read(msg));
  13648. EXPECT_EQ("hello", msg);
  13649. client2.close();
  13650. svr.stop();
  13651. t.join();
  13652. }
  13653. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13654. class WebSocketSSLIntegrationTest : public ::testing::Test {
  13655. protected:
  13656. void SetUp() override {
  13657. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  13658. SERVER_PRIVATE_KEY_FILE);
  13659. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  13660. std::string msg;
  13661. ws::ReadResult ret;
  13662. while ((ret = ws.read(msg))) {
  13663. if (ret == ws::Binary) {
  13664. ws.send(msg.data(), msg.size());
  13665. } else {
  13666. ws.send(msg);
  13667. }
  13668. }
  13669. });
  13670. port_ = server_->bind_to_any_port(HOST);
  13671. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13672. server_->wait_until_ready();
  13673. }
  13674. void TearDown() override {
  13675. server_->stop();
  13676. if (server_thread_.joinable()) { server_thread_.join(); }
  13677. }
  13678. std::unique_ptr<SSLServer> server_;
  13679. std::thread server_thread_;
  13680. int port_ = 0;
  13681. };
  13682. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  13683. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  13684. "/ws-echo");
  13685. client.enable_server_certificate_verification(false);
  13686. ASSERT_TRUE(client.connect());
  13687. ASSERT_TRUE(client.is_open());
  13688. ASSERT_TRUE(client.send("Hello WSS"));
  13689. std::string msg;
  13690. EXPECT_EQ(ws::Text, client.read(msg));
  13691. EXPECT_EQ("Hello WSS", msg);
  13692. client.close();
  13693. }
  13694. #endif