test.cc 522 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #if __cplusplus >= 202002L
  28. inline std::string u8_to_string(const char8_t *s) {
  29. return std::string(reinterpret_cast<const char *>(s));
  30. }
  31. #define U8(x) u8_to_string(u8##x)
  32. #else
  33. #define U8(x) u8##x
  34. #endif
  35. #define SERVER_CERT_FILE "./cert.pem"
  36. #define SERVER_CERT2_FILE "./cert2.pem"
  37. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  38. #define CA_CERT_FILE "./ca-bundle.crt"
  39. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  40. #define CLIENT_CA_CERT_DIR "."
  41. #define CLIENT_CERT_FILE "./client.cert.pem"
  42. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  43. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  44. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  45. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  46. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  47. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  48. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  49. using namespace std;
  50. using namespace httplib;
  51. const char *HOST = "localhost";
  52. static int get_base_port() {
  53. const char *shard = getenv("GTEST_SHARD_INDEX");
  54. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  55. }
  56. const int PORT = get_base_port();
  57. const string LONG_QUERY_VALUE = string(25000, '@');
  58. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  59. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  60. const string TOO_LONG_QUERY_URL =
  61. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  62. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  63. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  64. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  65. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  66. return file.name == key;
  67. });
  68. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  69. return *it;
  70. #else
  71. if (it != items.end()) { return *it; }
  72. throw std::runtime_error("invalid multipart form data name error");
  73. #endif
  74. }
  75. static void read_file(const std::string &path, std::string &out) {
  76. std::ifstream fs(path, std::ios_base::binary);
  77. if (!fs) {
  78. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  79. return;
  80. #else
  81. throw std::runtime_error("File not found: " + path);
  82. #endif
  83. }
  84. fs.seekg(0, std::ios_base::end);
  85. auto size = fs.tellg();
  86. fs.seekg(0);
  87. out.resize(static_cast<size_t>(size));
  88. fs.read(&out[0], static_cast<std::streamsize>(size));
  89. }
  90. void performance_test(const char *host) {
  91. Server svr;
  92. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  93. res.set_content("Benchmark Response", "text/plain");
  94. });
  95. auto listen_thread = std::thread([&]() { svr.listen(host, PORT); });
  96. auto se = detail::scope_exit([&] {
  97. svr.stop();
  98. listen_thread.join();
  99. ASSERT_FALSE(svr.is_running());
  100. });
  101. svr.wait_until_ready();
  102. Client cli(host, PORT);
  103. // Warm-up request to establish connection and resolve DNS
  104. auto warmup_res = cli.Get("/benchmark");
  105. ASSERT_TRUE(warmup_res); // Ensure server is responding correctly
  106. // Run multiple trials and collect timings
  107. const int num_trials = 20;
  108. std::vector<int64_t> timings;
  109. timings.reserve(num_trials);
  110. for (int i = 0; i < num_trials; i++) {
  111. auto start = std::chrono::high_resolution_clock::now();
  112. auto res = cli.Get("/benchmark");
  113. auto end = std::chrono::high_resolution_clock::now();
  114. auto elapsed =
  115. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  116. .count();
  117. // Assertions after timing measurement to avoid overhead
  118. ASSERT_TRUE(res);
  119. EXPECT_EQ(StatusCode::OK_200, res->status);
  120. timings.push_back(elapsed);
  121. }
  122. // Calculate 25th percentile (lower quartile)
  123. std::sort(timings.begin(), timings.end());
  124. auto p25 = timings[num_trials / 4];
  125. // Format timings for output
  126. std::ostringstream timings_str;
  127. timings_str << "[";
  128. for (size_t i = 0; i < timings.size(); i++) {
  129. if (i > 0) timings_str << ", ";
  130. timings_str << timings[i];
  131. }
  132. timings_str << "]";
  133. // Localhost HTTP GET should be fast even in CI environments
  134. EXPECT_LE(p25, 5) << "25th percentile performance is too slow: " << p25
  135. << "ms (Issue #1777). Timings: " << timings_str.str();
  136. }
  137. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  138. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  139. class UnixSocketTest : public ::testing::Test {
  140. protected:
  141. void TearDown() override { std::remove(pathname_.c_str()); }
  142. void client_GET(const std::string &addr) {
  143. httplib::Client cli{addr};
  144. cli.set_address_family(AF_UNIX);
  145. ASSERT_TRUE(cli.is_valid());
  146. const auto &result = cli.Get(pattern_);
  147. ASSERT_TRUE(result) << "error: " << result.error();
  148. const auto &resp = result.value();
  149. EXPECT_EQ(resp.status, StatusCode::OK_200);
  150. EXPECT_EQ(resp.body, content_);
  151. }
  152. static std::string make_sock_path() {
  153. const char *shard = getenv("GTEST_SHARD_INDEX");
  154. return shard ? std::string("./httplib-server-") + shard + ".sock"
  155. : "./httplib-server.sock";
  156. }
  157. const std::string pathname_{make_sock_path()};
  158. const std::string pattern_{"/hi"};
  159. const std::string content_{"Hello World!"};
  160. };
  161. TEST_F(UnixSocketTest, pathname) {
  162. httplib::Server svr;
  163. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  164. res.set_content(content_, "text/plain");
  165. });
  166. std::thread t{[&] {
  167. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  168. }};
  169. auto se = detail::scope_exit([&] {
  170. svr.stop();
  171. t.join();
  172. ASSERT_FALSE(svr.is_running());
  173. });
  174. svr.wait_until_ready();
  175. ASSERT_TRUE(svr.is_running());
  176. client_GET(pathname_);
  177. }
  178. #if defined(__linux__) || \
  179. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  180. TEST_F(UnixSocketTest, PeerPid) {
  181. httplib::Server svr;
  182. std::string remote_port_val;
  183. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  184. res.set_content(content_, "text/plain");
  185. remote_port_val = std::to_string(req.remote_port);
  186. });
  187. std::thread t{[&] {
  188. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  189. }};
  190. auto se = detail::scope_exit([&] {
  191. svr.stop();
  192. t.join();
  193. ASSERT_FALSE(svr.is_running());
  194. });
  195. svr.wait_until_ready();
  196. ASSERT_TRUE(svr.is_running());
  197. client_GET(pathname_);
  198. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  199. }
  200. #endif
  201. #ifdef __linux__
  202. TEST_F(UnixSocketTest, abstract) {
  203. constexpr char svr_path[]{"\x00httplib-server.sock"};
  204. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  205. httplib::Server svr;
  206. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  207. res.set_content(content_, "text/plain");
  208. });
  209. std::thread t{[&] {
  210. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  211. }};
  212. auto se = detail::scope_exit([&] {
  213. svr.stop();
  214. t.join();
  215. ASSERT_FALSE(svr.is_running());
  216. });
  217. svr.wait_until_ready();
  218. ASSERT_TRUE(svr.is_running());
  219. client_GET(abstract_addr);
  220. }
  221. #endif
  222. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  223. httplib::Server svr;
  224. std::string received_host_header;
  225. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  226. // Capture the Host header sent by the client
  227. auto host_iter = req.headers.find("Host");
  228. if (host_iter != req.headers.end()) {
  229. received_host_header = host_iter->second;
  230. }
  231. res.set_content(content_, "text/plain");
  232. });
  233. std::thread t{[&] {
  234. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  235. }};
  236. auto se = detail::scope_exit([&] {
  237. svr.stop();
  238. t.join();
  239. ASSERT_FALSE(svr.is_running());
  240. });
  241. svr.wait_until_ready();
  242. ASSERT_TRUE(svr.is_running());
  243. // Test that Host header is automatically set to "localhost" for Unix socket
  244. // connections
  245. httplib::Client cli{pathname_};
  246. cli.set_address_family(AF_UNIX);
  247. ASSERT_TRUE(cli.is_valid());
  248. const auto &result = cli.Get(pattern_);
  249. ASSERT_TRUE(result) << "error: " << result.error();
  250. const auto &resp = result.value();
  251. EXPECT_EQ(resp.status, StatusCode::OK_200);
  252. EXPECT_EQ(resp.body, content_);
  253. // Verify that Host header was automatically set to "localhost"
  254. EXPECT_EQ(received_host_header, "localhost");
  255. }
  256. #ifndef _WIN32
  257. TEST(SocketStream, wait_writable_UNIX) {
  258. int fds[2];
  259. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  260. const auto asSocketStream = [&](socket_t fd,
  261. std::function<bool(Stream &)> func) {
  262. return detail::process_client_socket(
  263. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  264. };
  265. asSocketStream(fds[0], [&](Stream &s0) {
  266. EXPECT_EQ(s0.socket(), fds[0]);
  267. EXPECT_TRUE(s0.wait_writable());
  268. EXPECT_TRUE(s0.is_peer_alive());
  269. EXPECT_EQ(0, close(fds[1]));
  270. EXPECT_FALSE(s0.is_peer_alive());
  271. return true;
  272. });
  273. EXPECT_EQ(0, close(fds[0]));
  274. }
  275. TEST(SocketStream, wait_writable_INET) {
  276. sockaddr_in addr;
  277. memset(&addr, 0, sizeof(addr));
  278. addr.sin_family = AF_INET;
  279. addr.sin_port = htons(PORT + 1);
  280. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  281. int disconnected_svr_sock = -1;
  282. std::thread svr{[&] {
  283. const int s = socket(AF_INET, SOCK_STREAM, 0);
  284. ASSERT_LE(0, s);
  285. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  286. ASSERT_EQ(0, listen(s, 1));
  287. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  288. ASSERT_EQ(0, close(s));
  289. }};
  290. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  291. std::thread cli{[&] {
  292. const int s = socket(AF_INET, SOCK_STREAM, 0);
  293. ASSERT_LE(0, s);
  294. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  295. ASSERT_EQ(0, close(s));
  296. }};
  297. cli.join();
  298. svr.join();
  299. ASSERT_NE(disconnected_svr_sock, -1);
  300. const auto asSocketStream = [&](socket_t fd,
  301. std::function<bool(Stream &)> func) {
  302. return detail::process_client_socket(
  303. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  304. };
  305. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  306. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  307. // wait_writable() returns true because select_write() only checks if the
  308. // send buffer has space. Peer disconnection is detected later by send().
  309. EXPECT_TRUE(ss.wait_writable());
  310. return true;
  311. });
  312. ASSERT_EQ(0, close(disconnected_svr_sock));
  313. }
  314. #endif // #ifndef _WIN32
  315. TEST(ClientTest, MoveConstructible) {
  316. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  317. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  318. }
  319. TEST(ClientTest, MoveAssignable) {
  320. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  321. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  322. }
  323. #ifdef _WIN32
  324. TEST(StartupTest, WSAStartup) {
  325. WSADATA wsaData;
  326. int ret = WSAStartup(0x0002, &wsaData);
  327. ASSERT_EQ(0, ret);
  328. }
  329. #endif
  330. TEST(DecodePathTest, PercentCharacter) {
  331. EXPECT_EQ(
  332. decode_path_component(
  333. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  334. U8("descrip=Gastos áéíóúñÑ 6"));
  335. }
  336. TEST(DecodePathTest, PercentCharacterNUL) {
  337. string expected;
  338. expected.push_back('x');
  339. expected.push_back('\0');
  340. expected.push_back('x');
  341. EXPECT_EQ(decode_path_component("x%00x"), expected);
  342. }
  343. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  344. string unescapedCharacters = "-_.!~*'()";
  345. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  346. }
  347. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  348. string reservedCharacters = ";,/?:@&=+$";
  349. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  350. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  351. }
  352. TEST(ClientQueryOrder, PreserveOrder) {
  353. // This test reproduces Issue #2259: client may reorder query parameters
  354. // when sending a GET request. The expected behavior is that the client
  355. // preserves the original query string order when the caller supplied it
  356. // as part of the path.
  357. Server svr;
  358. svr.Get("/", [&](const Request &req, Response &res) {
  359. // Echo back the raw target so the test can assert ordering
  360. res.set_content(req.target, "text/plain");
  361. });
  362. std::thread t{[&] { svr.listen(HOST, PORT); }};
  363. auto se = detail::scope_exit([&] {
  364. svr.stop();
  365. t.join();
  366. ASSERT_FALSE(svr.is_running());
  367. });
  368. svr.wait_until_ready();
  369. Client cli(HOST, PORT);
  370. ASSERT_TRUE(cli.is_valid());
  371. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  372. auto res = cli.Get(original);
  373. ASSERT_TRUE(res);
  374. // Expect the echoed target to exactly match the original path (order
  375. // preserved)
  376. EXPECT_EQ(res->body, original);
  377. }
  378. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  379. string chineseCharacters = U8("中国語");
  380. string russianCharacters = U8("дом");
  381. string brazilianCharacters = U8("óculos");
  382. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  383. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  384. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  385. "%D0%B4%D0%BE%D0%BC");
  386. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  387. }
  388. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  389. string unescapedCharacters = "-_.!~*'()";
  390. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  391. }
  392. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  393. string reservedCharacters = ";,/?:@&=+$";
  394. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  395. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  396. }
  397. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  398. string chineseCharacters = U8("中国語");
  399. string russianCharacters = U8("дом");
  400. string brazilianCharacters = U8("óculos");
  401. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  402. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  403. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  404. "%D0%B4%D0%BE%D0%BC");
  405. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  406. }
  407. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  408. // Issue #2082 use case: encoding path component with ampersand
  409. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  410. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  411. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  412. }
  413. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  414. string unescapedCharacters = "-_.!~*'()";
  415. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  416. }
  417. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  418. string reservedCharacters = ";,/?:@&=+$#";
  419. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  420. }
  421. TEST(EncodeUriTest, TestUTF8Characters) {
  422. string chineseCharacters = U8("中国語");
  423. string russianCharacters = U8("дом");
  424. string brazilianCharacters = U8("óculos");
  425. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  426. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  427. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  428. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  429. }
  430. TEST(EncodeUriTest, TestCompleteUri) {
  431. string uri =
  432. "https://example.com/path/to/resource?query=value&param=test#fragment";
  433. EXPECT_EQ(
  434. httplib::encode_uri(uri),
  435. "https://example.com/path/to/resource?query=value&param=test#fragment");
  436. }
  437. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  438. string uri =
  439. "https://example.com/path with spaces/file name.html?q=hello world";
  440. EXPECT_EQ(httplib::encode_uri(uri),
  441. "https://example.com/path%20with%20spaces/"
  442. "file%20name.html?q=hello%20world");
  443. }
  444. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  445. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  446. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  447. }
  448. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  449. string unescapedCharacters = "-_.!~*'()";
  450. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  451. }
  452. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  453. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  454. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  455. string encodedBrazilian = "%C3%B3culos";
  456. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  457. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  458. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  459. }
  460. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  461. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  462. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  463. "Piri Tommy Villiers - on & on");
  464. }
  465. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  466. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  467. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  468. }
  469. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  470. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  471. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  472. }
  473. TEST(DecodeUriTest, TestUTF8Characters) {
  474. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  475. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  476. string encodedBrazilian = "%C3%B3culos";
  477. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  478. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  479. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  480. }
  481. TEST(DecodeUriTest, TestCompleteUri) {
  482. string encodedUri = "https://example.com/path%20with%20spaces/"
  483. "file%20name.html?q=hello%20world";
  484. EXPECT_EQ(
  485. httplib::decode_uri(encodedUri),
  486. "https://example.com/path with spaces/file name.html?q=hello world");
  487. }
  488. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  489. string original =
  490. "https://example.com/path with spaces/file name.html?q=hello world";
  491. string encoded = httplib::encode_uri(original);
  492. string decoded = httplib::decode_uri(encoded);
  493. EXPECT_EQ(decoded, original);
  494. }
  495. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  496. string original = "Piri Tommy Villiers - on & on";
  497. string encoded = httplib::encode_uri_component(original);
  498. string decoded = httplib::decode_uri_component(encoded);
  499. EXPECT_EQ(decoded, original);
  500. }
  501. TEST(TrimTests, TrimStringTests) {
  502. EXPECT_EQ("abc", detail::trim_copy("abc"));
  503. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  504. EXPECT_TRUE(detail::trim_copy("").empty());
  505. }
  506. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  507. // Simple case without quality values
  508. std::vector<std::string> result1;
  509. EXPECT_TRUE(detail::parse_accept_header(
  510. "text/html,application/json,text/plain", result1));
  511. EXPECT_EQ(result1.size(), 3U);
  512. EXPECT_EQ(result1[0], "text/html");
  513. EXPECT_EQ(result1[1], "application/json");
  514. EXPECT_EQ(result1[2], "text/plain");
  515. // With quality values
  516. std::vector<std::string> result2;
  517. EXPECT_TRUE(detail::parse_accept_header(
  518. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  519. EXPECT_EQ(result2.size(), 3U);
  520. EXPECT_EQ(result2[0], "application/json"); // highest q value
  521. EXPECT_EQ(result2[1], "text/html");
  522. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  523. }
  524. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  525. // Mixed with and without quality values
  526. std::vector<std::string> result;
  527. EXPECT_TRUE(detail::parse_accept_header(
  528. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  529. EXPECT_EQ(result.size(), 3U);
  530. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  531. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  532. EXPECT_EQ(result[2], "application/json"); // q=0.5
  533. }
  534. TEST(ParseAcceptHeaderTest, EdgeCases) {
  535. // Empty header
  536. std::vector<std::string> empty_result;
  537. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  538. EXPECT_TRUE(empty_result.empty());
  539. // Single type
  540. std::vector<std::string> single_result;
  541. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  542. EXPECT_EQ(single_result.size(), 1U);
  543. EXPECT_EQ(single_result[0], "application/json");
  544. // Wildcard types
  545. std::vector<std::string> wildcard_result;
  546. EXPECT_TRUE(detail::parse_accept_header(
  547. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  548. EXPECT_EQ(wildcard_result.size(), 3U);
  549. EXPECT_EQ(wildcard_result[0], "application/json");
  550. EXPECT_EQ(wildcard_result[1], "text/*");
  551. EXPECT_EQ(wildcard_result[2], "*/*");
  552. }
  553. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  554. // Common browser Accept header
  555. std::vector<std::string> browser_result;
  556. EXPECT_TRUE(
  557. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  558. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  559. browser_result));
  560. EXPECT_EQ(browser_result.size(), 6U);
  561. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  562. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  563. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  564. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  565. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  566. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  567. // API client header
  568. std::vector<std::string> api_result;
  569. EXPECT_TRUE(detail::parse_accept_header(
  570. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  571. api_result));
  572. EXPECT_EQ(api_result.size(), 3U);
  573. EXPECT_EQ(api_result[0], "application/json");
  574. EXPECT_EQ(api_result[1], "application/xml");
  575. EXPECT_EQ(api_result[2], "text/plain");
  576. }
  577. TEST(ParseAcceptHeaderTest, SpecialCases) {
  578. // Quality value with 3 decimal places
  579. std::vector<std::string> decimal_result;
  580. EXPECT_TRUE(detail::parse_accept_header(
  581. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  582. EXPECT_EQ(decimal_result.size(), 2U);
  583. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  584. EXPECT_EQ(decimal_result[1], "text/html");
  585. // Zero quality (should still be included but with lowest priority)
  586. std::vector<std::string> zero_q_result;
  587. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  588. zero_q_result));
  589. EXPECT_EQ(zero_q_result.size(), 2U);
  590. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  591. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  592. // No spaces around commas
  593. std::vector<std::string> no_space_result;
  594. EXPECT_TRUE(detail::parse_accept_header(
  595. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  596. no_space_result));
  597. EXPECT_EQ(no_space_result.size(), 3U);
  598. EXPECT_EQ(no_space_result[0], "text/html");
  599. EXPECT_EQ(no_space_result[1], "application/json");
  600. EXPECT_EQ(no_space_result[2], "text/plain");
  601. }
  602. TEST(ParseAcceptHeaderTest, InvalidCases) {
  603. std::vector<std::string> result;
  604. // Invalid quality value (> 1.0)
  605. EXPECT_FALSE(
  606. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  607. // Invalid quality value (< 0.0)
  608. EXPECT_FALSE(
  609. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  610. // Invalid quality value (not a number)
  611. EXPECT_FALSE(detail::parse_accept_header(
  612. "text/html;q=invalid,application/json", result));
  613. // Empty quality value
  614. EXPECT_FALSE(
  615. detail::parse_accept_header("text/html;q=,application/json", result));
  616. // Invalid media type format (no slash and not wildcard)
  617. EXPECT_FALSE(
  618. detail::parse_accept_header("invalidtype,application/json", result));
  619. // Empty media type
  620. result.clear();
  621. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  622. // Only commas
  623. result.clear();
  624. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  625. // Valid cases should still work
  626. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  627. EXPECT_EQ(result.size(), 1U);
  628. EXPECT_EQ(result[0], "*/*");
  629. EXPECT_TRUE(detail::parse_accept_header("*", result));
  630. EXPECT_EQ(result.size(), 1U);
  631. EXPECT_EQ(result[0], "*");
  632. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  633. EXPECT_EQ(result.size(), 1U);
  634. EXPECT_EQ(result[0], "text/*");
  635. }
  636. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  637. Server svr;
  638. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  639. EXPECT_EQ(req.accept_content_types.size(), 3U);
  640. EXPECT_EQ(req.accept_content_types[0], "application/json");
  641. EXPECT_EQ(req.accept_content_types[1], "text/html");
  642. EXPECT_EQ(req.accept_content_types[2], "*/*");
  643. res.set_content("ok", "text/plain");
  644. });
  645. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  646. EXPECT_TRUE(false);
  647. res.set_content("bad request", "text/plain");
  648. });
  649. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  650. auto se = detail::scope_exit([&] {
  651. svr.stop();
  652. listen_thread.join();
  653. ASSERT_FALSE(svr.is_running());
  654. });
  655. svr.wait_until_ready();
  656. Client cli("localhost", PORT);
  657. {
  658. auto res =
  659. cli.Get("/accept_ok",
  660. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  661. ASSERT_TRUE(res);
  662. EXPECT_EQ(StatusCode::OK_200, res->status);
  663. }
  664. {
  665. auto res = cli.Get("/accept_bad_request",
  666. {{"Accept", "text/html;q=abc,application/json"}});
  667. ASSERT_TRUE(res);
  668. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  669. }
  670. }
  671. TEST(DivideTest, DivideStringTests) {
  672. auto divide = [](const std::string &str, char d) {
  673. std::string lhs;
  674. std::string rhs;
  675. detail::divide(str, d,
  676. [&](const char *lhs_data, std::size_t lhs_size,
  677. const char *rhs_data, std::size_t rhs_size) {
  678. lhs.assign(lhs_data, lhs_size);
  679. rhs.assign(rhs_data, rhs_size);
  680. });
  681. return std::make_pair(std::move(lhs), std::move(rhs));
  682. };
  683. {
  684. const auto res = divide("", '=');
  685. EXPECT_EQ(res.first, "");
  686. EXPECT_EQ(res.second, "");
  687. }
  688. {
  689. const auto res = divide("=", '=');
  690. EXPECT_EQ(res.first, "");
  691. EXPECT_EQ(res.second, "");
  692. }
  693. {
  694. const auto res = divide(" ", '=');
  695. EXPECT_EQ(res.first, " ");
  696. EXPECT_EQ(res.second, "");
  697. }
  698. {
  699. const auto res = divide("a", '=');
  700. EXPECT_EQ(res.first, "a");
  701. EXPECT_EQ(res.second, "");
  702. }
  703. {
  704. const auto res = divide("a=", '=');
  705. EXPECT_EQ(res.first, "a");
  706. EXPECT_EQ(res.second, "");
  707. }
  708. {
  709. const auto res = divide("=b", '=');
  710. EXPECT_EQ(res.first, "");
  711. EXPECT_EQ(res.second, "b");
  712. }
  713. {
  714. const auto res = divide("a=b", '=');
  715. EXPECT_EQ(res.first, "a");
  716. EXPECT_EQ(res.second, "b");
  717. }
  718. {
  719. const auto res = divide("a=b=", '=');
  720. EXPECT_EQ(res.first, "a");
  721. EXPECT_EQ(res.second, "b=");
  722. }
  723. {
  724. const auto res = divide("a=b=c", '=');
  725. EXPECT_EQ(res.first, "a");
  726. EXPECT_EQ(res.second, "b=c");
  727. }
  728. }
  729. TEST(SplitTest, ParseQueryString) {
  730. string s = "key1=val1&key2=val2&key3=val3";
  731. Params dic;
  732. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  733. [&](const char *b, const char *e) {
  734. string key, val;
  735. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  736. if (key.empty()) {
  737. key.assign(b2, e2);
  738. } else {
  739. val.assign(b2, e2);
  740. }
  741. });
  742. dic.emplace(key, val);
  743. });
  744. EXPECT_EQ("val1", dic.find("key1")->second);
  745. EXPECT_EQ("val2", dic.find("key2")->second);
  746. EXPECT_EQ("val3", dic.find("key3")->second);
  747. }
  748. TEST(SplitTest, ParseInvalidQueryTests) {
  749. {
  750. string s = " ";
  751. Params dict;
  752. detail::parse_query_text(s, dict);
  753. EXPECT_TRUE(dict.empty());
  754. }
  755. {
  756. string s = " = =";
  757. Params dict;
  758. detail::parse_query_text(s, dict);
  759. EXPECT_TRUE(dict.empty());
  760. }
  761. }
  762. TEST(ParseQueryTest, ParseQueryString) {
  763. {
  764. std::string s = "key1=val1&key2=val2&key3=val3";
  765. Params dic;
  766. detail::parse_query_text(s, dic);
  767. EXPECT_EQ("val1", dic.find("key1")->second);
  768. EXPECT_EQ("val2", dic.find("key2")->second);
  769. EXPECT_EQ("val3", dic.find("key3")->second);
  770. }
  771. {
  772. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  773. Params dic;
  774. detail::parse_query_text(s, dic);
  775. EXPECT_EQ("", dic.find("key1")->second);
  776. EXPECT_EQ("val1", dic.find("key2")->second);
  777. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  778. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  779. }
  780. }
  781. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  782. Params dic;
  783. EXPECT_EQ(detail::params_to_query_str(dic), "");
  784. dic.emplace("key1", "val1");
  785. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  786. dic.emplace("key2", "val2");
  787. dic.emplace("key3", "val3");
  788. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  789. }
  790. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  791. string content_type = "multipart/form-data; boundary=something";
  792. string boundary;
  793. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  794. EXPECT_TRUE(ret);
  795. EXPECT_EQ(boundary, "something");
  796. }
  797. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  798. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  799. string boundary;
  800. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  801. EXPECT_TRUE(ret);
  802. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  803. }
  804. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  805. string content_type =
  806. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  807. string boundary;
  808. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  809. EXPECT_TRUE(ret);
  810. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  811. }
  812. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  813. string content_type =
  814. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  815. string boundary;
  816. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  817. EXPECT_TRUE(ret);
  818. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  819. }
  820. TEST(GetHeaderValueTest, DefaultValue) {
  821. Headers headers = {{"Dummy", "Dummy"}};
  822. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  823. EXPECT_STREQ("text/plain", val);
  824. }
  825. TEST(GetHeaderValueTest, DefaultValueInt) {
  826. Headers headers = {{"Dummy", "Dummy"}};
  827. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  828. EXPECT_EQ(100ull, val);
  829. }
  830. TEST(GetHeaderValueTest, RegularValue) {
  831. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  832. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  833. EXPECT_STREQ("text/html", val);
  834. }
  835. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  836. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  837. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  838. EXPECT_STREQ("text/html", val);
  839. }
  840. TEST(GetHeaderValueTest, SetContent) {
  841. Response res;
  842. res.set_content("html", "text/html");
  843. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  844. res.set_content("text", "text/plain");
  845. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  846. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  847. }
  848. TEST(GetHeaderValueTest, RegularValueInt) {
  849. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  850. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  851. EXPECT_EQ(100ull, val);
  852. }
  853. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  854. Headers headers = {{"Content-Length", "x"}};
  855. auto is_invalid_value = false;
  856. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  857. is_invalid_value);
  858. EXPECT_EQ(0ull, val);
  859. EXPECT_TRUE(is_invalid_value);
  860. }
  861. TEST(GetHeaderValueTest, Range) {
  862. {
  863. Headers headers = {make_range_header({{1, -1}})};
  864. auto val = detail::get_header_value(headers, "Range", 0, 0);
  865. EXPECT_STREQ("bytes=1-", val);
  866. }
  867. {
  868. Headers headers = {make_range_header({{-1, 1}})};
  869. auto val = detail::get_header_value(headers, "Range", 0, 0);
  870. EXPECT_STREQ("bytes=-1", val);
  871. }
  872. {
  873. Headers headers = {make_range_header({{1, 10}})};
  874. auto val = detail::get_header_value(headers, "Range", 0, 0);
  875. EXPECT_STREQ("bytes=1-10", val);
  876. }
  877. {
  878. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  879. auto val = detail::get_header_value(headers, "Range", 0, 0);
  880. EXPECT_STREQ("bytes=1-10, 100-", val);
  881. }
  882. {
  883. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  884. auto val = detail::get_header_value(headers, "Range", 0, 0);
  885. EXPECT_STREQ("bytes=1-10, 100-200", val);
  886. }
  887. {
  888. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  889. auto val = detail::get_header_value(headers, "Range", 0, 0);
  890. EXPECT_STREQ("bytes=0-0, -1", val);
  891. }
  892. }
  893. TEST(ParseHeaderValueTest, Range) {
  894. {
  895. Ranges ranges;
  896. auto ret = detail::parse_range_header("bytes=1-", ranges);
  897. EXPECT_TRUE(ret);
  898. EXPECT_EQ(1u, ranges.size());
  899. EXPECT_EQ(1u, ranges[0].first);
  900. EXPECT_EQ(-1, ranges[0].second);
  901. }
  902. {
  903. Ranges ranges;
  904. auto ret = detail::parse_range_header("bytes=-1", ranges);
  905. EXPECT_TRUE(ret);
  906. EXPECT_EQ(1u, ranges.size());
  907. EXPECT_EQ(-1, ranges[0].first);
  908. EXPECT_EQ(1u, ranges[0].second);
  909. }
  910. {
  911. Ranges ranges;
  912. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  913. EXPECT_TRUE(ret);
  914. EXPECT_EQ(1u, ranges.size());
  915. EXPECT_EQ(1u, ranges[0].first);
  916. EXPECT_EQ(10u, ranges[0].second);
  917. }
  918. {
  919. Ranges ranges;
  920. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  921. EXPECT_FALSE(ret);
  922. }
  923. {
  924. Ranges ranges;
  925. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  926. EXPECT_TRUE(ret);
  927. EXPECT_EQ(2u, ranges.size());
  928. EXPECT_EQ(1u, ranges[0].first);
  929. EXPECT_EQ(10u, ranges[0].second);
  930. EXPECT_EQ(100u, ranges[1].first);
  931. EXPECT_EQ(-1, ranges[1].second);
  932. }
  933. {
  934. Ranges ranges;
  935. auto ret =
  936. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  937. EXPECT_TRUE(ret);
  938. EXPECT_EQ(3u, ranges.size());
  939. EXPECT_EQ(1u, ranges[0].first);
  940. EXPECT_EQ(10u, ranges[0].second);
  941. EXPECT_EQ(100u, ranges[1].first);
  942. EXPECT_EQ(200u, ranges[1].second);
  943. EXPECT_EQ(300u, ranges[2].first);
  944. EXPECT_EQ(400u, ranges[2].second);
  945. }
  946. {
  947. Ranges ranges;
  948. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  949. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  950. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  951. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  952. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  953. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  954. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  955. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  956. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  957. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  958. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  959. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  960. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  961. EXPECT_TRUE(ranges.empty());
  962. }
  963. }
  964. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  965. Request req;
  966. req.set_header("Accept-Encoding", "gzip");
  967. Response res;
  968. res.set_header("Content-Type", "text/plain");
  969. auto ret = detail::encoding_type(req, res);
  970. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  971. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  972. #else
  973. EXPECT_TRUE(ret == detail::EncodingType::None);
  974. #endif
  975. }
  976. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  977. Request req;
  978. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  979. Response res;
  980. res.set_header("Content-Type", "text/plain");
  981. auto ret = detail::encoding_type(req, res);
  982. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  983. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  984. #elif CPPHTTPLIB_ZLIB_SUPPORT
  985. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  986. #elif CPPHTTPLIB_ZSTD_SUPPORT
  987. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  988. #else
  989. EXPECT_TRUE(ret == detail::EncodingType::None);
  990. #endif
  991. }
  992. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  993. Request req;
  994. req.set_header("Accept-Encoding",
  995. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  996. Response res;
  997. res.set_header("Content-Type", "text/plain");
  998. auto ret = detail::encoding_type(req, res);
  999. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1000. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1001. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1002. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1003. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1004. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1005. #else
  1006. EXPECT_TRUE(ret == detail::EncodingType::None);
  1007. #endif
  1008. }
  1009. TEST(BufferStreamTest, read) {
  1010. detail::BufferStream strm1;
  1011. Stream &strm = strm1;
  1012. EXPECT_EQ(5, strm.write("hello"));
  1013. char buf[512];
  1014. EXPECT_EQ(2, strm.read(buf, 2));
  1015. EXPECT_EQ('h', buf[0]);
  1016. EXPECT_EQ('e', buf[1]);
  1017. EXPECT_EQ(2, strm.read(buf, 2));
  1018. EXPECT_EQ('l', buf[0]);
  1019. EXPECT_EQ('l', buf[1]);
  1020. EXPECT_EQ(1, strm.read(buf, 1));
  1021. EXPECT_EQ('o', buf[0]);
  1022. EXPECT_EQ(0, strm.read(buf, 1));
  1023. }
  1024. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1025. auto host = "www.httpwatch.com";
  1026. auto ip = hosted_at(host);
  1027. EXPECT_EQ("23.96.13.243", ip);
  1028. std::vector<std::string> addrs;
  1029. hosted_at(host, addrs);
  1030. EXPECT_EQ(1u, addrs.size());
  1031. }
  1032. #if 0 // It depends on each test environment...
  1033. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1034. auto host = "www.youtube.com";
  1035. std::vector<std::string> addrs;
  1036. hosted_at(host, addrs);
  1037. EXPECT_EQ(20u, addrs.size());
  1038. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1039. EXPECT_TRUE(it != addrs.end());
  1040. }
  1041. #endif
  1042. class ChunkedEncodingTest : public ::testing::Test {
  1043. protected:
  1044. ChunkedEncodingTest()
  1045. : cli_(HOST, PORT)
  1046. #ifdef CPPHTTPLIB_SSL_ENABLED
  1047. ,
  1048. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1049. #endif
  1050. {
  1051. cli_.set_connection_timeout(2);
  1052. #ifdef CPPHTTPLIB_SSL_ENABLED
  1053. cli_.enable_server_certificate_verification(false);
  1054. #endif
  1055. }
  1056. virtual void SetUp() {
  1057. read_file("./image.jpg", image_data_);
  1058. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1059. res.set_content("Hello World!", "text/plain");
  1060. });
  1061. svr_.Get(
  1062. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1063. res.set_chunked_content_provider(
  1064. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1065. size_t remaining = image_data_.size() - offset;
  1066. if (remaining == 0) {
  1067. sink.done();
  1068. } else {
  1069. constexpr size_t CHUNK_SIZE = 1024;
  1070. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1071. sink.write(&image_data_[offset], send_size);
  1072. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1073. }
  1074. return true;
  1075. });
  1076. });
  1077. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1078. svr_.wait_until_ready();
  1079. }
  1080. virtual void TearDown() {
  1081. svr_.stop();
  1082. if (!request_threads_.empty()) {
  1083. std::this_thread::sleep_for(std::chrono::seconds(1));
  1084. for (auto &t : request_threads_) {
  1085. t.join();
  1086. }
  1087. }
  1088. t_.join();
  1089. }
  1090. #ifdef CPPHTTPLIB_SSL_ENABLED
  1091. SSLClient cli_;
  1092. SSLServer svr_;
  1093. #else
  1094. Client cli_;
  1095. Server svr_;
  1096. #endif
  1097. thread t_;
  1098. std::vector<thread> request_threads_;
  1099. std::string image_data_;
  1100. };
  1101. TEST_F(ChunkedEncodingTest, NormalGet) {
  1102. auto res = cli_.Get("/chunked");
  1103. ASSERT_TRUE(res);
  1104. std::string out;
  1105. read_file("./image.jpg", out);
  1106. EXPECT_EQ(StatusCode::OK_200, res->status);
  1107. EXPECT_EQ(out, res->body);
  1108. }
  1109. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1110. std::string body;
  1111. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1112. body.append(data, data_length);
  1113. return true;
  1114. });
  1115. ASSERT_TRUE(res);
  1116. std::string out;
  1117. read_file("./image.jpg", out);
  1118. EXPECT_EQ(StatusCode::OK_200, res->status);
  1119. EXPECT_EQ(out, body);
  1120. }
  1121. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1122. std::string body;
  1123. auto res = cli_.Get(
  1124. "/chunked",
  1125. [&](const Response &response) {
  1126. EXPECT_EQ(StatusCode::OK_200, response.status);
  1127. return true;
  1128. },
  1129. [&](const char *data, size_t data_length) {
  1130. body.append(data, data_length);
  1131. return true;
  1132. });
  1133. ASSERT_TRUE(res);
  1134. std::string out;
  1135. read_file("./image.jpg", out);
  1136. EXPECT_EQ(StatusCode::OK_200, res->status);
  1137. EXPECT_EQ(out, body);
  1138. }
  1139. TEST(RangeTest, FromHTTPBin_Online) {
  1140. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1141. auto host = "httpcan.org";
  1142. auto path = std::string{"/range/32"};
  1143. #else
  1144. auto host = "nghttp2.org";
  1145. auto path = std::string{"/httpbin/range/32"};
  1146. #endif
  1147. #ifdef CPPHTTPLIB_SSL_ENABLED
  1148. auto port = 443;
  1149. SSLClient cli(host, port);
  1150. #else
  1151. auto port = 80;
  1152. Client cli(host, port);
  1153. #endif
  1154. cli.set_connection_timeout(5);
  1155. {
  1156. auto res = cli.Get(path);
  1157. ASSERT_TRUE(res);
  1158. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1159. EXPECT_EQ(StatusCode::OK_200, res->status);
  1160. }
  1161. {
  1162. Headers headers = {make_range_header({{1, -1}})};
  1163. auto res = cli.Get(path, headers);
  1164. ASSERT_TRUE(res);
  1165. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1166. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1167. }
  1168. {
  1169. Headers headers = {make_range_header({{1, 10}})};
  1170. auto res = cli.Get(path, headers);
  1171. ASSERT_TRUE(res);
  1172. EXPECT_EQ("bcdefghijk", res->body);
  1173. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1174. }
  1175. {
  1176. Headers headers = {make_range_header({{0, 31}})};
  1177. auto res = cli.Get(path, headers);
  1178. ASSERT_TRUE(res);
  1179. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1180. EXPECT_EQ(StatusCode::OK_200, res->status);
  1181. }
  1182. {
  1183. Headers headers = {make_range_header({{0, -1}})};
  1184. auto res = cli.Get(path, headers);
  1185. ASSERT_TRUE(res);
  1186. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1187. EXPECT_EQ(StatusCode::OK_200, res->status);
  1188. }
  1189. {
  1190. Headers headers = {make_range_header({{0, 32}})};
  1191. auto res = cli.Get(path, headers);
  1192. ASSERT_TRUE(res);
  1193. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1194. }
  1195. }
  1196. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1197. auto host = "unresolvableaddress.local";
  1198. auto path = std::string{"/"};
  1199. #ifdef CPPHTTPLIB_SSL_ENABLED
  1200. auto port = 443;
  1201. SSLClient cli(host, port);
  1202. #else
  1203. auto port = 80;
  1204. Client cli(host, port);
  1205. #endif
  1206. cli.set_connection_timeout(1);
  1207. {
  1208. auto res = cli.Get(path);
  1209. ASSERT_FALSE(res);
  1210. }
  1211. std::this_thread::sleep_for(std::chrono::seconds(8));
  1212. }
  1213. TEST(ConnectionErrorTest, InvalidHost) {
  1214. auto host = "-abcde.com";
  1215. #ifdef CPPHTTPLIB_SSL_ENABLED
  1216. auto port = 443;
  1217. SSLClient cli(host, port);
  1218. #else
  1219. auto port = 80;
  1220. Client cli(host, port);
  1221. #endif
  1222. cli.set_connection_timeout(std::chrono::seconds(2));
  1223. auto res = cli.Get("/");
  1224. ASSERT_TRUE(!res);
  1225. EXPECT_EQ(Error::Connection, res.error());
  1226. }
  1227. TEST(ConnectionErrorTest, InvalidHost2) {
  1228. auto host = "httpcan.org/";
  1229. #ifdef CPPHTTPLIB_SSL_ENABLED
  1230. SSLClient cli(host);
  1231. #else
  1232. Client cli(host);
  1233. #endif
  1234. cli.set_connection_timeout(std::chrono::seconds(2));
  1235. auto res = cli.Get("/");
  1236. ASSERT_TRUE(!res);
  1237. EXPECT_EQ(Error::Connection, res.error());
  1238. }
  1239. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1240. auto host = "httpcan.org/";
  1241. #ifdef CPPHTTPLIB_SSL_ENABLED
  1242. SSLClient cli(host);
  1243. #else
  1244. Client cli(host);
  1245. #endif
  1246. cli.set_connection_timeout(std::chrono::seconds(2));
  1247. auto res = cli.Get("/");
  1248. ASSERT_TRUE(!res);
  1249. stringstream s;
  1250. s << "error code: " << res.error();
  1251. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1252. }
  1253. TEST(ConnectionErrorTest, InvalidPort) {
  1254. auto host = "localhost";
  1255. auto port = 44380;
  1256. #ifdef CPPHTTPLIB_SSL_ENABLED
  1257. SSLClient cli(host, port);
  1258. #else
  1259. Client cli(host, port);
  1260. #endif
  1261. cli.set_connection_timeout(std::chrono::seconds(2));
  1262. auto res = cli.Get("/");
  1263. ASSERT_TRUE(!res);
  1264. EXPECT_TRUE(Error::Connection == res.error() ||
  1265. Error::ConnectionTimeout == res.error());
  1266. }
  1267. TEST(ConnectionErrorTest, Timeout_Online) {
  1268. auto host = "google.com";
  1269. #ifdef CPPHTTPLIB_SSL_ENABLED
  1270. auto port = 44380;
  1271. SSLClient cli(host, port);
  1272. #else
  1273. auto port = 8080;
  1274. Client cli(host, port);
  1275. #endif
  1276. cli.set_connection_timeout(std::chrono::seconds(2));
  1277. // only probe one address type so that the error reason
  1278. // correlates to the timed-out IPv4, not the unsupported
  1279. // IPv6 connection attempt
  1280. cli.set_address_family(AF_INET);
  1281. auto res = cli.Get("/");
  1282. ASSERT_TRUE(!res);
  1283. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1284. }
  1285. TEST(CancelTest, NoCancel_Online) {
  1286. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1287. auto host = "httpcan.org";
  1288. auto path = std::string{"/range/32"};
  1289. #else
  1290. auto host = "nghttp2.org";
  1291. auto path = std::string{"/httpbin/range/32"};
  1292. #endif
  1293. #ifdef CPPHTTPLIB_SSL_ENABLED
  1294. auto port = 443;
  1295. SSLClient cli(host, port);
  1296. #else
  1297. auto port = 80;
  1298. Client cli(host, port);
  1299. #endif
  1300. cli.set_connection_timeout(std::chrono::seconds(5));
  1301. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1302. ASSERT_TRUE(res);
  1303. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1304. EXPECT_EQ(StatusCode::OK_200, res->status);
  1305. }
  1306. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1307. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1308. auto host = "httpcan.org";
  1309. auto path = std::string{"/range/32"};
  1310. #else
  1311. auto host = "nghttp2.org";
  1312. auto path = std::string{"/httpbin/range/32"};
  1313. #endif
  1314. #ifdef CPPHTTPLIB_SSL_ENABLED
  1315. auto port = 443;
  1316. SSLClient cli(host, port);
  1317. #else
  1318. auto port = 80;
  1319. Client cli(host, port);
  1320. #endif
  1321. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1322. cli.set_connection_timeout(std::chrono::seconds(5));
  1323. ASSERT_TRUE(!res);
  1324. EXPECT_EQ(Error::Canceled, res.error());
  1325. }
  1326. TEST(CancelTest, WithCancelLargePayload_Online) {
  1327. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1328. auto host = "httpcan.org";
  1329. auto path = std::string{"/range/65536"};
  1330. #else
  1331. auto host = "nghttp2.org";
  1332. auto path = std::string{"/httpbin/range/65536"};
  1333. #endif
  1334. #ifdef CPPHTTPLIB_SSL_ENABLED
  1335. auto port = 443;
  1336. SSLClient cli(host, port);
  1337. #else
  1338. auto port = 80;
  1339. Client cli(host, port);
  1340. #endif
  1341. cli.set_connection_timeout(std::chrono::seconds(5));
  1342. uint32_t count = 0;
  1343. auto res =
  1344. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1345. ASSERT_TRUE(!res);
  1346. EXPECT_EQ(Error::Canceled, res.error());
  1347. }
  1348. TEST(CancelTest, NoCancelPost) {
  1349. Server svr;
  1350. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1351. res.set_content("Hello World!", "text/plain");
  1352. });
  1353. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1354. auto se = detail::scope_exit([&] {
  1355. svr.stop();
  1356. thread.join();
  1357. ASSERT_FALSE(svr.is_running());
  1358. });
  1359. svr.wait_until_ready();
  1360. Client cli(HOST, PORT);
  1361. cli.set_connection_timeout(std::chrono::seconds(5));
  1362. auto res =
  1363. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1364. "application/json", [](uint64_t, uint64_t) { return true; });
  1365. ASSERT_TRUE(res);
  1366. EXPECT_EQ("Hello World!", res->body);
  1367. EXPECT_EQ(StatusCode::OK_200, res->status);
  1368. }
  1369. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1370. Server svr;
  1371. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1372. res.set_content("Hello World!", "text/plain");
  1373. });
  1374. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1375. auto se = detail::scope_exit([&] {
  1376. svr.stop();
  1377. thread.join();
  1378. ASSERT_FALSE(svr.is_running());
  1379. });
  1380. svr.wait_until_ready();
  1381. Client cli(HOST, PORT);
  1382. cli.set_connection_timeout(std::chrono::seconds(5));
  1383. auto res =
  1384. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1385. "application/json", [](uint64_t, uint64_t) { return false; });
  1386. ASSERT_TRUE(!res);
  1387. EXPECT_EQ(Error::Canceled, res.error());
  1388. }
  1389. TEST(CancelTest, WithCancelLargePayloadPost) {
  1390. Server svr;
  1391. svr.set_payload_max_length(200 * 1024 * 1024);
  1392. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1393. res.set_content(LARGE_DATA, "text/plain");
  1394. });
  1395. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1396. auto se = detail::scope_exit([&] {
  1397. svr.stop();
  1398. thread.join();
  1399. ASSERT_FALSE(svr.is_running());
  1400. });
  1401. svr.wait_until_ready();
  1402. Client cli(HOST, PORT);
  1403. cli.set_payload_max_length(200 * 1024 * 1024);
  1404. cli.set_connection_timeout(std::chrono::seconds(5));
  1405. auto res =
  1406. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1407. "application/json", [](uint64_t, uint64_t) { return false; });
  1408. ASSERT_TRUE(!res);
  1409. EXPECT_EQ(Error::Canceled, res.error());
  1410. }
  1411. TEST(CancelTest, NoCancelPut) {
  1412. Server svr;
  1413. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1414. res.set_content("Hello World!", "text/plain");
  1415. });
  1416. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1417. auto se = detail::scope_exit([&] {
  1418. svr.stop();
  1419. thread.join();
  1420. ASSERT_FALSE(svr.is_running());
  1421. });
  1422. svr.wait_until_ready();
  1423. Client cli(HOST, PORT);
  1424. cli.set_connection_timeout(std::chrono::seconds(5));
  1425. auto res =
  1426. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1427. "application/json", [](uint64_t, uint64_t) { return true; });
  1428. ASSERT_TRUE(res);
  1429. EXPECT_EQ("Hello World!", res->body);
  1430. EXPECT_EQ(StatusCode::OK_200, res->status);
  1431. }
  1432. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1433. Server svr;
  1434. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1435. res.set_content("Hello World!", "text/plain");
  1436. });
  1437. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1438. auto se = detail::scope_exit([&] {
  1439. svr.stop();
  1440. thread.join();
  1441. ASSERT_FALSE(svr.is_running());
  1442. });
  1443. svr.wait_until_ready();
  1444. Client cli(HOST, PORT);
  1445. cli.set_connection_timeout(std::chrono::seconds(5));
  1446. auto res =
  1447. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1448. "application/json", [](uint64_t, uint64_t) { return false; });
  1449. ASSERT_TRUE(!res);
  1450. EXPECT_EQ(Error::Canceled, res.error());
  1451. }
  1452. TEST(CancelTest, WithCancelLargePayloadPut) {
  1453. Server svr;
  1454. svr.set_payload_max_length(200 * 1024 * 1024);
  1455. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1456. res.set_content(LARGE_DATA, "text/plain");
  1457. });
  1458. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1459. auto se = detail::scope_exit([&] {
  1460. svr.stop();
  1461. thread.join();
  1462. ASSERT_FALSE(svr.is_running());
  1463. });
  1464. svr.wait_until_ready();
  1465. Client cli(HOST, PORT);
  1466. cli.set_payload_max_length(200 * 1024 * 1024);
  1467. cli.set_connection_timeout(std::chrono::seconds(5));
  1468. auto res =
  1469. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1470. "application/json", [](uint64_t, uint64_t) { return false; });
  1471. ASSERT_TRUE(!res);
  1472. EXPECT_EQ(Error::Canceled, res.error());
  1473. }
  1474. TEST(CancelTest, NoCancelPatch) {
  1475. Server svr;
  1476. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1477. res.set_content("Hello World!", "text/plain");
  1478. });
  1479. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1480. auto se = detail::scope_exit([&] {
  1481. svr.stop();
  1482. thread.join();
  1483. ASSERT_FALSE(svr.is_running());
  1484. });
  1485. svr.wait_until_ready();
  1486. Client cli(HOST, PORT);
  1487. cli.set_connection_timeout(std::chrono::seconds(5));
  1488. auto res =
  1489. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1490. "application/json", [](uint64_t, uint64_t) { return true; });
  1491. ASSERT_TRUE(res);
  1492. EXPECT_EQ("Hello World!", res->body);
  1493. EXPECT_EQ(StatusCode::OK_200, res->status);
  1494. }
  1495. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1496. Server svr;
  1497. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1498. res.set_content("Hello World!", "text/plain");
  1499. });
  1500. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1501. auto se = detail::scope_exit([&] {
  1502. svr.stop();
  1503. thread.join();
  1504. ASSERT_FALSE(svr.is_running());
  1505. });
  1506. svr.wait_until_ready();
  1507. Client cli(HOST, PORT);
  1508. cli.set_connection_timeout(std::chrono::seconds(5));
  1509. auto res =
  1510. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1511. "application/json", [](uint64_t, uint64_t) { return false; });
  1512. ASSERT_TRUE(!res);
  1513. EXPECT_EQ(Error::Canceled, res.error());
  1514. }
  1515. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1516. Server svr;
  1517. svr.set_payload_max_length(200 * 1024 * 1024);
  1518. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1519. res.set_content(LARGE_DATA, "text/plain");
  1520. });
  1521. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1522. auto se = detail::scope_exit([&] {
  1523. svr.stop();
  1524. thread.join();
  1525. ASSERT_FALSE(svr.is_running());
  1526. });
  1527. svr.wait_until_ready();
  1528. Client cli(HOST, PORT);
  1529. cli.set_payload_max_length(200 * 1024 * 1024);
  1530. cli.set_connection_timeout(std::chrono::seconds(5));
  1531. auto res =
  1532. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1533. "application/json", [](uint64_t, uint64_t) { return false; });
  1534. ASSERT_TRUE(!res);
  1535. EXPECT_EQ(Error::Canceled, res.error());
  1536. }
  1537. TEST(CancelTest, NoCancelDelete) {
  1538. Server svr;
  1539. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1540. res.set_content("Hello World!", "text/plain");
  1541. });
  1542. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1543. auto se = detail::scope_exit([&] {
  1544. svr.stop();
  1545. thread.join();
  1546. ASSERT_FALSE(svr.is_running());
  1547. });
  1548. svr.wait_until_ready();
  1549. Client cli(HOST, PORT);
  1550. cli.set_connection_timeout(std::chrono::seconds(5));
  1551. auto res =
  1552. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1553. "application/json", [](uint64_t, uint64_t) { return true; });
  1554. ASSERT_TRUE(res);
  1555. EXPECT_EQ("Hello World!", res->body);
  1556. EXPECT_EQ(StatusCode::OK_200, res->status);
  1557. }
  1558. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1559. Server svr;
  1560. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1561. res.set_content("Hello World!", "text/plain");
  1562. });
  1563. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1564. auto se = detail::scope_exit([&] {
  1565. svr.stop();
  1566. thread.join();
  1567. ASSERT_FALSE(svr.is_running());
  1568. });
  1569. svr.wait_until_ready();
  1570. Client cli(HOST, PORT);
  1571. cli.set_connection_timeout(std::chrono::seconds(5));
  1572. auto res =
  1573. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1574. "application/json", [](uint64_t, uint64_t) { return false; });
  1575. ASSERT_TRUE(!res);
  1576. EXPECT_EQ(Error::Canceled, res.error());
  1577. }
  1578. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1579. Server svr;
  1580. svr.set_payload_max_length(200 * 1024 * 1024);
  1581. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1582. res.set_content(LARGE_DATA, "text/plain");
  1583. });
  1584. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1585. auto se = detail::scope_exit([&] {
  1586. svr.stop();
  1587. thread.join();
  1588. ASSERT_FALSE(svr.is_running());
  1589. });
  1590. svr.wait_until_ready();
  1591. Client cli(HOST, PORT);
  1592. cli.set_payload_max_length(200 * 1024 * 1024);
  1593. cli.set_connection_timeout(std::chrono::seconds(5));
  1594. auto res =
  1595. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1596. "application/json", [](uint64_t, uint64_t) { return false; });
  1597. ASSERT_TRUE(!res);
  1598. EXPECT_EQ(Error::Canceled, res.error());
  1599. }
  1600. static std::string remove_whitespace(const std::string &input) {
  1601. std::string output;
  1602. output.reserve(input.size());
  1603. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1604. [](unsigned char c) { return !std::isspace(c); });
  1605. return output;
  1606. }
  1607. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1608. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1609. auto host = "httpcan.org";
  1610. auto path = std::string{"/basic-auth/hello/world"};
  1611. #else
  1612. auto host = "nghttp2.org";
  1613. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1614. #endif
  1615. #ifdef CPPHTTPLIB_SSL_ENABLED
  1616. auto port = 443;
  1617. SSLClient cli(host, port);
  1618. #else
  1619. auto port = 80;
  1620. Client cli(host, port);
  1621. #endif
  1622. {
  1623. auto res = cli.Get(path);
  1624. ASSERT_TRUE(res);
  1625. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1626. }
  1627. {
  1628. auto res =
  1629. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1630. ASSERT_TRUE(res);
  1631. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1632. remove_whitespace(res->body));
  1633. EXPECT_EQ(StatusCode::OK_200, res->status);
  1634. }
  1635. {
  1636. cli.set_basic_auth("hello", "world");
  1637. auto res = cli.Get(path);
  1638. ASSERT_TRUE(res);
  1639. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1640. remove_whitespace(res->body));
  1641. EXPECT_EQ(StatusCode::OK_200, res->status);
  1642. }
  1643. {
  1644. cli.set_basic_auth("hello", "bad");
  1645. auto res = cli.Get(path);
  1646. ASSERT_TRUE(res);
  1647. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1648. }
  1649. {
  1650. cli.set_basic_auth("bad", "world");
  1651. auto res = cli.Get(path);
  1652. ASSERT_TRUE(res);
  1653. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1654. }
  1655. }
  1656. #ifdef CPPHTTPLIB_SSL_ENABLED
  1657. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1658. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1659. auto host = "httpcan.org";
  1660. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1661. auto paths = std::vector<std::string>{
  1662. "/digest-auth/auth/hello/world/MD5",
  1663. "/digest-auth/auth/hello/world/SHA-256",
  1664. "/digest-auth/auth/hello/world/SHA-512",
  1665. };
  1666. #else
  1667. auto host = "nghttp2.org";
  1668. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1669. auto paths = std::vector<std::string>{
  1670. "/httpbin/digest-auth/auth/hello/world/MD5",
  1671. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1672. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1673. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1674. };
  1675. #endif
  1676. auto port = 443;
  1677. SSLClient cli(host, port);
  1678. {
  1679. auto res = cli.Get(unauth_path);
  1680. ASSERT_TRUE(res);
  1681. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1682. }
  1683. {
  1684. cli.set_digest_auth("hello", "world");
  1685. for (const auto &path : paths) {
  1686. auto res = cli.Get(path.c_str());
  1687. ASSERT_TRUE(res);
  1688. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1689. std::string algo(path.substr(path.rfind('/') + 1));
  1690. EXPECT_EQ(
  1691. remove_whitespace("{\"algorithm\":\"" + algo +
  1692. "\",\"authenticated\":true,\"user\":\"hello\"}\n"),
  1693. remove_whitespace(res->body));
  1694. #else
  1695. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1696. remove_whitespace(res->body));
  1697. #endif
  1698. EXPECT_EQ(StatusCode::OK_200, res->status);
  1699. }
  1700. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1701. cli.set_digest_auth("hello", "bad");
  1702. for (const auto &path : paths) {
  1703. auto res = cli.Get(path.c_str());
  1704. ASSERT_TRUE(res);
  1705. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1706. }
  1707. #endif
  1708. }
  1709. }
  1710. #endif
  1711. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1712. auto host = "google.com";
  1713. auto another_host = "example.com";
  1714. auto wrong_ip = "0.0.0.0";
  1715. #ifdef CPPHTTPLIB_SSL_ENABLED
  1716. SSLClient cli(host);
  1717. #else
  1718. Client cli(host);
  1719. #endif
  1720. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1721. auto res = cli.Get("/");
  1722. ASSERT_TRUE(res);
  1723. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1724. }
  1725. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1726. auto host = "google.com";
  1727. auto wrong_ip = "0.0.0.0";
  1728. #ifdef CPPHTTPLIB_SSL_ENABLED
  1729. SSLClient cli(host);
  1730. #else
  1731. Client cli(host);
  1732. #endif
  1733. cli.set_hostname_addr_map({{host, wrong_ip}});
  1734. auto res = cli.Get("/");
  1735. ASSERT_TRUE(!res);
  1736. EXPECT_EQ(Error::Connection, res.error());
  1737. }
  1738. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1739. auto host = "nghttp2.org";
  1740. #ifdef CPPHTTPLIB_SSL_ENABLED
  1741. SSLClient cli(host);
  1742. #else
  1743. Client cli(host);
  1744. #endif
  1745. cli.set_follow_location(true);
  1746. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1747. ASSERT_TRUE(res);
  1748. EXPECT_EQ(StatusCode::OK_200, res->status);
  1749. }
  1750. TEST(RedirectTest, Redirect_Online) {
  1751. auto host = "nghttp2.org";
  1752. #ifdef CPPHTTPLIB_SSL_ENABLED
  1753. SSLClient cli(host);
  1754. #else
  1755. Client cli(host);
  1756. #endif
  1757. cli.set_follow_location(true);
  1758. auto res = cli.Get("/httpbin/redirect/3");
  1759. ASSERT_TRUE(res);
  1760. EXPECT_EQ(StatusCode::OK_200, res->status);
  1761. }
  1762. TEST(RelativeRedirectTest, Redirect_Online) {
  1763. auto host = "nghttp2.org";
  1764. #ifdef CPPHTTPLIB_SSL_ENABLED
  1765. SSLClient cli(host);
  1766. #else
  1767. Client cli(host);
  1768. #endif
  1769. cli.set_follow_location(true);
  1770. auto res = cli.Get("/httpbin/relative-redirect/3");
  1771. ASSERT_TRUE(res);
  1772. EXPECT_EQ(StatusCode::OK_200, res->status);
  1773. }
  1774. TEST(TooManyRedirectTest, Redirect_Online) {
  1775. auto host = "nghttp2.org";
  1776. #ifdef CPPHTTPLIB_SSL_ENABLED
  1777. SSLClient cli(host);
  1778. #else
  1779. Client cli(host);
  1780. #endif
  1781. cli.set_follow_location(true);
  1782. auto res = cli.Get("/httpbin/redirect/21");
  1783. ASSERT_TRUE(!res);
  1784. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1785. }
  1786. #ifdef CPPHTTPLIB_SSL_ENABLED
  1787. TEST(YahooRedirectTest, Redirect_Online) {
  1788. Client cli("yahoo.com");
  1789. auto res = cli.Get("/");
  1790. ASSERT_TRUE(res);
  1791. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1792. cli.set_follow_location(true);
  1793. res = cli.Get("/");
  1794. ASSERT_TRUE(res);
  1795. EXPECT_EQ(StatusCode::OK_200, res->status);
  1796. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1797. }
  1798. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1799. #define REDIR_HOST "httpbingo.org"
  1800. #define REDIR_PATH "/redirect-to"
  1801. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1802. SSLClient cli(REDIR_HOST);
  1803. cli.set_follow_location(true);
  1804. auto res =
  1805. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1806. ASSERT_TRUE(res);
  1807. EXPECT_EQ(StatusCode::OK_200, res->status);
  1808. }
  1809. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1810. SSLClient cli(REDIR_HOST);
  1811. cli.set_follow_location(true);
  1812. Params params;
  1813. params.emplace("url", "http://example.com");
  1814. params.emplace("status_code", "302");
  1815. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1816. ASSERT_TRUE(res);
  1817. EXPECT_EQ(StatusCode::OK_200, res->status);
  1818. }
  1819. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1820. SSLClient cli(REDIR_HOST);
  1821. cli.set_follow_location(true);
  1822. Params params;
  1823. params.emplace("url", "http://example.com");
  1824. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1825. ASSERT_TRUE(res);
  1826. EXPECT_EQ(StatusCode::OK_200, res->status);
  1827. }
  1828. TEST(UrlWithSpace, Redirect_Online) {
  1829. SSLClient cli("edge.forgecdn.net");
  1830. cli.set_follow_location(true);
  1831. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1832. ASSERT_TRUE(res);
  1833. EXPECT_EQ(StatusCode::OK_200, res->status);
  1834. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1835. }
  1836. #endif
  1837. #if !defined(_WIN32) && !defined(_WIN64)
  1838. TEST(ReceiveSignals, Signal) {
  1839. auto setupSignalHandlers = []() {
  1840. struct sigaction act;
  1841. sigemptyset(&act.sa_mask);
  1842. act.sa_flags = SA_SIGINFO;
  1843. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1844. switch (sig) {
  1845. case SIGINT:
  1846. default: break;
  1847. }
  1848. };
  1849. ::sigaction(SIGINT, &act, nullptr);
  1850. };
  1851. Server svr;
  1852. int port = 0;
  1853. auto thread = std::thread([&]() {
  1854. setupSignalHandlers();
  1855. port = svr.bind_to_any_port(HOST);
  1856. svr.listen_after_bind();
  1857. });
  1858. auto se = detail::scope_exit([&] {
  1859. svr.stop();
  1860. thread.join();
  1861. ASSERT_FALSE(svr.is_running());
  1862. });
  1863. svr.wait_until_ready();
  1864. ASSERT_TRUE(svr.is_running());
  1865. pthread_kill(thread.native_handle(), SIGINT);
  1866. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1867. ASSERT_TRUE(svr.is_running());
  1868. }
  1869. #endif
  1870. TEST(RedirectToDifferentPort, Redirect) {
  1871. Server svr1;
  1872. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1873. res.set_content("Hello World!", "text/plain");
  1874. });
  1875. int svr1_port = 0;
  1876. auto thread1 = std::thread([&]() {
  1877. svr1_port = svr1.bind_to_any_port(HOST);
  1878. svr1.listen_after_bind();
  1879. });
  1880. Server svr2;
  1881. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1882. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1883. });
  1884. int svr2_port = 0;
  1885. auto thread2 = std::thread([&]() {
  1886. svr2_port = svr2.bind_to_any_port(HOST);
  1887. svr2.listen_after_bind();
  1888. });
  1889. auto se = detail::scope_exit([&] {
  1890. svr2.stop();
  1891. thread2.join();
  1892. svr1.stop();
  1893. thread1.join();
  1894. ASSERT_FALSE(svr2.is_running());
  1895. ASSERT_FALSE(svr1.is_running());
  1896. });
  1897. svr1.wait_until_ready();
  1898. svr2.wait_until_ready();
  1899. Client cli("localhost", svr2_port);
  1900. cli.set_follow_location(true);
  1901. auto res = cli.Get("/2");
  1902. ASSERT_TRUE(res);
  1903. EXPECT_EQ(StatusCode::OK_200, res->status);
  1904. EXPECT_EQ("Hello World!", res->body);
  1905. }
  1906. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  1907. Server svr;
  1908. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  1909. // Port number that overflows int — should not crash
  1910. res.set_redirect("http://localhost:99999999999999999999/target");
  1911. });
  1912. auto port = svr.bind_to_any_port(HOST);
  1913. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  1914. auto se = detail::scope_exit([&] {
  1915. svr.stop();
  1916. thread.join();
  1917. ASSERT_FALSE(svr.is_running());
  1918. });
  1919. svr.wait_until_ready();
  1920. Client cli(HOST, port);
  1921. cli.set_follow_location(true);
  1922. auto res = cli.Get("/redir");
  1923. // Should fail gracefully, not crash (no valid response due to bad port)
  1924. EXPECT_FALSE(res);
  1925. }
  1926. TEST(RedirectFromPageWithContent, Redirect) {
  1927. Server svr;
  1928. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1929. res.set_content("___", "text/plain");
  1930. res.set_redirect("/2");
  1931. });
  1932. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1933. res.set_content("Hello World!", "text/plain");
  1934. });
  1935. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1936. auto se = detail::scope_exit([&] {
  1937. svr.stop();
  1938. th.join();
  1939. ASSERT_FALSE(svr.is_running());
  1940. });
  1941. svr.wait_until_ready();
  1942. {
  1943. Client cli("localhost", PORT);
  1944. cli.set_follow_location(true);
  1945. std::string body;
  1946. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1947. body.append(data, data_length);
  1948. return true;
  1949. });
  1950. ASSERT_TRUE(res);
  1951. EXPECT_EQ(StatusCode::OK_200, res->status);
  1952. EXPECT_EQ("Hello World!", body);
  1953. }
  1954. {
  1955. Client cli("localhost", PORT);
  1956. std::string body;
  1957. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1958. body.append(data, data_length);
  1959. return true;
  1960. });
  1961. ASSERT_TRUE(res);
  1962. EXPECT_EQ(StatusCode::Found_302, res->status);
  1963. EXPECT_EQ("___", body);
  1964. }
  1965. }
  1966. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1967. Server svr;
  1968. auto port_str = std::to_string(PORT);
  1969. auto redirect_url = "http://[::1]:" + port_str + "/2";
  1970. auto expected_host = "[::1]:" + port_str;
  1971. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1972. res.set_content("___", "text/plain");
  1973. // res.set_redirect("/2");
  1974. res.set_redirect(redirect_url);
  1975. });
  1976. svr.Get("/2", [&](const Request &req, Response &res) {
  1977. auto host_header = req.headers.find("Host");
  1978. ASSERT_TRUE(host_header != req.headers.end());
  1979. EXPECT_EQ(expected_host, host_header->second);
  1980. res.set_content("Hello World!", "text/plain");
  1981. });
  1982. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  1983. auto se = detail::scope_exit([&] {
  1984. svr.stop();
  1985. th.join();
  1986. ASSERT_FALSE(svr.is_running());
  1987. });
  1988. // When IPV6 support isn't available svr.listen("::1", PORT) never
  1989. // actually starts anything, so the condition !svr.is_running() will
  1990. // always remain true, and the loop never stops.
  1991. // This basically counts how many milliseconds have passed since the
  1992. // call to svr.listen(), and if after 5 seconds nothing started yet
  1993. // aborts the test.
  1994. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1995. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1996. ASSERT_LT(milliseconds, 5000U);
  1997. }
  1998. {
  1999. Client cli("::1", PORT);
  2000. cli.set_follow_location(true);
  2001. std::string body;
  2002. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2003. body.append(data, data_length);
  2004. return true;
  2005. });
  2006. ASSERT_TRUE(res);
  2007. EXPECT_EQ(StatusCode::OK_200, res->status);
  2008. EXPECT_EQ("Hello World!", body);
  2009. }
  2010. {
  2011. Client cli("::1", PORT);
  2012. std::string body;
  2013. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2014. body.append(data, data_length);
  2015. return true;
  2016. });
  2017. ASSERT_TRUE(res);
  2018. EXPECT_EQ(StatusCode::Found_302, res->status);
  2019. EXPECT_EQ("___", body);
  2020. }
  2021. }
  2022. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2023. Server svr;
  2024. svr.Get("/foo", [](const Request &req, Response &res) {
  2025. auto a = req.params.find("a");
  2026. if (a != req.params.end()) {
  2027. res.set_content((*a).second, "text/plain");
  2028. res.status = StatusCode::OK_200;
  2029. } else {
  2030. res.status = StatusCode::BadRequest_400;
  2031. }
  2032. });
  2033. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2034. auto se = detail::scope_exit([&] {
  2035. svr.stop();
  2036. thread.join();
  2037. ASSERT_FALSE(svr.is_running());
  2038. });
  2039. svr.wait_until_ready();
  2040. {
  2041. Client cli(HOST, PORT);
  2042. cli.set_path_encode(false);
  2043. auto res = cli.Get("/foo?a=explicitly+encoded");
  2044. ASSERT_TRUE(res);
  2045. EXPECT_EQ(StatusCode::OK_200, res->status);
  2046. // This expects it back with a space, as the `+` won't have been
  2047. // url-encoded, and server-side the params get decoded turning `+`
  2048. // into spaces.
  2049. EXPECT_EQ("explicitly encoded", res->body);
  2050. }
  2051. }
  2052. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2053. Server svr;
  2054. svr.Get("/", [](const Request &req, Response &) {
  2055. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2056. });
  2057. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2058. auto se = detail::scope_exit([&] {
  2059. svr.stop();
  2060. thread.join();
  2061. ASSERT_FALSE(svr.is_running());
  2062. });
  2063. svr.wait_until_ready();
  2064. {
  2065. Client cli(HOST, PORT);
  2066. cli.set_path_encode(false);
  2067. auto res = cli.Get("/?something=%0A");
  2068. ASSERT_TRUE(res);
  2069. EXPECT_EQ(StatusCode::OK_200, res->status);
  2070. }
  2071. }
  2072. TEST(BindServerTest, DISABLED_BindDualStack) {
  2073. Server svr;
  2074. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2075. res.set_content("Hello World!", "text/plain");
  2076. });
  2077. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2078. auto se = detail::scope_exit([&] {
  2079. svr.stop();
  2080. thread.join();
  2081. ASSERT_FALSE(svr.is_running());
  2082. });
  2083. svr.wait_until_ready();
  2084. {
  2085. Client cli("127.0.0.1", PORT);
  2086. auto res = cli.Get("/1");
  2087. ASSERT_TRUE(res);
  2088. EXPECT_EQ(StatusCode::OK_200, res->status);
  2089. EXPECT_EQ("Hello World!", res->body);
  2090. }
  2091. {
  2092. Client cli("::1", PORT);
  2093. auto res = cli.Get("/1");
  2094. ASSERT_TRUE(res);
  2095. EXPECT_EQ(StatusCode::OK_200, res->status);
  2096. EXPECT_EQ("Hello World!", res->body);
  2097. }
  2098. }
  2099. TEST(BindServerTest, BindAndListenSeparately) {
  2100. Server svr;
  2101. int port = svr.bind_to_any_port("0.0.0.0");
  2102. ASSERT_TRUE(svr.is_valid());
  2103. ASSERT_TRUE(port > 0);
  2104. svr.stop();
  2105. }
  2106. #ifdef CPPHTTPLIB_SSL_ENABLED
  2107. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2108. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2109. CLIENT_CA_CERT_DIR);
  2110. int port = svr.bind_to_any_port("0.0.0.0");
  2111. ASSERT_TRUE(svr.is_valid());
  2112. ASSERT_TRUE(port > 0);
  2113. svr.stop();
  2114. }
  2115. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2116. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2117. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2118. int port = svr.bind_to_any_port("0.0.0.0");
  2119. ASSERT_TRUE(svr.is_valid());
  2120. ASSERT_TRUE(port > 0);
  2121. svr.stop();
  2122. }
  2123. TEST(BindServerTest, UpdateCertsPem) {
  2124. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2125. int port = svr.bind_to_any_port("0.0.0.0");
  2126. ASSERT_TRUE(svr.is_valid());
  2127. ASSERT_TRUE(port > 0);
  2128. // Read PEM files
  2129. std::string cert_pem, key_pem, ca_pem;
  2130. read_file(SERVER_CERT_FILE, cert_pem);
  2131. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2132. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2133. // Update server certificates using PEM API
  2134. ASSERT_TRUE(
  2135. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2136. ASSERT_TRUE(svr.is_valid());
  2137. svr.stop();
  2138. }
  2139. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2140. // Start server with client CA (enables client auth)
  2141. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2142. ASSERT_TRUE(svr.is_valid());
  2143. bool handler_called = false;
  2144. svr.Get("/test", [&](const Request &req, Response &res) {
  2145. handler_called = true;
  2146. // Verify client certificate is present
  2147. auto cert = req.peer_cert();
  2148. EXPECT_TRUE(static_cast<bool>(cert));
  2149. res.set_content("ok", "text/plain");
  2150. });
  2151. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2152. auto se = detail::scope_exit([&] {
  2153. svr.stop();
  2154. t.join();
  2155. ASSERT_FALSE(svr.is_running());
  2156. });
  2157. svr.wait_until_ready();
  2158. // Read PEM files
  2159. std::string cert_pem, key_pem, ca_pem;
  2160. read_file(SERVER_CERT_FILE, cert_pem);
  2161. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2162. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2163. // Update server certificates and client CA using PEM API while server running
  2164. ASSERT_TRUE(
  2165. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2166. // Connect with client certificate
  2167. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2168. cli.enable_server_certificate_verification(false);
  2169. cli.set_connection_timeout(30);
  2170. auto res = cli.Get("/test");
  2171. ASSERT_TRUE(res);
  2172. ASSERT_EQ(StatusCode::OK_200, res->status);
  2173. ASSERT_TRUE(handler_called);
  2174. EXPECT_EQ("ok", res->body);
  2175. }
  2176. #endif
  2177. TEST(ErrorHandlerTest, ContentLength) {
  2178. Server svr;
  2179. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2180. res.status = StatusCode::OK_200;
  2181. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2182. "text/html"); // <= Content-Length still 13
  2183. });
  2184. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2185. res.set_content("Hello World!\n", "text/plain");
  2186. res.status = 524;
  2187. });
  2188. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2189. auto se = detail::scope_exit([&] {
  2190. svr.stop();
  2191. thread.join();
  2192. ASSERT_FALSE(svr.is_running());
  2193. });
  2194. svr.wait_until_ready();
  2195. {
  2196. Client cli(HOST, PORT);
  2197. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2198. ASSERT_TRUE(res);
  2199. EXPECT_EQ(StatusCode::OK_200, res->status);
  2200. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2201. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2202. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2203. }
  2204. }
  2205. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2206. TEST(ExceptionTest, WithoutExceptionHandler) {
  2207. Server svr;
  2208. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2209. throw std::runtime_error("exception...");
  2210. });
  2211. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2212. throw std::runtime_error("exception\r\n...");
  2213. });
  2214. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2215. auto se = detail::scope_exit([&] {
  2216. svr.stop();
  2217. listen_thread.join();
  2218. ASSERT_FALSE(svr.is_running());
  2219. });
  2220. svr.wait_until_ready();
  2221. Client cli("localhost", PORT);
  2222. {
  2223. auto res = cli.Get("/exception");
  2224. ASSERT_TRUE(res);
  2225. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2226. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2227. }
  2228. {
  2229. auto res = cli.Get("/unknown");
  2230. ASSERT_TRUE(res);
  2231. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2232. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2233. }
  2234. }
  2235. TEST(ExceptionTest, WithExceptionHandler) {
  2236. Server svr;
  2237. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2238. std::exception_ptr ep) {
  2239. EXPECT_FALSE(ep == nullptr);
  2240. try {
  2241. std::rethrow_exception(ep);
  2242. } catch (std::exception &e) {
  2243. EXPECT_EQ("abc", std::string(e.what()));
  2244. } catch (...) {}
  2245. res.status = StatusCode::InternalServerError_500;
  2246. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2247. "text/html"); // <= Content-Length still 13 at this point
  2248. });
  2249. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2250. res.set_content("Hello World!\n", "text/plain");
  2251. throw std::runtime_error("abc");
  2252. });
  2253. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2254. auto se = detail::scope_exit([&] {
  2255. svr.stop();
  2256. thread.join();
  2257. ASSERT_FALSE(svr.is_running());
  2258. });
  2259. svr.wait_until_ready();
  2260. for (size_t i = 0; i < 10; i++) {
  2261. Client cli(HOST, PORT);
  2262. for (size_t j = 0; j < 100; j++) {
  2263. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2264. ASSERT_TRUE(res);
  2265. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2266. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2267. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2268. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2269. }
  2270. cli.set_keep_alive(true);
  2271. for (size_t j = 0; j < 100; j++) {
  2272. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2273. ASSERT_TRUE(res);
  2274. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2275. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2276. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2277. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2278. }
  2279. }
  2280. }
  2281. TEST(ExceptionTest, AndErrorHandler) {
  2282. Server svr;
  2283. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2284. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2285. });
  2286. svr.set_exception_handler(
  2287. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2288. EXPECT_FALSE(ep == nullptr);
  2289. try {
  2290. std::rethrow_exception(ep);
  2291. } catch (std::exception &e) {
  2292. res.set_content(e.what(), "text/html");
  2293. } catch (...) {}
  2294. res.status = StatusCode::InternalServerError_500;
  2295. });
  2296. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2297. throw std::runtime_error("EXCEPTION");
  2298. });
  2299. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2300. res.set_content("ERROR", "text/html");
  2301. res.status = StatusCode::InternalServerError_500;
  2302. });
  2303. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2304. auto se = detail::scope_exit([&] {
  2305. svr.stop();
  2306. thread.join();
  2307. ASSERT_FALSE(svr.is_running());
  2308. });
  2309. svr.wait_until_ready();
  2310. Client cli(HOST, PORT);
  2311. {
  2312. auto res = cli.Get("/exception");
  2313. ASSERT_TRUE(res);
  2314. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2315. EXPECT_EQ("EXCEPTION", res->body);
  2316. }
  2317. {
  2318. auto res = cli.Get("/error");
  2319. ASSERT_TRUE(res);
  2320. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2321. EXPECT_EQ("ERROR", res->body);
  2322. }
  2323. {
  2324. auto res = cli.Get("/invalid");
  2325. ASSERT_TRUE(res);
  2326. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2327. EXPECT_EQ("NOT_FOUND", res->body);
  2328. }
  2329. }
  2330. #endif
  2331. TEST(NoContentTest, ContentLength) {
  2332. Server svr;
  2333. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2334. res.status = StatusCode::NoContent_204;
  2335. });
  2336. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2337. auto se = detail::scope_exit([&] {
  2338. svr.stop();
  2339. thread.join();
  2340. ASSERT_FALSE(svr.is_running());
  2341. });
  2342. svr.wait_until_ready();
  2343. {
  2344. Client cli(HOST, PORT);
  2345. auto res = cli.Get("/hi");
  2346. ASSERT_TRUE(res);
  2347. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2348. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2349. }
  2350. }
  2351. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2352. #ifdef CPPHTTPLIB_SSL_ENABLED
  2353. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2354. ASSERT_TRUE(svr.is_valid());
  2355. #else
  2356. Server svr;
  2357. #endif
  2358. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2359. if (req.path == "/routing_handler") {
  2360. res.set_header("PRE_ROUTING", "on");
  2361. res.set_content("Routing Handler", "text/plain");
  2362. return httplib::Server::HandlerResponse::Handled;
  2363. }
  2364. return httplib::Server::HandlerResponse::Unhandled;
  2365. });
  2366. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2367. res.set_content("Error", "text/html");
  2368. });
  2369. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2370. if (req.path == "/routing_handler") {
  2371. res.set_header("POST_ROUTING", "on");
  2372. }
  2373. });
  2374. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2375. res.set_content("Hello World!\n", "text/plain");
  2376. });
  2377. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2378. auto se = detail::scope_exit([&] {
  2379. svr.stop();
  2380. thread.join();
  2381. ASSERT_FALSE(svr.is_running());
  2382. });
  2383. svr.wait_until_ready();
  2384. {
  2385. #ifdef CPPHTTPLIB_SSL_ENABLED
  2386. SSLClient cli(HOST, PORT);
  2387. cli.enable_server_certificate_verification(false);
  2388. #else
  2389. Client cli(HOST, PORT);
  2390. #endif
  2391. auto res = cli.Get("/routing_handler");
  2392. ASSERT_TRUE(res);
  2393. EXPECT_EQ(StatusCode::OK_200, res->status);
  2394. EXPECT_EQ("Routing Handler", res->body);
  2395. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2396. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2397. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2398. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2399. }
  2400. {
  2401. #ifdef CPPHTTPLIB_SSL_ENABLED
  2402. SSLClient cli(HOST, PORT);
  2403. cli.enable_server_certificate_verification(false);
  2404. #else
  2405. Client cli(HOST, PORT);
  2406. #endif
  2407. auto res = cli.Get("/hi");
  2408. ASSERT_TRUE(res);
  2409. EXPECT_EQ(StatusCode::OK_200, res->status);
  2410. EXPECT_EQ("Hello World!\n", res->body);
  2411. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2412. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2413. }
  2414. {
  2415. #ifdef CPPHTTPLIB_SSL_ENABLED
  2416. SSLClient cli(HOST, PORT);
  2417. cli.enable_server_certificate_verification(false);
  2418. #else
  2419. Client cli(HOST, PORT);
  2420. #endif
  2421. auto res = cli.Get("/aaa");
  2422. ASSERT_TRUE(res);
  2423. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2424. EXPECT_EQ("Error", res->body);
  2425. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2426. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2427. }
  2428. }
  2429. TEST(RequestHandlerTest, PreRequestHandler) {
  2430. auto route_path = "/user/:user";
  2431. Server svr;
  2432. svr.Get("/hi", [](const Request &, Response &res) {
  2433. res.set_content("hi", "text/plain");
  2434. });
  2435. svr.Get(route_path, [](const Request &req, Response &res) {
  2436. res.set_content(req.path_params.at("user"), "text/plain");
  2437. });
  2438. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2439. if (req.matched_route == route_path) {
  2440. auto user = req.path_params.at("user");
  2441. if (user != "john") {
  2442. res.status = StatusCode::Forbidden_403;
  2443. res.set_content("error", "text/html");
  2444. return Server::HandlerResponse::Handled;
  2445. }
  2446. }
  2447. return Server::HandlerResponse::Unhandled;
  2448. });
  2449. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2450. auto se = detail::scope_exit([&] {
  2451. svr.stop();
  2452. thread.join();
  2453. ASSERT_FALSE(svr.is_running());
  2454. });
  2455. svr.wait_until_ready();
  2456. Client cli(HOST, PORT);
  2457. {
  2458. auto res = cli.Get("/hi");
  2459. ASSERT_TRUE(res);
  2460. EXPECT_EQ(StatusCode::OK_200, res->status);
  2461. EXPECT_EQ("hi", res->body);
  2462. }
  2463. {
  2464. auto res = cli.Get("/user/john");
  2465. ASSERT_TRUE(res);
  2466. EXPECT_EQ(StatusCode::OK_200, res->status);
  2467. EXPECT_EQ("john", res->body);
  2468. }
  2469. {
  2470. auto res = cli.Get("/user/invalid-user");
  2471. ASSERT_TRUE(res);
  2472. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2473. EXPECT_EQ("error", res->body);
  2474. }
  2475. }
  2476. TEST(AnyTest, BasicOperations) {
  2477. // Default construction
  2478. httplib::any a;
  2479. EXPECT_FALSE(a.has_value());
  2480. // Value construction and any_cast (pointer form, noexcept)
  2481. httplib::any b(42);
  2482. EXPECT_TRUE(b.has_value());
  2483. auto *p = httplib::any_cast<int>(&b);
  2484. ASSERT_NE(nullptr, p);
  2485. EXPECT_EQ(42, *p);
  2486. // Type mismatch → nullptr
  2487. auto *q = httplib::any_cast<std::string>(&b);
  2488. EXPECT_EQ(nullptr, q);
  2489. // any_cast (value form) succeeds
  2490. EXPECT_EQ(42, httplib::any_cast<int>(b));
  2491. // any_cast (value form) throws on type mismatch
  2492. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2493. EXPECT_THROW(httplib::any_cast<std::string>(b), httplib::bad_any_cast);
  2494. #endif
  2495. // Copy
  2496. httplib::any c = b;
  2497. EXPECT_EQ(42, httplib::any_cast<int>(c));
  2498. // Move
  2499. httplib::any d = std::move(c);
  2500. EXPECT_EQ(42, httplib::any_cast<int>(d));
  2501. // Assignment with different type
  2502. b = std::string("hello");
  2503. EXPECT_EQ("hello", httplib::any_cast<std::string>(b));
  2504. // Reset
  2505. b.reset();
  2506. EXPECT_FALSE(b.has_value());
  2507. }
  2508. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2509. struct AuthCtx {
  2510. std::string user_id;
  2511. };
  2512. Server svr;
  2513. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2514. res.user_data["auth"] = AuthCtx{"alice"};
  2515. return Server::HandlerResponse::Unhandled;
  2516. });
  2517. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2518. auto *ctx = httplib::any_cast<AuthCtx>(&res.user_data["auth"]);
  2519. ASSERT_NE(nullptr, ctx);
  2520. res.set_content("Hello " + ctx->user_id, "text/plain");
  2521. });
  2522. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2523. auto se = detail::scope_exit([&] {
  2524. svr.stop();
  2525. thread.join();
  2526. ASSERT_FALSE(svr.is_running());
  2527. });
  2528. svr.wait_until_ready();
  2529. Client cli(HOST, PORT);
  2530. auto res = cli.Get("/me");
  2531. ASSERT_TRUE(res);
  2532. EXPECT_EQ(StatusCode::OK_200, res->status);
  2533. EXPECT_EQ("Hello alice", res->body);
  2534. }
  2535. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2536. struct RoleCtx {
  2537. std::string role;
  2538. };
  2539. Server svr;
  2540. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2541. res.user_data["role"] = RoleCtx{"admin"};
  2542. return Server::HandlerResponse::Unhandled;
  2543. });
  2544. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2545. auto *ctx = httplib::any_cast<RoleCtx>(&res.user_data["role"]);
  2546. ASSERT_NE(nullptr, ctx);
  2547. res.set_content(ctx->role, "text/plain");
  2548. });
  2549. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2550. auto se = detail::scope_exit([&] {
  2551. svr.stop();
  2552. thread.join();
  2553. ASSERT_FALSE(svr.is_running());
  2554. });
  2555. svr.wait_until_ready();
  2556. Client cli(HOST, PORT);
  2557. auto res = cli.Get("/role");
  2558. ASSERT_TRUE(res);
  2559. EXPECT_EQ(StatusCode::OK_200, res->status);
  2560. EXPECT_EQ("admin", res->body);
  2561. }
  2562. TEST(InvalidFormatTest, StatusCode) {
  2563. Server svr;
  2564. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2565. res.set_content("Hello World!\n", "text/plain");
  2566. res.status = 9999; // Status should be a three-digit code...
  2567. });
  2568. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2569. auto se = detail::scope_exit([&] {
  2570. svr.stop();
  2571. thread.join();
  2572. ASSERT_FALSE(svr.is_running());
  2573. });
  2574. svr.wait_until_ready();
  2575. {
  2576. Client cli(HOST, PORT);
  2577. auto res = cli.Get("/hi");
  2578. ASSERT_FALSE(res);
  2579. }
  2580. }
  2581. TEST(URLFragmentTest, WithFragment) {
  2582. Server svr;
  2583. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2584. EXPECT_TRUE(req.target == "/hi");
  2585. });
  2586. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2587. auto se = detail::scope_exit([&] {
  2588. svr.stop();
  2589. thread.join();
  2590. ASSERT_FALSE(svr.is_running());
  2591. });
  2592. svr.wait_until_ready();
  2593. {
  2594. Client cli(HOST, PORT);
  2595. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2596. EXPECT_TRUE(res);
  2597. EXPECT_EQ(StatusCode::OK_200, res->status);
  2598. res = cli.Get("/hi%23key1=val1=key2=val2");
  2599. EXPECT_TRUE(res);
  2600. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2601. }
  2602. }
  2603. TEST(HeaderWriter, SetHeaderWriter) {
  2604. Server svr;
  2605. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2606. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2607. return detail::write_headers(strm, hdrs);
  2608. });
  2609. svr.Get("/hi", [](const Request &req, Response &res) {
  2610. auto it = req.headers.find("CustomClientHeader");
  2611. EXPECT_TRUE(it != req.headers.end());
  2612. EXPECT_EQ(it->second, "CustomClientValue");
  2613. res.set_content("Hello World!\n", "text/plain");
  2614. });
  2615. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2616. auto se = detail::scope_exit([&] {
  2617. svr.stop();
  2618. thread.join();
  2619. ASSERT_FALSE(svr.is_running());
  2620. });
  2621. svr.wait_until_ready();
  2622. {
  2623. Client cli(HOST, PORT);
  2624. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2625. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2626. return detail::write_headers(strm, hdrs);
  2627. });
  2628. auto res = cli.Get("/hi");
  2629. EXPECT_TRUE(res);
  2630. EXPECT_EQ(StatusCode::OK_200, res->status);
  2631. auto it = res->headers.find("CustomServerHeader");
  2632. EXPECT_TRUE(it != res->headers.end());
  2633. EXPECT_EQ(it->second, "CustomServerValue");
  2634. }
  2635. }
  2636. class ServerTest : public ::testing::Test {
  2637. protected:
  2638. ServerTest()
  2639. : cli_(HOST, PORT)
  2640. #ifdef CPPHTTPLIB_SSL_ENABLED
  2641. ,
  2642. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2643. #endif
  2644. {
  2645. #ifdef CPPHTTPLIB_SSL_ENABLED
  2646. cli_.enable_server_certificate_verification(false);
  2647. #endif
  2648. // Allow LARGE_DATA (100MB) responses
  2649. cli_.set_payload_max_length(200 * 1024 * 1024);
  2650. }
  2651. virtual void SetUp() {
  2652. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2653. svr_.set_payload_max_length(200 * 1024 * 1024);
  2654. svr_.set_mount_point("/", "./www");
  2655. svr_.set_mount_point("/mount", "./www2");
  2656. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2657. svr_.Get("/hi",
  2658. [&](const Request & /*req*/, Response &res) {
  2659. res.set_content("Hello World!", "text/plain");
  2660. })
  2661. .Get("/file_content",
  2662. [&](const Request & /*req*/, Response &res) {
  2663. res.set_file_content("./www/dir/test.html");
  2664. })
  2665. .Get("/file_content_with_content_type",
  2666. [&](const Request & /*req*/, Response &res) {
  2667. res.set_file_content("./www/file", "text/plain");
  2668. })
  2669. .Get("/invalid_file_content",
  2670. [&](const Request & /*req*/, Response &res) {
  2671. res.set_file_content("./www/dir/invalid_file_path");
  2672. })
  2673. .Get("/http_response_splitting",
  2674. [&](const Request & /*req*/, Response &res) {
  2675. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2676. EXPECT_EQ(0U, res.headers.size());
  2677. EXPECT_FALSE(res.has_header("a"));
  2678. res.set_header("a", "1\nSet-Cookie: a=1");
  2679. EXPECT_EQ(0U, res.headers.size());
  2680. EXPECT_FALSE(res.has_header("a"));
  2681. res.set_header("a", "1\rSet-Cookie: a=1");
  2682. EXPECT_EQ(0U, res.headers.size());
  2683. EXPECT_FALSE(res.has_header("a"));
  2684. res.set_header("a\r\nb", "0");
  2685. EXPECT_EQ(0U, res.headers.size());
  2686. EXPECT_FALSE(res.has_header("a"));
  2687. res.set_header("a\rb", "0");
  2688. EXPECT_EQ(0U, res.headers.size());
  2689. EXPECT_FALSE(res.has_header("a"));
  2690. res.set_header("a\nb", "0");
  2691. EXPECT_EQ(0U, res.headers.size());
  2692. EXPECT_FALSE(res.has_header("a"));
  2693. res.set_redirect("1\r\nSet-Cookie: a=1");
  2694. EXPECT_EQ(0U, res.headers.size());
  2695. EXPECT_FALSE(res.has_header("Location"));
  2696. })
  2697. .Get("/slow",
  2698. [&](const Request & /*req*/, Response &res) {
  2699. std::this_thread::sleep_for(std::chrono::seconds(2));
  2700. res.set_content("slow", "text/plain");
  2701. })
  2702. #if 0
  2703. .Post("/slowpost",
  2704. [&](const Request & /*req*/, Response &res) {
  2705. std::this_thread::sleep_for(std::chrono::seconds(2));
  2706. res.set_content("slow", "text/plain");
  2707. })
  2708. #endif
  2709. .Get("/remote_addr",
  2710. [&](const Request &req, Response &res) {
  2711. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2712. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2713. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2714. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2715. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2716. #endif
  2717. res.set_content(req.remote_addr, "text/plain");
  2718. })
  2719. .Get("/local_addr",
  2720. [&](const Request &req, Response &res) {
  2721. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2722. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2723. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2724. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2725. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2726. #endif
  2727. auto local_addr = req.local_addr;
  2728. auto local_port = std::to_string(req.local_port);
  2729. res.set_content(local_addr.append(":").append(local_port),
  2730. "text/plain");
  2731. })
  2732. .Get("/endwith%",
  2733. [&](const Request & /*req*/, Response &res) {
  2734. res.set_content("Hello World!", "text/plain");
  2735. })
  2736. .Get("/a\\+\\+b",
  2737. [&](const Request &req, Response &res) {
  2738. ASSERT_TRUE(req.has_param("a +b"));
  2739. auto val = req.get_param_value("a +b");
  2740. res.set_content(val, "text/plain");
  2741. })
  2742. .Get("/", [&](const Request & /*req*/,
  2743. Response &res) { res.set_redirect("/hi"); })
  2744. .Post("/1",
  2745. [](const Request & /*req*/, Response &res) {
  2746. res.set_redirect("/2", StatusCode::SeeOther_303);
  2747. })
  2748. .Get("/2",
  2749. [](const Request & /*req*/, Response &res) {
  2750. res.set_content("redirected.", "text/plain");
  2751. res.status = StatusCode::OK_200;
  2752. })
  2753. .Post("/person",
  2754. [&](const Request &req, Response &res) {
  2755. if (req.has_param("name") && req.has_param("note")) {
  2756. persons_[req.get_param_value("name")] =
  2757. req.get_param_value("note");
  2758. } else {
  2759. res.status = StatusCode::BadRequest_400;
  2760. }
  2761. })
  2762. .Put("/person",
  2763. [&](const Request &req, Response &res) {
  2764. if (req.has_param("name") && req.has_param("note")) {
  2765. persons_[req.get_param_value("name")] =
  2766. req.get_param_value("note");
  2767. } else {
  2768. res.status = StatusCode::BadRequest_400;
  2769. }
  2770. })
  2771. .Get("/person/(.*)",
  2772. [&](const Request &req, Response &res) {
  2773. string name = req.matches[1];
  2774. if (persons_.find(name) != persons_.end()) {
  2775. auto note = persons_[name];
  2776. res.set_content(note, "text/plain");
  2777. } else {
  2778. res.status = StatusCode::NotFound_404;
  2779. }
  2780. })
  2781. .Delete("/person",
  2782. [&](const Request &req, Response &res) {
  2783. if (req.has_param("name")) {
  2784. string name = req.get_param_value("name");
  2785. if (persons_.find(name) != persons_.end()) {
  2786. persons_.erase(name);
  2787. res.set_content("DELETED", "text/plain");
  2788. } else {
  2789. res.status = StatusCode::NotFound_404;
  2790. }
  2791. } else {
  2792. res.status = StatusCode::BadRequest_400;
  2793. }
  2794. })
  2795. .Post("/x-www-form-urlencoded-json",
  2796. [&](const Request &req, Response &res) {
  2797. auto json = req.get_param_value("json");
  2798. ASSERT_EQ(JSON_DATA, json);
  2799. res.set_content(json, "appliation/json");
  2800. res.status = StatusCode::OK_200;
  2801. })
  2802. .Get("/streamed-chunked",
  2803. [&](const Request & /*req*/, Response &res) {
  2804. res.set_chunked_content_provider(
  2805. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2806. sink.os << "123";
  2807. sink.os << "456";
  2808. sink.os << "789";
  2809. sink.done();
  2810. return true;
  2811. });
  2812. })
  2813. .Get("/streamed-chunked-with-prohibited-trailer",
  2814. [&](const Request & /*req*/, Response &res) {
  2815. auto i = new int(0);
  2816. // Declare both a prohibited trailer (Content-Length) and an
  2817. // allowed one
  2818. res.set_header("Trailer", "Content-Length, X-Allowed");
  2819. res.set_chunked_content_provider(
  2820. "text/plain",
  2821. [i](size_t /*offset*/, DataSink &sink) {
  2822. switch (*i) {
  2823. case 0: sink.os << "123"; break;
  2824. case 1: sink.os << "456"; break;
  2825. case 2: sink.os << "789"; break;
  2826. case 3: {
  2827. sink.done_with_trailer(
  2828. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2829. } break;
  2830. }
  2831. (*i)++;
  2832. return true;
  2833. },
  2834. [i](bool success) {
  2835. EXPECT_TRUE(success);
  2836. delete i;
  2837. });
  2838. })
  2839. .Get("/streamed-chunked2",
  2840. [&](const Request & /*req*/, Response &res) {
  2841. auto i = new int(0);
  2842. res.set_chunked_content_provider(
  2843. "text/plain",
  2844. [i](size_t /*offset*/, DataSink &sink) {
  2845. switch (*i) {
  2846. case 0: sink.os << "123"; break;
  2847. case 1: sink.os << "456"; break;
  2848. case 2: sink.os << "789"; break;
  2849. case 3: sink.done(); break;
  2850. }
  2851. (*i)++;
  2852. return true;
  2853. },
  2854. [i](bool success) {
  2855. EXPECT_TRUE(success);
  2856. delete i;
  2857. });
  2858. })
  2859. .Get("/streamed-chunked-with-trailer",
  2860. [&](const Request & /*req*/, Response &res) {
  2861. auto i = new int(0);
  2862. res.set_header("Trailer", "Dummy1, Dummy2");
  2863. res.set_chunked_content_provider(
  2864. "text/plain",
  2865. [i](size_t /*offset*/, DataSink &sink) {
  2866. switch (*i) {
  2867. case 0: sink.os << "123"; break;
  2868. case 1: sink.os << "456"; break;
  2869. case 2: sink.os << "789"; break;
  2870. case 3: {
  2871. sink.done_with_trailer(
  2872. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2873. } break;
  2874. }
  2875. (*i)++;
  2876. return true;
  2877. },
  2878. [i](bool success) {
  2879. EXPECT_TRUE(success);
  2880. delete i;
  2881. });
  2882. })
  2883. .Get("/streamed",
  2884. [&](const Request & /*req*/, Response &res) {
  2885. res.set_content_provider(
  2886. 6, "text/plain",
  2887. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2888. sink.os << (offset < 3 ? "a" : "b");
  2889. return true;
  2890. });
  2891. })
  2892. .Get("/streamed-with-range",
  2893. [&](const Request &req, Response &res) {
  2894. auto data = new std::string("abcdefg");
  2895. res.set_content_provider(
  2896. data->size(), "text/plain",
  2897. [data](size_t offset, size_t length, DataSink &sink) {
  2898. size_t DATA_CHUNK_SIZE = 4;
  2899. const auto &d = *data;
  2900. auto out_len =
  2901. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2902. auto ret =
  2903. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2904. EXPECT_TRUE(ret);
  2905. return true;
  2906. },
  2907. [data, &req](bool success) {
  2908. EXPECT_EQ(success, !req.has_param("error"));
  2909. delete data;
  2910. });
  2911. })
  2912. .Get("/streamed-cancel",
  2913. [&](const Request & /*req*/, Response &res) {
  2914. res.set_content_provider(
  2915. size_t(-1), "text/plain",
  2916. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2917. sink.os << "data_chunk";
  2918. return true;
  2919. });
  2920. })
  2921. .Get("/regex-with-delimiter",
  2922. [&](const Request &req, Response & /*res*/) {
  2923. ASSERT_TRUE(req.has_param("key"));
  2924. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2925. })
  2926. .Get("/with-range",
  2927. [&](const Request & /*req*/, Response &res) {
  2928. res.set_content("abcdefg", "text/plain");
  2929. })
  2930. .Get("/test-start-time",
  2931. [&](const Request &req, Response & /*res*/) {
  2932. EXPECT_NE(req.start_time_,
  2933. std::chrono::steady_clock::time_point::min());
  2934. })
  2935. .Get("/with-range-customized-response",
  2936. [&](const Request & /*req*/, Response &res) {
  2937. res.status = StatusCode::BadRequest_400;
  2938. res.set_content(JSON_DATA, "application/json");
  2939. })
  2940. .Post("/chunked",
  2941. [&](const Request &req, Response & /*res*/) {
  2942. EXPECT_EQ(req.body, "dechunked post body");
  2943. })
  2944. .Post("/large-chunked",
  2945. [&](const Request &req, Response & /*res*/) {
  2946. std::string expected(6 * 30 * 1024u, 'a');
  2947. EXPECT_EQ(req.body, expected);
  2948. })
  2949. .Post("/multipart",
  2950. [&](const Request &req, Response & /*res*/) {
  2951. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2952. req.form.get_field_count("text2") +
  2953. req.form.get_field_count("file3") +
  2954. req.form.get_field_count("file4"));
  2955. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2956. req.form.get_file_count("file2"));
  2957. ASSERT_TRUE(!req.form.has_file("???"));
  2958. ASSERT_TRUE(!req.form.has_field("???"));
  2959. ASSERT_TRUE(req.body.empty());
  2960. {
  2961. const auto &text = req.form.get_field("text1");
  2962. EXPECT_EQ("text default", text);
  2963. }
  2964. {
  2965. const auto &text = req.form.get_field("text2");
  2966. EXPECT_EQ("aωb", text);
  2967. }
  2968. {
  2969. const auto &file = req.form.get_file("file1");
  2970. EXPECT_EQ("hello.txt", file.filename);
  2971. EXPECT_EQ("text/plain", file.content_type);
  2972. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2973. }
  2974. {
  2975. const auto &file = req.form.get_file("file2");
  2976. EXPECT_EQ("world.json", file.filename);
  2977. EXPECT_EQ("application/json", file.content_type);
  2978. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2979. }
  2980. {
  2981. const auto &text = req.form.get_field("file3");
  2982. EXPECT_EQ(0u, text.size());
  2983. }
  2984. {
  2985. const auto &text = req.form.get_field("file4");
  2986. EXPECT_EQ(0u, text.size());
  2987. }
  2988. })
  2989. .Post("/multipart/multi_file_values",
  2990. [&](const Request &req, Response & /*res*/) {
  2991. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2992. req.form.get_field_count("multi_text1"));
  2993. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2994. ASSERT_TRUE(!req.form.has_file("???"));
  2995. ASSERT_TRUE(!req.form.has_field("???"));
  2996. ASSERT_TRUE(req.body.empty());
  2997. {
  2998. const auto &text = req.form.get_field("text");
  2999. EXPECT_EQ("default text", text);
  3000. }
  3001. {
  3002. const auto &text1_values = req.form.get_fields("multi_text1");
  3003. EXPECT_EQ(2u, text1_values.size());
  3004. EXPECT_EQ("aaaaa", text1_values[0]);
  3005. EXPECT_EQ("bbbbb", text1_values[1]);
  3006. }
  3007. {
  3008. const auto &file1_values = req.form.get_files("multi_file1");
  3009. EXPECT_EQ(2u, file1_values.size());
  3010. auto file1 = file1_values[0];
  3011. EXPECT_EQ(file1.filename, "hello.txt");
  3012. EXPECT_EQ(file1.content_type, "text/plain");
  3013. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3014. auto file2 = file1_values[1];
  3015. EXPECT_EQ(file2.filename, "world.json");
  3016. EXPECT_EQ(file2.content_type, "application/json");
  3017. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3018. }
  3019. })
  3020. .Post("/empty",
  3021. [&](const Request &req, Response &res) {
  3022. EXPECT_EQ(req.body, "");
  3023. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3024. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3025. res.set_content("empty", "text/plain");
  3026. })
  3027. .Post("/empty-no-content-type",
  3028. [&](const Request &req, Response &res) {
  3029. EXPECT_EQ(req.body, "");
  3030. EXPECT_FALSE(req.has_header("Content-Type"));
  3031. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3032. res.set_content("empty-no-content-type", "text/plain");
  3033. })
  3034. .Post("/path-only",
  3035. [&](const Request &req, Response &res) {
  3036. EXPECT_EQ(req.body, "");
  3037. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3038. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3039. res.set_content("path-only", "text/plain");
  3040. })
  3041. .Post("/path-headers-only",
  3042. [&](const Request &req, Response &res) {
  3043. EXPECT_EQ(req.body, "");
  3044. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3045. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3046. EXPECT_EQ("world", req.get_header_value("hello"));
  3047. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3048. res.set_content("path-headers-only", "text/plain");
  3049. })
  3050. .Post("/post-large",
  3051. [&](const Request &req, Response &res) {
  3052. EXPECT_EQ(req.body, LARGE_DATA);
  3053. res.set_content(req.body, "text/plain");
  3054. })
  3055. .Post("/post-loopback",
  3056. [&](const Request &, Response &res,
  3057. ContentReader const &content_reader) {
  3058. std::string body;
  3059. content_reader([&](const char *data, size_t data_length) {
  3060. body.append(data, data_length);
  3061. return true;
  3062. });
  3063. res.set_content(body, "text/plain");
  3064. })
  3065. .Put("/put-loopback",
  3066. [&](const Request &, Response &res,
  3067. ContentReader const &content_reader) {
  3068. std::string body;
  3069. content_reader([&](const char *data, size_t data_length) {
  3070. body.append(data, data_length);
  3071. return true;
  3072. });
  3073. res.set_content(body, "text/plain");
  3074. })
  3075. .Patch("/patch-loopback",
  3076. [&](const Request &, Response &res,
  3077. ContentReader const &content_reader) {
  3078. std::string body;
  3079. content_reader([&](const char *data, size_t data_length) {
  3080. body.append(data, data_length);
  3081. return true;
  3082. });
  3083. res.set_content(body, "text/plain");
  3084. })
  3085. .Put("/empty-no-content-type",
  3086. [&](const Request &req, Response &res) {
  3087. EXPECT_EQ(req.body, "");
  3088. EXPECT_FALSE(req.has_header("Content-Type"));
  3089. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3090. res.set_content("empty-no-content-type", "text/plain");
  3091. })
  3092. .Put("/put",
  3093. [&](const Request &req, Response &res) {
  3094. EXPECT_EQ(req.body, "PUT");
  3095. res.set_content(req.body, "text/plain");
  3096. })
  3097. .Put("/put-large",
  3098. [&](const Request &req, Response &res) {
  3099. EXPECT_EQ(req.body, LARGE_DATA);
  3100. res.set_content(req.body, "text/plain");
  3101. })
  3102. .Patch("/patch",
  3103. [&](const Request &req, Response &res) {
  3104. EXPECT_EQ(req.body, "PATCH");
  3105. res.set_content(req.body, "text/plain");
  3106. })
  3107. .Delete("/delete",
  3108. [&](const Request & /*req*/, Response &res) {
  3109. res.set_content("DELETE", "text/plain");
  3110. })
  3111. .Delete("/delete-body",
  3112. [&](const Request &req, Response &res) {
  3113. EXPECT_EQ(req.body, "content");
  3114. res.set_content(req.body, "text/plain");
  3115. })
  3116. .Options(R"(\*)",
  3117. [&](const Request & /*req*/, Response &res) {
  3118. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3119. })
  3120. .Get("/request-target",
  3121. [&](const Request &req, Response & /*res*/) {
  3122. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3123. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3124. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3125. })
  3126. .Get("/long-query-value",
  3127. [&](const Request &req, Response & /*res*/) {
  3128. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3129. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3130. })
  3131. .Get("/too-long-query-value",
  3132. [&](const Request &req, Response & /*res*/) {
  3133. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3134. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3135. })
  3136. .Get("/array-param",
  3137. [&](const Request &req, Response & /*res*/) {
  3138. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3139. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3140. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3141. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3142. })
  3143. .Post("/validate-no-multiple-headers",
  3144. [&](const Request &req, Response & /*res*/) {
  3145. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3146. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3147. })
  3148. .Post("/content_receiver",
  3149. [&](const Request &req, Response &res,
  3150. const ContentReader &content_reader) {
  3151. if (req.is_multipart_form_data()) {
  3152. std::vector<FormData> items;
  3153. content_reader(
  3154. [&](const FormData &file) {
  3155. items.push_back(file);
  3156. return true;
  3157. },
  3158. [&](const char *data, size_t data_length) {
  3159. items.back().content.append(data, data_length);
  3160. return true;
  3161. });
  3162. EXPECT_EQ(5u, items.size());
  3163. {
  3164. const auto &file = get_file_value(items, "text1");
  3165. EXPECT_TRUE(file.filename.empty());
  3166. EXPECT_EQ("text default", file.content);
  3167. }
  3168. {
  3169. const auto &file = get_file_value(items, "text2");
  3170. EXPECT_TRUE(file.filename.empty());
  3171. EXPECT_EQ("aωb", file.content);
  3172. }
  3173. {
  3174. const auto &file = get_file_value(items, "file1");
  3175. EXPECT_EQ("hello.txt", file.filename);
  3176. EXPECT_EQ("text/plain", file.content_type);
  3177. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3178. }
  3179. {
  3180. const auto &file = get_file_value(items, "file2");
  3181. EXPECT_EQ("world.json", file.filename);
  3182. EXPECT_EQ("application/json", file.content_type);
  3183. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3184. }
  3185. {
  3186. const auto &file = get_file_value(items, "file3");
  3187. EXPECT_TRUE(file.filename.empty());
  3188. EXPECT_EQ("application/octet-stream", file.content_type);
  3189. EXPECT_EQ(0u, file.content.size());
  3190. }
  3191. } else {
  3192. std::string body;
  3193. content_reader([&](const char *data, size_t data_length) {
  3194. EXPECT_EQ(7U, data_length);
  3195. body.append(data, data_length);
  3196. return true;
  3197. });
  3198. EXPECT_EQ(body, "content");
  3199. res.set_content(body, "text/plain");
  3200. }
  3201. })
  3202. .Put("/content_receiver",
  3203. [&](const Request & /*req*/, Response &res,
  3204. const ContentReader &content_reader) {
  3205. std::string body;
  3206. content_reader([&](const char *data, size_t data_length) {
  3207. body.append(data, data_length);
  3208. return true;
  3209. });
  3210. EXPECT_EQ(body, "content");
  3211. res.set_content(body, "text/plain");
  3212. })
  3213. .Patch("/content_receiver",
  3214. [&](const Request & /*req*/, Response &res,
  3215. const ContentReader &content_reader) {
  3216. std::string body;
  3217. content_reader([&](const char *data, size_t data_length) {
  3218. body.append(data, data_length);
  3219. return true;
  3220. });
  3221. EXPECT_EQ(body, "content");
  3222. res.set_content(body, "text/plain");
  3223. })
  3224. .Post("/query-string-and-body",
  3225. [&](const Request &req, Response & /*res*/) {
  3226. ASSERT_TRUE(req.has_param("key"));
  3227. EXPECT_EQ(req.get_param_value("key"), "value");
  3228. EXPECT_EQ(req.body, "content");
  3229. })
  3230. .Get("/last-request",
  3231. [&](const Request &req, Response & /*res*/) {
  3232. EXPECT_EQ("close", req.get_header_value("Connection"));
  3233. })
  3234. .Get(R"(/redirect/(\d+))",
  3235. [&](const Request &req, Response &res) {
  3236. auto num = std::stoi(req.matches[1]) + 1;
  3237. std::string url = "/redirect/" + std::to_string(num);
  3238. res.set_redirect(url);
  3239. })
  3240. .Post("/binary",
  3241. [&](const Request &req, Response &res) {
  3242. EXPECT_EQ(4U, req.body.size());
  3243. EXPECT_EQ("application/octet-stream",
  3244. req.get_header_value("Content-Type"));
  3245. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3246. res.set_content(req.body, "application/octet-stream");
  3247. })
  3248. .Put("/binary",
  3249. [&](const Request &req, Response &res) {
  3250. EXPECT_EQ(4U, req.body.size());
  3251. EXPECT_EQ("application/octet-stream",
  3252. req.get_header_value("Content-Type"));
  3253. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3254. res.set_content(req.body, "application/octet-stream");
  3255. })
  3256. .Patch("/binary",
  3257. [&](const Request &req, Response &res) {
  3258. EXPECT_EQ(4U, req.body.size());
  3259. EXPECT_EQ("application/octet-stream",
  3260. req.get_header_value("Content-Type"));
  3261. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3262. res.set_content(req.body, "application/octet-stream");
  3263. })
  3264. .Delete("/binary",
  3265. [&](const Request &req, Response &res) {
  3266. EXPECT_EQ(4U, req.body.size());
  3267. EXPECT_EQ("application/octet-stream",
  3268. req.get_header_value("Content-Type"));
  3269. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3270. res.set_content(req.body, "application/octet-stream");
  3271. })
  3272. .Get("/issue1772",
  3273. [&](const Request & /*req*/, Response &res) {
  3274. res.status = 401;
  3275. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3276. })
  3277. .Delete("/issue609",
  3278. [](const httplib::Request &, httplib::Response &res,
  3279. const httplib::ContentReader &) {
  3280. res.set_content("ok", "text/plain");
  3281. })
  3282. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3283. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3284. .Get("/compress",
  3285. [&](const Request & /*req*/, Response &res) {
  3286. res.set_content(
  3287. "12345678901234567890123456789012345678901234567890123456789"
  3288. "01234567890123456789012345678901234567890",
  3289. "text/plain");
  3290. })
  3291. .Get("/compress-with-charset",
  3292. [&](const Request & /*req*/, Response &res) {
  3293. res.set_content(
  3294. "12345678901234567890123456789012345678901234567890123456789"
  3295. "01234567890123456789012345678901234567890",
  3296. "application/json; charset=utf-8");
  3297. })
  3298. .Get("/nocompress",
  3299. [&](const Request & /*req*/, Response &res) {
  3300. res.set_content(
  3301. "12345678901234567890123456789012345678901234567890123456789"
  3302. "01234567890123456789012345678901234567890",
  3303. "application/octet-stream");
  3304. })
  3305. .Post("/compress-multipart",
  3306. [&](const Request &req, Response & /*res*/) {
  3307. EXPECT_EQ(2u, req.form.fields.size());
  3308. ASSERT_TRUE(!req.form.has_field("???"));
  3309. {
  3310. const auto &text = req.form.get_field("key1");
  3311. EXPECT_EQ("test", text);
  3312. }
  3313. {
  3314. const auto &text = req.form.get_field("key2");
  3315. EXPECT_EQ("--abcdefg123", text);
  3316. }
  3317. })
  3318. #endif
  3319. ;
  3320. persons_["john"] = "programmer";
  3321. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3322. svr_.wait_until_ready();
  3323. }
  3324. virtual void TearDown() {
  3325. svr_.stop();
  3326. if (!request_threads_.empty()) {
  3327. std::this_thread::sleep_for(std::chrono::seconds(1));
  3328. for (auto &t : request_threads_) {
  3329. t.join();
  3330. }
  3331. }
  3332. t_.join();
  3333. }
  3334. map<string, string> persons_;
  3335. #ifdef CPPHTTPLIB_SSL_ENABLED
  3336. SSLClient cli_;
  3337. SSLServer svr_;
  3338. #else
  3339. Client cli_;
  3340. Server svr_;
  3341. #endif
  3342. thread t_;
  3343. std::vector<thread> request_threads_;
  3344. };
  3345. TEST_F(ServerTest, GetMethod200) {
  3346. auto res = cli_.Get("/hi");
  3347. ASSERT_TRUE(res);
  3348. EXPECT_EQ("HTTP/1.1", res->version);
  3349. EXPECT_EQ(StatusCode::OK_200, res->status);
  3350. EXPECT_EQ("OK", res->reason);
  3351. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3352. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3353. EXPECT_EQ("Hello World!", res->body);
  3354. }
  3355. TEST_F(ServerTest, GetEmptyFile) {
  3356. auto res = cli_.Get("/empty_file");
  3357. ASSERT_TRUE(res);
  3358. EXPECT_EQ(StatusCode::OK_200, res->status);
  3359. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3360. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3361. EXPECT_EQ("", res->body);
  3362. }
  3363. TEST_F(ServerTest, GetFileContent) {
  3364. auto res = cli_.Get("/file_content");
  3365. ASSERT_TRUE(res);
  3366. EXPECT_EQ(StatusCode::OK_200, res->status);
  3367. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3368. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3369. EXPECT_EQ("test.html", res->body);
  3370. }
  3371. TEST_F(ServerTest, GetFileContentWithRange) {
  3372. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3373. ASSERT_TRUE(res);
  3374. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3375. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3376. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3377. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3378. EXPECT_EQ("est", res->body);
  3379. }
  3380. TEST_F(ServerTest, GetFileContentWithContentType) {
  3381. auto res = cli_.Get("/file_content_with_content_type");
  3382. ASSERT_TRUE(res);
  3383. EXPECT_EQ(StatusCode::OK_200, res->status);
  3384. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3385. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3386. EXPECT_EQ("file\n", res->body);
  3387. }
  3388. TEST_F(ServerTest, GetInvalidFileContent) {
  3389. auto res = cli_.Get("/invalid_file_content");
  3390. ASSERT_TRUE(res);
  3391. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3392. }
  3393. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3394. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3395. ASSERT_TRUE(res);
  3396. EXPECT_EQ("HTTP/1.1", res->version);
  3397. EXPECT_EQ(StatusCode::OK_200, res->status);
  3398. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3399. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3400. EXPECT_EQ("Hello World!", res->body);
  3401. }
  3402. TEST_F(ServerTest, GetMethod302) {
  3403. auto res = cli_.Get("/");
  3404. ASSERT_TRUE(res);
  3405. EXPECT_EQ(StatusCode::Found_302, res->status);
  3406. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3407. }
  3408. TEST_F(ServerTest, GetMethod302Redirect) {
  3409. cli_.set_follow_location(true);
  3410. auto res = cli_.Get("/");
  3411. ASSERT_TRUE(res);
  3412. EXPECT_EQ(StatusCode::OK_200, res->status);
  3413. EXPECT_EQ("Hello World!", res->body);
  3414. EXPECT_EQ("/hi", res->location);
  3415. }
  3416. TEST_F(ServerTest, GetMethod404) {
  3417. auto res = cli_.Get("/invalid");
  3418. ASSERT_TRUE(res);
  3419. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3420. }
  3421. TEST_F(ServerTest, HeadMethod200) {
  3422. auto res = cli_.Head("/hi");
  3423. ASSERT_TRUE(res);
  3424. EXPECT_EQ(StatusCode::OK_200, res->status);
  3425. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3426. EXPECT_TRUE(res->body.empty());
  3427. }
  3428. TEST_F(ServerTest, HeadMethod200Static) {
  3429. auto res = cli_.Head("/mount/dir/index.html");
  3430. ASSERT_TRUE(res);
  3431. EXPECT_EQ(StatusCode::OK_200, res->status);
  3432. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3433. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3434. EXPECT_TRUE(res->body.empty());
  3435. }
  3436. TEST_F(ServerTest, HeadMethod404) {
  3437. auto res = cli_.Head("/invalid");
  3438. ASSERT_TRUE(res);
  3439. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3440. EXPECT_TRUE(res->body.empty());
  3441. }
  3442. TEST_F(ServerTest, GetMethodPersonJohn) {
  3443. auto res = cli_.Get("/person/john");
  3444. ASSERT_TRUE(res);
  3445. EXPECT_EQ(StatusCode::OK_200, res->status);
  3446. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3447. EXPECT_EQ("programmer", res->body);
  3448. }
  3449. TEST_F(ServerTest, PostMethod1) {
  3450. auto res = cli_.Get("/person/john1");
  3451. ASSERT_TRUE(res);
  3452. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3453. res = cli_.Post("/person", "name=john1&note=coder",
  3454. "application/x-www-form-urlencoded");
  3455. ASSERT_TRUE(res);
  3456. ASSERT_EQ(StatusCode::OK_200, res->status);
  3457. res = cli_.Get("/person/john1");
  3458. ASSERT_TRUE(res);
  3459. ASSERT_EQ(StatusCode::OK_200, res->status);
  3460. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3461. ASSERT_EQ("coder", res->body);
  3462. }
  3463. TEST_F(ServerTest, PostMethod2) {
  3464. auto res = cli_.Get("/person/john2");
  3465. ASSERT_TRUE(res);
  3466. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3467. Params params;
  3468. params.emplace("name", "john2");
  3469. params.emplace("note", "coder");
  3470. res = cli_.Post("/person", params);
  3471. ASSERT_TRUE(res);
  3472. ASSERT_EQ(StatusCode::OK_200, res->status);
  3473. res = cli_.Get("/person/john2");
  3474. ASSERT_TRUE(res);
  3475. ASSERT_EQ(StatusCode::OK_200, res->status);
  3476. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3477. ASSERT_EQ("coder", res->body);
  3478. }
  3479. TEST_F(ServerTest, PutMethod3) {
  3480. auto res = cli_.Get("/person/john3");
  3481. ASSERT_TRUE(res);
  3482. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3483. Params params;
  3484. params.emplace("name", "john3");
  3485. params.emplace("note", "coder");
  3486. res = cli_.Put("/person", params);
  3487. ASSERT_TRUE(res);
  3488. ASSERT_EQ(StatusCode::OK_200, res->status);
  3489. res = cli_.Get("/person/john3");
  3490. ASSERT_TRUE(res);
  3491. ASSERT_EQ(StatusCode::OK_200, res->status);
  3492. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3493. ASSERT_EQ("coder", res->body);
  3494. }
  3495. TEST_F(ServerTest, DeleteMethod1) {
  3496. auto res = cli_.Get("/person/john4");
  3497. ASSERT_TRUE(res);
  3498. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3499. Params params;
  3500. params.emplace("name", "john4");
  3501. params.emplace("note", "coder");
  3502. res = cli_.Post("/person", params);
  3503. ASSERT_TRUE(res);
  3504. ASSERT_EQ(StatusCode::OK_200, res->status);
  3505. res = cli_.Get("/person/john4");
  3506. ASSERT_TRUE(res);
  3507. ASSERT_EQ(StatusCode::OK_200, res->status);
  3508. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3509. ASSERT_EQ("coder", res->body);
  3510. Params delete_params;
  3511. delete_params.emplace("name", "john4");
  3512. res = cli_.Delete("/person", delete_params);
  3513. ASSERT_TRUE(res);
  3514. ASSERT_EQ(StatusCode::OK_200, res->status);
  3515. ASSERT_EQ("DELETED", res->body);
  3516. res = cli_.Get("/person/john4");
  3517. ASSERT_TRUE(res);
  3518. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3519. }
  3520. TEST_F(ServerTest, DeleteMethod2) {
  3521. auto res = cli_.Get("/person/john5");
  3522. ASSERT_TRUE(res);
  3523. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3524. Params params;
  3525. params.emplace("name", "john5");
  3526. params.emplace("note", "developer");
  3527. res = cli_.Post("/person", params);
  3528. ASSERT_TRUE(res);
  3529. ASSERT_EQ(StatusCode::OK_200, res->status);
  3530. res = cli_.Get("/person/john5");
  3531. ASSERT_TRUE(res);
  3532. ASSERT_EQ(StatusCode::OK_200, res->status);
  3533. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3534. ASSERT_EQ("developer", res->body);
  3535. Params delete_params;
  3536. delete_params.emplace("name", "john5");
  3537. Headers headers;
  3538. headers.emplace("Custom-Header", "test-value");
  3539. res = cli_.Delete("/person", headers, delete_params);
  3540. ASSERT_TRUE(res);
  3541. ASSERT_EQ(StatusCode::OK_200, res->status);
  3542. ASSERT_EQ("DELETED", res->body);
  3543. res = cli_.Get("/person/john5");
  3544. ASSERT_TRUE(res);
  3545. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3546. }
  3547. TEST_F(ServerTest, DeleteMethod3) {
  3548. auto res = cli_.Get("/person/john6");
  3549. ASSERT_TRUE(res);
  3550. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3551. Params params;
  3552. params.emplace("name", "john6");
  3553. params.emplace("note", "tester");
  3554. res = cli_.Post("/person", params);
  3555. ASSERT_TRUE(res);
  3556. ASSERT_EQ(StatusCode::OK_200, res->status);
  3557. res = cli_.Get("/person/john6");
  3558. ASSERT_TRUE(res);
  3559. ASSERT_EQ(StatusCode::OK_200, res->status);
  3560. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3561. ASSERT_EQ("tester", res->body);
  3562. Params delete_params;
  3563. delete_params.emplace("name", "john6");
  3564. Headers headers;
  3565. headers.emplace("Custom-Header", "test-value");
  3566. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3567. ASSERT_TRUE(res);
  3568. ASSERT_EQ(StatusCode::OK_200, res->status);
  3569. ASSERT_EQ("DELETED", res->body);
  3570. res = cli_.Get("/person/john6");
  3571. ASSERT_TRUE(res);
  3572. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3573. }
  3574. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3575. Params params;
  3576. params.emplace("json", JSON_DATA);
  3577. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3578. ASSERT_TRUE(res);
  3579. ASSERT_EQ(StatusCode::OK_200, res->status);
  3580. ASSERT_EQ(JSON_DATA, res->body);
  3581. }
  3582. TEST_F(ServerTest, PostEmptyContent) {
  3583. auto res = cli_.Post("/empty", "", "text/plain");
  3584. ASSERT_TRUE(res);
  3585. ASSERT_EQ(StatusCode::OK_200, res->status);
  3586. ASSERT_EQ("empty", res->body);
  3587. }
  3588. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3589. auto res = cli_.Post("/empty-no-content-type");
  3590. ASSERT_TRUE(res);
  3591. ASSERT_EQ(StatusCode::OK_200, res->status);
  3592. ASSERT_EQ("empty-no-content-type", res->body);
  3593. }
  3594. TEST_F(ServerTest, PostPathOnly) {
  3595. auto res = cli_.Post("/path-only");
  3596. ASSERT_TRUE(res);
  3597. ASSERT_EQ(StatusCode::OK_200, res->status);
  3598. ASSERT_EQ("path-only", res->body);
  3599. }
  3600. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3601. auto res = cli_.Post("/path-headers-only",
  3602. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3603. ASSERT_TRUE(res);
  3604. ASSERT_EQ(StatusCode::OK_200, res->status);
  3605. ASSERT_EQ("path-headers-only", res->body);
  3606. }
  3607. TEST_F(ServerTest, PostLarge) {
  3608. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3609. ASSERT_TRUE(res);
  3610. ASSERT_EQ(StatusCode::OK_200, res->status);
  3611. EXPECT_EQ(LARGE_DATA, res->body);
  3612. }
  3613. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3614. auto res = cli_.Put("/empty-no-content-type");
  3615. ASSERT_TRUE(res);
  3616. ASSERT_EQ(StatusCode::OK_200, res->status);
  3617. ASSERT_EQ("empty-no-content-type", res->body);
  3618. }
  3619. TEST_F(ServerTest, GetMethodDir) {
  3620. auto res = cli_.Get("/dir/");
  3621. ASSERT_TRUE(res);
  3622. EXPECT_EQ(StatusCode::OK_200, res->status);
  3623. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3624. auto body = R"(<html>
  3625. <head>
  3626. </head>
  3627. <body>
  3628. <a href="/dir/test.html">Test</a>
  3629. <a href="/hi">hi</a>
  3630. </body>
  3631. </html>
  3632. )";
  3633. EXPECT_EQ(body, res->body);
  3634. }
  3635. TEST_F(ServerTest, GetMethodDirTest) {
  3636. auto res = cli_.Get("/dir/test.html");
  3637. ASSERT_TRUE(res);
  3638. EXPECT_EQ(StatusCode::OK_200, res->status);
  3639. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3640. EXPECT_EQ("test.html", res->body);
  3641. }
  3642. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3643. auto res = cli_.Get("/dir/../dir/test.html");
  3644. ASSERT_TRUE(res);
  3645. EXPECT_EQ(StatusCode::OK_200, res->status);
  3646. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3647. EXPECT_EQ("test.html", res->body);
  3648. }
  3649. TEST_F(ServerTest, GetMethodInvalidPath) {
  3650. auto res = cli_.Get("/dir/../test.html");
  3651. ASSERT_TRUE(res);
  3652. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3653. }
  3654. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3655. auto res = cli_.Get("/../www/dir/test.html");
  3656. ASSERT_TRUE(res);
  3657. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3658. }
  3659. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3660. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3661. ASSERT_TRUE(res);
  3662. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3663. }
  3664. TEST_F(ServerTest, GetMethodDirMountTest) {
  3665. auto res = cli_.Get("/mount/dir/test.html");
  3666. ASSERT_TRUE(res);
  3667. EXPECT_EQ(StatusCode::OK_200, res->status);
  3668. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3669. EXPECT_EQ("test.html", res->body);
  3670. }
  3671. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3672. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3673. ASSERT_TRUE(res);
  3674. EXPECT_EQ(StatusCode::OK_200, res->status);
  3675. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3676. EXPECT_EQ("test.html", res->body);
  3677. }
  3678. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3679. auto res = cli_.Get("/mount/dir/../test.html");
  3680. ASSERT_TRUE(res);
  3681. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3682. }
  3683. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3684. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3685. ASSERT_TRUE(res);
  3686. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3687. }
  3688. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3689. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3690. ASSERT_TRUE(res);
  3691. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3692. }
  3693. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3694. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3695. ASSERT_TRUE(res);
  3696. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3697. }
  3698. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3699. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3700. ASSERT_TRUE(res);
  3701. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3702. }
  3703. TEST_F(ServerTest, PostMethod303) {
  3704. auto res = cli_.Post("/1", "body", "text/plain");
  3705. ASSERT_TRUE(res);
  3706. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3707. EXPECT_EQ("/2", res->get_header_value("Location"));
  3708. }
  3709. TEST_F(ServerTest, PostMethod303Redirect) {
  3710. cli_.set_follow_location(true);
  3711. auto res = cli_.Post("/1", "body", "text/plain");
  3712. ASSERT_TRUE(res);
  3713. EXPECT_EQ(StatusCode::OK_200, res->status);
  3714. EXPECT_EQ("redirected.", res->body);
  3715. EXPECT_EQ("/2", res->location);
  3716. }
  3717. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3718. auto res = cli_.Get("/dir/test.abcde");
  3719. ASSERT_TRUE(res);
  3720. EXPECT_EQ(StatusCode::OK_200, res->status);
  3721. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3722. EXPECT_EQ("abcde", res->body);
  3723. }
  3724. TEST_F(ServerTest, StaticFileRange) {
  3725. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3726. ASSERT_TRUE(res);
  3727. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3728. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3729. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3730. EXPECT_EQ(true, res->has_header("Content-Range"));
  3731. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3732. EXPECT_EQ(std::string("cd"), res->body);
  3733. }
  3734. TEST_F(ServerTest, StaticFileRanges) {
  3735. auto res =
  3736. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3737. ASSERT_TRUE(res);
  3738. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3739. EXPECT_TRUE(
  3740. res->get_header_value("Content-Type")
  3741. .find(
  3742. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3743. 0);
  3744. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3745. }
  3746. TEST_F(ServerTest, StaticFileRangeHead) {
  3747. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3748. ASSERT_TRUE(res);
  3749. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3750. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3751. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3752. EXPECT_EQ(true, res->has_header("Content-Range"));
  3753. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3754. }
  3755. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3756. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3757. ASSERT_TRUE(res);
  3758. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3759. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3760. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3761. EXPECT_EQ(true, res->has_header("Content-Range"));
  3762. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3763. res->get_header_value("Content-Range"));
  3764. EXPECT_EQ("LAST\n", res->body);
  3765. }
  3766. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3767. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3768. ASSERT_TRUE(res);
  3769. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3770. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3771. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3772. EXPECT_EQ(true, res->has_header("Content-Range"));
  3773. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3774. }
  3775. TEST_F(ServerTest, StaticFileBigFile) {
  3776. auto res = cli_.Get("/dir/1MB.txt");
  3777. ASSERT_TRUE(res);
  3778. EXPECT_EQ(StatusCode::OK_200, res->status);
  3779. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3780. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3781. }
  3782. TEST_F(ServerTest, InvalidBaseDirMount) {
  3783. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3784. }
  3785. TEST_F(ServerTest, Binary) {
  3786. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3787. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3788. "application/octet-stream");
  3789. ASSERT_TRUE(res);
  3790. ASSERT_EQ(StatusCode::OK_200, res->status);
  3791. ASSERT_EQ(4U, res->body.size());
  3792. res = cli_.Put("/binary", binary.data(), binary.size(),
  3793. "application/octet-stream");
  3794. ASSERT_TRUE(res);
  3795. ASSERT_EQ(StatusCode::OK_200, res->status);
  3796. ASSERT_EQ(4U, res->body.size());
  3797. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3798. "application/octet-stream");
  3799. ASSERT_TRUE(res);
  3800. ASSERT_EQ(StatusCode::OK_200, res->status);
  3801. ASSERT_EQ(4U, res->body.size());
  3802. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3803. "application/octet-stream");
  3804. ASSERT_TRUE(res);
  3805. ASSERT_EQ(StatusCode::OK_200, res->status);
  3806. ASSERT_EQ(4U, res->body.size());
  3807. }
  3808. TEST_F(ServerTest, BinaryString) {
  3809. auto binary = std::string("\x00\x01\x02\x03", 4);
  3810. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3811. ASSERT_TRUE(res);
  3812. ASSERT_EQ(StatusCode::OK_200, res->status);
  3813. ASSERT_EQ(4U, res->body.size());
  3814. res = cli_.Put("/binary", binary, "application/octet-stream");
  3815. ASSERT_TRUE(res);
  3816. ASSERT_EQ(StatusCode::OK_200, res->status);
  3817. ASSERT_EQ(4U, res->body.size());
  3818. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3819. ASSERT_TRUE(res);
  3820. ASSERT_EQ(StatusCode::OK_200, res->status);
  3821. ASSERT_EQ(4U, res->body.size());
  3822. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3823. ASSERT_TRUE(res);
  3824. ASSERT_EQ(StatusCode::OK_200, res->status);
  3825. ASSERT_EQ(4U, res->body.size());
  3826. }
  3827. TEST_F(ServerTest, EmptyRequest) {
  3828. auto res = cli_.Get("");
  3829. ASSERT_TRUE(!res);
  3830. EXPECT_EQ(Error::Connection, res.error());
  3831. }
  3832. TEST_F(ServerTest, LongRequest) {
  3833. std::string request;
  3834. for (size_t i = 0; i < 545; i++) {
  3835. request += "/TooLongRequest";
  3836. }
  3837. request += "OK";
  3838. auto res = cli_.Get(request.c_str());
  3839. ASSERT_TRUE(res);
  3840. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3841. }
  3842. TEST_F(ServerTest, TooLongRequest) {
  3843. std::string request;
  3844. for (size_t i = 0; i < 546; i++) {
  3845. request += "/TooLongRequest";
  3846. }
  3847. request += "_NG";
  3848. auto start = std::chrono::high_resolution_clock::now();
  3849. cli_.set_keep_alive(true);
  3850. auto res = cli_.Get(request.c_str());
  3851. auto end = std::chrono::high_resolution_clock::now();
  3852. auto elapsed =
  3853. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3854. .count();
  3855. ASSERT_TRUE(res);
  3856. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3857. EXPECT_LE(elapsed, 1000);
  3858. EXPECT_EQ("close", res->get_header_value("Connection"));
  3859. EXPECT_FALSE(cli_.is_socket_open());
  3860. }
  3861. TEST_F(ServerTest, AlmostTooLongRequest) {
  3862. // test for #2046 - URI length check shouldn't include other content on req
  3863. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3864. // leading /, space, HTTP/1.1)
  3865. std::string request =
  3866. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3867. auto res = cli_.Get(request.c_str());
  3868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3869. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3870. }
  3871. TEST_F(ServerTest, LongHeader) {
  3872. Request req;
  3873. req.method = "GET";
  3874. req.path = "/hi";
  3875. std::string host_and_port;
  3876. host_and_port += HOST;
  3877. host_and_port += ":";
  3878. host_and_port += std::to_string(PORT);
  3879. req.headers.emplace("Host", host_and_port.c_str());
  3880. req.headers.emplace("Accept", "*/*");
  3881. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3882. req.headers.emplace(
  3883. "Header-Name",
  3884. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3885. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3886. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3887. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3888. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3889. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3890. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3891. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3892. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3893. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3894. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3895. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3896. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3897. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3898. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3899. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3900. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3901. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3902. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3903. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3904. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3905. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3906. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3907. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3908. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3909. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3910. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3911. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3912. "@@@@@@@@@@@@@@@@");
  3913. auto res = std::make_shared<Response>();
  3914. auto error = Error::Success;
  3915. auto ret = cli_.send(req, *res, error);
  3916. ASSERT_TRUE(ret);
  3917. EXPECT_EQ(StatusCode::OK_200, res->status);
  3918. }
  3919. TEST_F(ServerTest, LongQueryValue) {
  3920. auto start = std::chrono::high_resolution_clock::now();
  3921. cli_.set_keep_alive(true);
  3922. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3923. auto end = std::chrono::high_resolution_clock::now();
  3924. auto elapsed =
  3925. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3926. .count();
  3927. ASSERT_TRUE(res);
  3928. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3929. EXPECT_LE(elapsed, 1000);
  3930. EXPECT_EQ("close", res->get_header_value("Connection"));
  3931. EXPECT_FALSE(cli_.is_socket_open());
  3932. }
  3933. TEST_F(ServerTest, TooLongQueryValue) {
  3934. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3935. ASSERT_FALSE(res);
  3936. EXPECT_EQ(Error::Read, res.error());
  3937. }
  3938. TEST_F(ServerTest, TooLongHeader) {
  3939. Request req;
  3940. req.method = "GET";
  3941. req.path = "/hi";
  3942. std::string host_and_port;
  3943. host_and_port += HOST;
  3944. host_and_port += ":";
  3945. host_and_port += std::to_string(PORT);
  3946. req.headers.emplace("Host", host_and_port.c_str());
  3947. req.headers.emplace("Accept", "*/*");
  3948. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3949. req.headers.emplace(
  3950. "Header-Name",
  3951. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3952. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3953. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3954. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3955. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3956. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3957. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3958. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3959. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3960. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3961. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3962. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3963. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3964. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3965. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3966. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3967. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3968. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3969. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3970. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3971. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3972. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3973. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3974. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3975. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3976. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3977. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3978. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3979. "@@@@@@@@@@@@@@@@@");
  3980. auto res = std::make_shared<Response>();
  3981. auto error = Error::Success;
  3982. auto ret = cli_.send(req, *res, error);
  3983. ASSERT_TRUE(ret);
  3984. EXPECT_EQ(StatusCode::OK_200, res->status);
  3985. }
  3986. TEST_F(ServerTest, HeaderCountAtLimit) {
  3987. // Test with headers just under the 100 limit
  3988. httplib::Headers headers;
  3989. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3990. // This should keep us just under the 100 header limit
  3991. for (int i = 0; i < 95; i++) {
  3992. std::string name = "X-Test-Header-" + std::to_string(i);
  3993. std::string value = "value" + std::to_string(i);
  3994. headers.emplace(name, value);
  3995. }
  3996. // This should work fine as we're under the limit
  3997. auto res = cli_.Get("/hi", headers);
  3998. EXPECT_TRUE(res);
  3999. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4000. }
  4001. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4002. // Test with many headers to exceed the 100 limit
  4003. httplib::Headers headers;
  4004. // Add 150 headers to definitely exceed the 100 limit
  4005. for (int i = 0; i < 150; i++) {
  4006. std::string name = "X-Test-Header-" + std::to_string(i);
  4007. std::string value = "value" + std::to_string(i);
  4008. headers.emplace(name, value);
  4009. }
  4010. // This should fail due to exceeding header count limit
  4011. cli_.set_keep_alive(true);
  4012. auto res = cli_.Get("/hi", headers);
  4013. // The server should respond with 400 Bad Request
  4014. ASSERT_TRUE(res);
  4015. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4016. EXPECT_EQ("close", res->get_header_value("Connection"));
  4017. EXPECT_FALSE(cli_.is_socket_open());
  4018. }
  4019. TEST_F(ServerTest, PercentEncoding) {
  4020. auto res = cli_.Get("/e%6edwith%");
  4021. ASSERT_TRUE(res);
  4022. EXPECT_EQ(StatusCode::OK_200, res->status);
  4023. }
  4024. TEST_F(ServerTest, PercentEncodingUnicode) {
  4025. auto res = cli_.Get("/e%u006edwith%");
  4026. ASSERT_TRUE(res);
  4027. EXPECT_EQ(StatusCode::OK_200, res->status);
  4028. }
  4029. TEST_F(ServerTest, InvalidPercentEncoding) {
  4030. auto res = cli_.Get("/%endwith%");
  4031. ASSERT_TRUE(res);
  4032. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4033. }
  4034. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4035. auto res = cli_.Get("/%uendwith%");
  4036. ASSERT_TRUE(res);
  4037. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4038. }
  4039. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4040. auto res = cli_.Get("/hello?aaa=bbb%");
  4041. ASSERT_TRUE(res);
  4042. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4043. }
  4044. TEST_F(ServerTest, PlusSignEncoding) {
  4045. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4046. ASSERT_TRUE(res);
  4047. EXPECT_EQ(StatusCode::OK_200, res->status);
  4048. EXPECT_EQ("a +b", res->body);
  4049. }
  4050. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4051. // This test simulates a potential DoS attack using many headers
  4052. // to verify our security fix prevents memory exhaustion
  4053. httplib::Headers attack_headers;
  4054. // Attempt to add many headers like an attacker would (200 headers to far
  4055. // exceed limit)
  4056. for (int i = 0; i < 200; i++) {
  4057. std::string name = "X-Attack-Header-" + std::to_string(i);
  4058. std::string value = "attack_payload_" + std::to_string(i);
  4059. attack_headers.emplace(name, value);
  4060. }
  4061. // Try to POST with excessive headers
  4062. cli_.set_keep_alive(true);
  4063. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4064. // Should either fail or return 400 Bad Request due to security limit
  4065. if (res) {
  4066. // If we get a response, it should be 400 Bad Request
  4067. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4068. EXPECT_EQ("close", res->get_header_value("Connection"));
  4069. }
  4070. EXPECT_FALSE(cli_.is_socket_open());
  4071. }
  4072. TEST_F(ServerTest, MultipartFormData) {
  4073. UploadFormDataItems items = {
  4074. {"text1", "text default", "", ""},
  4075. {"text2", "aωb", "", ""},
  4076. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4077. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4078. {"file3", "", "", "application/octet-stream"},
  4079. {"file4", "", "", " application/json tmp-string "}};
  4080. auto res = cli_.Post("/multipart", items);
  4081. ASSERT_TRUE(res);
  4082. EXPECT_EQ(StatusCode::OK_200, res->status);
  4083. }
  4084. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4085. UploadFormDataItems items = {
  4086. {"text", "default text", "", ""},
  4087. {"multi_text1", "aaaaa", "", ""},
  4088. {"multi_text1", "bbbbb", "", ""},
  4089. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4090. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4091. "application/json"},
  4092. };
  4093. auto res = cli_.Post("/multipart/multi_file_values", items);
  4094. ASSERT_TRUE(res);
  4095. EXPECT_EQ(StatusCode::OK_200, res->status);
  4096. }
  4097. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4098. auto res = cli_.Get("/hi");
  4099. ASSERT_TRUE(res);
  4100. EXPECT_EQ(StatusCode::OK_200, res->status);
  4101. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4102. EXPECT_EQ("Hello World!", res->body);
  4103. }
  4104. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4105. Request req;
  4106. req.method = "POST";
  4107. req.path = "/chunked";
  4108. std::string host_and_port;
  4109. host_and_port += HOST;
  4110. host_and_port += ":";
  4111. host_and_port += std::to_string(PORT);
  4112. req.headers.emplace("Host", host_and_port.c_str());
  4113. req.headers.emplace("Accept", "*/*");
  4114. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4115. req.headers.emplace("Content-Type", "text/plain");
  4116. req.headers.emplace("Content-Length", "0");
  4117. req.headers.emplace(
  4118. "Transfer-Encoding",
  4119. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4120. // Client does not chunk, so make a chunked body manually.
  4121. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4122. auto res = std::make_shared<Response>();
  4123. auto error = Error::Success;
  4124. auto ret = cli_.send(req, *res, error);
  4125. ASSERT_TRUE(ret);
  4126. EXPECT_EQ(StatusCode::OK_200, res->status);
  4127. }
  4128. TEST_F(ServerTest, GetStreamed2) {
  4129. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4130. ASSERT_TRUE(res);
  4131. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4132. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4133. EXPECT_EQ(true, res->has_header("Content-Range"));
  4134. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4135. EXPECT_EQ(std::string("ab"), res->body);
  4136. }
  4137. TEST_F(ServerTest, GetStreamed) {
  4138. auto res = cli_.Get("/streamed");
  4139. ASSERT_TRUE(res);
  4140. EXPECT_EQ(StatusCode::OK_200, res->status);
  4141. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4142. EXPECT_EQ(std::string("aaabbb"), res->body);
  4143. }
  4144. TEST_F(ServerTest, GetStreamedWithRange1) {
  4145. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4146. ASSERT_TRUE(res);
  4147. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4148. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4149. EXPECT_EQ(true, res->has_header("Content-Range"));
  4150. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4151. EXPECT_EQ(std::string("def"), res->body);
  4152. }
  4153. TEST_F(ServerTest, GetStreamedWithRange2) {
  4154. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4155. ASSERT_TRUE(res);
  4156. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4157. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4158. EXPECT_EQ(true, res->has_header("Content-Range"));
  4159. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4160. EXPECT_EQ(std::string("bcdefg"), res->body);
  4161. }
  4162. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4163. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4164. ASSERT_TRUE(res);
  4165. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4166. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4167. EXPECT_EQ(true, res->has_header("Content-Range"));
  4168. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4169. EXPECT_EQ(std::string("efg"), res->body);
  4170. }
  4171. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4172. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4173. ASSERT_TRUE(res);
  4174. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4175. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4176. EXPECT_EQ(false, res->has_header("Content-Range"));
  4177. EXPECT_EQ(0U, res->body.size());
  4178. }
  4179. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4180. auto res = cli_.Get("/streamed-with-range",
  4181. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4182. "92233720368547758079223372036854775807"}});
  4183. ASSERT_TRUE(res);
  4184. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4185. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4186. EXPECT_EQ(false, res->has_header("Content-Range"));
  4187. EXPECT_EQ(0U, res->body.size());
  4188. }
  4189. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4190. auto res = cli_.Get(
  4191. "/with-range",
  4192. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4193. {"Accept-Encoding", ""}});
  4194. ASSERT_TRUE(res);
  4195. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4196. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4197. EXPECT_EQ(true, res->has_header("Content-Range"));
  4198. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4199. EXPECT_EQ(std::string("abcdefg"), res->body);
  4200. }
  4201. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4202. auto res = cli_.Get("/with-range", {
  4203. {"Range", "bytes=0-"},
  4204. {"Accept-Encoding", ""},
  4205. });
  4206. ASSERT_TRUE(res);
  4207. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4208. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4209. EXPECT_EQ(true, res->has_header("Content-Range"));
  4210. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4211. EXPECT_EQ(std::string("abcdefg"), res->body);
  4212. }
  4213. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4214. auto res =
  4215. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4216. ASSERT_TRUE(res);
  4217. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4218. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4219. EXPECT_EQ(false, res->has_header("Content-Range"));
  4220. EXPECT_EQ(267U, res->body.size());
  4221. // Check that both range contents are present
  4222. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4223. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4224. // Check that Content-Range headers are present for both ranges
  4225. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4226. std::string::npos);
  4227. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4228. std::string::npos);
  4229. }
  4230. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4231. Ranges ranges;
  4232. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4233. ranges.emplace_back(0, -1);
  4234. }
  4235. auto res =
  4236. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4237. ASSERT_TRUE(res);
  4238. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4239. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4240. EXPECT_EQ(false, res->has_header("Content-Range"));
  4241. EXPECT_EQ(0U, res->body.size());
  4242. }
  4243. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4244. auto res =
  4245. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4246. ASSERT_TRUE(res);
  4247. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4248. EXPECT_EQ(5U, res->body.size());
  4249. // Check that overlapping ranges are coalesced into a single range
  4250. EXPECT_EQ("bcdef", res->body);
  4251. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4252. // Should be single range, not multipart
  4253. EXPECT_TRUE(res->has_header("Content-Range"));
  4254. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4255. }
  4256. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4257. auto res =
  4258. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4259. ASSERT_TRUE(res);
  4260. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4261. EXPECT_EQ(268U, res->body.size());
  4262. // Check that both range contents are present
  4263. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4264. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4265. // Check that Content-Range headers are present for both ranges
  4266. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4267. std::string::npos);
  4268. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4269. std::string::npos);
  4270. }
  4271. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4272. auto res =
  4273. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4274. ASSERT_TRUE(res);
  4275. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4276. EXPECT_EQ(269U, res->body.size());
  4277. // Check that both duplicate range contents are present
  4278. size_t first_abc = res->body.find("abc\r\n");
  4279. EXPECT_TRUE(first_abc != std::string::npos);
  4280. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4281. EXPECT_TRUE(second_abc != std::string::npos);
  4282. // Check that Content-Range headers are present for both ranges
  4283. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4284. EXPECT_TRUE(first_range != std::string::npos);
  4285. size_t second_range =
  4286. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4287. EXPECT_TRUE(second_range != std::string::npos);
  4288. }
  4289. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4290. auto res = cli_.Get("/streamed-with-range?error",
  4291. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4292. ASSERT_TRUE(res);
  4293. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4294. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4295. EXPECT_EQ(false, res->has_header("Content-Range"));
  4296. EXPECT_EQ(0U, res->body.size());
  4297. }
  4298. TEST_F(ServerTest, GetStreamedEndless) {
  4299. uint64_t offset = 0;
  4300. auto res = cli_.Get("/streamed-cancel",
  4301. [&](const char * /*data*/, uint64_t data_length) {
  4302. if (offset < 100) {
  4303. offset += data_length;
  4304. return true;
  4305. }
  4306. return false;
  4307. });
  4308. ASSERT_TRUE(!res);
  4309. EXPECT_EQ(Error::Canceled, res.error());
  4310. }
  4311. TEST_F(ServerTest, ClientStop) {
  4312. std::atomic_size_t count{4};
  4313. std::vector<std::thread> threads;
  4314. for (auto i = count.load(); i != 0; --i) {
  4315. threads.emplace_back([&]() {
  4316. auto res = cli_.Get("/streamed-cancel",
  4317. [&](const char *, uint64_t) { return true; });
  4318. --count;
  4319. ASSERT_TRUE(!res);
  4320. EXPECT_TRUE(res.error() == Error::Canceled ||
  4321. res.error() == Error::Read || res.error() == Error::Write);
  4322. });
  4323. }
  4324. std::this_thread::sleep_for(std::chrono::seconds(2));
  4325. while (count != 0) {
  4326. cli_.stop();
  4327. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4328. }
  4329. for (auto &t : threads) {
  4330. t.join();
  4331. }
  4332. }
  4333. TEST_F(ServerTest, GetWithRange1) {
  4334. auto res = cli_.Get("/with-range", {
  4335. make_range_header({{3, 5}}),
  4336. {"Accept-Encoding", ""},
  4337. });
  4338. ASSERT_TRUE(res);
  4339. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4340. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4341. EXPECT_EQ(true, res->has_header("Content-Range"));
  4342. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4343. EXPECT_EQ(std::string("def"), res->body);
  4344. }
  4345. TEST_F(ServerTest, GetWithRange2) {
  4346. auto res = cli_.Get("/with-range", {
  4347. make_range_header({{1, -1}}),
  4348. {"Accept-Encoding", ""},
  4349. });
  4350. ASSERT_TRUE(res);
  4351. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4352. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4353. EXPECT_EQ(true, res->has_header("Content-Range"));
  4354. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4355. EXPECT_EQ(std::string("bcdefg"), res->body);
  4356. }
  4357. TEST_F(ServerTest, GetWithRange3) {
  4358. auto res = cli_.Get("/with-range", {
  4359. make_range_header({{0, 0}}),
  4360. {"Accept-Encoding", ""},
  4361. });
  4362. ASSERT_TRUE(res);
  4363. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4364. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4365. EXPECT_EQ(true, res->has_header("Content-Range"));
  4366. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4367. EXPECT_EQ(std::string("a"), res->body);
  4368. }
  4369. TEST_F(ServerTest, GetWithRange4) {
  4370. auto res = cli_.Get("/with-range", {
  4371. make_range_header({{-1, 2}}),
  4372. {"Accept-Encoding", ""},
  4373. });
  4374. ASSERT_TRUE(res);
  4375. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4376. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4377. EXPECT_EQ(true, res->has_header("Content-Range"));
  4378. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4379. EXPECT_EQ(std::string("fg"), res->body);
  4380. }
  4381. TEST_F(ServerTest, GetWithRange5) {
  4382. auto res = cli_.Get("/with-range", {
  4383. make_range_header({{0, 5}}),
  4384. {"Accept-Encoding", ""},
  4385. });
  4386. ASSERT_TRUE(res);
  4387. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4388. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4389. EXPECT_EQ(true, res->has_header("Content-Range"));
  4390. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4391. EXPECT_EQ(std::string("abcdef"), res->body);
  4392. }
  4393. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4394. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4395. ASSERT_TRUE(res);
  4396. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4397. }
  4398. TEST_F(ServerTest, GetWithRangeMultipart) {
  4399. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4400. ASSERT_TRUE(res);
  4401. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4402. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4403. EXPECT_EQ(false, res->has_header("Content-Range"));
  4404. EXPECT_EQ(267U, res->body.size());
  4405. }
  4406. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4407. auto res =
  4408. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4409. ASSERT_TRUE(res);
  4410. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4411. }
  4412. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4413. auto res = cli_.Get("/with-range-customized-response",
  4414. {{make_range_header({{1, 2}})}});
  4415. ASSERT_TRUE(res);
  4416. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4417. EXPECT_EQ(true, res->has_header("Content-Length"));
  4418. EXPECT_EQ(false, res->has_header("Content-Range"));
  4419. EXPECT_EQ(JSON_DATA, res->body);
  4420. }
  4421. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4422. auto res = cli_.Get("/with-range-customized-response",
  4423. {{make_range_header({{1, 2}, {4, 5}})}});
  4424. ASSERT_TRUE(res);
  4425. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4426. EXPECT_EQ(true, res->has_header("Content-Length"));
  4427. EXPECT_EQ(false, res->has_header("Content-Range"));
  4428. EXPECT_EQ(JSON_DATA, res->body);
  4429. }
  4430. TEST_F(ServerTest, Issue1772) {
  4431. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4432. ASSERT_TRUE(res);
  4433. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4434. }
  4435. TEST_F(ServerTest, Issue609) {
  4436. auto res = cli_.Delete("/issue609");
  4437. ASSERT_TRUE(res);
  4438. EXPECT_EQ(StatusCode::OK_200, res->status);
  4439. EXPECT_EQ(std::string("ok"), res->body);
  4440. }
  4441. TEST_F(ServerTest, GetStreamedChunked) {
  4442. auto res = cli_.Get("/streamed-chunked");
  4443. ASSERT_TRUE(res);
  4444. EXPECT_EQ(StatusCode::OK_200, res->status);
  4445. EXPECT_EQ(std::string("123456789"), res->body);
  4446. }
  4447. TEST_F(ServerTest, GetStreamedChunked2) {
  4448. auto res = cli_.Get("/streamed-chunked2");
  4449. ASSERT_TRUE(res);
  4450. EXPECT_EQ(StatusCode::OK_200, res->status);
  4451. EXPECT_EQ(std::string("123456789"), res->body);
  4452. }
  4453. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4454. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4455. ASSERT_TRUE(res);
  4456. EXPECT_EQ(StatusCode::OK_200, res->status);
  4457. EXPECT_EQ(std::string("123456789"), res->body);
  4458. EXPECT_TRUE(res->has_header("Trailer"));
  4459. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4460. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4461. // Trailers are now stored separately from headers (security fix)
  4462. EXPECT_EQ(2U, res->trailers.size());
  4463. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4464. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4465. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4466. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4467. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4468. // Verify trailers are NOT in headers (security verification)
  4469. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4470. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4471. }
  4472. TEST_F(ServerTest, LargeChunkedPost) {
  4473. Request req;
  4474. req.method = "POST";
  4475. req.path = "/large-chunked";
  4476. std::string host_and_port;
  4477. host_and_port += HOST;
  4478. host_and_port += ":";
  4479. host_and_port += std::to_string(PORT);
  4480. req.headers.emplace("Host", host_and_port.c_str());
  4481. req.headers.emplace("Accept", "*/*");
  4482. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4483. req.headers.emplace("Content-Type", "text/plain");
  4484. req.headers.emplace("Content-Length", "0");
  4485. req.headers.emplace("Transfer-Encoding", "chunked");
  4486. std::string long_string(30 * 1024u, 'a');
  4487. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4488. // Attempt to make a large enough post to exceed OS buffers, to test that
  4489. // the server handles short reads if the full chunk data isn't available.
  4490. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4491. auto res = std::make_shared<Response>();
  4492. auto error = Error::Success;
  4493. auto ret = cli_.send(req, *res, error);
  4494. ASSERT_TRUE(ret);
  4495. EXPECT_EQ(StatusCode::OK_200, res->status);
  4496. }
  4497. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4498. auto res = cli_.Get("/remote_addr");
  4499. ASSERT_TRUE(res);
  4500. EXPECT_EQ(StatusCode::OK_200, res->status);
  4501. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4502. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4503. }
  4504. TEST_F(ServerTest, GetMethodLocalAddr) {
  4505. auto res = cli_.Get("/local_addr");
  4506. ASSERT_TRUE(res);
  4507. EXPECT_EQ(StatusCode::OK_200, res->status);
  4508. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4509. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4510. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4511. }
  4512. TEST_F(ServerTest, HTTPResponseSplitting) {
  4513. auto res = cli_.Get("/http_response_splitting");
  4514. ASSERT_TRUE(res);
  4515. EXPECT_EQ(StatusCode::OK_200, res->status);
  4516. }
  4517. TEST_F(ServerTest, SlowRequest) {
  4518. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4519. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4520. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4521. }
  4522. #if 0
  4523. TEST_F(ServerTest, SlowPost) {
  4524. char buffer[64 * 1024];
  4525. memset(buffer, 0x42, sizeof(buffer));
  4526. auto res = cli_.Post(
  4527. "/slowpost", 64 * 1024 * 1024,
  4528. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4529. auto ret = sink.write(buffer, sizeof(buffer));
  4530. EXPECT_TRUE(ret);
  4531. return true;
  4532. },
  4533. "text/plain");
  4534. ASSERT_TRUE(res);
  4535. EXPECT_EQ(StatusCode::OK_200, res->status);
  4536. }
  4537. TEST_F(ServerTest, SlowPostFail) {
  4538. char buffer[64 * 1024];
  4539. memset(buffer, 0x42, sizeof(buffer));
  4540. cli_.set_write_timeout(std::chrono::seconds(0));
  4541. auto res = cli_.Post(
  4542. "/slowpost", 64 * 1024 * 1024,
  4543. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4544. sink.write(buffer, sizeof(buffer));
  4545. return true;
  4546. },
  4547. "text/plain");
  4548. ASSERT_TRUE(!res);
  4549. EXPECT_EQ(Error::Write, res.error());
  4550. }
  4551. #endif
  4552. TEST_F(ServerTest, Put) {
  4553. auto res = cli_.Put("/put", "PUT", "text/plain");
  4554. ASSERT_TRUE(res);
  4555. EXPECT_EQ(StatusCode::OK_200, res->status);
  4556. EXPECT_EQ("PUT", res->body);
  4557. }
  4558. TEST_F(ServerTest, PutWithContentProvider) {
  4559. auto res = cli_.Put(
  4560. "/put", 3,
  4561. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4562. sink.os << "PUT";
  4563. return true;
  4564. },
  4565. "text/plain");
  4566. ASSERT_TRUE(res);
  4567. EXPECT_EQ(StatusCode::OK_200, res->status);
  4568. EXPECT_EQ("PUT", res->body);
  4569. }
  4570. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4571. auto res = cli_.Post(
  4572. "/post", 42,
  4573. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4574. return false;
  4575. },
  4576. "text/plain");
  4577. ASSERT_TRUE(!res);
  4578. EXPECT_EQ(Error::Canceled, res.error());
  4579. }
  4580. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4581. auto res = cli_.Put(
  4582. "/put",
  4583. [](size_t /*offset*/, DataSink &sink) {
  4584. sink.os << "PUT";
  4585. sink.done();
  4586. return true;
  4587. },
  4588. "text/plain");
  4589. ASSERT_TRUE(res);
  4590. EXPECT_EQ(StatusCode::OK_200, res->status);
  4591. EXPECT_EQ("PUT", res->body);
  4592. }
  4593. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4594. auto res = cli_.Post(
  4595. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4596. "text/plain");
  4597. ASSERT_TRUE(!res);
  4598. EXPECT_EQ(Error::Canceled, res.error());
  4599. }
  4600. TEST_F(ServerTest, PostLoopBack) {
  4601. std::string body;
  4602. auto res = cli_.Post(
  4603. "/post-loopback", 9,
  4604. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4605. EXPECT_EQ(9u, length);
  4606. sink.write("123", 3);
  4607. sink.write("456", 3);
  4608. sink.write("789", 3);
  4609. return true;
  4610. },
  4611. "text/plain",
  4612. [&body](const char *data, size_t data_length) {
  4613. body.append(data, data_length);
  4614. return true;
  4615. });
  4616. ASSERT_TRUE(res);
  4617. EXPECT_EQ(StatusCode::OK_200, res->status);
  4618. EXPECT_EQ("123456789", body);
  4619. }
  4620. TEST_F(ServerTest, PutLoopBack) {
  4621. std::string body;
  4622. auto res = cli_.Put(
  4623. "/put-loopback", 9,
  4624. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4625. EXPECT_EQ(9u, length);
  4626. sink.write("123", 3);
  4627. sink.write("456", 3);
  4628. sink.write("789", 3);
  4629. return true;
  4630. },
  4631. "text/plain",
  4632. [&body](const char *data, size_t data_length) {
  4633. body.append(data, data_length);
  4634. return true;
  4635. });
  4636. ASSERT_TRUE(res);
  4637. EXPECT_EQ(StatusCode::OK_200, res->status);
  4638. EXPECT_EQ("123456789", body);
  4639. }
  4640. TEST_F(ServerTest, PatchLoopBack) {
  4641. std::string body;
  4642. auto res = cli_.Patch(
  4643. "/patch-loopback", 9,
  4644. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4645. EXPECT_EQ(9u, length);
  4646. sink.write("123", 3);
  4647. sink.write("456", 3);
  4648. sink.write("789", 3);
  4649. return true;
  4650. },
  4651. "text/plain",
  4652. [&body](const char *data, size_t data_length) {
  4653. body.append(data, data_length);
  4654. return true;
  4655. });
  4656. ASSERT_TRUE(res);
  4657. EXPECT_EQ(StatusCode::OK_200, res->status);
  4658. EXPECT_EQ("123456789", body);
  4659. }
  4660. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4661. std::string body;
  4662. auto res = cli_.Post(
  4663. "/post-loopback",
  4664. [](size_t /*offset*/, DataSink &sink) {
  4665. sink.write("123", 3);
  4666. sink.write("456", 3);
  4667. sink.write("789", 3);
  4668. sink.done();
  4669. return true;
  4670. },
  4671. "text/plain",
  4672. [&body](const char *data, size_t data_length) {
  4673. body.append(data, data_length);
  4674. return true;
  4675. });
  4676. ASSERT_TRUE(res);
  4677. EXPECT_EQ(StatusCode::OK_200, res->status);
  4678. EXPECT_EQ("123456789", body);
  4679. }
  4680. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4681. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4682. cli_.set_compress(true);
  4683. auto res = cli_.Put(
  4684. "/put", 3,
  4685. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4686. sink.os << "PUT";
  4687. return true;
  4688. },
  4689. "text/plain");
  4690. ASSERT_TRUE(res);
  4691. EXPECT_EQ(StatusCode::OK_200, res->status);
  4692. EXPECT_EQ("PUT", res->body);
  4693. }
  4694. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4695. cli_.set_compress(true);
  4696. auto res = cli_.Post(
  4697. "/post", 42,
  4698. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4699. return false;
  4700. },
  4701. "text/plain");
  4702. ASSERT_TRUE(!res);
  4703. EXPECT_EQ(Error::Canceled, res.error());
  4704. }
  4705. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4706. cli_.set_compress(true);
  4707. auto res = cli_.Put(
  4708. "/put",
  4709. [](size_t /*offset*/, DataSink &sink) {
  4710. sink.os << "PUT";
  4711. sink.done();
  4712. return true;
  4713. },
  4714. "text/plain");
  4715. ASSERT_TRUE(res);
  4716. EXPECT_EQ(StatusCode::OK_200, res->status);
  4717. EXPECT_EQ("PUT", res->body);
  4718. }
  4719. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4720. cli_.set_compress(true);
  4721. auto res = cli_.Post(
  4722. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4723. "text/plain");
  4724. ASSERT_TRUE(!res);
  4725. EXPECT_EQ(Error::Canceled, res.error());
  4726. }
  4727. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4728. cli_.set_compress(true);
  4729. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4730. ASSERT_TRUE(res);
  4731. EXPECT_EQ(StatusCode::OK_200, res->status);
  4732. EXPECT_EQ(LARGE_DATA, res->body);
  4733. }
  4734. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4735. #ifdef CPPHTTPLIB_SSL_ENABLED
  4736. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4737. Client cli(s.c_str());
  4738. cli.enable_server_certificate_verification(false);
  4739. #else
  4740. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4741. Client cli(s.c_str());
  4742. #endif
  4743. cli.set_compress(true);
  4744. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4745. ASSERT_TRUE(res);
  4746. EXPECT_EQ(StatusCode::OK_200, res->status);
  4747. EXPECT_EQ(LARGE_DATA, res->body);
  4748. // The compressed size should be less than a 10th of the original. May vary
  4749. // depending on the zlib library.
  4750. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4751. static_cast<uint64_t>(10 * 1024 * 1024));
  4752. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4753. }
  4754. TEST_F(ServerTest, PutContentWithDeflate) {
  4755. cli_.set_compress(false);
  4756. Headers headers;
  4757. headers.emplace("Content-Encoding", "deflate");
  4758. // PUT in deflate format:
  4759. auto res = cli_.Put("/put", headers,
  4760. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4761. ASSERT_TRUE(res);
  4762. EXPECT_EQ(StatusCode::OK_200, res->status);
  4763. EXPECT_EQ("PUT", res->body);
  4764. }
  4765. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4766. Headers headers;
  4767. headers.emplace("Accept-Encoding", "gzip, deflate");
  4768. auto res = cli_.Get("/streamed-chunked", headers);
  4769. ASSERT_TRUE(res);
  4770. EXPECT_EQ(StatusCode::OK_200, res->status);
  4771. EXPECT_EQ(std::string("123456789"), res->body);
  4772. }
  4773. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4774. Headers headers;
  4775. headers.emplace("Accept-Encoding", "gzip, deflate");
  4776. auto res = cli_.Get("/streamed-chunked2", headers);
  4777. ASSERT_TRUE(res);
  4778. EXPECT_EQ(StatusCode::OK_200, res->status);
  4779. EXPECT_EQ(std::string("123456789"), res->body);
  4780. }
  4781. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4782. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4783. ASSERT_TRUE(res);
  4784. EXPECT_EQ(StatusCode::OK_200, res->status);
  4785. }
  4786. TEST(GzipDecompressor, ChunkedDecompression) {
  4787. std::string data;
  4788. for (size_t i = 0; i < 32 * 1024; ++i) {
  4789. data.push_back(static_cast<char>('a' + i % 26));
  4790. }
  4791. std::string compressed_data;
  4792. {
  4793. httplib::detail::gzip_compressor compressor;
  4794. bool result = compressor.compress(
  4795. data.data(), data.size(),
  4796. /*last=*/true,
  4797. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4798. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4799. compressed_data_size);
  4800. return true;
  4801. });
  4802. ASSERT_TRUE(result);
  4803. }
  4804. std::string decompressed_data;
  4805. {
  4806. httplib::detail::gzip_decompressor decompressor;
  4807. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4808. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4809. size_t chunk_size = 130;
  4810. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4811. chunk_begin += chunk_size) {
  4812. size_t current_chunk_size =
  4813. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4814. bool result = decompressor.decompress(
  4815. compressed_data.data() + chunk_begin, current_chunk_size,
  4816. [&](const char *decompressed_data_chunk,
  4817. size_t decompressed_data_chunk_size) {
  4818. decompressed_data.insert(decompressed_data.size(),
  4819. decompressed_data_chunk,
  4820. decompressed_data_chunk_size);
  4821. return true;
  4822. });
  4823. ASSERT_TRUE(result);
  4824. }
  4825. }
  4826. ASSERT_EQ(data, decompressed_data);
  4827. }
  4828. TEST(GzipDecompressor, DeflateDecompression) {
  4829. std::string original_text = "Raw deflate without gzip";
  4830. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4831. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4832. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4833. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4834. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4835. std::string decompressed_data;
  4836. {
  4837. httplib::detail::gzip_decompressor decompressor;
  4838. bool result = decompressor.decompress(
  4839. compressed_data.data(), compressed_data.size(),
  4840. [&](const char *decompressed_data_chunk,
  4841. size_t decompressed_data_chunk_size) {
  4842. decompressed_data.insert(decompressed_data.size(),
  4843. decompressed_data_chunk,
  4844. decompressed_data_chunk_size);
  4845. return true;
  4846. });
  4847. ASSERT_TRUE(result);
  4848. }
  4849. ASSERT_EQ(original_text, decompressed_data);
  4850. }
  4851. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4852. std::string original_text = "Raw deflate without gzip";
  4853. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4854. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4855. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4856. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4857. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4858. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4859. std::string decompressed_data;
  4860. {
  4861. httplib::detail::gzip_decompressor decompressor;
  4862. bool result = decompressor.decompress(
  4863. compressed_data.data(), compressed_data.size(),
  4864. [&](const char *decompressed_data_chunk,
  4865. size_t decompressed_data_chunk_size) {
  4866. decompressed_data.insert(decompressed_data.size(),
  4867. decompressed_data_chunk,
  4868. decompressed_data_chunk_size);
  4869. return true;
  4870. });
  4871. ASSERT_TRUE(result);
  4872. }
  4873. ASSERT_EQ(original_text, decompressed_data);
  4874. }
  4875. #ifdef _WIN32
  4876. TEST(GzipDecompressor, LargeRandomData) {
  4877. // prepare large random data that is difficult to be compressed and is
  4878. // expected to have large size even when compressed
  4879. std::random_device seed_gen;
  4880. std::mt19937 random(seed_gen());
  4881. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4882. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4883. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4884. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4885. // compress data over 4GiB
  4886. std::string compressed_data;
  4887. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4888. httplib::detail::gzip_compressor compressor;
  4889. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4890. data.size() * sizeof(std::uint32_t), true,
  4891. [&](const char *data, size_t size) {
  4892. compressed_data.insert(
  4893. compressed_data.size(), data, size);
  4894. return true;
  4895. });
  4896. ASSERT_TRUE(result);
  4897. // FIXME: compressed data size is expected to be greater than 4GiB,
  4898. // but there is no guarantee
  4899. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4900. // decompress data over 4GiB
  4901. std::string decompressed_data;
  4902. decompressed_data.reserve(data_size);
  4903. httplib::detail::gzip_decompressor decompressor;
  4904. result = decompressor.decompress(
  4905. compressed_data.data(), compressed_data.size(),
  4906. [&](const char *data, size_t size) {
  4907. decompressed_data.insert(decompressed_data.size(), data, size);
  4908. return true;
  4909. });
  4910. ASSERT_TRUE(result);
  4911. // compare
  4912. ASSERT_EQ(data_size, decompressed_data.size());
  4913. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4914. 0);
  4915. }
  4916. #endif
  4917. #endif
  4918. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4919. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4920. Headers headers;
  4921. headers.emplace("Accept-Encoding", "br");
  4922. auto res = cli_.Get("/streamed-chunked", headers);
  4923. ASSERT_TRUE(res);
  4924. EXPECT_EQ(StatusCode::OK_200, res->status);
  4925. EXPECT_EQ(std::string("123456789"), res->body);
  4926. }
  4927. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4928. Headers headers;
  4929. headers.emplace("Accept-Encoding", "br");
  4930. auto res = cli_.Get("/streamed-chunked2", headers);
  4931. ASSERT_TRUE(res);
  4932. EXPECT_EQ(StatusCode::OK_200, res->status);
  4933. EXPECT_EQ(std::string("123456789"), res->body);
  4934. }
  4935. #endif
  4936. TEST_F(ServerTest, Patch) {
  4937. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4938. ASSERT_TRUE(res);
  4939. EXPECT_EQ(StatusCode::OK_200, res->status);
  4940. EXPECT_EQ("PATCH", res->body);
  4941. }
  4942. TEST_F(ServerTest, Delete) {
  4943. auto res = cli_.Delete("/delete");
  4944. ASSERT_TRUE(res);
  4945. EXPECT_EQ(StatusCode::OK_200, res->status);
  4946. EXPECT_EQ("DELETE", res->body);
  4947. }
  4948. TEST_F(ServerTest, DeleteContentReceiver) {
  4949. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4950. ASSERT_TRUE(res);
  4951. EXPECT_EQ(StatusCode::OK_200, res->status);
  4952. EXPECT_EQ("content", res->body);
  4953. }
  4954. TEST_F(ServerTest, Options) {
  4955. auto res = cli_.Options("*");
  4956. ASSERT_TRUE(res);
  4957. EXPECT_EQ(StatusCode::OK_200, res->status);
  4958. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4959. EXPECT_TRUE(res->body.empty());
  4960. }
  4961. TEST_F(ServerTest, URL) {
  4962. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4963. ASSERT_TRUE(res);
  4964. EXPECT_EQ(StatusCode::OK_200, res->status);
  4965. }
  4966. TEST_F(ServerTest, ArrayParam) {
  4967. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4968. ASSERT_TRUE(res);
  4969. EXPECT_EQ(StatusCode::OK_200, res->status);
  4970. }
  4971. TEST_F(ServerTest, NoMultipleHeaders) {
  4972. Headers headers = {{"Content-Length", "5"}};
  4973. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4974. "text/plain");
  4975. ASSERT_TRUE(res);
  4976. EXPECT_EQ(StatusCode::OK_200, res->status);
  4977. }
  4978. TEST_F(ServerTest, PostContentReceiver) {
  4979. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4980. ASSERT_TRUE(res);
  4981. ASSERT_EQ(StatusCode::OK_200, res->status);
  4982. ASSERT_EQ("content", res->body);
  4983. }
  4984. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4985. UploadFormDataItems items = {
  4986. {"text1", "text default", "", ""},
  4987. {"text2", "aωb", "", ""},
  4988. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4989. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4990. {"file3", "", "", "application/octet-stream"},
  4991. };
  4992. auto res = cli_.Post("/content_receiver", items);
  4993. ASSERT_TRUE(res);
  4994. EXPECT_EQ(StatusCode::OK_200, res->status);
  4995. }
  4996. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4997. UploadFormDataItems items = {
  4998. {"text1", "text default", "", ""},
  4999. {"text2", "aωb", "", ""},
  5000. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5001. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5002. {"file3", "", "", "application/octet-stream"},
  5003. };
  5004. auto boundary = std::string("+++++");
  5005. std::string body;
  5006. for (const auto &item : items) {
  5007. body += "--" + boundary + "\r\n";
  5008. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5009. if (!item.filename.empty()) {
  5010. body += "; filename=\"" + item.filename + "\"";
  5011. }
  5012. body += "\r\n";
  5013. if (!item.content_type.empty()) {
  5014. body += "Content-Type: " + item.content_type + "\r\n";
  5015. }
  5016. body += "\r\n";
  5017. body += item.content + "\r\n";
  5018. }
  5019. body += "--" + boundary + "--\r\n";
  5020. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5021. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5022. ASSERT_TRUE(res);
  5023. EXPECT_EQ(StatusCode::OK_200, res->status);
  5024. }
  5025. TEST_F(ServerTest, PostContentReceiverGzip) {
  5026. cli_.set_compress(true);
  5027. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5028. ASSERT_TRUE(res);
  5029. ASSERT_EQ(StatusCode::OK_200, res->status);
  5030. ASSERT_EQ("content", res->body);
  5031. }
  5032. TEST_F(ServerTest, PutContentReceiver) {
  5033. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5034. ASSERT_TRUE(res);
  5035. ASSERT_EQ(StatusCode::OK_200, res->status);
  5036. ASSERT_EQ("content", res->body);
  5037. }
  5038. TEST_F(ServerTest, PatchContentReceiver) {
  5039. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5040. ASSERT_TRUE(res);
  5041. ASSERT_EQ(StatusCode::OK_200, res->status);
  5042. ASSERT_EQ("content", res->body);
  5043. }
  5044. template <typename ClientType>
  5045. void TestWithHeadersAndContentReceiver(
  5046. ClientType &cli,
  5047. std::function<Result(ClientType &, const std::string &, const Headers &,
  5048. const std::string &, const std::string &,
  5049. ContentReceiver, DownloadProgress)>
  5050. request_func) {
  5051. Headers headers;
  5052. headers.emplace("X-Custom-Header", "test-value");
  5053. std::string received_body;
  5054. auto res = request_func(
  5055. cli, "/content_receiver", headers, "content", "application/json",
  5056. [&](const char *data, size_t data_length) {
  5057. received_body.append(data, data_length);
  5058. return true;
  5059. },
  5060. nullptr);
  5061. ASSERT_TRUE(res);
  5062. EXPECT_EQ(StatusCode::OK_200, res->status);
  5063. EXPECT_EQ("content", received_body);
  5064. }
  5065. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5066. #ifdef CPPHTTPLIB_SSL_ENABLED
  5067. using ClientT = SSLClient;
  5068. #else
  5069. using ClientT = Client;
  5070. #endif
  5071. TestWithHeadersAndContentReceiver<ClientT>(
  5072. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5073. const std::string &body, const std::string &content_type,
  5074. ContentReceiver receiver, DownloadProgress progress) {
  5075. return cli.Post(path, headers, body, content_type, receiver, progress);
  5076. });
  5077. }
  5078. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5079. #ifdef CPPHTTPLIB_SSL_ENABLED
  5080. using ClientT = SSLClient;
  5081. #else
  5082. using ClientT = Client;
  5083. #endif
  5084. TestWithHeadersAndContentReceiver<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, DownloadProgress progress) {
  5088. return cli.Put(path, headers, body, content_type, receiver, progress);
  5089. });
  5090. }
  5091. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5092. #ifdef CPPHTTPLIB_SSL_ENABLED
  5093. using ClientT = SSLClient;
  5094. #else
  5095. using ClientT = Client;
  5096. #endif
  5097. TestWithHeadersAndContentReceiver<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, DownloadProgress progress) {
  5101. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5102. });
  5103. }
  5104. template <typename ClientType>
  5105. void TestWithHeadersAndContentReceiverWithProgress(
  5106. ClientType &cli,
  5107. std::function<Result(ClientType &, const std::string &, const Headers &,
  5108. const std::string &, const std::string &,
  5109. ContentReceiver, DownloadProgress)>
  5110. request_func) {
  5111. Headers headers;
  5112. headers.emplace("X-Test-Header", "progress-test");
  5113. std::string received_body;
  5114. auto progress_called = false;
  5115. auto res = request_func(
  5116. cli, "/content_receiver", headers, "content", "text/plain",
  5117. [&](const char *data, size_t data_length) {
  5118. received_body.append(data, data_length);
  5119. return true;
  5120. },
  5121. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5122. progress_called = true;
  5123. return true;
  5124. });
  5125. ASSERT_TRUE(res);
  5126. EXPECT_EQ(StatusCode::OK_200, res->status);
  5127. EXPECT_EQ("content", received_body);
  5128. EXPECT_TRUE(progress_called);
  5129. }
  5130. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5131. #ifdef CPPHTTPLIB_SSL_ENABLED
  5132. using ClientT = SSLClient;
  5133. #else
  5134. using ClientT = Client;
  5135. #endif
  5136. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5137. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5138. const std::string &body, const std::string &content_type,
  5139. ContentReceiver receiver, DownloadProgress progress) {
  5140. return cli.Post(path, headers, body, content_type, receiver, progress);
  5141. });
  5142. }
  5143. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5144. #ifdef CPPHTTPLIB_SSL_ENABLED
  5145. using ClientT = SSLClient;
  5146. #else
  5147. using ClientT = Client;
  5148. #endif
  5149. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5150. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5151. const std::string &body, const std::string &content_type,
  5152. ContentReceiver receiver, DownloadProgress progress) {
  5153. return cli.Put(path, headers, body, content_type, receiver, progress);
  5154. });
  5155. }
  5156. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5157. #ifdef CPPHTTPLIB_SSL_ENABLED
  5158. using ClientT = SSLClient;
  5159. #else
  5160. using ClientT = Client;
  5161. #endif
  5162. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5163. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5164. const std::string &body, const std::string &content_type,
  5165. ContentReceiver receiver, DownloadProgress progress) {
  5166. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5167. });
  5168. }
  5169. template <typename ClientType>
  5170. void TestWithHeadersAndContentReceiverError(
  5171. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5172. const Headers &, const std::string &,
  5173. const std::string &, ContentReceiver)>
  5174. request_func) {
  5175. Headers headers;
  5176. headers.emplace("X-Error-Test", "true");
  5177. std::string received_body;
  5178. auto receiver_failed = false;
  5179. auto res =
  5180. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5181. [&](const char *data, size_t data_length) {
  5182. received_body.append(data, data_length);
  5183. receiver_failed = true;
  5184. return false;
  5185. });
  5186. ASSERT_FALSE(res);
  5187. EXPECT_TRUE(receiver_failed);
  5188. }
  5189. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5190. #ifdef CPPHTTPLIB_SSL_ENABLED
  5191. using ClientT = SSLClient;
  5192. #else
  5193. using ClientT = Client;
  5194. #endif
  5195. TestWithHeadersAndContentReceiverError<ClientT>(
  5196. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5197. const std::string &body, const std::string &content_type,
  5198. ContentReceiver receiver) {
  5199. return cli.Post(path, headers, body, content_type, receiver);
  5200. });
  5201. }
  5202. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5203. #ifdef CPPHTTPLIB_SSL_ENABLED
  5204. using ClientT = SSLClient;
  5205. #else
  5206. using ClientT = Client;
  5207. #endif
  5208. TestWithHeadersAndContentReceiverError<ClientT>(
  5209. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5210. const std::string &body, const std::string &content_type,
  5211. ContentReceiver receiver) {
  5212. return cli.Put(path, headers, body, content_type, receiver);
  5213. });
  5214. }
  5215. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5216. #ifdef CPPHTTPLIB_SSL_ENABLED
  5217. using ClientT = SSLClient;
  5218. #else
  5219. using ClientT = Client;
  5220. #endif
  5221. TestWithHeadersAndContentReceiverError<ClientT>(
  5222. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5223. const std::string &body, const std::string &content_type,
  5224. ContentReceiver receiver) {
  5225. return cli.Patch(path, headers, body, content_type, receiver);
  5226. });
  5227. }
  5228. TEST_F(ServerTest, PostQueryStringAndBody) {
  5229. auto res =
  5230. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5231. ASSERT_TRUE(res);
  5232. ASSERT_EQ(StatusCode::OK_200, res->status);
  5233. }
  5234. TEST_F(ServerTest, HTTP2Magic) {
  5235. Request req;
  5236. req.method = "PRI";
  5237. req.path = "*";
  5238. req.body = "SM";
  5239. auto res = std::make_shared<Response>();
  5240. auto error = Error::Success;
  5241. auto ret = cli_.send(req, *res, error);
  5242. ASSERT_TRUE(ret);
  5243. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5244. }
  5245. TEST_F(ServerTest, KeepAlive) {
  5246. auto res = cli_.Get("/hi");
  5247. ASSERT_TRUE(res);
  5248. EXPECT_EQ(StatusCode::OK_200, res->status);
  5249. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5250. EXPECT_EQ("Hello World!", res->body);
  5251. res = cli_.Get("/hi");
  5252. ASSERT_TRUE(res);
  5253. EXPECT_EQ(StatusCode::OK_200, res->status);
  5254. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5255. EXPECT_EQ("Hello World!", res->body);
  5256. res = cli_.Get("/hi");
  5257. ASSERT_TRUE(res);
  5258. EXPECT_EQ(StatusCode::OK_200, res->status);
  5259. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5260. EXPECT_EQ("Hello World!", res->body);
  5261. res = cli_.Get("/not-exist");
  5262. ASSERT_TRUE(res);
  5263. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5264. res = cli_.Post("/empty", "", "text/plain");
  5265. ASSERT_TRUE(res);
  5266. EXPECT_EQ(StatusCode::OK_200, res->status);
  5267. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5268. EXPECT_EQ("empty", res->body);
  5269. EXPECT_EQ("close", res->get_header_value("Connection"));
  5270. res = cli_.Post(
  5271. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5272. "text/plain");
  5273. ASSERT_TRUE(res);
  5274. EXPECT_EQ(StatusCode::OK_200, res->status);
  5275. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5276. EXPECT_EQ("empty", res->body);
  5277. cli_.set_keep_alive(false);
  5278. res = cli_.Get("/last-request");
  5279. ASSERT_TRUE(res);
  5280. EXPECT_EQ(StatusCode::OK_200, res->status);
  5281. EXPECT_EQ("close", res->get_header_value("Connection"));
  5282. }
  5283. TEST_F(ServerTest, TooManyRedirect) {
  5284. cli_.set_follow_location(true);
  5285. auto res = cli_.Get("/redirect/0");
  5286. ASSERT_TRUE(!res);
  5287. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5288. }
  5289. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5290. Request req;
  5291. req.method = "FOOBAR";
  5292. req.path = "/hi";
  5293. cli_.set_keep_alive(true);
  5294. auto res = cli_.send(req);
  5295. ASSERT_TRUE(res);
  5296. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5297. EXPECT_EQ("close", res->get_header_value("Connection"));
  5298. EXPECT_FALSE(cli_.is_socket_open());
  5299. }
  5300. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5301. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5302. TEST_F(ServerTest, Gzip) {
  5303. Headers headers;
  5304. headers.emplace("Accept-Encoding", "gzip, deflate");
  5305. auto res = cli_.Get("/compress", headers);
  5306. ASSERT_TRUE(res);
  5307. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5308. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5309. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5310. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5311. "7890123456789012345678901234567890",
  5312. res->body);
  5313. EXPECT_EQ(StatusCode::OK_200, res->status);
  5314. }
  5315. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5316. Headers headers;
  5317. headers.emplace("Accept-Encoding", "gzip, deflate");
  5318. auto res = cli_.Get("/compress-with-charset", headers);
  5319. ASSERT_TRUE(res);
  5320. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5321. EXPECT_EQ("application/json; charset=utf-8",
  5322. res->get_header_value("Content-Type"));
  5323. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5324. "7890123456789012345678901234567890",
  5325. res->body);
  5326. EXPECT_EQ(StatusCode::OK_200, res->status);
  5327. }
  5328. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5329. Headers headers;
  5330. headers.emplace("Accept-Encoding", "");
  5331. auto res = cli_.Get("/compress", headers);
  5332. ASSERT_TRUE(res);
  5333. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5334. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5335. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5336. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5337. "7890123456789012345678901234567890",
  5338. res->body);
  5339. EXPECT_EQ(StatusCode::OK_200, res->status);
  5340. }
  5341. TEST_F(ServerTest, GzipWithContentReceiver) {
  5342. Headers headers;
  5343. headers.emplace("Accept-Encoding", "gzip, deflate");
  5344. std::string body;
  5345. auto res = cli_.Get("/compress", headers,
  5346. [&](const char *data, uint64_t data_length) {
  5347. EXPECT_EQ(100U, data_length);
  5348. body.append(data, data_length);
  5349. return true;
  5350. });
  5351. ASSERT_TRUE(res);
  5352. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5353. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5354. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5355. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5356. "7890123456789012345678901234567890",
  5357. body);
  5358. EXPECT_EQ(StatusCode::OK_200, res->status);
  5359. }
  5360. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5361. Headers headers;
  5362. headers.emplace("Accept-Encoding", "gzip, deflate");
  5363. cli_.set_decompress(false);
  5364. auto res = cli_.Get("/compress", headers);
  5365. ASSERT_TRUE(res);
  5366. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5367. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5368. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5369. EXPECT_EQ(33U, res->body.size());
  5370. EXPECT_EQ(StatusCode::OK_200, res->status);
  5371. }
  5372. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5373. Headers headers;
  5374. headers.emplace("Accept-Encoding", "");
  5375. std::string body;
  5376. auto res = cli_.Get("/compress", headers,
  5377. [&](const char *data, uint64_t data_length) {
  5378. EXPECT_EQ(100U, data_length);
  5379. body.append(data, data_length);
  5380. return true;
  5381. });
  5382. ASSERT_TRUE(res);
  5383. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5384. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5385. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5386. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5387. "7890123456789012345678901234567890",
  5388. body);
  5389. EXPECT_EQ(StatusCode::OK_200, res->status);
  5390. }
  5391. TEST_F(ServerTest, NoGzip) {
  5392. Headers headers;
  5393. headers.emplace("Accept-Encoding", "gzip, deflate");
  5394. auto res = cli_.Get("/nocompress", headers);
  5395. ASSERT_TRUE(res);
  5396. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5397. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5398. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5399. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5400. "7890123456789012345678901234567890",
  5401. res->body);
  5402. EXPECT_EQ(StatusCode::OK_200, res->status);
  5403. }
  5404. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5405. Headers headers;
  5406. headers.emplace("Accept-Encoding", "gzip, deflate");
  5407. std::string body;
  5408. auto res = cli_.Get("/nocompress", headers,
  5409. [&](const char *data, uint64_t data_length) {
  5410. EXPECT_EQ(100U, data_length);
  5411. body.append(data, data_length);
  5412. return true;
  5413. });
  5414. ASSERT_TRUE(res);
  5415. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5416. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5417. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5418. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5419. "7890123456789012345678901234567890",
  5420. body);
  5421. EXPECT_EQ(StatusCode::OK_200, res->status);
  5422. }
  5423. TEST_F(ServerTest, MultipartFormDataGzip) {
  5424. UploadFormDataItems items = {
  5425. {"key1", "test", "", ""},
  5426. {"key2", "--abcdefg123", "", ""},
  5427. };
  5428. cli_.set_compress(true);
  5429. auto res = cli_.Post("/compress-multipart", items);
  5430. ASSERT_TRUE(res);
  5431. EXPECT_EQ(StatusCode::OK_200, res->status);
  5432. }
  5433. #endif
  5434. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5435. TEST_F(ServerTest, Brotli) {
  5436. Headers headers;
  5437. headers.emplace("Accept-Encoding", "br");
  5438. auto res = cli_.Get("/compress", headers);
  5439. ASSERT_TRUE(res);
  5440. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5441. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5442. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5443. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5444. "7890123456789012345678901234567890",
  5445. res->body);
  5446. EXPECT_EQ(StatusCode::OK_200, res->status);
  5447. }
  5448. #endif
  5449. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5450. TEST_F(ServerTest, Zstd) {
  5451. Headers headers;
  5452. headers.emplace("Accept-Encoding", "zstd");
  5453. auto res = cli_.Get("/compress", headers);
  5454. ASSERT_TRUE(res);
  5455. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5456. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5457. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5458. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5459. "7890123456789012345678901234567890",
  5460. res->body);
  5461. EXPECT_EQ(StatusCode::OK_200, res->status);
  5462. }
  5463. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5464. Headers headers;
  5465. headers.emplace("Accept-Encoding", "");
  5466. auto res = cli_.Get("/compress", headers);
  5467. ASSERT_TRUE(res);
  5468. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5469. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5470. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5471. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5472. "7890123456789012345678901234567890",
  5473. res->body);
  5474. EXPECT_EQ(StatusCode::OK_200, res->status);
  5475. }
  5476. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5477. Headers headers;
  5478. headers.emplace("Accept-Encoding", "zstd");
  5479. std::string body;
  5480. auto res = cli_.Get("/compress", headers,
  5481. [&](const char *data, uint64_t data_length) {
  5482. EXPECT_EQ(100U, data_length);
  5483. body.append(data, data_length);
  5484. return true;
  5485. });
  5486. ASSERT_TRUE(res);
  5487. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5488. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5489. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5490. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5491. "7890123456789012345678901234567890",
  5492. body);
  5493. EXPECT_EQ(StatusCode::OK_200, res->status);
  5494. }
  5495. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5496. Headers headers;
  5497. headers.emplace("Accept-Encoding", "zstd");
  5498. cli_.set_decompress(false);
  5499. auto res = cli_.Get("/compress", headers);
  5500. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5501. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5502. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5503. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5504. ASSERT_TRUE(res);
  5505. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5506. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5507. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5508. EXPECT_EQ(StatusCode::OK_200, res->status);
  5509. ASSERT_EQ(26U, res->body.size());
  5510. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5511. 0);
  5512. }
  5513. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5514. Headers headers;
  5515. headers.emplace("Accept-Encoding", "");
  5516. std::string body;
  5517. auto res = cli_.Get("/compress", headers,
  5518. [&](const char *data, uint64_t data_length) {
  5519. EXPECT_EQ(100U, data_length);
  5520. body.append(data, data_length);
  5521. return true;
  5522. });
  5523. ASSERT_TRUE(res);
  5524. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5525. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5526. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5527. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5528. "7890123456789012345678901234567890",
  5529. body);
  5530. EXPECT_EQ(StatusCode::OK_200, res->status);
  5531. }
  5532. TEST_F(ServerTest, NoZstd) {
  5533. Headers headers;
  5534. headers.emplace("Accept-Encoding", "zstd");
  5535. auto res = cli_.Get("/nocompress", headers);
  5536. ASSERT_TRUE(res);
  5537. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5538. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5539. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5540. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5541. "7890123456789012345678901234567890",
  5542. res->body);
  5543. EXPECT_EQ(StatusCode::OK_200, res->status);
  5544. }
  5545. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5546. Headers headers;
  5547. headers.emplace("Accept-Encoding", "zstd");
  5548. std::string body;
  5549. auto res = cli_.Get("/nocompress", headers,
  5550. [&](const char *data, uint64_t data_length) {
  5551. EXPECT_EQ(100U, data_length);
  5552. body.append(data, data_length);
  5553. return true;
  5554. });
  5555. ASSERT_TRUE(res);
  5556. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5557. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5558. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5559. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5560. "7890123456789012345678901234567890",
  5561. body);
  5562. EXPECT_EQ(StatusCode::OK_200, res->status);
  5563. }
  5564. // TODO: How to enable zstd ??
  5565. TEST_F(ServerTest, MultipartFormDataZstd) {
  5566. UploadFormDataItems items = {
  5567. {"key1", "test", "", ""},
  5568. {"key2", "--abcdefg123", "", ""},
  5569. };
  5570. Headers headers;
  5571. headers.emplace("Accept-Encoding", "zstd");
  5572. cli_.set_compress(true);
  5573. auto res = cli_.Post("/compress-multipart", headers, items);
  5574. ASSERT_TRUE(res);
  5575. EXPECT_EQ(StatusCode::OK_200, res->status);
  5576. }
  5577. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5578. Headers headers;
  5579. headers.emplace("Accept-Encoding", "zstd");
  5580. cli_.set_compress(true);
  5581. auto res = cli_.Put(
  5582. "/put", headers, 3,
  5583. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5584. sink.os << "PUT";
  5585. return true;
  5586. },
  5587. "text/plain");
  5588. ASSERT_TRUE(res);
  5589. EXPECT_EQ(StatusCode::OK_200, res->status);
  5590. EXPECT_EQ("PUT", res->body);
  5591. }
  5592. // Pre-compression logging tests
  5593. TEST_F(ServerTest, PreCompressionLogging) {
  5594. // Test data for compression (matches the actual /compress endpoint content)
  5595. const std::string test_content =
  5596. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5597. "3456789012345678901234567890";
  5598. // Variables to capture logging data
  5599. std::string pre_compression_body;
  5600. std::string pre_compression_content_type;
  5601. std::string pre_compression_content_encoding;
  5602. std::string post_compression_body;
  5603. std::string post_compression_content_type;
  5604. std::string post_compression_content_encoding;
  5605. // Set up pre-compression logger
  5606. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5607. const Response &res) {
  5608. pre_compression_body = res.body;
  5609. pre_compression_content_type = res.get_header_value("Content-Type");
  5610. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5611. });
  5612. // Set up post-compression logger
  5613. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5614. post_compression_body = res.body;
  5615. post_compression_content_type = res.get_header_value("Content-Type");
  5616. post_compression_content_encoding =
  5617. res.get_header_value("Content-Encoding");
  5618. });
  5619. // Test with gzip compression
  5620. Headers headers;
  5621. headers.emplace("Accept-Encoding", "gzip");
  5622. auto res = cli_.Get("/compress", headers);
  5623. // Verify response was compressed
  5624. ASSERT_TRUE(res);
  5625. EXPECT_EQ(StatusCode::OK_200, res->status);
  5626. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5627. // Verify pre-compression logger captured uncompressed content
  5628. EXPECT_EQ(test_content, pre_compression_body);
  5629. EXPECT_EQ("text/plain", pre_compression_content_type);
  5630. EXPECT_TRUE(pre_compression_content_encoding
  5631. .empty()); // No encoding header before compression
  5632. // Verify post-compression logger captured compressed content
  5633. EXPECT_NE(test_content,
  5634. post_compression_body); // Should be different after compression
  5635. EXPECT_EQ("text/plain", post_compression_content_type);
  5636. EXPECT_EQ("gzip", post_compression_content_encoding);
  5637. // Verify compressed content is smaller
  5638. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5639. }
  5640. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5641. const std::string test_content =
  5642. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5643. "3456789012345678901234567890";
  5644. std::string pre_compression_body;
  5645. std::string post_compression_body;
  5646. svr_.set_pre_compression_logger(
  5647. [&](const Request & /*req*/, const Response &res) {
  5648. pre_compression_body = res.body;
  5649. });
  5650. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5651. post_compression_body = res.body;
  5652. });
  5653. Headers headers;
  5654. headers.emplace("Accept-Encoding", "br");
  5655. auto res = cli_.Get("/compress", headers);
  5656. ASSERT_TRUE(res);
  5657. EXPECT_EQ(StatusCode::OK_200, res->status);
  5658. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5659. // Verify pre-compression content is uncompressed
  5660. EXPECT_EQ(test_content, pre_compression_body);
  5661. // Verify post-compression content is compressed
  5662. EXPECT_NE(test_content, post_compression_body);
  5663. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5664. }
  5665. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5666. const std::string test_content =
  5667. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5668. "3456789012345678901234567890";
  5669. std::string pre_compression_body;
  5670. std::string post_compression_body;
  5671. svr_.set_pre_compression_logger(
  5672. [&](const Request & /*req*/, const Response &res) {
  5673. pre_compression_body = res.body;
  5674. });
  5675. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5676. post_compression_body = res.body;
  5677. });
  5678. // Request without compression (use /nocompress endpoint)
  5679. Headers headers;
  5680. auto res = cli_.Get("/nocompress", headers);
  5681. ASSERT_TRUE(res);
  5682. EXPECT_EQ(StatusCode::OK_200, res->status);
  5683. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5684. // Pre-compression logger should not be called when no compression is applied
  5685. EXPECT_TRUE(
  5686. pre_compression_body.empty()); // Pre-compression logger not called
  5687. EXPECT_EQ(
  5688. test_content,
  5689. post_compression_body); // Post-compression logger captures final content
  5690. }
  5691. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5692. const std::string test_content =
  5693. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5694. "3456789012345678901234567890";
  5695. std::string pre_compression_body;
  5696. bool pre_logger_called = false;
  5697. // Set only pre-compression logger
  5698. svr_.set_pre_compression_logger(
  5699. [&](const Request & /*req*/, const Response &res) {
  5700. pre_compression_body = res.body;
  5701. pre_logger_called = true;
  5702. });
  5703. Headers headers;
  5704. headers.emplace("Accept-Encoding", "gzip");
  5705. auto res = cli_.Get("/compress", headers);
  5706. ASSERT_TRUE(res);
  5707. EXPECT_EQ(StatusCode::OK_200, res->status);
  5708. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5709. // Verify pre-compression logger was called
  5710. EXPECT_TRUE(pre_logger_called);
  5711. EXPECT_EQ(test_content, pre_compression_body);
  5712. }
  5713. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5714. {
  5715. // Test with Expect: 100-continue header - success case
  5716. // Server returns 100 Continue, client sends body, server returns 200 OK
  5717. Request req;
  5718. req.method = "POST";
  5719. req.path = "/post-large";
  5720. req.set_header("Expect", "100-continue");
  5721. req.body = LARGE_DATA;
  5722. Response res;
  5723. auto error = Error::Success;
  5724. cli_.set_keep_alive(true);
  5725. auto ret = cli_.send(req, res, error);
  5726. EXPECT_TRUE(ret);
  5727. EXPECT_EQ(StatusCode::OK_200, res.status);
  5728. EXPECT_EQ(LARGE_DATA, res.body);
  5729. }
  5730. {
  5731. // Test with Expect: 100-continue header - error case
  5732. // Client should not send the body when server returns an error
  5733. Request req;
  5734. req.method = "POST";
  5735. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5736. req.set_header("Expect", "100-continue");
  5737. req.body = LARGE_DATA;
  5738. Response res;
  5739. auto error = Error::Success;
  5740. auto start = std::chrono::high_resolution_clock::now();
  5741. cli_.set_keep_alive(true);
  5742. auto ret = cli_.send(req, res, error);
  5743. auto end = std::chrono::high_resolution_clock::now();
  5744. auto elapsed =
  5745. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5746. .count();
  5747. // With Expect: 100-continue, request completes successfully but with error
  5748. EXPECT_TRUE(ret);
  5749. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5750. EXPECT_EQ("close", res.get_header_value("Connection"));
  5751. EXPECT_FALSE(cli_.is_socket_open());
  5752. EXPECT_LE(elapsed, 200);
  5753. }
  5754. {
  5755. // Send an extra GET request to ensure error recovery without hanging
  5756. Request req;
  5757. req.method = "GET";
  5758. req.path = "/hi";
  5759. auto start = std::chrono::high_resolution_clock::now();
  5760. auto res = cli_.send(req);
  5761. auto end = std::chrono::high_resolution_clock::now();
  5762. auto elapsed =
  5763. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5764. .count();
  5765. ASSERT_TRUE(res);
  5766. EXPECT_EQ(StatusCode::OK_200, res->status);
  5767. EXPECT_EQ("Hello World!", res->body);
  5768. EXPECT_LE(elapsed, 500);
  5769. }
  5770. }
  5771. TEST(ZstdDecompressor, ChunkedDecompression) {
  5772. std::string data;
  5773. for (size_t i = 0; i < 32 * 1024; ++i) {
  5774. data.push_back(static_cast<char>('a' + i % 26));
  5775. }
  5776. std::string compressed_data;
  5777. {
  5778. httplib::detail::zstd_compressor compressor;
  5779. bool result = compressor.compress(
  5780. data.data(), data.size(),
  5781. /*last=*/true,
  5782. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5783. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5784. compressed_data_size);
  5785. return true;
  5786. });
  5787. ASSERT_TRUE(result);
  5788. }
  5789. std::string decompressed_data;
  5790. {
  5791. httplib::detail::zstd_decompressor decompressor;
  5792. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5793. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5794. size_t chunk_size = 130;
  5795. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5796. chunk_begin += chunk_size) {
  5797. size_t current_chunk_size =
  5798. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5799. bool result = decompressor.decompress(
  5800. compressed_data.data() + chunk_begin, current_chunk_size,
  5801. [&](const char *decompressed_data_chunk,
  5802. size_t decompressed_data_chunk_size) {
  5803. decompressed_data.insert(decompressed_data.size(),
  5804. decompressed_data_chunk,
  5805. decompressed_data_chunk_size);
  5806. return true;
  5807. });
  5808. ASSERT_TRUE(result);
  5809. }
  5810. }
  5811. ASSERT_EQ(data, decompressed_data);
  5812. }
  5813. TEST(ZstdDecompressor, Decompress) {
  5814. std::string original_text = "Compressed with ZSTD";
  5815. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5816. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5817. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5818. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5819. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5820. std::string decompressed_data;
  5821. {
  5822. httplib::detail::zstd_decompressor decompressor;
  5823. bool result = decompressor.decompress(
  5824. compressed_data.data(), compressed_data.size(),
  5825. [&](const char *decompressed_data_chunk,
  5826. size_t decompressed_data_chunk_size) {
  5827. decompressed_data.insert(decompressed_data.size(),
  5828. decompressed_data_chunk,
  5829. decompressed_data_chunk_size);
  5830. return true;
  5831. });
  5832. ASSERT_TRUE(result);
  5833. }
  5834. ASSERT_EQ(original_text, decompressed_data);
  5835. }
  5836. #endif
  5837. // Sends a raw request to a server listening at HOST:PORT.
  5838. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5839. std::string *resp = nullptr) {
  5840. auto error = Error::Success;
  5841. auto client_sock = detail::create_client_socket(
  5842. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5843. /*connection_timeout_sec=*/5, 0,
  5844. /*read_timeout_sec=*/5, 0,
  5845. /*write_timeout_sec=*/5, 0, std::string(), error);
  5846. if (client_sock == INVALID_SOCKET) { return false; }
  5847. auto ret = detail::process_client_socket(
  5848. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5849. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5850. if (req.size() !=
  5851. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5852. return false;
  5853. }
  5854. char buf[512];
  5855. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5856. while (line_reader.getline()) {
  5857. if (resp) { *resp += line_reader.ptr(); }
  5858. }
  5859. return true;
  5860. });
  5861. detail::close_socket(client_sock);
  5862. return ret;
  5863. }
  5864. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5865. Server svr;
  5866. std::string header_value;
  5867. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5868. header_value = req.get_header_value("foo");
  5869. res.set_content("ok", "text/plain");
  5870. });
  5871. thread t = thread([&] { svr.listen(HOST, PORT); });
  5872. auto se = detail::scope_exit([&] {
  5873. svr.stop();
  5874. t.join();
  5875. ASSERT_FALSE(svr.is_running());
  5876. });
  5877. svr.wait_until_ready();
  5878. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5879. // like characters are not treated the same - use vertical tab and escape.
  5880. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5881. "foo: \t \v bar \x1B\t \r\n"
  5882. "Connection: close\r\n"
  5883. "\r\n";
  5884. std::string res;
  5885. ASSERT_TRUE(send_request(5, req, &res));
  5886. EXPECT_EQ(header_value, "");
  5887. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5888. }
  5889. // Sends a raw request and verifies that there isn't a crash or exception.
  5890. static void test_raw_request(const std::string &req,
  5891. std::string *out = nullptr) {
  5892. Server svr;
  5893. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5894. res.set_content("ok", "text/plain");
  5895. });
  5896. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5897. res.set_content("ok", "text/plain");
  5898. });
  5899. svr.Get("/header_field_value_check",
  5900. [&](const Request & /*req*/, Response &res) {
  5901. res.set_content("ok", "text/plain");
  5902. });
  5903. // Server read timeout must be longer than the client read timeout for the
  5904. // bug to reproduce, probably to force the server to process a request
  5905. // without a trailing blank line.
  5906. const time_t client_read_timeout_sec = 1;
  5907. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5908. bool listen_thread_ok = false;
  5909. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5910. auto se = detail::scope_exit([&] {
  5911. svr.stop();
  5912. t.join();
  5913. ASSERT_FALSE(svr.is_running());
  5914. EXPECT_TRUE(listen_thread_ok);
  5915. });
  5916. svr.wait_until_ready();
  5917. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5918. }
  5919. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5920. // A certain header line causes an exception if the header property is parsed
  5921. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5922. test_raw_request(
  5923. "GET /hi HTTP/1.1\r\n"
  5924. " : "
  5925. " "
  5926. " ");
  5927. }
  5928. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5929. // A certain header line causes an exception if the header property *name* is
  5930. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5931. // greedy matcher and requires backtracking when there are a lot of ":"
  5932. // characters.
  5933. // This occurs with libc++ but not libstdc++.
  5934. test_raw_request(
  5935. "GET /hi HTTP/1.1\r\n"
  5936. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5937. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5938. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5939. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5940. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5941. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5942. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5943. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5944. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5945. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5946. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5947. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5948. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5949. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5950. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5951. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5952. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5953. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5954. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5955. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5956. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5957. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5958. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5959. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5960. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5961. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5962. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5963. "&&&%%%");
  5964. }
  5965. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5966. // Make sure this doesn't crash the server.
  5967. // In a previous version of the header line regex, the "\r" rendered the line
  5968. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5969. // a new position where the leading white space ended and the field value
  5970. // began.
  5971. // The crash occurs with libc++ but not libstdc++.
  5972. test_raw_request("GET /hi HTTP/1.1\r\n"
  5973. "a:" +
  5974. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5975. "\r\n"
  5976. "\r\n");
  5977. }
  5978. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5979. std::string out;
  5980. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5981. "Content-Type: text/plain\r\n"
  5982. "Transfer-Encoding: chunked\r\n"
  5983. "\r\n"
  5984. "nothex\r\n",
  5985. &out);
  5986. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5987. }
  5988. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5989. std::string out;
  5990. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5991. "Content-Type: text/plain\r\n"
  5992. "Transfer-Encoding: chunked\r\n"
  5993. "\r\n"
  5994. "3\r\n"
  5995. "xyz\r\n"
  5996. "NaN\r\n",
  5997. &out);
  5998. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5999. }
  6000. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6001. std::string out;
  6002. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6003. "Content-Type: text/plain\r\n"
  6004. "Transfer-Encoding: chunked\r\n"
  6005. "\r\n"
  6006. // Length is too large for 64 bits.
  6007. "1ffffffffffffffff\r\n"
  6008. "xyz\r\n",
  6009. &out);
  6010. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6011. }
  6012. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6013. test_raw_request("GET /hi HTTP/1.1\r\n"
  6014. "Content-Type: text/plain\r\n\r");
  6015. }
  6016. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6017. std::string out;
  6018. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6019. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6020. }
  6021. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6022. Server svr;
  6023. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6024. EXPECT_TRUE(!req.remote_addr.empty());
  6025. });
  6026. thread t = thread([&] { svr.listen(HOST, PORT); });
  6027. auto se = detail::scope_exit([&] {
  6028. svr.stop();
  6029. t.join();
  6030. ASSERT_FALSE(svr.is_running());
  6031. });
  6032. svr.wait_until_ready();
  6033. // Send an invalid request line to trigger Bad Request
  6034. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6035. std::string out;
  6036. ASSERT_TRUE(send_request(5, bad_req, &out));
  6037. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6038. }
  6039. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6040. std::string out;
  6041. std::string request(
  6042. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6043. test_raw_request(request, &out);
  6044. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6045. }
  6046. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6047. std::string out;
  6048. std::string request(
  6049. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6050. test_raw_request(request, &out);
  6051. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6052. }
  6053. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6054. std::string out;
  6055. std::string request(
  6056. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6057. test_raw_request(request, &out);
  6058. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6059. }
  6060. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6061. std::string out;
  6062. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6063. "Test: \r\n\r\n",
  6064. &out);
  6065. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6066. }
  6067. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6068. Server svr;
  6069. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6070. res.set_header("Cache-Control", "no-cache");
  6071. res.set_chunked_content_provider(
  6072. "text/event-stream", [](size_t offset, DataSink &sink) {
  6073. std::string s = "data:";
  6074. s += std::to_string(offset);
  6075. s += "\n\n";
  6076. auto ret = sink.write(s.data(), s.size());
  6077. EXPECT_TRUE(ret);
  6078. std::this_thread::sleep_for(std::chrono::seconds(1));
  6079. return true;
  6080. });
  6081. });
  6082. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6083. svr.wait_until_ready();
  6084. Client client(HOST, PORT);
  6085. const Headers headers = {{"Accept", "text/event-stream"}};
  6086. auto get_thread = std::thread([&client, &headers]() {
  6087. auto res = client.Get(
  6088. "/events", headers,
  6089. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6090. });
  6091. auto se = detail::scope_exit([&] {
  6092. svr.stop();
  6093. get_thread.join();
  6094. listen_thread.join();
  6095. ASSERT_FALSE(svr.is_running());
  6096. });
  6097. // Give GET time to get a few messages.
  6098. std::this_thread::sleep_for(std::chrono::seconds(2));
  6099. }
  6100. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6101. httplib::Server svr;
  6102. svr.Post("/hi",
  6103. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6104. res.status = StatusCode::OK_200;
  6105. });
  6106. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6107. svr.wait_until_ready();
  6108. Client cli(HOST, PORT);
  6109. auto res = cli.Post("/hi", "data", "text/plain");
  6110. ASSERT_TRUE(res);
  6111. EXPECT_EQ(StatusCode::OK_200, res->status);
  6112. svr.stop();
  6113. thread.join();
  6114. ASSERT_FALSE(svr.is_running());
  6115. res = cli.Post("/hi", "data", "text/plain");
  6116. ASSERT_FALSE(res);
  6117. }
  6118. TEST(ServerStopTest, ListenFailure) {
  6119. Server svr;
  6120. auto t = thread([&]() {
  6121. auto ret = svr.listen("????", PORT);
  6122. EXPECT_FALSE(ret);
  6123. });
  6124. svr.wait_until_ready();
  6125. svr.stop();
  6126. t.join();
  6127. }
  6128. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6129. TEST(ServerStopTest, Decommision) {
  6130. Server svr;
  6131. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6132. for (int i = 0; i < 4; i++) {
  6133. auto is_even = !(i % 2);
  6134. std::thread t{[&] {
  6135. try {
  6136. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6137. if (is_even) {
  6138. throw std::runtime_error("Some thing that happens to go wrong.");
  6139. }
  6140. svr.listen(HOST, PORT);
  6141. } catch (...) { svr.decommission(); }
  6142. }};
  6143. svr.wait_until_ready();
  6144. // Server is up
  6145. {
  6146. Client cli(HOST, PORT);
  6147. auto res = cli.Get("/hi");
  6148. if (is_even) {
  6149. EXPECT_FALSE(res);
  6150. } else {
  6151. EXPECT_TRUE(res);
  6152. EXPECT_EQ("hi...", res->body);
  6153. }
  6154. }
  6155. svr.stop();
  6156. t.join();
  6157. // Server is down...
  6158. {
  6159. Client cli(HOST, PORT);
  6160. auto res = cli.Get("/hi");
  6161. EXPECT_FALSE(res);
  6162. }
  6163. }
  6164. }
  6165. #endif
  6166. // Helper function for string body upload progress tests
  6167. template <typename SetupHandler, typename ClientCall>
  6168. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6169. ClientCall &&client_call,
  6170. const string &body) {
  6171. Server svr;
  6172. setup_handler(svr);
  6173. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6174. auto se = detail::scope_exit([&] {
  6175. svr.stop();
  6176. t.join();
  6177. });
  6178. svr.wait_until_ready();
  6179. Client cli(HOST, PORT);
  6180. vector<uint64_t> progress_values;
  6181. bool progress_called = false;
  6182. auto res =
  6183. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6184. progress_values.push_back(current);
  6185. progress_called = true;
  6186. return true;
  6187. });
  6188. ASSERT_TRUE(res);
  6189. EXPECT_EQ(200, res->status);
  6190. EXPECT_TRUE(progress_called);
  6191. }
  6192. TEST(UploadProgressTest, PostStringBodyBasic) {
  6193. TestStringBodyUploadProgress(
  6194. [](Server &svr) {
  6195. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6196. res.set_content("received", "text/plain");
  6197. });
  6198. },
  6199. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6200. return cli.Post("/test", body, "text/plain", progress_callback);
  6201. },
  6202. "test data for upload progress");
  6203. }
  6204. TEST(UploadProgressTest, PutStringBodyBasic) {
  6205. TestStringBodyUploadProgress(
  6206. [](Server &svr) {
  6207. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6208. res.set_content("put received", "text/plain");
  6209. });
  6210. },
  6211. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6212. return cli.Put("/test", body, "text/plain", progress_callback);
  6213. },
  6214. "put test data for upload progress");
  6215. }
  6216. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6217. TestStringBodyUploadProgress(
  6218. [](Server &svr) {
  6219. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6220. res.set_content("patch received", "text/plain");
  6221. });
  6222. },
  6223. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6224. return cli.Patch("/test", body, "text/plain", progress_callback);
  6225. },
  6226. "patch test data for upload progress");
  6227. }
  6228. // Helper function for content provider upload progress tests
  6229. template <typename SetupHandler, typename ClientCall>
  6230. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6231. ClientCall &&client_call) {
  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. auto res =
  6243. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6244. progress_values.push_back(current);
  6245. return true;
  6246. });
  6247. ASSERT_TRUE(res);
  6248. EXPECT_EQ(200, res->status);
  6249. EXPECT_FALSE(progress_values.empty());
  6250. }
  6251. TEST(UploadProgressTest, PostContentProviderProgress) {
  6252. TestContentProviderUploadProgress(
  6253. [](Server &svr) {
  6254. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6255. res.set_content("provider received", "text/plain");
  6256. });
  6257. },
  6258. [](Client &cli, UploadProgress progress_callback) {
  6259. return cli.Post(
  6260. "/test", 10,
  6261. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6262. sink.os << "test data";
  6263. return true;
  6264. },
  6265. "text/plain", progress_callback);
  6266. });
  6267. }
  6268. // Helper function for multipart upload progress tests
  6269. template <typename SetupHandler, typename ClientCall>
  6270. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6271. ClientCall &&client_call,
  6272. const string &endpoint) {
  6273. Server svr;
  6274. setup_handler(svr);
  6275. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6276. auto se = detail::scope_exit([&] {
  6277. svr.stop();
  6278. t.join();
  6279. });
  6280. svr.wait_until_ready();
  6281. Client cli(HOST, PORT);
  6282. vector<uint64_t> progress_values;
  6283. UploadFormDataItems items = {
  6284. {"field1", "value1", "", ""},
  6285. {"field2", "longer value for progress tracking test", "", ""},
  6286. {"file1", "file content data for upload progress", "test.txt",
  6287. "text/plain"}};
  6288. auto res = client_call(cli, endpoint, items,
  6289. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6290. progress_values.push_back(current);
  6291. return true;
  6292. });
  6293. ASSERT_TRUE(res);
  6294. EXPECT_EQ(200, res->status);
  6295. EXPECT_FALSE(progress_values.empty());
  6296. }
  6297. TEST(UploadProgressTest, PostMultipartProgress) {
  6298. TestMultipartUploadProgress(
  6299. [](Server &svr) {
  6300. svr.Post("/multipart", [](const Request &req, Response &res) {
  6301. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6302. res.set_content("multipart received", "text/plain");
  6303. });
  6304. },
  6305. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6306. UploadProgress progress_callback) {
  6307. return cli.Post(endpoint, items, progress_callback);
  6308. },
  6309. "/multipart");
  6310. }
  6311. // Helper function for basic download progress tests
  6312. template <typename SetupHandler, typename ClientCall>
  6313. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6314. ClientCall &&client_call, const string &endpoint,
  6315. size_t expected_content_size) {
  6316. Server svr;
  6317. setup_handler(svr);
  6318. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6319. auto se = detail::scope_exit([&] {
  6320. svr.stop();
  6321. t.join();
  6322. });
  6323. svr.wait_until_ready();
  6324. Client cli(HOST, PORT);
  6325. vector<uint64_t> progress_values;
  6326. auto res = client_call(cli, endpoint,
  6327. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6328. progress_values.push_back(current);
  6329. return true;
  6330. });
  6331. ASSERT_TRUE(res);
  6332. EXPECT_EQ(200, res->status);
  6333. EXPECT_FALSE(progress_values.empty());
  6334. EXPECT_EQ(expected_content_size, res->body.size());
  6335. }
  6336. TEST(DownloadProgressTest, GetBasic) {
  6337. TestBasicDownloadProgress(
  6338. [](Server &svr) {
  6339. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6340. string content(1000, 'D');
  6341. res.set_content(content, "text/plain");
  6342. });
  6343. },
  6344. [](Client &cli, const string &endpoint,
  6345. DownloadProgress progress_callback) {
  6346. return cli.Get(endpoint, progress_callback);
  6347. },
  6348. "/download", 1000u);
  6349. }
  6350. // Helper function for content receiver download progress tests
  6351. template <typename SetupHandler, typename ClientCall>
  6352. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6353. ClientCall &&client_call,
  6354. const string &endpoint,
  6355. size_t expected_content_size) {
  6356. Server svr;
  6357. setup_handler(svr);
  6358. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6359. auto se = detail::scope_exit([&] {
  6360. svr.stop();
  6361. t.join();
  6362. });
  6363. svr.wait_until_ready();
  6364. Client cli(HOST, PORT);
  6365. vector<uint64_t> progress_values;
  6366. string received_body;
  6367. auto res = client_call(
  6368. cli, endpoint,
  6369. [&](const char *data, size_t data_length) -> bool {
  6370. received_body.append(data, data_length);
  6371. return true;
  6372. },
  6373. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6374. progress_values.push_back(current);
  6375. return true;
  6376. });
  6377. ASSERT_TRUE(res);
  6378. EXPECT_EQ(200, res->status);
  6379. EXPECT_FALSE(progress_values.empty());
  6380. EXPECT_EQ(expected_content_size, received_body.size());
  6381. EXPECT_TRUE(res->body.empty());
  6382. }
  6383. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6384. TestContentReceiverDownloadProgress(
  6385. [](Server &svr) {
  6386. svr.Get("/download-receiver",
  6387. [](const Request & /*req*/, Response &res) {
  6388. string content(2000, 'R');
  6389. res.set_content(content, "text/plain");
  6390. });
  6391. },
  6392. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6393. DownloadProgress progress_callback) {
  6394. return cli.Get(endpoint, content_receiver, progress_callback);
  6395. },
  6396. "/download-receiver", 2000u);
  6397. }
  6398. TEST(StreamingTest, NoContentLengthStreaming) {
  6399. Server svr;
  6400. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6401. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6402. if (offset < 6) {
  6403. sink.os << (offset < 3 ? "a" : "b");
  6404. } else {
  6405. sink.done();
  6406. }
  6407. return true;
  6408. });
  6409. });
  6410. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6411. auto listen_se = detail::scope_exit([&] {
  6412. svr.stop();
  6413. listen_thread.join();
  6414. ASSERT_FALSE(svr.is_running());
  6415. });
  6416. svr.wait_until_ready();
  6417. Client client(HOST, PORT);
  6418. auto get_thread = std::thread([&client]() {
  6419. std::string s;
  6420. auto res =
  6421. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6422. s += std::string(data, len);
  6423. return true;
  6424. });
  6425. ASSERT_TRUE(res);
  6426. EXPECT_EQ(StatusCode::OK_200, res->status);
  6427. EXPECT_EQ("aaabbb", s);
  6428. });
  6429. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6430. // Give GET time to get a few messages.
  6431. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6432. }
  6433. TEST(MountTest, Unmount) {
  6434. Server svr;
  6435. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6436. auto se = detail::scope_exit([&] {
  6437. svr.stop();
  6438. listen_thread.join();
  6439. ASSERT_FALSE(svr.is_running());
  6440. });
  6441. svr.wait_until_ready();
  6442. Client cli("localhost", PORT);
  6443. svr.set_mount_point("/mount2", "./www2");
  6444. auto res = cli.Get("/");
  6445. ASSERT_TRUE(res);
  6446. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6447. res = cli.Get("/mount2/dir/test.html");
  6448. ASSERT_TRUE(res);
  6449. EXPECT_EQ(StatusCode::OK_200, res->status);
  6450. svr.set_mount_point("/", "./www");
  6451. res = cli.Get("/dir/");
  6452. ASSERT_TRUE(res);
  6453. EXPECT_EQ(StatusCode::OK_200, res->status);
  6454. svr.remove_mount_point("/");
  6455. res = cli.Get("/dir/");
  6456. ASSERT_TRUE(res);
  6457. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6458. svr.remove_mount_point("/mount2");
  6459. res = cli.Get("/mount2/dir/test.html");
  6460. ASSERT_TRUE(res);
  6461. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6462. }
  6463. TEST(MountTest, Redicect) {
  6464. Server svr;
  6465. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6466. auto se = detail::scope_exit([&] {
  6467. svr.stop();
  6468. listen_thread.join();
  6469. ASSERT_FALSE(svr.is_running());
  6470. });
  6471. svr.set_mount_point("/", "./www");
  6472. svr.wait_until_ready();
  6473. Client cli("localhost", PORT);
  6474. auto res = cli.Get("/dir/");
  6475. ASSERT_TRUE(res);
  6476. EXPECT_EQ(StatusCode::OK_200, res->status);
  6477. res = cli.Get("/dir");
  6478. ASSERT_TRUE(res);
  6479. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6480. res = cli.Get("/file");
  6481. ASSERT_TRUE(res);
  6482. EXPECT_EQ(StatusCode::OK_200, res->status);
  6483. res = cli.Get("/file/");
  6484. ASSERT_TRUE(res);
  6485. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6486. cli.set_follow_location(true);
  6487. res = cli.Get("/dir");
  6488. ASSERT_TRUE(res);
  6489. EXPECT_EQ(StatusCode::OK_200, res->status);
  6490. }
  6491. TEST(MountTest, MultibytesPathName) {
  6492. Server svr;
  6493. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6494. auto se = detail::scope_exit([&] {
  6495. svr.stop();
  6496. listen_thread.join();
  6497. ASSERT_FALSE(svr.is_running());
  6498. });
  6499. svr.set_mount_point("/", "./www");
  6500. svr.wait_until_ready();
  6501. Client cli("localhost", PORT);
  6502. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6503. ASSERT_TRUE(res);
  6504. EXPECT_EQ(StatusCode::OK_200, res->status);
  6505. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6506. }
  6507. TEST(KeepAliveTest, ReadTimeout) {
  6508. Server svr;
  6509. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6510. std::this_thread::sleep_for(std::chrono::seconds(2));
  6511. res.set_content("a", "text/plain");
  6512. });
  6513. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6514. res.set_content("b", "text/plain");
  6515. });
  6516. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6517. auto se = detail::scope_exit([&] {
  6518. svr.stop();
  6519. listen_thread.join();
  6520. ASSERT_FALSE(svr.is_running());
  6521. });
  6522. svr.wait_until_ready();
  6523. Client cli("localhost", PORT);
  6524. cli.set_keep_alive(true);
  6525. cli.set_read_timeout(std::chrono::seconds(1));
  6526. auto resa = cli.Get("/a");
  6527. ASSERT_FALSE(resa);
  6528. EXPECT_EQ(Error::Read, resa.error());
  6529. auto resb = cli.Get("/b");
  6530. ASSERT_TRUE(resb);
  6531. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6532. EXPECT_EQ("b", resb->body);
  6533. }
  6534. TEST(KeepAliveTest, MaxCount) {
  6535. size_t keep_alive_max_count = 3;
  6536. Server svr;
  6537. svr.set_keep_alive_max_count(keep_alive_max_count);
  6538. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6539. res.set_content("Hello World!", "text/plain");
  6540. });
  6541. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6542. auto se = detail::scope_exit([&] {
  6543. svr.stop();
  6544. listen_thread.join();
  6545. ASSERT_FALSE(svr.is_running());
  6546. });
  6547. svr.wait_until_ready();
  6548. Client cli(HOST, PORT);
  6549. cli.set_keep_alive(true);
  6550. for (size_t i = 0; i < 5; i++) {
  6551. auto result = cli.Get("/hi");
  6552. ASSERT_TRUE(result);
  6553. EXPECT_EQ(StatusCode::OK_200, result->status);
  6554. if (i == keep_alive_max_count - 1) {
  6555. EXPECT_EQ("close", result->get_header_value("Connection"));
  6556. } else {
  6557. EXPECT_FALSE(result->has_header("Connection"));
  6558. }
  6559. }
  6560. }
  6561. TEST(KeepAliveTest, Issue1041) {
  6562. Server svr;
  6563. svr.set_keep_alive_timeout(3);
  6564. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6565. res.set_content("Hello World!", "text/plain");
  6566. });
  6567. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6568. auto se = detail::scope_exit([&] {
  6569. svr.stop();
  6570. listen_thread.join();
  6571. ASSERT_FALSE(svr.is_running());
  6572. });
  6573. svr.wait_until_ready();
  6574. Client cli(HOST, PORT);
  6575. cli.set_keep_alive(true);
  6576. auto result = cli.Get("/hi");
  6577. ASSERT_TRUE(result);
  6578. EXPECT_EQ(StatusCode::OK_200, result->status);
  6579. std::this_thread::sleep_for(std::chrono::seconds(5));
  6580. result = cli.Get("/hi");
  6581. ASSERT_TRUE(result);
  6582. EXPECT_EQ(StatusCode::OK_200, result->status);
  6583. }
  6584. TEST(KeepAliveTest, Issue1959) {
  6585. Server svr;
  6586. svr.set_keep_alive_timeout(5);
  6587. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6588. res.set_content("a", "text/plain");
  6589. });
  6590. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6591. auto se = detail::scope_exit([&] {
  6592. if (!svr.is_running()) return;
  6593. svr.stop();
  6594. listen_thread.join();
  6595. ASSERT_FALSE(svr.is_running());
  6596. });
  6597. svr.wait_until_ready();
  6598. Client cli("localhost", PORT);
  6599. cli.set_keep_alive(true);
  6600. using namespace std::chrono;
  6601. auto start = steady_clock::now();
  6602. cli.Get("/a");
  6603. svr.stop();
  6604. listen_thread.join();
  6605. auto end = steady_clock::now();
  6606. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6607. EXPECT_LT(elapsed, 5000);
  6608. }
  6609. #ifdef CPPHTTPLIB_SSL_ENABLED
  6610. TEST(KeepAliveTest, SSLClientReconnection) {
  6611. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6612. ASSERT_TRUE(svr.is_valid());
  6613. svr.set_keep_alive_timeout(1);
  6614. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6615. res.set_content("Hello World!", "text/plain");
  6616. });
  6617. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6618. auto se = detail::scope_exit([&] {
  6619. svr.stop();
  6620. listen_thread.join();
  6621. ASSERT_FALSE(svr.is_running());
  6622. });
  6623. svr.wait_until_ready();
  6624. SSLClient cli(HOST, PORT);
  6625. cli.enable_server_certificate_verification(false);
  6626. cli.set_keep_alive(true);
  6627. auto result = cli.Get("/hi");
  6628. ASSERT_TRUE(result);
  6629. EXPECT_EQ(StatusCode::OK_200, result->status);
  6630. result = cli.Get("/hi");
  6631. ASSERT_TRUE(result);
  6632. EXPECT_EQ(StatusCode::OK_200, result->status);
  6633. std::this_thread::sleep_for(std::chrono::seconds(2));
  6634. // Recoonect
  6635. result = cli.Get("/hi");
  6636. ASSERT_TRUE(result);
  6637. EXPECT_EQ(StatusCode::OK_200, result->status);
  6638. result = cli.Get("/hi");
  6639. ASSERT_TRUE(result);
  6640. EXPECT_EQ(StatusCode::OK_200, result->status);
  6641. }
  6642. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6643. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6644. ASSERT_TRUE(svr.is_valid());
  6645. svr.set_keep_alive_timeout(1);
  6646. std::string content = "reconnect";
  6647. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6648. res.set_content("Hello World!", "text/plain");
  6649. });
  6650. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6651. auto se = detail::scope_exit([&] {
  6652. svr.stop();
  6653. listen_thread.join();
  6654. ASSERT_FALSE(svr.is_running());
  6655. });
  6656. svr.wait_until_ready();
  6657. SSLClient cli(HOST, PORT);
  6658. cli.enable_server_certificate_verification(false);
  6659. cli.set_keep_alive(true);
  6660. auto result = cli.Post(
  6661. "/hi", content.size(),
  6662. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6663. sink.write(content.c_str(), content.size());
  6664. return true;
  6665. },
  6666. "text/plain");
  6667. ASSERT_TRUE(result);
  6668. EXPECT_EQ(200, result->status);
  6669. std::this_thread::sleep_for(std::chrono::seconds(2));
  6670. // Recoonect
  6671. result = cli.Post(
  6672. "/hi", content.size(),
  6673. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6674. sink.write(content.c_str(), content.size());
  6675. return true;
  6676. },
  6677. "text/plain");
  6678. ASSERT_TRUE(result);
  6679. EXPECT_EQ(200, result->status);
  6680. result = cli.Post(
  6681. "/hi", content.size(),
  6682. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6683. sink.write(content.c_str(), content.size());
  6684. return true;
  6685. },
  6686. "text/plain");
  6687. ASSERT_TRUE(result);
  6688. EXPECT_EQ(200, result->status);
  6689. }
  6690. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6691. using namespace httplib::tls;
  6692. {
  6693. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6694. ASSERT_TRUE(svr.is_valid());
  6695. svr.Get("/sni", [&](const Request &req, Response &res) {
  6696. std::string expected = req.sni();
  6697. EXPECT_EQ(expected, req.get_param_value("expected"));
  6698. res.set_content("ok", "text/plain");
  6699. });
  6700. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6701. auto se = detail::scope_exit([&] {
  6702. svr.stop();
  6703. listen_thread.join();
  6704. ASSERT_FALSE(svr.is_running());
  6705. });
  6706. svr.wait_until_ready();
  6707. {
  6708. SSLClient cli("localhost", PORT);
  6709. cli.enable_server_certificate_verification(false);
  6710. auto res = cli.Get("/sni?expected=localhost");
  6711. ASSERT_TRUE(res);
  6712. }
  6713. {
  6714. SSLClient cli("::1", PORT);
  6715. cli.enable_server_certificate_verification(false);
  6716. auto res = cli.Get("/sni?expected=");
  6717. // NOTE: This may fail if the server is listening on IPv4 only
  6718. // (e.g., when localhost resolves to 127.0.0.1 only)
  6719. if (res) {
  6720. EXPECT_EQ(StatusCode::OK_200, res->status);
  6721. } else {
  6722. EXPECT_EQ(Error::Connection, res.error());
  6723. }
  6724. }
  6725. }
  6726. }
  6727. #endif
  6728. TEST(ClientProblemDetectionTest, ContentProvider) {
  6729. Server svr;
  6730. size_t content_length = 1024 * 1024;
  6731. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6732. res.set_content_provider(
  6733. content_length, "text/plain",
  6734. [&](size_t offset, size_t length, DataSink &sink) {
  6735. auto out_len = std::min(length, static_cast<size_t>(1024));
  6736. std::string out(out_len, '@');
  6737. sink.write(out.data(), out_len);
  6738. return offset < 4096;
  6739. },
  6740. [](bool success) { ASSERT_FALSE(success); });
  6741. });
  6742. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6743. res.set_content_provider(
  6744. 0, "text/plain",
  6745. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6746. EXPECT_TRUE(false);
  6747. return true;
  6748. },
  6749. [](bool success) { ASSERT_FALSE(success); });
  6750. });
  6751. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6752. auto se = detail::scope_exit([&] {
  6753. svr.stop();
  6754. listen_thread.join();
  6755. ASSERT_FALSE(svr.is_running());
  6756. });
  6757. svr.wait_until_ready();
  6758. Client cli("localhost", PORT);
  6759. {
  6760. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6761. size_t /*data_length*/) { return false; });
  6762. ASSERT_FALSE(res);
  6763. }
  6764. {
  6765. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6766. size_t /*data_length*/) { return false; });
  6767. ASSERT_TRUE(res);
  6768. }
  6769. }
  6770. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6771. Server svr;
  6772. svr.set_error_handler([](Request const &, Response &res) -> void {
  6773. res.set_chunked_content_provider(
  6774. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6775. sink.os << "hello";
  6776. sink.os << "world";
  6777. sink.done();
  6778. return true;
  6779. });
  6780. });
  6781. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6782. auto se = detail::scope_exit([&] {
  6783. svr.stop();
  6784. listen_thread.join();
  6785. ASSERT_FALSE(svr.is_running());
  6786. });
  6787. svr.wait_until_ready();
  6788. Client cli("localhost", PORT);
  6789. auto res = cli.Get("/");
  6790. ASSERT_TRUE(res);
  6791. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6792. EXPECT_EQ("helloworld", res->body);
  6793. }
  6794. TEST(LongPollingTest, ClientCloseDetection) {
  6795. Server svr;
  6796. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6797. res.set_chunked_content_provider(
  6798. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6799. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6800. sink.os << "hello";
  6801. auto count = 10;
  6802. while (count > 0 && sink.is_writable()) {
  6803. this_thread::sleep_for(chrono::milliseconds(10));
  6804. count--;
  6805. }
  6806. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6807. return true;
  6808. });
  6809. });
  6810. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6811. auto se = detail::scope_exit([&] {
  6812. svr.stop();
  6813. listen_thread.join();
  6814. ASSERT_FALSE(svr.is_running());
  6815. });
  6816. svr.wait_until_ready();
  6817. Client cli("localhost", PORT);
  6818. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6819. EXPECT_EQ("hello", string(data, data_length));
  6820. return false; // close the socket immediately.
  6821. });
  6822. ASSERT_FALSE(res);
  6823. }
  6824. TEST(GetWithParametersTest, GetWithParameters) {
  6825. Server svr;
  6826. svr.Get("/", [&](const Request &req, Response &) {
  6827. EXPECT_EQ("world", req.get_param_value("hello"));
  6828. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6829. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6830. });
  6831. svr.Get("/params", [&](const Request &req, Response &) {
  6832. EXPECT_EQ("world", req.get_param_value("hello"));
  6833. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6834. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6835. });
  6836. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6837. EXPECT_EQ("resource-id", req.matches[1]);
  6838. EXPECT_EQ("foo", req.get_param_value("param1"));
  6839. EXPECT_EQ("bar", req.get_param_value("param2"));
  6840. });
  6841. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6842. EXPECT_EQ("user-id", req.path_params.at("id"));
  6843. EXPECT_EQ("foo", req.get_param_value("param1"));
  6844. EXPECT_EQ("bar", req.get_param_value("param2"));
  6845. });
  6846. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6847. auto se = detail::scope_exit([&] {
  6848. svr.stop();
  6849. listen_thread.join();
  6850. ASSERT_FALSE(svr.is_running());
  6851. });
  6852. svr.wait_until_ready();
  6853. {
  6854. Client cli(HOST, PORT);
  6855. Params params;
  6856. params.emplace("hello", "world");
  6857. params.emplace("hello2", "world2");
  6858. params.emplace("hello3", "world3");
  6859. auto res = cli.Get("/", params, Headers{});
  6860. ASSERT_TRUE(res);
  6861. EXPECT_EQ(StatusCode::OK_200, res->status);
  6862. }
  6863. {
  6864. Client cli(HOST, PORT);
  6865. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6866. ASSERT_TRUE(res);
  6867. EXPECT_EQ(StatusCode::OK_200, res->status);
  6868. }
  6869. {
  6870. Client cli(HOST, PORT);
  6871. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6872. ASSERT_TRUE(res);
  6873. EXPECT_EQ(StatusCode::OK_200, res->status);
  6874. }
  6875. {
  6876. Client cli(HOST, PORT);
  6877. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6878. ASSERT_TRUE(res);
  6879. EXPECT_EQ(StatusCode::OK_200, res->status);
  6880. }
  6881. }
  6882. TEST(GetWithParametersTest, GetWithParameters2) {
  6883. Server svr;
  6884. svr.Get("/", [&](const Request &req, Response &res) {
  6885. auto text = req.get_param_value("hello");
  6886. res.set_content(text, "text/plain");
  6887. });
  6888. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6889. auto se = detail::scope_exit([&] {
  6890. svr.stop();
  6891. listen_thread.join();
  6892. ASSERT_FALSE(svr.is_running());
  6893. });
  6894. svr.wait_until_ready();
  6895. Client cli("localhost", PORT);
  6896. Params params;
  6897. params.emplace("hello", "world");
  6898. std::string body;
  6899. auto res = cli.Get("/", params, Headers{},
  6900. [&](const char *data, size_t data_length) {
  6901. body.append(data, data_length);
  6902. return true;
  6903. });
  6904. ASSERT_TRUE(res);
  6905. EXPECT_EQ(StatusCode::OK_200, res->status);
  6906. EXPECT_EQ("world", body);
  6907. }
  6908. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6909. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6910. auto host = "httpcan.org";
  6911. auto path = std::string{"/range/32"};
  6912. #else
  6913. auto host = "nghttp2.org";
  6914. auto path = std::string{"/httpbin/range/32"};
  6915. #endif
  6916. #ifdef CPPHTTPLIB_SSL_ENABLED
  6917. SSLClient cli(host);
  6918. #else
  6919. Client cli(host);
  6920. #endif
  6921. cli.set_default_headers({make_range_header({{1, 10}})});
  6922. cli.set_connection_timeout(5);
  6923. {
  6924. auto res = cli.Get(path);
  6925. ASSERT_TRUE(res);
  6926. EXPECT_EQ("bcdefghijk", res->body);
  6927. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6928. }
  6929. {
  6930. auto res = cli.Get(path);
  6931. ASSERT_TRUE(res);
  6932. EXPECT_EQ("bcdefghijk", res->body);
  6933. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6934. }
  6935. }
  6936. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6937. Server svr;
  6938. svr.set_default_headers({{"Hello", "World"}});
  6939. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6940. res.set_content("ok", "text/plain");
  6941. });
  6942. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6943. auto se = detail::scope_exit([&] {
  6944. svr.stop();
  6945. listen_thread.join();
  6946. ASSERT_FALSE(svr.is_running());
  6947. });
  6948. svr.wait_until_ready();
  6949. Client cli("localhost", PORT);
  6950. auto res = cli.Get("/");
  6951. ASSERT_TRUE(res);
  6952. EXPECT_EQ(StatusCode::OK_200, res->status);
  6953. EXPECT_EQ("ok", res->body);
  6954. EXPECT_EQ("World", res->get_header_value("Hello"));
  6955. }
  6956. #ifdef CPPHTTPLIB_SSL_ENABLED
  6957. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6958. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6959. ASSERT_TRUE(svr.is_valid());
  6960. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6961. std::this_thread::sleep_for(std::chrono::seconds(2));
  6962. res.set_content("a", "text/plain");
  6963. });
  6964. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6965. res.set_content("b", "text/plain");
  6966. });
  6967. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6968. auto se = detail::scope_exit([&] {
  6969. svr.stop();
  6970. listen_thread.join();
  6971. ASSERT_FALSE(svr.is_running());
  6972. });
  6973. svr.wait_until_ready();
  6974. SSLClient cli("localhost", PORT);
  6975. cli.enable_server_certificate_verification(false);
  6976. cli.set_keep_alive(true);
  6977. cli.set_read_timeout(std::chrono::seconds(1));
  6978. auto resa = cli.Get("/a");
  6979. ASSERT_TRUE(!resa);
  6980. EXPECT_EQ(Error::Read, resa.error());
  6981. auto resb = cli.Get("/b");
  6982. ASSERT_TRUE(resb);
  6983. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6984. EXPECT_EQ("b", resb->body);
  6985. }
  6986. #endif
  6987. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6988. protected:
  6989. ServerTestWithAI_PASSIVE()
  6990. : cli_(HOST, PORT)
  6991. #ifdef CPPHTTPLIB_SSL_ENABLED
  6992. ,
  6993. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6994. #endif
  6995. {
  6996. #ifdef CPPHTTPLIB_SSL_ENABLED
  6997. cli_.enable_server_certificate_verification(false);
  6998. #endif
  6999. }
  7000. virtual void SetUp() {
  7001. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7002. res.set_content("Hello World!", "text/plain");
  7003. });
  7004. t_ = thread(
  7005. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7006. svr_.wait_until_ready();
  7007. }
  7008. virtual void TearDown() {
  7009. svr_.stop();
  7010. t_.join();
  7011. }
  7012. #ifdef CPPHTTPLIB_SSL_ENABLED
  7013. SSLClient cli_;
  7014. SSLServer svr_;
  7015. #else
  7016. Client cli_;
  7017. Server svr_;
  7018. #endif
  7019. thread t_;
  7020. };
  7021. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7022. auto res = cli_.Get("/hi");
  7023. ASSERT_TRUE(res);
  7024. EXPECT_EQ(StatusCode::OK_200, res->status);
  7025. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7026. EXPECT_EQ("Hello World!", res->body);
  7027. }
  7028. class ServerUpDownTest : public ::testing::Test {
  7029. protected:
  7030. ServerUpDownTest() : cli_(HOST, PORT) {}
  7031. virtual void SetUp() {
  7032. t_ = thread([&]() {
  7033. svr_.bind_to_any_port(HOST);
  7034. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7035. ASSERT_TRUE(svr_.listen_after_bind());
  7036. });
  7037. svr_.wait_until_ready();
  7038. }
  7039. virtual void TearDown() {
  7040. svr_.stop();
  7041. t_.join();
  7042. }
  7043. Client cli_;
  7044. Server svr_;
  7045. thread t_;
  7046. };
  7047. TEST_F(ServerUpDownTest, QuickStartStop) {
  7048. // Should not crash, especially when run with
  7049. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7050. }
  7051. class PayloadMaxLengthTest : public ::testing::Test {
  7052. protected:
  7053. PayloadMaxLengthTest()
  7054. : cli_(HOST, PORT)
  7055. #ifdef CPPHTTPLIB_SSL_ENABLED
  7056. ,
  7057. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7058. #endif
  7059. {
  7060. #ifdef CPPHTTPLIB_SSL_ENABLED
  7061. cli_.enable_server_certificate_verification(false);
  7062. #endif
  7063. }
  7064. virtual void SetUp() {
  7065. svr_.set_payload_max_length(8);
  7066. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7067. res.set_content("test", "text/plain");
  7068. });
  7069. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7070. svr_.wait_until_ready();
  7071. }
  7072. virtual void TearDown() {
  7073. svr_.stop();
  7074. t_.join();
  7075. }
  7076. #ifdef CPPHTTPLIB_SSL_ENABLED
  7077. SSLClient cli_;
  7078. SSLServer svr_;
  7079. #else
  7080. Client cli_;
  7081. Server svr_;
  7082. #endif
  7083. thread t_;
  7084. };
  7085. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7086. auto res = cli_.Post("/test", "123456789", "text/plain");
  7087. ASSERT_TRUE(res);
  7088. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7089. res = cli_.Post("/test", "12345678", "text/plain");
  7090. ASSERT_TRUE(res);
  7091. EXPECT_EQ(StatusCode::OK_200, res->status);
  7092. }
  7093. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7094. // Test chunked encoding with payload exceeding the 8-byte limit
  7095. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7096. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7097. ASSERT_TRUE(res);
  7098. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7099. }
  7100. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7101. // Test chunked encoding with payload within the 8-byte limit
  7102. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7103. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7104. ASSERT_TRUE(res);
  7105. EXPECT_EQ(StatusCode::OK_200, res->status);
  7106. }
  7107. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7108. // Test using send_request to send chunked data exceeding payload limit
  7109. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7110. "Host: " +
  7111. std::string(HOST) + ":" + std::to_string(PORT) +
  7112. "\r\n"
  7113. "Transfer-Encoding: chunked\r\n"
  7114. "Connection: close\r\n"
  7115. "\r\n"
  7116. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7117. "0123456789\r\n"
  7118. "0\r\n" // End chunk
  7119. "\r\n";
  7120. std::string response;
  7121. bool result = send_request(1, chunked_request, &response);
  7122. if (!result) {
  7123. // If send_request fails, it might be because the server closed the
  7124. // connection due to payload limit enforcement, which is acceptable
  7125. SUCCEED()
  7126. << "Server rejected oversized chunked request (connection closed)";
  7127. } else {
  7128. // If we got a response, check if it's an error response or connection was
  7129. // closed early Short response length indicates connection was closed due to
  7130. // payload limit
  7131. if (response.length() <= 10) {
  7132. SUCCEED() << "Server closed connection for oversized chunked request";
  7133. } else {
  7134. // Check for error status codes
  7135. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7136. response.find("Payload Too Large") != std::string::npos ||
  7137. response.find("400") != std::string::npos);
  7138. }
  7139. }
  7140. }
  7141. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7142. // Test request without Content-Length header exceeding payload limit
  7143. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7144. "Host: " +
  7145. std::string(HOST) + ":" +
  7146. std::to_string(PORT) +
  7147. "\r\n"
  7148. "Connection: close\r\n"
  7149. "\r\n";
  7150. // Add payload exceeding the 8-byte limit
  7151. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7152. request_without_content_length += large_payload;
  7153. std::string response;
  7154. bool result = send_request(1, request_without_content_length, &response);
  7155. if (!result) {
  7156. // If send_request fails, server likely closed connection due to payload
  7157. // limit
  7158. SUCCEED() << "Server rejected oversized request without Content-Length "
  7159. "(connection closed)";
  7160. } else {
  7161. // Check if server responded with error or closed connection early
  7162. if (response.length() <= 10) {
  7163. SUCCEED() << "Server closed connection for oversized request without "
  7164. "Content-Length";
  7165. } else {
  7166. // Check for error status codes
  7167. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7168. response.find("Payload Too Large") != std::string::npos ||
  7169. response.find("400") != std::string::npos);
  7170. }
  7171. }
  7172. }
  7173. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7174. // Test request without Content-Length header within payload limit
  7175. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7176. "Host: " +
  7177. std::string(HOST) + ":" +
  7178. std::to_string(PORT) +
  7179. "\r\n"
  7180. "Connection: close\r\n"
  7181. "\r\n";
  7182. // Add payload within the 8-byte limit
  7183. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7184. request_without_content_length += small_payload;
  7185. std::string response;
  7186. bool result = send_request(1, request_without_content_length, &response);
  7187. // For requests without Content-Length, the server may have different behavior
  7188. // The key is that it should not reject due to payload limit for small
  7189. // payloads
  7190. if (result) {
  7191. // Check for any HTTP response (success or error, but not connection closed)
  7192. if (response.length() > 10) {
  7193. SUCCEED()
  7194. << "Server processed request without Content-Length within limit";
  7195. } else {
  7196. // Short response might indicate connection closed, which is acceptable
  7197. SUCCEED() << "Server closed connection for request without "
  7198. "Content-Length (acceptable behavior)";
  7199. }
  7200. } else {
  7201. // Connection failure might be due to protocol requirements
  7202. SUCCEED() << "Connection issue with request without Content-Length "
  7203. "(environment-specific)";
  7204. }
  7205. }
  7206. class LargePayloadMaxLengthTest : public ::testing::Test {
  7207. protected:
  7208. LargePayloadMaxLengthTest()
  7209. : cli_(HOST, PORT)
  7210. #ifdef CPPHTTPLIB_SSL_ENABLED
  7211. ,
  7212. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7213. #endif
  7214. {
  7215. #ifdef CPPHTTPLIB_SSL_ENABLED
  7216. cli_.enable_server_certificate_verification(false);
  7217. #endif
  7218. }
  7219. virtual void SetUp() {
  7220. // Set 10MB payload limit
  7221. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7222. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7223. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7224. res.set_content("Large payload test", "text/plain");
  7225. });
  7226. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7227. svr_.wait_until_ready();
  7228. }
  7229. virtual void TearDown() {
  7230. svr_.stop();
  7231. t_.join();
  7232. }
  7233. #ifdef CPPHTTPLIB_SSL_ENABLED
  7234. SSLClient cli_;
  7235. SSLServer svr_;
  7236. #else
  7237. Client cli_;
  7238. Server svr_;
  7239. #endif
  7240. thread t_;
  7241. };
  7242. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7243. // Test chunked encoding with payload within 10MB limit
  7244. std::string medium_payload(5 * 1024 * 1024,
  7245. 'A'); // 5MB payload, within 10MB limit
  7246. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7247. ASSERT_TRUE(res);
  7248. EXPECT_EQ(StatusCode::OK_200, res->status);
  7249. }
  7250. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7251. // Test chunked encoding with payload exceeding 10MB limit
  7252. std::string large_payload(12 * 1024 * 1024,
  7253. 'B'); // 12MB payload, exceeds 10MB limit
  7254. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7255. // Server may either return 413 or close the connection
  7256. if (res) {
  7257. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7258. } else {
  7259. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7260. }
  7261. }
  7262. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7263. // Test request without Content-Length header within 10MB limit
  7264. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7265. "Host: " +
  7266. std::string(HOST) + ":" +
  7267. std::to_string(PORT) +
  7268. "\r\n"
  7269. "Connection: close\r\n"
  7270. "\r\n";
  7271. // Add 1MB payload (within 10MB limit)
  7272. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7273. request_without_content_length += medium_payload;
  7274. std::string response;
  7275. bool result = send_request(5, request_without_content_length, &response);
  7276. if (result) {
  7277. // Should get a proper HTTP response for payloads within limit
  7278. if (response.length() > 10) {
  7279. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7280. "10MB limit";
  7281. } else {
  7282. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7283. "Content-Length)";
  7284. }
  7285. } else {
  7286. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7287. }
  7288. }
  7289. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7290. // Test request without Content-Length header exceeding 10MB limit
  7291. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7292. "Host: " +
  7293. std::string(HOST) + ":" +
  7294. std::to_string(PORT) +
  7295. "\r\n"
  7296. "Connection: close\r\n"
  7297. "\r\n";
  7298. // Add 12MB payload (exceeds 10MB limit)
  7299. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7300. request_without_content_length += large_payload;
  7301. std::string response;
  7302. bool result = send_request(10, request_without_content_length, &response);
  7303. if (!result) {
  7304. // Server should close connection due to payload limit
  7305. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7306. "(connection closed)";
  7307. } else {
  7308. // Check for error response
  7309. if (response.length() <= 10) {
  7310. SUCCEED()
  7311. << "Server closed connection for 12MB request exceeding 10MB limit";
  7312. } else {
  7313. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7314. response.find("Payload Too Large") != std::string::npos ||
  7315. response.find("400") != std::string::npos);
  7316. }
  7317. }
  7318. }
  7319. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7320. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7321. // path.
  7322. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7323. Server svr;
  7324. const size_t LIMIT = 64 * 1024; // 64KB
  7325. svr.set_payload_max_length(LIMIT);
  7326. size_t total = 0;
  7327. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7328. const ContentReader &content_reader) {
  7329. content_reader([&](const char * /*data*/, size_t len) {
  7330. total += len;
  7331. return true;
  7332. });
  7333. res.status = 200;
  7334. res.set_content("stream_ok", "text/plain");
  7335. });
  7336. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7337. auto se = detail::scope_exit([&] {
  7338. svr.stop();
  7339. thread.join();
  7340. ASSERT_FALSE(svr.is_running());
  7341. });
  7342. svr.wait_until_ready();
  7343. // Prepare 256KB raw data and gzip-compress it
  7344. std::string raw(256 * 1024, 'A');
  7345. std::string gz;
  7346. {
  7347. z_stream zs{};
  7348. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7349. Z_DEFAULT_STRATEGY);
  7350. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7351. zs.avail_in = static_cast<uInt>(raw.size());
  7352. char outbuf[4096];
  7353. int ret;
  7354. do {
  7355. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7356. zs.avail_out = sizeof(outbuf);
  7357. ret = deflate(&zs, Z_FINISH);
  7358. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7359. } while (ret != Z_STREAM_END);
  7360. deflateEnd(&zs);
  7361. }
  7362. Client cli(HOST, PORT);
  7363. cli.set_connection_timeout(std::chrono::seconds(5));
  7364. Headers headers = {{"Content-Encoding", "gzip"}};
  7365. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7366. "application/octet-stream");
  7367. ASSERT_TRUE(res);
  7368. // Server must reject oversized decompressed payloads with 413.
  7369. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7370. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7371. EXPECT_LE(total, LIMIT);
  7372. }
  7373. #endif
  7374. // Regression test for DoS vulnerability: a malicious server sending a response
  7375. // without Content-Length header must not cause unbounded memory consumption on
  7376. // the client side. The client should stop reading after a reasonable limit,
  7377. // similar to the server-side set_payload_max_length protection.
  7378. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7379. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7380. #ifndef _WIN32
  7381. signal(SIGPIPE, SIG_IGN);
  7382. #endif
  7383. auto server_thread = std::thread([] {
  7384. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7385. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7386. default_socket_options(srv);
  7387. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7388. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7389. sockaddr_in addr{};
  7390. addr.sin_family = AF_INET;
  7391. addr.sin_port = htons(PORT + 2);
  7392. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7393. int opt = 1;
  7394. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7395. #ifdef _WIN32
  7396. reinterpret_cast<const char *>(&opt),
  7397. #else
  7398. &opt,
  7399. #endif
  7400. sizeof(opt));
  7401. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7402. ::listen(srv, 1);
  7403. sockaddr_in cli_addr{};
  7404. socklen_t cli_len = sizeof(cli_addr);
  7405. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7406. if (cli != INVALID_SOCKET) {
  7407. char buf[4096];
  7408. ::recv(cli, buf, sizeof(buf), 0);
  7409. // Malicious response: no Content-Length, no chunked encoding
  7410. std::string response_header = "HTTP/1.1 200 OK\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. // Send 10MB of data
  7422. std::string chunk(64 * 1024, 'A');
  7423. size_t total_sent = 0;
  7424. while (total_sent < MALICIOUS_DATA_SIZE) {
  7425. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7426. auto sent = ::send(cli,
  7427. #ifdef _WIN32
  7428. static_cast<const char *>(chunk.c_str()),
  7429. static_cast<int>(to_send),
  7430. #else
  7431. chunk.c_str(), to_send,
  7432. #endif
  7433. 0);
  7434. if (sent <= 0) break;
  7435. total_sent += static_cast<size_t>(sent);
  7436. }
  7437. detail::close_socket(cli);
  7438. }
  7439. detail::close_socket(srv);
  7440. });
  7441. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7442. size_t total_read = 0;
  7443. {
  7444. Client cli("127.0.0.1", PORT + 2);
  7445. cli.set_read_timeout(5, 0);
  7446. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7447. auto stream = cli.open_stream("GET", "/malicious");
  7448. ASSERT_TRUE(stream.is_valid());
  7449. char buffer[64 * 1024];
  7450. ssize_t n;
  7451. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7452. total_read += static_cast<size_t>(n);
  7453. }
  7454. } // StreamHandle and Client destroyed here, closing the socket
  7455. server_thread.join();
  7456. // With set_payload_max_length, the client must stop reading before consuming
  7457. // all 10MB. The read loop should be cut off at or near the configured limit.
  7458. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7459. << "Client read " << total_read << " bytes, exceeding the configured "
  7460. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7461. }
  7462. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7463. // the entire response body without truncation.
  7464. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7465. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  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. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7495. "Connection: close\r\n"
  7496. "\r\n";
  7497. ::send(cli,
  7498. #ifdef _WIN32
  7499. static_cast<const char *>(response_header.c_str()),
  7500. static_cast<int>(response_header.size()),
  7501. #else
  7502. response_header.c_str(), response_header.size(),
  7503. #endif
  7504. 0);
  7505. std::string chunk(64 * 1024, 'A');
  7506. size_t total_sent = 0;
  7507. while (total_sent < DATA_SIZE) {
  7508. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7509. auto sent = ::send(cli,
  7510. #ifdef _WIN32
  7511. static_cast<const char *>(chunk.c_str()),
  7512. static_cast<int>(to_send),
  7513. #else
  7514. chunk.c_str(), to_send,
  7515. #endif
  7516. 0);
  7517. if (sent <= 0) break;
  7518. total_sent += static_cast<size_t>(sent);
  7519. }
  7520. #ifdef _WIN32
  7521. ::shutdown(cli, SD_SEND);
  7522. #else
  7523. ::shutdown(cli, SHUT_WR);
  7524. #endif
  7525. // Drain until the client closes its end, ensuring all data is delivered
  7526. char drain[1024];
  7527. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7528. detail::close_socket(cli);
  7529. }
  7530. detail::close_socket(srv);
  7531. });
  7532. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7533. size_t total_read = 0;
  7534. {
  7535. Client cli("127.0.0.1", PORT + 2);
  7536. cli.set_read_timeout(5, 0);
  7537. cli.set_payload_max_length(0); // 0 means no limit
  7538. auto stream = cli.open_stream("GET", "/data");
  7539. ASSERT_TRUE(stream.is_valid());
  7540. char buffer[64 * 1024];
  7541. ssize_t n;
  7542. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7543. total_read += static_cast<size_t>(n);
  7544. }
  7545. }
  7546. server_thread.join();
  7547. EXPECT_EQ(total_read, DATA_SIZE)
  7548. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7549. << " bytes without truncation, but only read " << total_read << " bytes.";
  7550. }
  7551. // Verify that content_receiver bypasses the default payload_max_length,
  7552. // allowing streaming downloads larger than 100MB without requiring an explicit
  7553. // set_payload_max_length call.
  7554. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  7555. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7556. #ifndef _WIN32
  7557. signal(SIGPIPE, SIG_IGN);
  7558. #endif
  7559. auto server_thread = std::thread([] {
  7560. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7561. default_socket_options(srv);
  7562. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7563. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7564. sockaddr_in addr{};
  7565. addr.sin_family = AF_INET;
  7566. addr.sin_port = htons(PORT + 2);
  7567. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7568. int opt = 1;
  7569. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7570. #ifdef _WIN32
  7571. reinterpret_cast<const char *>(&opt),
  7572. #else
  7573. &opt,
  7574. #endif
  7575. sizeof(opt));
  7576. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7577. ::listen(srv, 1);
  7578. sockaddr_in cli_addr{};
  7579. socklen_t cli_len = sizeof(cli_addr);
  7580. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7581. if (cli != INVALID_SOCKET) {
  7582. char buf[4096];
  7583. ::recv(cli, buf, sizeof(buf), 0);
  7584. // Response with Content-Length larger than default 100MB limit
  7585. auto content_length = std::to_string(DATA_SIZE);
  7586. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7587. "Content-Length: " +
  7588. content_length +
  7589. "\r\n"
  7590. "Connection: close\r\n"
  7591. "\r\n";
  7592. ::send(cli,
  7593. #ifdef _WIN32
  7594. static_cast<const char *>(response_header.c_str()),
  7595. static_cast<int>(response_header.size()),
  7596. #else
  7597. response_header.c_str(), response_header.size(),
  7598. #endif
  7599. 0);
  7600. std::string chunk(64 * 1024, 'A');
  7601. size_t total_sent = 0;
  7602. while (total_sent < DATA_SIZE) {
  7603. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7604. auto sent = ::send(cli,
  7605. #ifdef _WIN32
  7606. static_cast<const char *>(chunk.c_str()),
  7607. static_cast<int>(to_send),
  7608. #else
  7609. chunk.c_str(), to_send,
  7610. #endif
  7611. 0);
  7612. if (sent <= 0) break;
  7613. total_sent += static_cast<size_t>(sent);
  7614. }
  7615. detail::close_socket(cli);
  7616. }
  7617. detail::close_socket(srv);
  7618. });
  7619. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7620. size_t total_received = 0;
  7621. {
  7622. Client cli("127.0.0.1", PORT + 2);
  7623. cli.set_read_timeout(10, 0);
  7624. // Do NOT call set_payload_max_length — use the default 100MB limit
  7625. auto res =
  7626. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7627. total_received += data_length;
  7628. return true;
  7629. });
  7630. ASSERT_TRUE(res);
  7631. EXPECT_EQ(StatusCode::OK_200, res->status);
  7632. }
  7633. server_thread.join();
  7634. EXPECT_EQ(total_received, DATA_SIZE)
  7635. << "With content_receiver, the client should read all " << DATA_SIZE
  7636. << " bytes despite the default 100MB payload_max_length, but only read "
  7637. << total_received << " bytes.";
  7638. }
  7639. // Verify that an explicit set_payload_max_length smaller than the response is
  7640. // enforced even when a content_receiver is used.
  7641. TEST(ClientVulnerabilityTest,
  7642. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  7643. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7644. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  7645. #ifndef _WIN32
  7646. signal(SIGPIPE, SIG_IGN);
  7647. #endif
  7648. auto server_thread = std::thread([] {
  7649. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7650. default_socket_options(srv);
  7651. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7652. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7653. sockaddr_in addr{};
  7654. addr.sin_family = AF_INET;
  7655. addr.sin_port = htons(PORT + 2);
  7656. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7657. int opt = 1;
  7658. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7659. #ifdef _WIN32
  7660. reinterpret_cast<const char *>(&opt),
  7661. #else
  7662. &opt,
  7663. #endif
  7664. sizeof(opt));
  7665. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7666. ::listen(srv, 1);
  7667. sockaddr_in cli_addr{};
  7668. socklen_t cli_len = sizeof(cli_addr);
  7669. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7670. if (cli != INVALID_SOCKET) {
  7671. char buf[4096];
  7672. ::recv(cli, buf, sizeof(buf), 0);
  7673. auto content_length = std::to_string(DATA_SIZE);
  7674. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7675. "Content-Length: " +
  7676. content_length +
  7677. "\r\n"
  7678. "Connection: close\r\n"
  7679. "\r\n";
  7680. ::send(cli,
  7681. #ifdef _WIN32
  7682. static_cast<const char *>(response_header.c_str()),
  7683. static_cast<int>(response_header.size()),
  7684. #else
  7685. response_header.c_str(), response_header.size(),
  7686. #endif
  7687. 0);
  7688. std::string chunk(64 * 1024, 'A');
  7689. size_t total_sent = 0;
  7690. while (total_sent < DATA_SIZE) {
  7691. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7692. auto sent = ::send(cli,
  7693. #ifdef _WIN32
  7694. static_cast<const char *>(chunk.c_str()),
  7695. static_cast<int>(to_send),
  7696. #else
  7697. chunk.c_str(), to_send,
  7698. #endif
  7699. 0);
  7700. if (sent <= 0) break;
  7701. total_sent += static_cast<size_t>(sent);
  7702. }
  7703. detail::close_socket(cli);
  7704. }
  7705. detail::close_socket(srv);
  7706. });
  7707. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7708. size_t total_received = 0;
  7709. {
  7710. Client cli("127.0.0.1", PORT + 2);
  7711. cli.set_read_timeout(10, 0);
  7712. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  7713. auto res =
  7714. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7715. total_received += data_length;
  7716. return true;
  7717. });
  7718. // Should fail because 200MB exceeds the explicit 150MB limit
  7719. EXPECT_FALSE(res);
  7720. }
  7721. server_thread.join();
  7722. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  7723. << "Client with content_receiver should respect the explicit "
  7724. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  7725. << total_received << " bytes.";
  7726. }
  7727. // Verify that an explicit set_payload_max_length larger than the response
  7728. // allows the content_receiver to read all data successfully.
  7729. TEST(ClientVulnerabilityTest,
  7730. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  7731. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7732. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  7733. #ifndef _WIN32
  7734. signal(SIGPIPE, SIG_IGN);
  7735. #endif
  7736. auto server_thread = std::thread([] {
  7737. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7738. default_socket_options(srv);
  7739. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7740. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7741. sockaddr_in addr{};
  7742. addr.sin_family = AF_INET;
  7743. addr.sin_port = htons(PORT + 2);
  7744. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7745. int opt = 1;
  7746. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7747. #ifdef _WIN32
  7748. reinterpret_cast<const char *>(&opt),
  7749. #else
  7750. &opt,
  7751. #endif
  7752. sizeof(opt));
  7753. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7754. ::listen(srv, 1);
  7755. sockaddr_in cli_addr{};
  7756. socklen_t cli_len = sizeof(cli_addr);
  7757. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7758. if (cli != INVALID_SOCKET) {
  7759. char buf[4096];
  7760. ::recv(cli, buf, sizeof(buf), 0);
  7761. auto content_length = std::to_string(DATA_SIZE);
  7762. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7763. "Content-Length: " +
  7764. content_length +
  7765. "\r\n"
  7766. "Connection: close\r\n"
  7767. "\r\n";
  7768. ::send(cli,
  7769. #ifdef _WIN32
  7770. static_cast<const char *>(response_header.c_str()),
  7771. static_cast<int>(response_header.size()),
  7772. #else
  7773. response_header.c_str(), response_header.size(),
  7774. #endif
  7775. 0);
  7776. std::string chunk(64 * 1024, 'A');
  7777. size_t total_sent = 0;
  7778. while (total_sent < DATA_SIZE) {
  7779. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7780. auto sent = ::send(cli,
  7781. #ifdef _WIN32
  7782. static_cast<const char *>(chunk.c_str()),
  7783. static_cast<int>(to_send),
  7784. #else
  7785. chunk.c_str(), to_send,
  7786. #endif
  7787. 0);
  7788. if (sent <= 0) break;
  7789. total_sent += static_cast<size_t>(sent);
  7790. }
  7791. #ifdef _WIN32
  7792. ::shutdown(cli, SD_SEND);
  7793. #else
  7794. ::shutdown(cli, SHUT_WR);
  7795. #endif
  7796. char drain[1024];
  7797. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7798. detail::close_socket(cli);
  7799. }
  7800. detail::close_socket(srv);
  7801. });
  7802. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7803. size_t total_received = 0;
  7804. {
  7805. Client cli("127.0.0.1", PORT + 2);
  7806. cli.set_read_timeout(10, 0);
  7807. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  7808. auto res =
  7809. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7810. total_received += data_length;
  7811. return true;
  7812. });
  7813. ASSERT_TRUE(res);
  7814. EXPECT_EQ(StatusCode::OK_200, res->status);
  7815. }
  7816. server_thread.join();
  7817. EXPECT_EQ(total_received, DATA_SIZE)
  7818. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  7819. << " bytes (larger than " << DATA_SIZE
  7820. << " bytes response), content_receiver should read all data, but only "
  7821. "read "
  7822. << total_received << " bytes.";
  7823. }
  7824. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  7825. // Regression test for "zip bomb" attack on the client side: a malicious server
  7826. // sends a small gzip-compressed response that decompresses to a huge payload.
  7827. // The client must enforce payload_max_length on the decompressed size.
  7828. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  7829. constexpr size_t DECOMPRESSED_SIZE =
  7830. 10 * 1024 * 1024; // 10MB after decompression
  7831. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7832. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  7833. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  7834. std::string compressed;
  7835. {
  7836. httplib::detail::gzip_compressor compressor;
  7837. bool ok =
  7838. compressor.compress(uncompressed.data(), uncompressed.size(),
  7839. /*last=*/true, [&](const char *buf, size_t len) {
  7840. compressed.append(buf, len);
  7841. return true;
  7842. });
  7843. ASSERT_TRUE(ok);
  7844. }
  7845. // Sanity: compressed data should be much smaller than the decompressed size
  7846. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  7847. #ifndef _WIN32
  7848. signal(SIGPIPE, SIG_IGN);
  7849. #endif
  7850. // Set up the listening socket in the main thread so the server is guaranteed
  7851. // to be ready before the client connects (eliminates race condition).
  7852. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7853. default_socket_options(srv);
  7854. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7855. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7856. sockaddr_in addr{};
  7857. addr.sin_family = AF_INET;
  7858. addr.sin_port = htons(PORT + 3);
  7859. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7860. int opt = 1;
  7861. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7862. #ifdef _WIN32
  7863. reinterpret_cast<const char *>(&opt),
  7864. #else
  7865. &opt,
  7866. #endif
  7867. sizeof(opt));
  7868. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  7869. ASSERT_EQ(0, ::listen(srv, 1));
  7870. auto server_thread = std::thread([&compressed, srv] {
  7871. sockaddr_in cli_addr{};
  7872. socklen_t cli_len = sizeof(cli_addr);
  7873. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7874. if (cli != INVALID_SOCKET) {
  7875. // Read the full HTTP request (until \r\n\r\n)
  7876. char buf[4096];
  7877. size_t total = 0;
  7878. while (total < sizeof(buf)) {
  7879. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  7880. if (n <= 0) break;
  7881. total += static_cast<size_t>(n);
  7882. // Check for end of headers
  7883. if (total >= 4) {
  7884. std::string req(buf, total);
  7885. if (req.find("\r\n\r\n") != std::string::npos) break;
  7886. }
  7887. }
  7888. // Malicious response: gzip-compressed body, no Content-Length
  7889. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7890. "Content-Encoding: gzip\r\n"
  7891. "Connection: close\r\n"
  7892. "\r\n";
  7893. ::send(cli,
  7894. #ifdef _WIN32
  7895. static_cast<const char *>(response_header.c_str()),
  7896. static_cast<int>(response_header.size()),
  7897. #else
  7898. response_header.c_str(), response_header.size(),
  7899. #endif
  7900. 0);
  7901. // Send the compressed payload (small on the wire, huge when decompressed)
  7902. size_t total_sent = 0;
  7903. while (total_sent < compressed.size()) {
  7904. auto to_send = std::min(compressed.size() - total_sent,
  7905. static_cast<size_t>(64 * 1024));
  7906. auto sent =
  7907. ::send(cli,
  7908. #ifdef _WIN32
  7909. static_cast<const char *>(compressed.c_str() + total_sent),
  7910. static_cast<int>(to_send),
  7911. #else
  7912. compressed.c_str() + total_sent, to_send,
  7913. #endif
  7914. 0);
  7915. if (sent <= 0) break;
  7916. total_sent += static_cast<size_t>(sent);
  7917. }
  7918. detail::close_socket(cli);
  7919. }
  7920. });
  7921. auto se = detail::scope_exit([&] {
  7922. detail::close_socket(srv);
  7923. server_thread.join();
  7924. });
  7925. size_t total_decompressed = 0;
  7926. {
  7927. Client cli("127.0.0.1", PORT + 3);
  7928. cli.set_read_timeout(5, 0);
  7929. cli.set_decompress(true);
  7930. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7931. auto stream = cli.open_stream("GET", "/zipbomb");
  7932. ASSERT_TRUE(stream.is_valid());
  7933. char buffer[64 * 1024];
  7934. ssize_t n;
  7935. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7936. total_decompressed += static_cast<size_t>(n);
  7937. }
  7938. }
  7939. // The decompressed size must be capped by payload_max_length. Without
  7940. // protection, the client would decompress the full 10MB from a tiny
  7941. // compressed payload, enabling a zip bomb DoS attack.
  7942. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  7943. << "Client decompressed " << total_decompressed
  7944. << " bytes from a gzip response. The decompressed size should be "
  7945. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  7946. }
  7947. #endif
  7948. TEST(HostAndPortPropertiesTest, NoSSL) {
  7949. httplib::Client cli("www.google.com", 1234);
  7950. ASSERT_EQ("www.google.com", cli.host());
  7951. ASSERT_EQ(1234, cli.port());
  7952. }
  7953. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7954. httplib::Client cli("www.google.com:1234");
  7955. ASSERT_EQ("www.google.com", cli.host());
  7956. ASSERT_EQ(1234, cli.port());
  7957. }
  7958. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  7959. // Port number that overflows int — should not crash, client becomes invalid
  7960. httplib::Client cli("http://www.google.com:99999999999999999999");
  7961. ASSERT_FALSE(cli.is_valid());
  7962. }
  7963. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  7964. // Port 99999 exceeds valid range (1-65535) — should not crash
  7965. httplib::Client cli("http://www.google.com:99999");
  7966. ASSERT_FALSE(cli.is_valid());
  7967. }
  7968. #ifdef CPPHTTPLIB_SSL_ENABLED
  7969. TEST(HostAndPortPropertiesTest, SSL) {
  7970. httplib::SSLClient cli("www.google.com");
  7971. ASSERT_EQ("www.google.com", cli.host());
  7972. ASSERT_EQ(443, cli.port());
  7973. }
  7974. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  7975. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  7976. std::string cert;
  7977. read_file(CA_CERT_FILE, cert);
  7978. httplib::SSLClient httplib_client("www.google.com");
  7979. // Load CA store first time
  7980. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  7981. // Load CA store second time (update)
  7982. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  7983. // Verify client is still valid and can make connections
  7984. httplib_client.enable_server_certificate_verification(true);
  7985. auto res = httplib_client.Get("/");
  7986. ASSERT_TRUE(res);
  7987. // Google may return 200 or 301 depending on various factors
  7988. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  7989. res->status == StatusCode::MovedPermanently_301);
  7990. }
  7991. TEST(SSLClientTest, ServerNameIndication_Online) {
  7992. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7993. auto host = "httpcan.org";
  7994. auto path = std::string{"/get"};
  7995. #else
  7996. auto host = "nghttp2.org";
  7997. auto path = std::string{"/httpbin/get"};
  7998. #endif
  7999. SSLClient cli(host, 443);
  8000. auto res = cli.Get(path);
  8001. ASSERT_TRUE(res);
  8002. ASSERT_EQ(StatusCode::OK_200, res->status);
  8003. }
  8004. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8005. // Use a site that will cause SSL verification failure due to self-signed cert
  8006. SSLClient cli("self-signed.badssl.com", 443);
  8007. cli.enable_server_certificate_verification(true);
  8008. auto res = cli.Get("/");
  8009. ASSERT_TRUE(!res);
  8010. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8011. // Verify backend error is captured for SSLServerVerification
  8012. // This occurs when certificate verification fails
  8013. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8014. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8015. EXPECT_NE(0UL, res.ssl_backend_error());
  8016. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8017. // For OpenSSL, ssl_error is 0 for verification errors
  8018. EXPECT_EQ(0, res.ssl_error());
  8019. #if !defined(_WIN32) || \
  8020. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8021. // On non-Windows or when Windows Schannel is disabled, the error comes
  8022. // from OpenSSL's verification
  8023. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8024. res.ssl_backend_error());
  8025. #endif
  8026. #endif
  8027. }
  8028. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8029. // Use a site where hostname doesn't match the certificate
  8030. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8031. SSLClient cli("wrong.host.badssl.com", 443);
  8032. cli.enable_server_certificate_verification(true);
  8033. cli.enable_server_hostname_verification(true);
  8034. auto res = cli.Get("/");
  8035. ASSERT_TRUE(!res);
  8036. // The error type depends on when hostname verification occurs:
  8037. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8038. // - Mbed TLS: SSLServerVerification (during handshake)
  8039. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8040. res.error() == Error::SSLServerVerification);
  8041. // Verify backend error is captured for hostname verification failure
  8042. EXPECT_NE(0UL, res.ssl_backend_error());
  8043. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8044. // For OpenSSL, ssl_error is 0 for verification errors
  8045. EXPECT_EQ(0, res.ssl_error());
  8046. #if !defined(_WIN32) || \
  8047. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8048. // On non-Windows or when Windows Schannel is disabled, the error comes
  8049. // from OpenSSL's hostname verification
  8050. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8051. res.ssl_backend_error());
  8052. #endif
  8053. #endif
  8054. }
  8055. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8056. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8057. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8058. SSLClient cli("www.google.com", 443);
  8059. cli.enable_server_certificate_verification(true);
  8060. auto res = cli.Get("/");
  8061. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8062. }
  8063. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8064. SSLClient cli("www.google.com", 443);
  8065. cli.enable_server_certificate_verification(true);
  8066. cli.enable_windows_certificate_verification(false);
  8067. auto res = cli.Get("/");
  8068. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8069. }
  8070. #endif
  8071. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8072. Client cli("https://google.com");
  8073. auto res = cli.Get("/");
  8074. ASSERT_TRUE(res);
  8075. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8076. }
  8077. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8078. SSLClient cli("google.com");
  8079. cli.set_ca_cert_path(CA_CERT_FILE);
  8080. auto res = cli.Get("/");
  8081. ASSERT_TRUE(res);
  8082. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8083. }
  8084. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8085. SSLClient cli("google.com");
  8086. cli.enable_server_certificate_verification(true);
  8087. cli.set_ca_cert_path("hello");
  8088. auto res = cli.Get("/");
  8089. ASSERT_TRUE(!res);
  8090. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8091. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8092. // should be set
  8093. EXPECT_EQ(0, res.ssl_error());
  8094. // Verify backend error is captured for SSLLoadingCerts
  8095. // This error occurs when loading CA certificates fails
  8096. EXPECT_NE(0UL, res.ssl_backend_error());
  8097. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8098. // OpenSSL specific error codes:
  8099. // > openssl errstr 0x80000002
  8100. // error:80000002:system library::No such file or directory
  8101. // > openssl errstr 0xA000126
  8102. // error:0A000126:SSL routines::unexpected eof while reading
  8103. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8104. res.ssl_backend_error() == 0xA000126);
  8105. #endif
  8106. }
  8107. TEST(SSLClientTest, ServerCertificateVerification4) {
  8108. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8109. ASSERT_TRUE(svr.is_valid());
  8110. svr.Get("/test", [&](const Request &, Response &res) {
  8111. res.set_content("test", "text/plain");
  8112. svr.stop();
  8113. ASSERT_TRUE(true);
  8114. });
  8115. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8116. auto se = detail::scope_exit([&] {
  8117. t.join();
  8118. ASSERT_FALSE(svr.is_running());
  8119. });
  8120. svr.wait_until_ready();
  8121. SSLClient cli("127.0.0.1", PORT);
  8122. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8123. cli.enable_server_certificate_verification(true);
  8124. cli.set_connection_timeout(30);
  8125. auto res = cli.Get("/test");
  8126. ASSERT_TRUE(res);
  8127. ASSERT_EQ(StatusCode::OK_200, res->status);
  8128. }
  8129. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8130. std::string cert;
  8131. read_file(CA_CERT_FILE, cert);
  8132. SSLClient cli("google.com");
  8133. cli.load_ca_cert_store(cert.data(), cert.size());
  8134. const auto res = cli.Get("/");
  8135. ASSERT_TRUE(res);
  8136. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8137. }
  8138. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8139. // clang-format off
  8140. static constexpr char cert[] =
  8141. "GlobalSign Root CA\n"
  8142. "==================\n"
  8143. "-----BEGIN CERTIFICATE-----\n"
  8144. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8145. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8146. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8147. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8148. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8149. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8150. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8151. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8152. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8153. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8154. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8155. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8156. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8157. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8158. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8159. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8160. "-----END CERTIFICATE-----\n";
  8161. // clang-format on
  8162. SSLClient cli("google.com");
  8163. cli.load_ca_cert_store(cert, sizeof(cert));
  8164. const auto res = cli.Get("/");
  8165. ASSERT_TRUE(res);
  8166. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8167. }
  8168. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8169. SSLClient cli("www.youtube.com");
  8170. cli.set_ca_cert_path(CA_CERT_FILE);
  8171. cli.enable_server_certificate_verification(true);
  8172. cli.set_follow_location(true);
  8173. auto res = cli.Get("/");
  8174. ASSERT_TRUE(res);
  8175. ASSERT_EQ(StatusCode::OK_200, res->status);
  8176. }
  8177. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8178. SSLClient cli("wWw.YouTube.Com");
  8179. cli.set_ca_cert_path(CA_CERT_FILE);
  8180. cli.enable_server_certificate_verification(true);
  8181. cli.enable_server_hostname_verification(true);
  8182. cli.set_follow_location(true);
  8183. auto res = cli.Get("/");
  8184. ASSERT_TRUE(res);
  8185. ASSERT_EQ(StatusCode::OK_200, res->status);
  8186. }
  8187. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8188. SSLClient cli("gOoGlE.COm");
  8189. cli.enable_server_certificate_verification(true);
  8190. cli.enable_server_hostname_verification(true);
  8191. cli.set_follow_location(true);
  8192. auto res = cli.Get("/");
  8193. ASSERT_TRUE(res);
  8194. ASSERT_EQ(StatusCode::OK_200, res->status);
  8195. }
  8196. TEST(SSLClientTest, Issue2004_Online) {
  8197. Client client("https://google.com");
  8198. client.set_follow_location(true);
  8199. auto res = client.Get("/");
  8200. ASSERT_TRUE(res);
  8201. ASSERT_EQ(StatusCode::OK_200, res->status);
  8202. auto body = res->body;
  8203. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8204. }
  8205. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8206. // Create SSLClient with invalid cert/key to make is_valid() return false
  8207. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8208. "nonexistent_key.pem");
  8209. // is_valid() should be false due to cert loading failure
  8210. ASSERT_FALSE(cli.is_valid());
  8211. auto res = cli.Get("/");
  8212. ASSERT_FALSE(res);
  8213. EXPECT_EQ(Error::SSLConnection, res.error());
  8214. }
  8215. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8216. // Test for Issue #2251: SSL error not properly reported when client cert
  8217. // and key paths are swapped or mismatched
  8218. // This simulates the scenario where user accidentally swaps the cert and key
  8219. // files
  8220. // Using client cert file as private key and vice versa (completely wrong)
  8221. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8222. // Should fail validation due to cert/key mismatch
  8223. ASSERT_FALSE(cli.is_valid());
  8224. // Attempt to make a request should fail with proper error
  8225. auto res = cli.Get("/");
  8226. ASSERT_FALSE(res);
  8227. EXPECT_EQ(Error::SSLConnection, res.error());
  8228. // SSL error should be recorded in the Result object (this is the key fix for
  8229. // Issue #2251)
  8230. auto backend_error = res.ssl_backend_error();
  8231. EXPECT_NE(0u, backend_error);
  8232. }
  8233. // Tests cert/key mismatch detection at the TLS context level
  8234. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8235. // Test that using mismatched cert/key causes connection failure.
  8236. // We verify this at the SSLClient level rather than through internal
  8237. // TLS API functions.
  8238. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8239. cli.enable_server_certificate_verification(false);
  8240. cli.set_connection_timeout(2);
  8241. // The mismatch should cause a connection or handshake error
  8242. auto res = cli.Get("/test");
  8243. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8244. // Either way, the request should fail
  8245. EXPECT_FALSE(res);
  8246. }
  8247. #endif
  8248. #if 0
  8249. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8250. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8251. ASSERT_TRUE(cli != nullptr);
  8252. cli->set_address_family(AF_INET6);
  8253. cli->set_interface("en0");
  8254. auto res = cli->Get("/get");
  8255. ASSERT_TRUE(res);
  8256. ASSERT_EQ(StatusCode::OK_200, res->status);
  8257. }
  8258. #endif
  8259. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8260. #ifdef CPPHTTPLIB_SSL_ENABLED
  8261. void ClientCertPresent(
  8262. const std::string &client_cert_file,
  8263. const std::string &client_private_key_file,
  8264. const std::string &client_encrypted_private_key_pass = std::string()) {
  8265. using namespace httplib::tls;
  8266. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8267. CLIENT_CA_CERT_DIR);
  8268. ASSERT_TRUE(svr.is_valid());
  8269. svr.Get("/test", [&](const Request &req, Response &res) {
  8270. res.set_content("test", "text/plain");
  8271. auto cert = req.peer_cert();
  8272. ASSERT_TRUE(static_cast<bool>(cert));
  8273. std::string common_name = cert.subject_cn();
  8274. EXPECT_EQ("Common Name", common_name);
  8275. });
  8276. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8277. auto se = detail::scope_exit([&] {
  8278. svr.stop();
  8279. t.join();
  8280. ASSERT_FALSE(svr.is_running());
  8281. });
  8282. svr.wait_until_ready();
  8283. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8284. client_encrypted_private_key_pass);
  8285. cli.enable_server_certificate_verification(false);
  8286. cli.set_connection_timeout(30);
  8287. auto res = cli.Get("/test");
  8288. ASSERT_TRUE(res);
  8289. ASSERT_EQ(StatusCode::OK_200, res->status);
  8290. }
  8291. TEST(SSLClientServerTest, ClientCertPresent) {
  8292. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8293. }
  8294. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8295. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8296. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8297. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8298. }
  8299. // PEM memory-based constructor tests (works with all TLS backends)
  8300. void PemMemoryClientCertPresent(
  8301. const std::string &client_cert_file,
  8302. const std::string &client_private_key_file,
  8303. const std::string &client_encrypted_private_key_pass = std::string()) {
  8304. // Read PEM files into memory
  8305. std::string server_cert_pem, server_key_pem;
  8306. std::string client_ca_pem;
  8307. std::string client_cert_pem, client_key_pem;
  8308. read_file(SERVER_CERT_FILE, server_cert_pem);
  8309. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8310. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8311. read_file(client_cert_file, client_cert_pem);
  8312. read_file(client_private_key_file, client_key_pem);
  8313. // Create server with PEM memory
  8314. SSLServer::PemMemory server_pem = {
  8315. server_cert_pem.c_str(),
  8316. server_cert_pem.size(),
  8317. server_key_pem.c_str(),
  8318. server_key_pem.size(),
  8319. client_ca_pem.c_str(),
  8320. client_ca_pem.size(),
  8321. nullptr // no password for server key
  8322. };
  8323. SSLServer svr(server_pem);
  8324. ASSERT_TRUE(svr.is_valid());
  8325. svr.Get("/test", [&](const Request &, Response &res) {
  8326. res.set_content("test", "text/plain");
  8327. });
  8328. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8329. auto se = detail::scope_exit([&] {
  8330. svr.stop();
  8331. t.join();
  8332. ASSERT_FALSE(svr.is_running());
  8333. });
  8334. svr.wait_until_ready();
  8335. // Create client with PEM memory
  8336. const char *password = client_encrypted_private_key_pass.empty()
  8337. ? nullptr
  8338. : client_encrypted_private_key_pass.c_str();
  8339. SSLClient::PemMemory client_pem = {
  8340. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8341. client_key_pem.size(), password};
  8342. SSLClient cli(HOST, PORT, client_pem);
  8343. cli.enable_server_certificate_verification(false);
  8344. cli.set_connection_timeout(30);
  8345. auto res = cli.Get("/test");
  8346. ASSERT_TRUE(res);
  8347. ASSERT_EQ(StatusCode::OK_200, res->status);
  8348. }
  8349. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8350. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8351. }
  8352. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8353. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8354. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8355. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8356. }
  8357. TEST(SSLClientServerTest, ClientCertMissing) {
  8358. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8359. CLIENT_CA_CERT_DIR);
  8360. ASSERT_TRUE(svr.is_valid());
  8361. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8362. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8363. auto se = detail::scope_exit([&] {
  8364. svr.stop();
  8365. t.join();
  8366. ASSERT_FALSE(svr.is_running());
  8367. });
  8368. svr.wait_until_ready();
  8369. SSLClient cli(HOST, PORT);
  8370. cli.set_connection_timeout(30);
  8371. auto res = cli.Get("/test");
  8372. ASSERT_TRUE(!res);
  8373. // When client cert is missing and server requires it, connection fails
  8374. // Error type depends on backend implementation
  8375. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8376. res.error() == Error::SSLConnection);
  8377. // Verify backend error is captured
  8378. // Note: This test may have different error codes depending on the exact
  8379. // verification failure
  8380. EXPECT_NE(0UL, res.ssl_backend_error());
  8381. }
  8382. TEST(SSLClientServerTest, TrustDirOptional) {
  8383. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8384. ASSERT_TRUE(svr.is_valid());
  8385. svr.Get("/test", [&](const Request &, Response &res) {
  8386. res.set_content("test", "text/plain");
  8387. });
  8388. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8389. auto se = detail::scope_exit([&] {
  8390. svr.stop();
  8391. t.join();
  8392. ASSERT_FALSE(svr.is_running());
  8393. });
  8394. svr.wait_until_ready();
  8395. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8396. cli.enable_server_certificate_verification(false);
  8397. cli.set_connection_timeout(30);
  8398. auto res = cli.Get("/test");
  8399. ASSERT_TRUE(res);
  8400. ASSERT_EQ(StatusCode::OK_200, res->status);
  8401. }
  8402. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8403. class NoListenSSLServer : public SSLServer {
  8404. public:
  8405. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8406. const char *client_ca_cert_file_path,
  8407. const char *client_ca_cert_dir_path = nullptr)
  8408. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8409. client_ca_cert_dir_path),
  8410. stop_(false) {}
  8411. std::atomic_bool stop_;
  8412. private:
  8413. bool process_and_close_socket(socket_t /*sock*/) override {
  8414. // Don't create SSL context
  8415. while (!stop_.load()) {
  8416. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8417. }
  8418. return true;
  8419. }
  8420. };
  8421. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8422. CLIENT_CA_CERT_FILE);
  8423. ASSERT_TRUE(svr.is_valid());
  8424. svr.Get("/test", [&](const Request &, Response &res) {
  8425. res.set_content("test", "text/plain");
  8426. });
  8427. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8428. auto se = detail::scope_exit([&] {
  8429. svr.stop_ = true;
  8430. svr.stop();
  8431. t.join();
  8432. ASSERT_FALSE(svr.is_running());
  8433. });
  8434. svr.wait_until_ready();
  8435. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8436. cli.enable_server_certificate_verification(false);
  8437. cli.set_connection_timeout(1);
  8438. auto res = cli.Get("/test");
  8439. ASSERT_TRUE(!res);
  8440. EXPECT_EQ(Error::SSLConnection, res.error());
  8441. // Timeout results in WantRead error code (maps to backend-specific value)
  8442. EXPECT_NE(0, res.ssl_error());
  8443. }
  8444. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8445. // Test SSLServer with client certificate verification using the standard
  8446. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8447. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8448. CLIENT_CA_CERT_DIR);
  8449. ASSERT_TRUE(svr.is_valid());
  8450. svr.Get("/test", [&](const Request &req, Response &res) {
  8451. res.set_content("test", "text/plain");
  8452. auto cert = req.peer_cert();
  8453. ASSERT_TRUE(static_cast<bool>(cert));
  8454. auto common_name = cert.subject_cn();
  8455. EXPECT_EQ("Common Name", common_name);
  8456. });
  8457. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8458. auto se = detail::scope_exit([&] {
  8459. svr.stop();
  8460. t.join();
  8461. ASSERT_FALSE(svr.is_running());
  8462. });
  8463. svr.wait_until_ready();
  8464. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8465. cli.enable_server_certificate_verification(false);
  8466. cli.set_connection_timeout(30);
  8467. auto res = cli.Get("/test");
  8468. ASSERT_TRUE(res);
  8469. ASSERT_EQ(StatusCode::OK_200, res->status);
  8470. }
  8471. // Test verify_hostname for both OpenSSL and MbedTLS backends
  8472. // Verifies that wildcard matching and exact matching work consistently
  8473. TEST(SSLClientServerTest, TlsVerifyHostname) {
  8474. using namespace httplib::tls;
  8475. // We need a running server to test against
  8476. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8477. ASSERT_TRUE(svr.is_valid());
  8478. svr.Get("/test", [](const Request &, Response &res) {
  8479. res.set_content("ok", "text/plain");
  8480. });
  8481. thread t([&]() { svr.listen(HOST, PORT); });
  8482. auto se = detail::scope_exit([&] {
  8483. svr.stop();
  8484. t.join();
  8485. });
  8486. svr.wait_until_ready();
  8487. bool verify_callback_called = false;
  8488. bool verify_result_wrong = false;
  8489. SSLClient cli(HOST, PORT);
  8490. cli.enable_server_certificate_verification(true);
  8491. cli.set_ca_cert_path(CA_CERT_FILE);
  8492. cli.set_connection_timeout(5);
  8493. // Note: Test certificate has CN="Common Name", not "localhost"
  8494. bool verify_result_cn = false;
  8495. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8496. verify_callback_called = true;
  8497. if (!ctx.cert) return false;
  8498. // Test 1: "Common Name" should match (our test server cert CN)
  8499. verify_result_cn = ctx.check_hostname("Common Name");
  8500. // Test 2: wrong hostname should not match
  8501. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  8502. return true; // Accept for the purpose of this test
  8503. });
  8504. auto res = cli.Get("/test");
  8505. // The request may succeed or fail depending on cert configuration
  8506. // but the callback should have been called
  8507. ASSERT_TRUE(verify_callback_called)
  8508. << "Verify callback should have been called";
  8509. // CN="Common Name" should match our test certificate
  8510. EXPECT_TRUE(verify_result_cn)
  8511. << "verify_hostname should match 'Common Name' (certificate CN)";
  8512. // Wrong hostname should not match
  8513. EXPECT_FALSE(verify_result_wrong)
  8514. << "verify_hostname should not match 'wronghost.example.com'";
  8515. }
  8516. #endif
  8517. // mbedTLS-specific callback constructor test
  8518. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8519. #ifdef CPPHTTPLIB_SSL_ENABLED
  8520. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8521. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8522. ASSERT_TRUE(svr.is_valid());
  8523. // Set up a handler to verify client certificate is present
  8524. bool client_cert_verified = false;
  8525. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8526. // Verify that client certificate was provided
  8527. client_cert_verified = true;
  8528. res.set_content("success", "text/plain");
  8529. });
  8530. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8531. auto se = detail::scope_exit([&] {
  8532. svr.stop();
  8533. t.join();
  8534. ASSERT_FALSE(svr.is_running());
  8535. });
  8536. svr.wait_until_ready();
  8537. // Client with certificate
  8538. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8539. cli.enable_server_certificate_verification(false);
  8540. cli.set_connection_timeout(30);
  8541. auto res = cli.Get("/test");
  8542. ASSERT_TRUE(res);
  8543. ASSERT_EQ(StatusCode::OK_200, res->status);
  8544. ASSERT_TRUE(client_cert_verified);
  8545. EXPECT_EQ("success", res->body);
  8546. }
  8547. #endif
  8548. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  8549. // backends
  8550. #ifdef CPPHTTPLIB_SSL_ENABLED
  8551. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  8552. using namespace httplib::tls;
  8553. // Test that when client CA cert file is provided,
  8554. // the server properly requests and validates client certificates
  8555. // Create a server with client authentication
  8556. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8557. ASSERT_TRUE(svr.is_valid());
  8558. bool handler_called = false;
  8559. svr.Get("/test", [&](const Request &req, Response &res) {
  8560. handler_called = true;
  8561. // Verify that a client certificate was provided
  8562. auto cert = req.peer_cert();
  8563. ASSERT_TRUE(static_cast<bool>(cert));
  8564. // Get the issuer name
  8565. std::string issuer_str = cert.issuer_name();
  8566. ASSERT_FALSE(issuer_str.empty());
  8567. // The client certificate should be issued by our test CA
  8568. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  8569. res.set_content("authenticated", "text/plain");
  8570. });
  8571. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8572. auto se = detail::scope_exit([&] {
  8573. svr.stop();
  8574. t.join();
  8575. ASSERT_FALSE(svr.is_running());
  8576. });
  8577. svr.wait_until_ready();
  8578. // Connect with a client certificate issued by the CA
  8579. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8580. cli.enable_server_certificate_verification(false);
  8581. cli.set_connection_timeout(30);
  8582. auto res = cli.Get("/test");
  8583. ASSERT_TRUE(res);
  8584. ASSERT_EQ(StatusCode::OK_200, res->status);
  8585. ASSERT_TRUE(handler_called);
  8586. EXPECT_EQ("authenticated", res->body);
  8587. }
  8588. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  8589. using namespace httplib::tls;
  8590. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8591. ASSERT_TRUE(svr.is_valid());
  8592. svr.Get("/test", [](const Request &, Response &res) {
  8593. res.set_content("ok", "text/plain");
  8594. });
  8595. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8596. auto se = detail::scope_exit([&] {
  8597. svr.stop();
  8598. t.join();
  8599. });
  8600. svr.wait_until_ready();
  8601. SSLClient cli(HOST, PORT);
  8602. cli.enable_server_certificate_verification(false);
  8603. cli.set_connection_timeout(30);
  8604. bool cert_checked = false;
  8605. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8606. if (ctx.cert) {
  8607. auto sans = ctx.sans();
  8608. // Test certificate may or may not have SANs - just verify the API
  8609. // works If SANs exist, verify the types are valid
  8610. for (const auto &san : sans) {
  8611. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  8612. san.type == SanType::EMAIL || san.type == SanType::URI ||
  8613. san.type == SanType::OTHER);
  8614. EXPECT_FALSE(san.value.empty());
  8615. }
  8616. cert_checked = true;
  8617. }
  8618. return true;
  8619. });
  8620. auto res = cli.Get("/test");
  8621. ASSERT_TRUE(res);
  8622. EXPECT_TRUE(cert_checked);
  8623. }
  8624. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  8625. using namespace httplib::tls;
  8626. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8627. ASSERT_TRUE(svr.is_valid());
  8628. svr.Get("/test", [](const Request &, Response &res) {
  8629. res.set_content("ok", "text/plain");
  8630. });
  8631. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8632. auto se = detail::scope_exit([&] {
  8633. svr.stop();
  8634. t.join();
  8635. });
  8636. svr.wait_until_ready();
  8637. SSLClient cli(HOST, PORT);
  8638. cli.enable_server_certificate_verification(false);
  8639. cli.set_connection_timeout(30);
  8640. bool validity_checked = false;
  8641. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8642. if (ctx.cert) {
  8643. time_t not_before = 0, not_after = 0;
  8644. bool result = ctx.validity(not_before, not_after);
  8645. EXPECT_TRUE(result);
  8646. // Verify that not_before < now < not_after for a valid cert
  8647. time_t now = time(nullptr);
  8648. EXPECT_LT(not_before, now);
  8649. EXPECT_GT(not_after, now);
  8650. validity_checked = true;
  8651. }
  8652. return true;
  8653. });
  8654. auto res = cli.Get("/test");
  8655. ASSERT_TRUE(res);
  8656. EXPECT_TRUE(validity_checked);
  8657. }
  8658. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  8659. using namespace httplib::tls;
  8660. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8661. ASSERT_TRUE(svr.is_valid());
  8662. svr.Get("/test", [](const Request &, Response &res) {
  8663. res.set_content("ok", "text/plain");
  8664. });
  8665. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8666. auto se = detail::scope_exit([&] {
  8667. svr.stop();
  8668. t.join();
  8669. });
  8670. svr.wait_until_ready();
  8671. SSLClient cli(HOST, PORT);
  8672. cli.enable_server_certificate_verification(false);
  8673. cli.set_connection_timeout(30);
  8674. bool serial_checked = false;
  8675. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8676. if (ctx.cert) {
  8677. std::string serial = ctx.serial();
  8678. EXPECT_FALSE(serial.empty());
  8679. // Serial should be a hex string
  8680. for (char c : serial) {
  8681. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  8682. (c >= 'a' && c <= 'f'));
  8683. }
  8684. serial_checked = true;
  8685. }
  8686. return true;
  8687. });
  8688. auto res = cli.Get("/test");
  8689. ASSERT_TRUE(res);
  8690. EXPECT_TRUE(serial_checked);
  8691. }
  8692. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  8693. // Test 1: Valid CA file - no error should be recorded
  8694. {
  8695. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8696. CLIENT_CA_CERT_FILE);
  8697. ASSERT_TRUE(svr.is_valid());
  8698. // With valid setup, last_ssl_error should be 0
  8699. EXPECT_EQ(0, svr.ssl_last_error());
  8700. }
  8701. // Test 2: Invalid CA file content
  8702. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  8703. {
  8704. // Create a temporary file with completely invalid content
  8705. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  8706. {
  8707. std::ofstream ofs(temp_invalid_ca);
  8708. ofs << "This is not a certificate file at all\n";
  8709. ofs << "Just plain text content\n";
  8710. }
  8711. // Create server with invalid CA file
  8712. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  8713. // Clean up temporary file
  8714. std::remove(temp_invalid_ca);
  8715. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  8716. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  8717. // Note: SSL_CTX_load_verify_locations typically fails first,
  8718. // but our error handling code path is still exercised
  8719. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  8720. }
  8721. }
  8722. TEST(VerifyCallbackTest, VerifyContextFields) {
  8723. using namespace httplib::tls;
  8724. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8725. ASSERT_TRUE(svr.is_valid());
  8726. svr.Get("/test", [](const Request &, Response &res) {
  8727. res.set_content("ok", "text/plain");
  8728. });
  8729. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8730. auto se = detail::scope_exit([&] {
  8731. svr.stop();
  8732. t.join();
  8733. });
  8734. svr.wait_until_ready();
  8735. SSLClient cli(HOST, PORT);
  8736. cli.enable_server_certificate_verification(false);
  8737. cli.set_connection_timeout(30);
  8738. int callback_count = 0;
  8739. bool saw_leaf_cert = false;
  8740. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8741. if (ctx.cert) {
  8742. callback_count++;
  8743. // We should see at least one certificate (the leaf)
  8744. std::string cn = ctx.subject_cn();
  8745. if (!cn.empty()) { saw_leaf_cert = true; }
  8746. // Verify context fields are populated
  8747. EXPECT_NE(ctx.session, nullptr);
  8748. EXPECT_GE(ctx.depth, 0);
  8749. }
  8750. return true;
  8751. });
  8752. auto res = cli.Get("/test");
  8753. ASSERT_TRUE(res);
  8754. EXPECT_GT(callback_count, 0);
  8755. EXPECT_TRUE(saw_leaf_cert);
  8756. }
  8757. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  8758. using httplib::tls::TlsError;
  8759. // Test that verify_error_to_string returns empty for success
  8760. std::string success_str = TlsError::verify_error_to_string(0);
  8761. EXPECT_TRUE(success_str.empty());
  8762. // Test that verify_error_to_string returns non-empty for error codes
  8763. // Using a common error code (certificate expired)
  8764. std::string error_str =
  8765. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  8766. EXPECT_FALSE(error_str.empty());
  8767. }
  8768. TEST(SessionVerifierTest, CertificateAccepted) {
  8769. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8770. ASSERT_TRUE(svr.is_valid());
  8771. svr.Get("/test", [](const Request &, Response &res) {
  8772. res.set_content("ok", "text/plain");
  8773. });
  8774. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8775. auto se = detail::scope_exit([&] {
  8776. svr.stop();
  8777. t.join();
  8778. });
  8779. svr.wait_until_ready();
  8780. SSLClient cli(HOST, PORT);
  8781. cli.enable_server_certificate_verification(false);
  8782. cli.set_connection_timeout(30);
  8783. bool callback_called = false;
  8784. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8785. EXPECT_NE(session, nullptr);
  8786. callback_called = true;
  8787. return SSLVerifierResponse::CertificateAccepted;
  8788. });
  8789. auto res = cli.Get("/test");
  8790. ASSERT_TRUE(res);
  8791. EXPECT_EQ(200, res->status);
  8792. EXPECT_TRUE(callback_called);
  8793. }
  8794. TEST(SessionVerifierTest, CertificateRejected) {
  8795. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8796. ASSERT_TRUE(svr.is_valid());
  8797. svr.Get("/test", [](const Request &, Response &res) {
  8798. res.set_content("ok", "text/plain");
  8799. });
  8800. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8801. auto se = detail::scope_exit([&] {
  8802. svr.stop();
  8803. t.join();
  8804. });
  8805. svr.wait_until_ready();
  8806. SSLClient cli(HOST, PORT);
  8807. cli.enable_server_certificate_verification(false);
  8808. cli.set_connection_timeout(30);
  8809. bool callback_called = false;
  8810. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8811. EXPECT_NE(session, nullptr);
  8812. callback_called = true;
  8813. return SSLVerifierResponse::CertificateRejected;
  8814. });
  8815. auto res = cli.Get("/test");
  8816. EXPECT_FALSE(res);
  8817. EXPECT_TRUE(callback_called);
  8818. }
  8819. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  8820. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8821. ASSERT_TRUE(svr.is_valid());
  8822. svr.Get("/test", [](const Request &, Response &res) {
  8823. res.set_content("ok", "text/plain");
  8824. });
  8825. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8826. auto se = detail::scope_exit([&] {
  8827. svr.stop();
  8828. t.join();
  8829. });
  8830. svr.wait_until_ready();
  8831. // NoDecisionMade with verification disabled should succeed (no default check)
  8832. SSLClient cli(HOST, PORT);
  8833. cli.enable_server_certificate_verification(false);
  8834. cli.set_connection_timeout(30);
  8835. bool callback_called = false;
  8836. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8837. EXPECT_NE(session, nullptr);
  8838. callback_called = true;
  8839. return SSLVerifierResponse::NoDecisionMade;
  8840. });
  8841. auto res = cli.Get("/test");
  8842. ASSERT_TRUE(res);
  8843. EXPECT_EQ(200, res->status);
  8844. EXPECT_TRUE(callback_called);
  8845. }
  8846. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  8847. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8848. ASSERT_TRUE(svr.is_valid());
  8849. svr.Get("/test", [](const Request &, Response &res) {
  8850. res.set_content("ok", "text/plain");
  8851. });
  8852. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8853. auto se = detail::scope_exit([&] {
  8854. svr.stop();
  8855. t.join();
  8856. });
  8857. svr.wait_until_ready();
  8858. // NoDecisionMade with verification enabled should fail (self-signed cert).
  8859. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  8860. // so we only check that the request fails, not whether the callback was
  8861. // called.
  8862. SSLClient cli(HOST, PORT);
  8863. cli.enable_server_certificate_verification(true);
  8864. cli.set_connection_timeout(30);
  8865. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8866. EXPECT_NE(session, nullptr);
  8867. return SSLVerifierResponse::NoDecisionMade;
  8868. });
  8869. auto res = cli.Get("/test");
  8870. EXPECT_FALSE(res);
  8871. }
  8872. TEST(SSLClientServerTest, ClientCAListFromPem) {
  8873. // Test SSL server using PemMemory constructor with client CA certificates
  8874. // Read PEM files
  8875. std::string server_cert_pem, server_key_pem, client_ca_pem;
  8876. read_file(SERVER_CERT_FILE, server_cert_pem);
  8877. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8878. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8879. // Create SSLServer with PemMemory constructor including client CA
  8880. SSLServer::PemMemory server_pem = {
  8881. server_cert_pem.c_str(),
  8882. server_cert_pem.size(),
  8883. server_key_pem.c_str(),
  8884. server_key_pem.size(),
  8885. client_ca_pem.c_str(),
  8886. client_ca_pem.size(),
  8887. nullptr // no password for server key
  8888. };
  8889. SSLServer svr(server_pem);
  8890. ASSERT_TRUE(svr.is_valid());
  8891. // No SSL error should be recorded for valid setup
  8892. EXPECT_EQ(0, svr.ssl_last_error());
  8893. // Set up server endpoints
  8894. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  8895. res.set_content("ok", "text/plain");
  8896. });
  8897. // Start server in a thread
  8898. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  8899. svr.wait_until_ready();
  8900. // Connect with client certificate (using constructor with paths)
  8901. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8902. cli.enable_server_certificate_verification(false);
  8903. auto res = cli.Get("/test-pem-ca");
  8904. ASSERT_TRUE(res);
  8905. EXPECT_EQ(200, res->status);
  8906. EXPECT_EQ("ok", res->body);
  8907. svr.stop();
  8908. server_thread.join();
  8909. }
  8910. #endif
  8911. #ifdef _WIN32
  8912. TEST(CleanupTest, WSACleanup) {
  8913. int ret = WSACleanup();
  8914. ASSERT_EQ(0, ret);
  8915. }
  8916. #endif
  8917. #ifndef CPPHTTPLIB_SSL_ENABLED
  8918. TEST(NoSSLSupport, SimpleInterface) {
  8919. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  8920. }
  8921. #endif
  8922. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8923. TEST(InvalidScheme, SimpleInterface) {
  8924. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  8925. }
  8926. #endif
  8927. TEST(NoScheme, SimpleInterface) {
  8928. Client cli("yahoo.com:80");
  8929. ASSERT_TRUE(cli.is_valid());
  8930. }
  8931. TEST(SendAPI, SimpleInterface_Online) {
  8932. Client cli("http://yahoo.com");
  8933. Request req;
  8934. req.method = "GET";
  8935. req.path = "/";
  8936. auto res = cli.send(req);
  8937. ASSERT_TRUE(res);
  8938. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8939. }
  8940. TEST(SendAPI, WithParamsInRequest) {
  8941. Server svr;
  8942. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  8943. EXPECT_TRUE(req.has_param("test"));
  8944. EXPECT_EQ("test_value", req.get_param_value("test"));
  8945. });
  8946. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  8947. auto se = detail::scope_exit([&] {
  8948. svr.stop();
  8949. t.join();
  8950. ASSERT_FALSE(svr.is_running());
  8951. });
  8952. svr.wait_until_ready();
  8953. Client cli(HOST, PORT);
  8954. {
  8955. Request req;
  8956. req.method = "GET";
  8957. req.path = "/";
  8958. req.params.emplace("test", "test_value");
  8959. auto res = cli.send(req);
  8960. ASSERT_TRUE(res);
  8961. }
  8962. {
  8963. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  8964. ASSERT_TRUE(res);
  8965. }
  8966. }
  8967. TEST(ClientImplMethods, GetSocketTest) {
  8968. httplib::Server svr;
  8969. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  8970. res.status = StatusCode::OK_200;
  8971. });
  8972. auto port = svr.bind_to_any_port("127.0.0.1");
  8973. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  8974. auto se = detail::scope_exit([&] {
  8975. svr.stop();
  8976. thread.join();
  8977. ASSERT_FALSE(svr.is_running());
  8978. });
  8979. svr.wait_until_ready();
  8980. {
  8981. httplib::Client cli("127.0.0.1", port);
  8982. cli.set_keep_alive(true);
  8983. // Use the behavior of cpp-httplib of opening the connection
  8984. // only when the first request happens. If that changes,
  8985. // this test would be obsolete.
  8986. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  8987. // This also implicitly tests the server. But other tests would fail much
  8988. // earlier than this one to be considered.
  8989. auto res = cli.Get("/");
  8990. ASSERT_TRUE(res);
  8991. EXPECT_EQ(StatusCode::OK_200, res->status);
  8992. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  8993. }
  8994. }
  8995. // Disabled due to out-of-memory problem on GitHub Actions
  8996. #ifdef _WIN64
  8997. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  8998. // allocate content size larger than 2GB in memory
  8999. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  9000. char *content = (char *)malloc(content_size);
  9001. ASSERT_TRUE(content);
  9002. Server svr;
  9003. svr.Get("/foo",
  9004. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  9005. res.set_content(content, content_size, "application/octet-stream");
  9006. });
  9007. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9008. auto se = detail::scope_exit([&] {
  9009. svr.stop();
  9010. listen_thread.join();
  9011. if (content) free(content);
  9012. ASSERT_FALSE(svr.is_running());
  9013. });
  9014. svr.wait_until_ready();
  9015. Client cli(HOST, PORT);
  9016. auto res = cli.Get("/foo");
  9017. ASSERT_TRUE(res);
  9018. EXPECT_EQ(StatusCode::OK_200, res->status);
  9019. EXPECT_EQ(content_size, res->body.length());
  9020. }
  9021. #endif
  9022. #ifdef CPPHTTPLIB_SSL_ENABLED
  9023. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9024. Client cli("http://yahoo.com");
  9025. auto res = cli.Get("/");
  9026. ASSERT_TRUE(res);
  9027. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9028. cli.set_follow_location(true);
  9029. res = cli.Get("/");
  9030. ASSERT_TRUE(res);
  9031. EXPECT_EQ(StatusCode::OK_200, res->status);
  9032. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9033. }
  9034. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9035. Client cli("https://yahoo.com");
  9036. auto res = cli.Get("/");
  9037. ASSERT_TRUE(res);
  9038. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9039. cli.set_follow_location(true);
  9040. res = cli.Get("/");
  9041. ASSERT_TRUE(res);
  9042. EXPECT_EQ(StatusCode::OK_200, res->status);
  9043. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9044. }
  9045. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9046. Client cli("https://yahoo.com");
  9047. auto res = cli.Get("/");
  9048. ASSERT_TRUE(res);
  9049. ASSERT_FALSE(!res);
  9050. ASSERT_TRUE(res);
  9051. ASSERT_FALSE(res == nullptr);
  9052. ASSERT_TRUE(res != nullptr);
  9053. EXPECT_EQ(Error::Success, res.error());
  9054. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9055. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9056. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9057. cli.set_follow_location(true);
  9058. res = cli.Get("/");
  9059. ASSERT_TRUE(res);
  9060. EXPECT_EQ(Error::Success, res.error());
  9061. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9062. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9063. EXPECT_EQ(StatusCode::OK_200, res->status);
  9064. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9065. }
  9066. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9067. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9068. Client cli("https://cdnjs.cloudflare.com");
  9069. auto res =
  9070. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9071. ASSERT_TRUE(res);
  9072. EXPECT_EQ(StatusCode::OK_200, res->status);
  9073. EXPECT_EQ(287630U, res->body.size());
  9074. EXPECT_EQ("application/javascript; charset=utf-8",
  9075. res->get_header_value("Content-Type"));
  9076. }
  9077. #endif
  9078. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9079. #undef REDIR_HOST // Silence compiler warning
  9080. #define REDIR_HOST "https://httpbingo.org"
  9081. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9082. Client cli(REDIR_HOST);
  9083. cli.set_follow_location(true);
  9084. auto res =
  9085. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9086. ASSERT_TRUE(res);
  9087. EXPECT_EQ(StatusCode::OK_200, res->status);
  9088. }
  9089. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9090. Client cli(REDIR_HOST);
  9091. cli.set_follow_location(true);
  9092. Params params;
  9093. params.emplace("url", "http://example.com");
  9094. params.emplace("status_code", "302");
  9095. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9096. ASSERT_TRUE(res);
  9097. EXPECT_EQ(StatusCode::OK_200, res->status);
  9098. }
  9099. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9100. Client cli(REDIR_HOST);
  9101. cli.set_follow_location(true);
  9102. Params params;
  9103. params.emplace("url", "http://example.com");
  9104. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9105. ASSERT_TRUE(res);
  9106. EXPECT_EQ(StatusCode::OK_200, res->status);
  9107. }
  9108. TEST(HttpToHttpsRedirectTest, CertFile) {
  9109. auto ssl_port = PORT + 1;
  9110. Server svr;
  9111. ASSERT_TRUE(svr.is_valid());
  9112. svr.Get("/index", [&](const Request &, Response &res) {
  9113. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9114. "/index");
  9115. svr.stop();
  9116. });
  9117. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9118. ASSERT_TRUE(ssl_svr.is_valid());
  9119. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9120. res.set_content("test", "text/plain");
  9121. ssl_svr.stop();
  9122. });
  9123. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9124. thread t2 =
  9125. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9126. auto se = detail::scope_exit([&] {
  9127. t2.join();
  9128. t.join();
  9129. ASSERT_FALSE(svr.is_running());
  9130. });
  9131. svr.wait_until_ready();
  9132. ssl_svr.wait_until_ready();
  9133. Client cli("127.0.0.1", PORT);
  9134. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9135. cli.enable_server_certificate_verification(true);
  9136. cli.set_follow_location(true);
  9137. cli.set_connection_timeout(30);
  9138. auto res = cli.Get("/index");
  9139. ASSERT_TRUE(res);
  9140. ASSERT_EQ(StatusCode::OK_200, res->status);
  9141. }
  9142. TEST(SSLClientRedirectTest, CertFile) {
  9143. auto ssl_port = PORT + 1;
  9144. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9145. ASSERT_TRUE(ssl_svr1.is_valid());
  9146. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9147. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9148. "/index");
  9149. ssl_svr1.stop();
  9150. });
  9151. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9152. ASSERT_TRUE(ssl_svr2.is_valid());
  9153. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9154. res.set_content("test", "text/plain");
  9155. ssl_svr2.stop();
  9156. });
  9157. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9158. thread t2 =
  9159. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9160. auto se = detail::scope_exit([&] {
  9161. t2.join();
  9162. t.join();
  9163. ASSERT_FALSE(ssl_svr1.is_running());
  9164. });
  9165. ssl_svr1.wait_until_ready();
  9166. ssl_svr2.wait_until_ready();
  9167. SSLClient cli("127.0.0.1", PORT);
  9168. std::string cert;
  9169. read_file(SERVER_CERT2_FILE, cert);
  9170. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9171. cli.enable_server_certificate_verification(true);
  9172. cli.set_follow_location(true);
  9173. cli.set_connection_timeout(30);
  9174. auto res = cli.Get("/index");
  9175. ASSERT_TRUE(res);
  9176. ASSERT_EQ(StatusCode::OK_200, res->status);
  9177. }
  9178. #endif
  9179. #ifdef CPPHTTPLIB_SSL_ENABLED
  9180. // Test that set_ca_cert_store() skips system certs (consistent with
  9181. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9182. // should be trusted - system certs should NOT be loaded.
  9183. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9184. // Load a specific cert that is NOT a system CA cert
  9185. std::string cert;
  9186. read_file(SERVER_CERT2_FILE, cert);
  9187. SSLClient cli("google.com");
  9188. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9189. cli.enable_server_certificate_verification(true);
  9190. // This should FAIL because:
  9191. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9192. // 2. System certs should NOT be loaded when custom store is set
  9193. // If system certs WERE loaded, this would succeed
  9194. auto res = cli.Get("/");
  9195. ASSERT_FALSE(res);
  9196. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9197. }
  9198. TEST(MultipartFormDataTest, LargeData) {
  9199. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9200. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9201. const ContentReader &content_reader) {
  9202. if (req.is_multipart_form_data()) {
  9203. std::vector<FormData> items;
  9204. content_reader(
  9205. [&](const FormData &file) {
  9206. items.push_back(file);
  9207. return true;
  9208. },
  9209. [&](const char *data, size_t data_length) {
  9210. items.back().content.append(data, data_length);
  9211. return true;
  9212. });
  9213. EXPECT_TRUE(std::string(items[0].name) == "document");
  9214. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9215. EXPECT_TRUE(items[0].filename == "2MB_data");
  9216. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9217. EXPECT_TRUE(items[1].name == "hello");
  9218. EXPECT_TRUE(items[1].content == "world");
  9219. EXPECT_TRUE(items[1].filename == "");
  9220. EXPECT_TRUE(items[1].content_type == "");
  9221. } else {
  9222. std::string body;
  9223. content_reader([&](const char *data, size_t data_length) {
  9224. body.append(data, data_length);
  9225. return true;
  9226. });
  9227. }
  9228. });
  9229. auto port = svr.bind_to_any_port(HOST);
  9230. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9231. auto se = detail::scope_exit([&] {
  9232. svr.stop();
  9233. t.join();
  9234. ASSERT_FALSE(svr.is_running());
  9235. });
  9236. svr.wait_until_ready();
  9237. {
  9238. std::string data(1024 * 1024 * 2, '.');
  9239. std::stringstream buffer;
  9240. buffer << data;
  9241. SSLClient cli(HOST, port);
  9242. cli.enable_server_certificate_verification(false);
  9243. UploadFormDataItems items{
  9244. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9245. {"hello", "world", "", ""},
  9246. };
  9247. auto res = cli.Post("/post", items);
  9248. ASSERT_TRUE(res);
  9249. ASSERT_EQ(StatusCode::OK_200, res->status);
  9250. }
  9251. }
  9252. TEST(MultipartFormDataTest, DataProviderItems) {
  9253. std::random_device seed_gen;
  9254. std::mt19937 random(seed_gen());
  9255. std::string rand1;
  9256. rand1.resize(1000);
  9257. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9258. std::string rand2;
  9259. rand2.resize(3000);
  9260. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9261. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9262. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9263. const ContentReader &content_reader) {
  9264. ASSERT_FALSE(req.is_multipart_form_data());
  9265. std::string body;
  9266. content_reader([&](const char *data, size_t data_length) {
  9267. body.append(data, data_length);
  9268. return true;
  9269. });
  9270. EXPECT_EQ(body, "");
  9271. });
  9272. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9273. const ContentReader &content_reader) {
  9274. ASSERT_TRUE(req.is_multipart_form_data());
  9275. std::vector<FormData> items;
  9276. content_reader(
  9277. [&](const FormData &file) {
  9278. items.push_back(file);
  9279. return true;
  9280. },
  9281. [&](const char *data, size_t data_length) {
  9282. items.back().content.append(data, data_length);
  9283. return true;
  9284. });
  9285. ASSERT_TRUE(items.size() == 2);
  9286. EXPECT_EQ(std::string(items[0].name), "name1");
  9287. EXPECT_EQ(items[0].content, "Testing123");
  9288. EXPECT_EQ(items[0].filename, "filename1");
  9289. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9290. EXPECT_EQ(items[1].name, "name2");
  9291. EXPECT_EQ(items[1].content, "Testing456");
  9292. EXPECT_EQ(items[1].filename, "");
  9293. EXPECT_EQ(items[1].content_type, "");
  9294. });
  9295. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9296. const ContentReader &content_reader) {
  9297. ASSERT_TRUE(req.is_multipart_form_data());
  9298. std::vector<FormData> items;
  9299. content_reader(
  9300. [&](const FormData &file) {
  9301. items.push_back(file);
  9302. return true;
  9303. },
  9304. [&](const char *data, size_t data_length) {
  9305. items.back().content.append(data, data_length);
  9306. return true;
  9307. });
  9308. ASSERT_TRUE(items.size() == 2);
  9309. EXPECT_EQ(items[0].name, "name3");
  9310. EXPECT_EQ(items[0].content, rand1);
  9311. EXPECT_EQ(items[0].filename, "filename3");
  9312. EXPECT_EQ(items[0].content_type, "");
  9313. EXPECT_EQ(items[1].name, "name4");
  9314. EXPECT_EQ(items[1].content, rand2);
  9315. EXPECT_EQ(items[1].filename, "filename4");
  9316. EXPECT_EQ(items[1].content_type, "");
  9317. });
  9318. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9319. const ContentReader &content_reader) {
  9320. ASSERT_TRUE(req.is_multipart_form_data());
  9321. std::vector<FormData> items;
  9322. content_reader(
  9323. [&](const FormData &file) {
  9324. items.push_back(file);
  9325. return true;
  9326. },
  9327. [&](const char *data, size_t data_length) {
  9328. items.back().content.append(data, data_length);
  9329. return true;
  9330. });
  9331. ASSERT_TRUE(items.size() == 4);
  9332. EXPECT_EQ(std::string(items[0].name), "name1");
  9333. EXPECT_EQ(items[0].content, "Testing123");
  9334. EXPECT_EQ(items[0].filename, "filename1");
  9335. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9336. EXPECT_EQ(items[1].name, "name2");
  9337. EXPECT_EQ(items[1].content, "Testing456");
  9338. EXPECT_EQ(items[1].filename, "");
  9339. EXPECT_EQ(items[1].content_type, "");
  9340. EXPECT_EQ(items[2].name, "name3");
  9341. EXPECT_EQ(items[2].content, rand1);
  9342. EXPECT_EQ(items[2].filename, "filename3");
  9343. EXPECT_EQ(items[2].content_type, "");
  9344. EXPECT_EQ(items[3].name, "name4");
  9345. EXPECT_EQ(items[3].content, rand2);
  9346. EXPECT_EQ(items[3].filename, "filename4");
  9347. EXPECT_EQ(items[3].content_type, "");
  9348. });
  9349. auto port = svr.bind_to_any_port("localhost");
  9350. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9351. auto se = detail::scope_exit([&] {
  9352. svr.stop();
  9353. t.join();
  9354. ASSERT_FALSE(svr.is_running());
  9355. });
  9356. svr.wait_until_ready();
  9357. {
  9358. SSLClient cli("localhost", port);
  9359. cli.enable_server_certificate_verification(false);
  9360. UploadFormDataItems items{
  9361. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9362. {"name2", "Testing456", "", ""}, // not a file
  9363. };
  9364. {
  9365. auto res = cli.Post("/post-none", {}, {}, {});
  9366. ASSERT_TRUE(res);
  9367. ASSERT_EQ(StatusCode::OK_200, res->status);
  9368. }
  9369. FormDataProviderItems providers;
  9370. {
  9371. auto res =
  9372. cli.Post("/post-items", {}, items, providers); // empty providers
  9373. ASSERT_TRUE(res);
  9374. ASSERT_EQ(StatusCode::OK_200, res->status);
  9375. }
  9376. providers.push_back({"name3",
  9377. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9378. // test the offset is given correctly at each step
  9379. if (!offset)
  9380. sink.os.write(rand1.data(), 30);
  9381. else if (offset == 30)
  9382. sink.os.write(rand1.data() + 30, 300);
  9383. else if (offset == 330)
  9384. sink.os.write(rand1.data() + 330, 670);
  9385. else if (offset == rand1.size())
  9386. sink.done();
  9387. return true;
  9388. },
  9389. "filename3",
  9390. {}});
  9391. providers.push_back({"name4",
  9392. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9393. // test the offset is given correctly at each step
  9394. if (!offset)
  9395. sink.os.write(rand2.data(), 2000);
  9396. else if (offset == 2000)
  9397. sink.os.write(rand2.data() + 2000, 1);
  9398. else if (offset == 2001)
  9399. sink.os.write(rand2.data() + 2001, 999);
  9400. else if (offset == rand2.size())
  9401. sink.done();
  9402. return true;
  9403. },
  9404. "filename4",
  9405. {}});
  9406. {
  9407. auto res = cli.Post("/post-providers", {}, {}, providers);
  9408. ASSERT_TRUE(res);
  9409. ASSERT_EQ(StatusCode::OK_200, res->status);
  9410. }
  9411. {
  9412. auto res = cli.Post("/post-both", {}, items, providers);
  9413. ASSERT_TRUE(res);
  9414. ASSERT_EQ(StatusCode::OK_200, res->status);
  9415. }
  9416. }
  9417. }
  9418. TEST(MultipartFormDataTest, BadHeader) {
  9419. Server svr;
  9420. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9421. res.set_content("ok", "text/plain");
  9422. });
  9423. thread t = thread([&] { svr.listen(HOST, PORT); });
  9424. auto se = detail::scope_exit([&] {
  9425. svr.stop();
  9426. t.join();
  9427. ASSERT_FALSE(svr.is_running());
  9428. });
  9429. svr.wait_until_ready();
  9430. const std::string body =
  9431. "This is the preamble. It is to be ignored, though it\r\n"
  9432. "is a handy place for composition agents to include an\r\n"
  9433. "explanatory note to non-MIME conformant readers.\r\n"
  9434. "\r\n"
  9435. "\r\n"
  9436. "--simple boundary\r\n"
  9437. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9438. ": BAD...\r\n"
  9439. "\r\n"
  9440. "value1\r\n"
  9441. "--simple boundary\r\n"
  9442. "Content-Disposition: form-data; name=\"field2\"; "
  9443. "filename=\"example.txt\"\r\n"
  9444. "\r\n"
  9445. "value2\r\n"
  9446. "--simple boundary--\r\n"
  9447. "This is the epilogue. It is also to be ignored.\r\n";
  9448. std::string content_type =
  9449. R"(multipart/form-data; boundary="simple boundary")";
  9450. Client cli(HOST, PORT);
  9451. auto res = cli.Post("/post", body, content_type.c_str());
  9452. ASSERT_TRUE(res);
  9453. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9454. }
  9455. TEST(MultipartFormDataTest, WithPreamble) {
  9456. Server svr;
  9457. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9458. res.set_content("ok", "text/plain");
  9459. });
  9460. thread t = thread([&] { svr.listen(HOST, PORT); });
  9461. auto se = detail::scope_exit([&] {
  9462. svr.stop();
  9463. t.join();
  9464. ASSERT_FALSE(svr.is_running());
  9465. });
  9466. svr.wait_until_ready();
  9467. const std::string body =
  9468. "This is the preamble. It is to be ignored, though it\r\n"
  9469. "is a handy place for composition agents to include an\r\n"
  9470. "explanatory note to non-MIME conformant readers.\r\n"
  9471. "\r\n"
  9472. "\r\n"
  9473. "--simple boundary\r\n"
  9474. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9475. "\r\n"
  9476. "value1\r\n"
  9477. "--simple boundary\r\n"
  9478. "Content-Disposition: form-data; name=\"field2\"; "
  9479. "filename=\"example.txt\"\r\n"
  9480. "\r\n"
  9481. "value2\r\n"
  9482. "--simple boundary--\r\n"
  9483. "This is the epilogue. It is also to be ignored.\r\n";
  9484. std::string content_type =
  9485. R"(multipart/form-data; boundary="simple boundary")";
  9486. Client cli(HOST, PORT);
  9487. auto res = cli.Post("/post", body, content_type.c_str());
  9488. ASSERT_TRUE(res);
  9489. EXPECT_EQ(StatusCode::OK_200, res->status);
  9490. }
  9491. TEST(MultipartFormDataTest, PostCustomBoundary) {
  9492. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9493. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  9494. const ContentReader &content_reader) {
  9495. if (req.is_multipart_form_data()) {
  9496. std::vector<FormData> items;
  9497. content_reader(
  9498. [&](const FormData &file) {
  9499. items.push_back(file);
  9500. return true;
  9501. },
  9502. [&](const char *data, size_t data_length) {
  9503. items.back().content.append(data, data_length);
  9504. return true;
  9505. });
  9506. EXPECT_TRUE(std::string(items[0].name) == "document");
  9507. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9508. EXPECT_TRUE(items[0].filename == "2MB_data");
  9509. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9510. EXPECT_TRUE(items[1].name == "hello");
  9511. EXPECT_TRUE(items[1].content == "world");
  9512. EXPECT_TRUE(items[1].filename == "");
  9513. EXPECT_TRUE(items[1].content_type == "");
  9514. } else {
  9515. std::string body;
  9516. content_reader([&](const char *data, size_t data_length) {
  9517. body.append(data, data_length);
  9518. return true;
  9519. });
  9520. }
  9521. });
  9522. auto port = svr.bind_to_any_port("localhost");
  9523. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9524. auto se = detail::scope_exit([&] {
  9525. svr.stop();
  9526. t.join();
  9527. ASSERT_FALSE(svr.is_running());
  9528. });
  9529. svr.wait_until_ready();
  9530. {
  9531. std::string data(1024 * 1024 * 2, '.');
  9532. std::stringstream buffer;
  9533. buffer << data;
  9534. SSLClient cli("localhost", port);
  9535. cli.enable_server_certificate_verification(false);
  9536. UploadFormDataItems items{
  9537. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9538. {"hello", "world", "", ""},
  9539. };
  9540. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9541. ASSERT_TRUE(res);
  9542. ASSERT_EQ(StatusCode::OK_200, res->status);
  9543. }
  9544. }
  9545. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9546. std::string data(1024 * 1024 * 2, '&');
  9547. std::stringstream buffer;
  9548. buffer << data;
  9549. Client cli("https://localhost:8080");
  9550. UploadFormDataItems items{
  9551. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9552. {"hello", "world", "", ""},
  9553. };
  9554. for (const char &c : " \t\r\n") {
  9555. auto res =
  9556. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9557. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9558. ASSERT_FALSE(res);
  9559. }
  9560. }
  9561. TEST(MultipartFormDataTest, PutFormData) {
  9562. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9563. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9564. const ContentReader &content_reader) {
  9565. if (req.is_multipart_form_data()) {
  9566. std::vector<FormData> items;
  9567. content_reader(
  9568. [&](const FormData &file) {
  9569. items.push_back(file);
  9570. return true;
  9571. },
  9572. [&](const char *data, size_t data_length) {
  9573. items.back().content.append(data, data_length);
  9574. return true;
  9575. });
  9576. EXPECT_TRUE(std::string(items[0].name) == "document");
  9577. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9578. EXPECT_TRUE(items[0].filename == "2MB_data");
  9579. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9580. EXPECT_TRUE(items[1].name == "hello");
  9581. EXPECT_TRUE(items[1].content == "world");
  9582. EXPECT_TRUE(items[1].filename == "");
  9583. EXPECT_TRUE(items[1].content_type == "");
  9584. } else {
  9585. std::string body;
  9586. content_reader([&](const char *data, size_t data_length) {
  9587. body.append(data, data_length);
  9588. return true;
  9589. });
  9590. }
  9591. });
  9592. auto port = svr.bind_to_any_port("localhost");
  9593. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9594. auto se = detail::scope_exit([&] {
  9595. svr.stop();
  9596. t.join();
  9597. ASSERT_FALSE(svr.is_running());
  9598. });
  9599. svr.wait_until_ready();
  9600. {
  9601. std::string data(1024 * 1024 * 2, '&');
  9602. std::stringstream buffer;
  9603. buffer << data;
  9604. SSLClient cli("localhost", port);
  9605. cli.enable_server_certificate_verification(false);
  9606. UploadFormDataItems items{
  9607. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9608. {"hello", "world", "", ""},
  9609. };
  9610. auto res = cli.Put("/put", items);
  9611. ASSERT_TRUE(res);
  9612. ASSERT_EQ(StatusCode::OK_200, res->status);
  9613. }
  9614. }
  9615. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  9616. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9617. svr.Put("/put_customboundary",
  9618. [&](const Request &req, const Response & /*res*/,
  9619. const ContentReader &content_reader) {
  9620. if (req.is_multipart_form_data()) {
  9621. std::vector<FormData> items;
  9622. content_reader(
  9623. [&](const FormData &file) {
  9624. items.push_back(file);
  9625. return true;
  9626. },
  9627. [&](const char *data, size_t data_length) {
  9628. items.back().content.append(data, data_length);
  9629. return true;
  9630. });
  9631. EXPECT_TRUE(std::string(items[0].name) == "document");
  9632. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9633. EXPECT_TRUE(items[0].filename == "2MB_data");
  9634. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9635. EXPECT_TRUE(items[1].name == "hello");
  9636. EXPECT_TRUE(items[1].content == "world");
  9637. EXPECT_TRUE(items[1].filename == "");
  9638. EXPECT_TRUE(items[1].content_type == "");
  9639. } else {
  9640. std::string body;
  9641. content_reader([&](const char *data, size_t data_length) {
  9642. body.append(data, data_length);
  9643. return true;
  9644. });
  9645. }
  9646. });
  9647. auto port = svr.bind_to_any_port("localhost");
  9648. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9649. auto se = detail::scope_exit([&] {
  9650. svr.stop();
  9651. t.join();
  9652. ASSERT_FALSE(svr.is_running());
  9653. });
  9654. svr.wait_until_ready();
  9655. {
  9656. std::string data(1024 * 1024 * 2, '&');
  9657. std::stringstream buffer;
  9658. buffer << data;
  9659. SSLClient cli("localhost", port);
  9660. cli.enable_server_certificate_verification(false);
  9661. UploadFormDataItems items{
  9662. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9663. {"hello", "world", "", ""},
  9664. };
  9665. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  9666. ASSERT_TRUE(res);
  9667. ASSERT_EQ(StatusCode::OK_200, res->status);
  9668. }
  9669. }
  9670. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  9671. std::string data(1024 * 1024 * 2, '&');
  9672. std::stringstream buffer;
  9673. buffer << data;
  9674. Client cli("https://localhost:8080");
  9675. cli.enable_server_certificate_verification(false);
  9676. UploadFormDataItems items{
  9677. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9678. {"hello", "world", "", ""},
  9679. };
  9680. for (const char &c : " \t\r\n") {
  9681. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  9682. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9683. ASSERT_FALSE(res);
  9684. }
  9685. }
  9686. TEST(MultipartFormDataTest, AlternateFilename) {
  9687. auto handled = false;
  9688. Server svr;
  9689. svr.Post("/test", [&](const Request &req, Response &res) {
  9690. ASSERT_EQ(2u, req.form.files.size());
  9691. ASSERT_EQ(1u, req.form.fields.size());
  9692. // Test files
  9693. const auto &file1 = req.form.get_file("file1");
  9694. ASSERT_EQ("file1", file1.name);
  9695. ASSERT_EQ("A.txt", file1.filename);
  9696. ASSERT_EQ("text/plain", file1.content_type);
  9697. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  9698. const auto &file2 = req.form.get_file("file2");
  9699. ASSERT_EQ("file2", file2.name);
  9700. ASSERT_EQ("a.html", file2.filename);
  9701. ASSERT_EQ("text/html", file2.content_type);
  9702. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  9703. file2.content);
  9704. // Test text field
  9705. const auto &text = req.form.get_field("text");
  9706. ASSERT_EQ("text default", text);
  9707. res.set_content("ok", "text/plain");
  9708. handled = true;
  9709. });
  9710. thread t = thread([&] { svr.listen(HOST, PORT); });
  9711. auto se = detail::scope_exit([&] {
  9712. svr.stop();
  9713. t.join();
  9714. ASSERT_FALSE(svr.is_running());
  9715. ASSERT_TRUE(handled);
  9716. });
  9717. svr.wait_until_ready();
  9718. auto req = "POST /test HTTP/1.1\r\n"
  9719. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9720. "Content-Length: 399\r\n"
  9721. "\r\n"
  9722. "----------\r\n"
  9723. "Content-Disposition: form-data; name=\"text\"\r\n"
  9724. "\r\n"
  9725. "text default\r\n"
  9726. "----------\r\n"
  9727. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  9728. "filename=\"a.txt\"; name=\"file1\"\r\n"
  9729. "Content-Type: text/plain\r\n"
  9730. "\r\n"
  9731. "Content of a.txt.\r\n"
  9732. "\r\n"
  9733. "----------\r\n"
  9734. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  9735. "\"a.html\"\r\n"
  9736. "Content-Type: text/html\r\n"
  9737. "\r\n"
  9738. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  9739. "\r\n"
  9740. "------------\r\n";
  9741. ASSERT_TRUE(send_request(1, req));
  9742. }
  9743. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  9744. auto handled = false;
  9745. Server svr;
  9746. svr.Post("/test", [&](const Request &req, Response &res) {
  9747. // Case-insensitive "utf-8''" prefix with a long value
  9748. const auto &file = req.form.get_file("file1");
  9749. ASSERT_EQ("file1", file.name);
  9750. // 8000 chars exercises both the Content-Disposition parser and the
  9751. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  9752. // Prior to the fix, std::regex_match on this header would cause O(N)
  9753. // stack recursion in libstdc++, leading to SIGSEGV.
  9754. std::string expected_filename(8000, 'A');
  9755. ASSERT_EQ(expected_filename, file.filename);
  9756. res.set_content("ok", "text/plain");
  9757. handled = true;
  9758. });
  9759. thread t = thread([&] { svr.listen(HOST, PORT); });
  9760. auto se = detail::scope_exit([&] {
  9761. svr.stop();
  9762. t.join();
  9763. ASSERT_FALSE(svr.is_running());
  9764. ASSERT_TRUE(handled);
  9765. });
  9766. svr.wait_until_ready();
  9767. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  9768. // Regression test for GHSA-qq6v-r583-3h69
  9769. std::string long_filename(8000, 'A');
  9770. std::string body = "----------\r\n"
  9771. "Content-Disposition: form-data; name=\"file1\"; "
  9772. "filename*=\"Utf-8''" +
  9773. long_filename +
  9774. "\"\r\n"
  9775. "\r\n"
  9776. "hello\r\n"
  9777. "------------\r\n";
  9778. auto req = "POST /test HTTP/1.1\r\n"
  9779. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9780. "Content-Length: " +
  9781. std::to_string(body.size()) + "\r\n\r\n" + body;
  9782. ASSERT_TRUE(send_request(1, req));
  9783. }
  9784. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  9785. auto handled = false;
  9786. Server svr;
  9787. svr.Post("/test", [&](const Request &req, Response &) {
  9788. ASSERT_EQ(2u, req.form.fields.size());
  9789. const auto &text1 = req.form.get_field("text1");
  9790. ASSERT_EQ("text1", text1);
  9791. const auto &text2 = req.form.get_field("text2");
  9792. ASSERT_EQ("text2", text2);
  9793. handled = true;
  9794. });
  9795. thread t = thread([&] { svr.listen(HOST, PORT); });
  9796. auto se = detail::scope_exit([&] {
  9797. svr.stop();
  9798. t.join();
  9799. ASSERT_FALSE(svr.is_running());
  9800. ASSERT_TRUE(handled);
  9801. });
  9802. svr.wait_until_ready();
  9803. auto req = "POST /test HTTP/1.1\r\n"
  9804. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9805. "Content-Length: 146\r\n"
  9806. "\r\n----------\r\n"
  9807. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9808. "\r\n"
  9809. "text1"
  9810. "\r\n----------\r\n"
  9811. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9812. "\r\n"
  9813. "text2"
  9814. "\r\n------------";
  9815. std::string response;
  9816. ASSERT_TRUE(send_request(1, req, &response));
  9817. ASSERT_EQ("200", response.substr(9, 3));
  9818. }
  9819. TEST(MultipartFormDataTest, ContentLength) {
  9820. auto handled = false;
  9821. Server svr;
  9822. svr.Post("/test", [&](const Request &req, Response &) {
  9823. ASSERT_EQ(2u, req.form.fields.size());
  9824. const auto &text1 = req.form.get_field("text1");
  9825. ASSERT_EQ("text1", text1);
  9826. const auto &text2 = req.form.get_field("text2");
  9827. ASSERT_EQ("text2", text2);
  9828. handled = true;
  9829. });
  9830. thread t = thread([&] { svr.listen(HOST, PORT); });
  9831. auto se = detail::scope_exit([&] {
  9832. svr.stop();
  9833. t.join();
  9834. ASSERT_FALSE(svr.is_running());
  9835. ASSERT_TRUE(handled);
  9836. });
  9837. svr.wait_until_ready();
  9838. auto req = "POST /test HTTP/1.1\r\n"
  9839. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9840. "Content-Length: 167\r\n"
  9841. "\r\n----------\r\n"
  9842. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9843. "Content-Length: 5\r\n"
  9844. "\r\n"
  9845. "text1"
  9846. "\r\n----------\r\n"
  9847. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9848. "\r\n"
  9849. "text2"
  9850. "\r\n------------\r\n";
  9851. std::string response;
  9852. ASSERT_TRUE(send_request(1, req, &response));
  9853. ASSERT_EQ("200", response.substr(9, 3));
  9854. }
  9855. TEST(MultipartFormDataTest, AccessPartHeaders) {
  9856. auto handled = false;
  9857. Server svr;
  9858. svr.Post("/test", [&](const Request &req, Response &) {
  9859. ASSERT_EQ(2u, req.form.fields.size());
  9860. const auto &text1 = req.form.get_field("text1");
  9861. ASSERT_EQ("text1", text1);
  9862. // TODO: Add header access for text fields if needed
  9863. const auto &text2 = req.form.get_field("text2");
  9864. ASSERT_EQ("text2", text2);
  9865. // TODO: Header access for text fields needs to be implemented
  9866. // auto &headers = it->second.headers;
  9867. // ASSERT_EQ(3U, headers.size());
  9868. // auto custom_header = headers.find("x-whatever");
  9869. // ASSERT_TRUE(custom_header != headers.end());
  9870. // ASSERT_NE("customvalue", custom_header->second);
  9871. // ASSERT_EQ("CustomValue", custom_header->second);
  9872. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  9873. handled = true;
  9874. });
  9875. thread t = thread([&] { svr.listen(HOST, PORT); });
  9876. auto se = detail::scope_exit([&] {
  9877. svr.stop();
  9878. t.join();
  9879. ASSERT_FALSE(svr.is_running());
  9880. ASSERT_TRUE(handled);
  9881. });
  9882. svr.wait_until_ready();
  9883. auto req = "POST /test HTTP/1.1\r\n"
  9884. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9885. "Content-Length: 232\r\n"
  9886. "\r\n----------\r\n"
  9887. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9888. "Content-Length: 5\r\n"
  9889. "X-Test: 1\r\n"
  9890. "\r\n"
  9891. "text1"
  9892. "\r\n----------\r\n"
  9893. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9894. "Content-Type: text/plain\r\n"
  9895. "X-Whatever: CustomValue\r\n"
  9896. "\r\n"
  9897. "text2"
  9898. "\r\n------------\r\n"
  9899. "That should be disregarded. Not even read";
  9900. std::string response;
  9901. ASSERT_TRUE(send_request(1, req, &response));
  9902. ASSERT_EQ("200", response.substr(9, 3));
  9903. }
  9904. TEST(MultipartFormDataTest, LargeHeader) {
  9905. auto handled = false;
  9906. Server svr;
  9907. svr.Post("/test", [&](const Request &req, Response &) {
  9908. ASSERT_EQ(1u, req.form.fields.size());
  9909. const auto &text = req.form.get_field("name1");
  9910. ASSERT_EQ("text1", text);
  9911. handled = true;
  9912. });
  9913. thread t = thread([&] { svr.listen(HOST, PORT); });
  9914. auto se = detail::scope_exit([&] {
  9915. svr.stop();
  9916. t.join();
  9917. ASSERT_FALSE(svr.is_running());
  9918. ASSERT_TRUE(handled);
  9919. });
  9920. svr.wait_until_ready();
  9921. auto boundary = std::string("cpp-httplib-multipart-data");
  9922. std::string content = "--" + boundary +
  9923. "\r\n"
  9924. "Content-Disposition: form-data; name=\"name1\"\r\n"
  9925. "\r\n"
  9926. "text1\r\n"
  9927. "--" +
  9928. boundary + "--\r\n";
  9929. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  9930. "Content-Type: multipart/form-data;boundary=" +
  9931. boundary +
  9932. "\r\n"
  9933. "Content-Length: " +
  9934. std::to_string(content.size()) +
  9935. "\r\n"
  9936. "Dummy-Header: ";
  9937. std::string header_suffix = "\r\n"
  9938. "\r\n";
  9939. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  9940. size_t header_dummy_size =
  9941. read_buff_size -
  9942. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  9943. auto header_dummy = std::string(header_dummy_size, '@');
  9944. auto req = header_prefix + header_dummy + header_suffix + content;
  9945. std::string response;
  9946. ASSERT_TRUE(send_request(1, req, &response));
  9947. ASSERT_EQ("200", response.substr(9, 3));
  9948. }
  9949. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  9950. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  9951. // (not chunked Transfer-Encoding) after the streaming refactor.
  9952. auto handled = false;
  9953. Server svr;
  9954. svr.Post("/upload", [&](const Request &req, Response &res) {
  9955. auto cl_it = req.headers.find("Content-Length");
  9956. EXPECT_TRUE(cl_it != req.headers.end());
  9957. auto te_it = req.headers.find("Transfer-Encoding");
  9958. EXPECT_TRUE(te_it == req.headers.end());
  9959. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  9960. res.set_content("ok", "text/plain");
  9961. handled = true;
  9962. });
  9963. auto port = svr.bind_to_any_port(HOST);
  9964. auto t = thread([&] { svr.listen_after_bind(); });
  9965. auto se = detail::scope_exit([&] {
  9966. svr.stop();
  9967. t.join();
  9968. ASSERT_FALSE(svr.is_running());
  9969. ASSERT_TRUE(handled);
  9970. });
  9971. svr.wait_until_ready();
  9972. UploadFormDataItems items = {
  9973. {"field1", "hello", "", "text/plain"},
  9974. {"file1", "world", "test.txt", "application/octet-stream"},
  9975. };
  9976. Client cli(HOST, port);
  9977. auto res = cli.Post("/upload", {}, items);
  9978. ASSERT_TRUE(res);
  9979. EXPECT_EQ(StatusCode::OK_200, res->status);
  9980. }
  9981. TEST(MultipartFormDataTest, MakeFileProvider) {
  9982. // Verify make_file_provider sends a file's contents correctly.
  9983. const std::string file_content(4096, 'Z');
  9984. const std::string tmp_path = "/tmp/httplib_test_make_file_provider.bin";
  9985. {
  9986. std::ofstream ofs(tmp_path, std::ios::binary);
  9987. ofs.write(file_content.data(),
  9988. static_cast<std::streamsize>(file_content.size()));
  9989. }
  9990. auto handled = false;
  9991. Server svr;
  9992. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  9993. const ContentReader &content_reader) {
  9994. ASSERT_TRUE(req.is_multipart_form_data());
  9995. std::vector<FormData> items;
  9996. content_reader(
  9997. [&](const FormData &file) {
  9998. items.push_back(file);
  9999. return true;
  10000. },
  10001. [&](const char *data, size_t data_length) {
  10002. items.back().content.append(data, data_length);
  10003. return true;
  10004. });
  10005. ASSERT_EQ(1u, items.size());
  10006. EXPECT_EQ("myfile", items[0].name);
  10007. EXPECT_EQ("data.bin", items[0].filename);
  10008. EXPECT_EQ("application/octet-stream", items[0].content_type);
  10009. EXPECT_EQ(file_content, items[0].content);
  10010. handled = true;
  10011. });
  10012. auto port = svr.bind_to_any_port(HOST);
  10013. auto t = thread([&] { svr.listen_after_bind(); });
  10014. auto se = detail::scope_exit([&] {
  10015. svr.stop();
  10016. t.join();
  10017. ASSERT_FALSE(svr.is_running());
  10018. ASSERT_TRUE(handled);
  10019. std::remove(tmp_path.c_str());
  10020. });
  10021. svr.wait_until_ready();
  10022. FormDataProviderItems providers;
  10023. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  10024. "application/octet-stream"));
  10025. Client cli(HOST, port);
  10026. auto res = cli.Post("/upload", {}, {}, providers);
  10027. ASSERT_TRUE(res);
  10028. EXPECT_EQ(StatusCode::OK_200, res->status);
  10029. }
  10030. TEST(MakeFileBodyTest, Basic) {
  10031. const std::string file_content(4096, 'Z');
  10032. const std::string tmp_path = "/tmp/httplib_test_make_file_body.bin";
  10033. {
  10034. std::ofstream ofs(tmp_path, std::ios::binary);
  10035. ofs.write(file_content.data(),
  10036. static_cast<std::streamsize>(file_content.size()));
  10037. }
  10038. auto handled = false;
  10039. Server svr;
  10040. svr.Post("/upload", [&](const Request &req, Response &res) {
  10041. EXPECT_EQ(file_content, req.body);
  10042. handled = true;
  10043. res.status = StatusCode::OK_200;
  10044. });
  10045. auto port = svr.bind_to_any_port(HOST);
  10046. auto t = thread([&] { svr.listen_after_bind(); });
  10047. auto se = detail::scope_exit([&] {
  10048. svr.stop();
  10049. t.join();
  10050. ASSERT_FALSE(svr.is_running());
  10051. ASSERT_TRUE(handled);
  10052. std::remove(tmp_path.c_str());
  10053. });
  10054. svr.wait_until_ready();
  10055. auto fb = make_file_body(tmp_path);
  10056. ASSERT_GT(fb.first, 0u);
  10057. Client cli(HOST, port);
  10058. auto res =
  10059. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  10060. ASSERT_TRUE(res);
  10061. EXPECT_EQ(StatusCode::OK_200, res->status);
  10062. }
  10063. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  10064. static constexpr unsigned int number_of_tasks{1000000};
  10065. std::atomic_uint count{0};
  10066. std::unique_ptr<TaskQueue> task_queue{
  10067. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  10068. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10069. auto queued = task_queue->enqueue(
  10070. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  10071. EXPECT_TRUE(queued);
  10072. }
  10073. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10074. task_queue->shutdown();
  10075. #else
  10076. EXPECT_NO_THROW(task_queue->shutdown());
  10077. #endif
  10078. EXPECT_EQ(number_of_tasks, count.load());
  10079. }
  10080. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  10081. static constexpr unsigned int number_of_tasks{1000000};
  10082. static constexpr unsigned int qlimit{2};
  10083. unsigned int queued_count{0};
  10084. std::atomic_uint count{0};
  10085. std::unique_ptr<TaskQueue> task_queue{
  10086. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  10087. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10088. if (task_queue->enqueue(
  10089. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  10090. queued_count++;
  10091. }
  10092. }
  10093. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10094. task_queue->shutdown();
  10095. #else
  10096. EXPECT_NO_THROW(task_queue->shutdown());
  10097. #endif
  10098. EXPECT_EQ(queued_count, count.load());
  10099. EXPECT_TRUE(queued_count <= number_of_tasks);
  10100. EXPECT_TRUE(queued_count >= qlimit);
  10101. }
  10102. TEST(TaskQueueTest, MaxQueuedRequests) {
  10103. static constexpr unsigned int qlimit{3};
  10104. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  10105. std::condition_variable sem_cv;
  10106. std::mutex sem_mtx;
  10107. int credits = 0;
  10108. bool queued;
  10109. /* Fill up the queue with tasks that will block until we give them credits to
  10110. * complete. */
  10111. for (unsigned int n = 0; n <= qlimit;) {
  10112. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  10113. std::unique_lock<std::mutex> lock(sem_mtx);
  10114. while (credits <= 0) {
  10115. sem_cv.wait(lock);
  10116. }
  10117. /* Consume the credit and signal the test code if they are all gone. */
  10118. if (--credits == 0) { sem_cv.notify_one(); }
  10119. });
  10120. if (n < qlimit) {
  10121. /* The first qlimit enqueues must succeed. */
  10122. EXPECT_TRUE(queued);
  10123. } else {
  10124. /* The last one will succeed only when the worker thread
  10125. * starts and dequeues the first blocking task. Although
  10126. * not necessary for the correctness of this test, we sleep for
  10127. * a short while to avoid busy waiting. */
  10128. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10129. }
  10130. if (queued) { n++; }
  10131. }
  10132. /* Further enqueues must fail since the queue is full. */
  10133. for (auto i = 0; i < 4; i++) {
  10134. queued = task_queue->enqueue([] {});
  10135. EXPECT_FALSE(queued);
  10136. }
  10137. /* Give the credits to allow the previous tasks to complete. */
  10138. {
  10139. std::unique_lock<std::mutex> lock(sem_mtx);
  10140. credits += qlimit + 1;
  10141. }
  10142. sem_cv.notify_all();
  10143. /* Wait for all the credits to be consumed. */
  10144. {
  10145. std::unique_lock<std::mutex> lock(sem_mtx);
  10146. while (credits > 0) {
  10147. sem_cv.wait(lock);
  10148. }
  10149. }
  10150. /* Check that we are able again to enqueue at least qlimit tasks. */
  10151. for (unsigned int i = 0; i < qlimit; i++) {
  10152. queued = task_queue->enqueue([] {});
  10153. EXPECT_TRUE(queued);
  10154. }
  10155. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10156. task_queue->shutdown();
  10157. #else
  10158. EXPECT_NO_THROW(task_queue->shutdown());
  10159. #endif
  10160. }
  10161. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  10162. Server svr;
  10163. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10164. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  10165. });
  10166. svr.Get("/hello", [](const Request &req, Response &res) {
  10167. res.set_content(req.get_param_value("key"), "text/plain");
  10168. });
  10169. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10170. auto se = detail::scope_exit([&] {
  10171. svr.stop();
  10172. thread.join();
  10173. ASSERT_FALSE(svr.is_running());
  10174. });
  10175. svr.wait_until_ready();
  10176. {
  10177. Client cli(HOST, PORT);
  10178. cli.set_follow_location(true);
  10179. auto res = cli.Get("/");
  10180. ASSERT_TRUE(res);
  10181. EXPECT_EQ(StatusCode::OK_200, res->status);
  10182. EXPECT_EQ("val&key2=val2", res->body);
  10183. }
  10184. }
  10185. #endif
  10186. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  10187. Server svr;
  10188. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10189. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  10190. });
  10191. svr.Get("/hello", [](const Request &req, Response &res) {
  10192. res.set_content(req.get_param_value("key"), "text/plain");
  10193. });
  10194. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10195. auto se = detail::scope_exit([&] {
  10196. svr.stop();
  10197. thread.join();
  10198. ASSERT_FALSE(svr.is_running());
  10199. });
  10200. svr.wait_until_ready();
  10201. {
  10202. Client cli(HOST, PORT);
  10203. cli.set_follow_location(true);
  10204. auto res = cli.Get("/");
  10205. ASSERT_TRUE(res);
  10206. EXPECT_EQ(StatusCode::OK_200, res->status);
  10207. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  10208. }
  10209. }
  10210. #ifdef CPPHTTPLIB_SSL_ENABLED
  10211. TEST(RedirectTest, Issue2185_Online) {
  10212. SSLClient client("github.com");
  10213. client.set_follow_location(true);
  10214. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  10215. "Coollab-Windows.zip");
  10216. ASSERT_TRUE(res);
  10217. EXPECT_EQ(StatusCode::OK_200, res->status);
  10218. EXPECT_EQ(9920427U, res->body.size());
  10219. }
  10220. #endif
  10221. TEST(VulnerabilityTest, CRLFInjection) {
  10222. Server svr;
  10223. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  10224. res.set_content("Hello 1", "text/plain");
  10225. });
  10226. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  10227. res.set_content("Hello 2", "text/plain");
  10228. });
  10229. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  10230. res.set_content("Hello 3", "text/plain");
  10231. });
  10232. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  10233. res.set_content("Hello 4", "text/plain");
  10234. });
  10235. svr.set_logger([](const Request &req, const Response & /*res*/) {
  10236. for (const auto &x : req.headers) {
  10237. auto key = x.first;
  10238. EXPECT_STRNE("evil", key.c_str());
  10239. }
  10240. });
  10241. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10242. auto se = detail::scope_exit([&] {
  10243. svr.stop();
  10244. thread.join();
  10245. ASSERT_FALSE(svr.is_running());
  10246. });
  10247. svr.wait_until_ready();
  10248. {
  10249. Client cli(HOST, PORT);
  10250. cli.Post("/test1", "A=B",
  10251. "application/x-www-form-urlencoded\r\nevil: hello1");
  10252. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  10253. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  10254. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  10255. }
  10256. }
  10257. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  10258. auto server_thread = std::thread([] {
  10259. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10260. default_socket_options(srv);
  10261. sockaddr_in addr{};
  10262. addr.sin_family = AF_INET;
  10263. addr.sin_port = htons(PORT + 1);
  10264. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10265. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10266. ::listen(srv, 1);
  10267. sockaddr_in cli_addr{};
  10268. socklen_t cli_len = sizeof(cli_addr);
  10269. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10270. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  10271. std::string buf_all;
  10272. char buf[2048];
  10273. ssize_t n;
  10274. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  10275. buf_all.append(buf, static_cast<size_t>(n));
  10276. size_t pos;
  10277. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  10278. auto request_block = buf_all.substr(0, pos + 4); // include separator
  10279. auto e = request_block.find("\r\n");
  10280. if (e != std::string::npos) {
  10281. auto request_line = request_block.substr(0, e);
  10282. std::string msg =
  10283. "CRLF injection detected in request line: '" + request_line + "'";
  10284. EXPECT_FALSE(true) << msg;
  10285. }
  10286. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  10287. ::send(cli,
  10288. #ifdef _WIN32
  10289. static_cast<const char *>(resp.c_str()),
  10290. static_cast<int>(resp.size()),
  10291. #else
  10292. resp.c_str(), resp.size(),
  10293. #endif
  10294. 0);
  10295. buf_all.erase(0, pos + 4);
  10296. }
  10297. }
  10298. detail::close_socket(cli);
  10299. detail::close_socket(srv);
  10300. });
  10301. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10302. auto cli = Client("127.0.0.1", PORT + 1);
  10303. auto headers = Headers{
  10304. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  10305. {"Connection", "keep-alive"}};
  10306. auto res = cli.Get("/hi", headers);
  10307. EXPECT_FALSE(res);
  10308. EXPECT_EQ(Error::InvalidHeaders, res.error());
  10309. server_thread.join();
  10310. }
  10311. TEST(PathParamsTest, StaticMatch) {
  10312. const auto pattern = "/users/all";
  10313. detail::PathParamsMatcher matcher(pattern);
  10314. Request request;
  10315. request.path = "/users/all";
  10316. ASSERT_TRUE(matcher.match(request));
  10317. std::unordered_map<std::string, std::string> expected_params = {};
  10318. EXPECT_EQ(request.path_params, expected_params);
  10319. }
  10320. TEST(PathParamsTest, StaticMismatch) {
  10321. const auto pattern = "/users/all";
  10322. detail::PathParamsMatcher matcher(pattern);
  10323. Request request;
  10324. request.path = "/users/1";
  10325. ASSERT_FALSE(matcher.match(request));
  10326. }
  10327. TEST(PathParamsTest, SingleParamInTheMiddle) {
  10328. const auto pattern = "/users/:id/subscriptions";
  10329. detail::PathParamsMatcher matcher(pattern);
  10330. Request request;
  10331. request.path = "/users/42/subscriptions";
  10332. ASSERT_TRUE(matcher.match(request));
  10333. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10334. EXPECT_EQ(request.path_params, expected_params);
  10335. }
  10336. TEST(PathParamsTest, SingleParamInTheEnd) {
  10337. const auto pattern = "/users/:id";
  10338. detail::PathParamsMatcher matcher(pattern);
  10339. Request request;
  10340. request.path = "/users/24";
  10341. ASSERT_TRUE(matcher.match(request));
  10342. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  10343. EXPECT_EQ(request.path_params, expected_params);
  10344. }
  10345. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  10346. const auto pattern = "/users/:id/";
  10347. detail::PathParamsMatcher matcher(pattern);
  10348. Request request;
  10349. request.path = "/users/42/";
  10350. ASSERT_TRUE(matcher.match(request));
  10351. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10352. EXPECT_EQ(request.path_params, expected_params);
  10353. }
  10354. TEST(PathParamsTest, EmptyParam) {
  10355. const auto pattern = "/users/:id/";
  10356. detail::PathParamsMatcher matcher(pattern);
  10357. Request request;
  10358. request.path = "/users//";
  10359. ASSERT_TRUE(matcher.match(request));
  10360. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10361. EXPECT_EQ(request.path_params, expected_params);
  10362. }
  10363. TEST(PathParamsTest, FragmentMismatch) {
  10364. const auto pattern = "/users/:id/";
  10365. detail::PathParamsMatcher matcher(pattern);
  10366. Request request;
  10367. request.path = "/admins/24/";
  10368. ASSERT_FALSE(matcher.match(request));
  10369. }
  10370. TEST(PathParamsTest, ExtraFragments) {
  10371. const auto pattern = "/users/:id";
  10372. detail::PathParamsMatcher matcher(pattern);
  10373. Request request;
  10374. request.path = "/users/42/subscriptions";
  10375. ASSERT_FALSE(matcher.match(request));
  10376. }
  10377. TEST(PathParamsTest, MissingTrailingParam) {
  10378. const auto pattern = "/users/:id";
  10379. detail::PathParamsMatcher matcher(pattern);
  10380. Request request;
  10381. request.path = "/users";
  10382. ASSERT_FALSE(matcher.match(request));
  10383. }
  10384. TEST(PathParamsTest, MissingParamInTheMiddle) {
  10385. const auto pattern = "/users/:id/subscriptions";
  10386. detail::PathParamsMatcher matcher(pattern);
  10387. Request request;
  10388. request.path = "/users/subscriptions";
  10389. ASSERT_FALSE(matcher.match(request));
  10390. }
  10391. TEST(PathParamsTest, MultipleParams) {
  10392. const auto pattern = "/users/:userid/subscriptions/:subid";
  10393. detail::PathParamsMatcher matcher(pattern);
  10394. Request request;
  10395. request.path = "/users/42/subscriptions/2";
  10396. ASSERT_TRUE(matcher.match(request));
  10397. std::unordered_map<std::string, std::string> expected_params = {
  10398. {"userid", "42"}, {"subid", "2"}};
  10399. EXPECT_EQ(request.path_params, expected_params);
  10400. }
  10401. TEST(PathParamsTest, SequenceOfParams) {
  10402. const auto pattern = "/values/:x/:y/:z";
  10403. detail::PathParamsMatcher matcher(pattern);
  10404. Request request;
  10405. request.path = "/values/1/2/3";
  10406. ASSERT_TRUE(matcher.match(request));
  10407. std::unordered_map<std::string, std::string> expected_params = {
  10408. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  10409. EXPECT_EQ(request.path_params, expected_params);
  10410. }
  10411. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  10412. const auto pattern = "/prefix:suffix";
  10413. detail::PathParamsMatcher matcher(pattern);
  10414. Request request;
  10415. request.path = "/prefix:suffix";
  10416. ASSERT_TRUE(matcher.match(request));
  10417. const std::unordered_map<std::string, std::string> expected_params = {};
  10418. EXPECT_EQ(request.path_params, expected_params);
  10419. }
  10420. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  10421. // If ipv6 regex working, regex match codepath is taken.
  10422. // else port will default to 80 in Client impl
  10423. int clientImplMagicPort = 80;
  10424. int port = 4321;
  10425. // above ports must be different to avoid false negative
  10426. EXPECT_NE(clientImplMagicPort, port);
  10427. std::string ipV6TestURL = "http://[ff06::c3]";
  10428. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  10429. CLIENT_PRIVATE_KEY_FILE);
  10430. EXPECT_EQ(cli.port(), port);
  10431. }
  10432. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  10433. auto file_path = "./www/dir/index.html";
  10434. auto dir_path = "./www/dir";
  10435. detail::FileStat stat_file(file_path);
  10436. EXPECT_TRUE(stat_file.is_file());
  10437. EXPECT_FALSE(stat_file.is_dir());
  10438. detail::FileStat stat_dir(dir_path);
  10439. EXPECT_FALSE(stat_dir.is_file());
  10440. EXPECT_TRUE(stat_dir.is_dir());
  10441. }
  10442. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  10443. // IPv4 with default HTTP port (80)
  10444. EXPECT_EQ("example.com",
  10445. detail::make_host_and_port_string("example.com", 80, false));
  10446. // IPv4 with default HTTPS port (443)
  10447. EXPECT_EQ("example.com",
  10448. detail::make_host_and_port_string("example.com", 443, true));
  10449. // IPv4 with non-default HTTP port
  10450. EXPECT_EQ("example.com:8080",
  10451. detail::make_host_and_port_string("example.com", 8080, false));
  10452. // IPv4 with non-default HTTPS port
  10453. EXPECT_EQ("example.com:8443",
  10454. detail::make_host_and_port_string("example.com", 8443, true));
  10455. // IPv6 with default HTTP port (80)
  10456. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  10457. // IPv6 with default HTTPS port (443)
  10458. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  10459. // IPv6 with non-default HTTP port
  10460. EXPECT_EQ("[::1]:8080",
  10461. detail::make_host_and_port_string("::1", 8080, false));
  10462. // IPv6 with non-default HTTPS port
  10463. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  10464. // IPv6 full address with default port
  10465. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  10466. detail::make_host_and_port_string(
  10467. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  10468. // IPv6 full address with non-default port
  10469. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  10470. detail::make_host_and_port_string(
  10471. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  10472. // IPv6 localhost with non-default port
  10473. EXPECT_EQ("[::1]:3000",
  10474. detail::make_host_and_port_string("::1", 3000, false));
  10475. // IPv6 with zone ID (link-local address) with default port
  10476. EXPECT_EQ("[fe80::1%eth0]",
  10477. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  10478. // IPv6 with zone ID (link-local address) with non-default port
  10479. EXPECT_EQ("[fe80::1%eth0]:8080",
  10480. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  10481. // Edge case: Port 443 with is_ssl=false (should add port)
  10482. EXPECT_EQ("example.com:443",
  10483. detail::make_host_and_port_string("example.com", 443, false));
  10484. // Edge case: Port 80 with is_ssl=true (should add port)
  10485. EXPECT_EQ("example.com:80",
  10486. detail::make_host_and_port_string("example.com", 80, true));
  10487. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  10488. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  10489. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  10490. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  10491. // Security fix: Already bracketed IPv6 should not get double brackets
  10492. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  10493. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  10494. EXPECT_EQ("[::1]:8080",
  10495. detail::make_host_and_port_string("[::1]", 8080, false));
  10496. EXPECT_EQ("[2001:db8::1]:8080",
  10497. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  10498. EXPECT_EQ("[fe80::1%eth0]",
  10499. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  10500. EXPECT_EQ("[fe80::1%eth0]:8080",
  10501. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  10502. // Edge case: Empty host (should return as-is)
  10503. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  10504. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  10505. // This is a known limitation but shouldn't crash
  10506. EXPECT_EQ("[host:name]",
  10507. detail::make_host_and_port_string("host:name", 80, false));
  10508. // Port number edge cases (no validation, but should not crash)
  10509. EXPECT_EQ("example.com:0",
  10510. detail::make_host_and_port_string("example.com", 0, false));
  10511. EXPECT_EQ("example.com:-1",
  10512. detail::make_host_and_port_string("example.com", -1, false));
  10513. EXPECT_EQ("example.com:65535",
  10514. detail::make_host_and_port_string("example.com", 65535, false));
  10515. EXPECT_EQ("example.com:65536",
  10516. detail::make_host_and_port_string("example.com", 65536, false));
  10517. }
  10518. #ifdef CPPHTTPLIB_SSL_ENABLED
  10519. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  10520. httplib::SSLClient cli("roblox.com", 443);
  10521. cli.set_follow_location(true);
  10522. auto res = cli.Get("/");
  10523. ASSERT_TRUE(res);
  10524. EXPECT_EQ(StatusCode::OK_200, res->status);
  10525. }
  10526. #endif
  10527. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  10528. Server svr;
  10529. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10530. EXPECT_EQ(res.status, 400);
  10531. });
  10532. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10533. auto se = detail::scope_exit([&] {
  10534. svr.stop();
  10535. thread.join();
  10536. ASSERT_FALSE(svr.is_running());
  10537. });
  10538. svr.wait_until_ready();
  10539. Client cli(HOST, PORT);
  10540. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  10541. }
  10542. TEST(InvalidHeaderCharsTest, is_field_name) {
  10543. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  10544. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  10545. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  10546. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  10547. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  10548. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  10549. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  10550. EXPECT_FALSE(detail::fields::is_field_name(""));
  10551. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  10552. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  10553. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  10554. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  10555. }
  10556. TEST(InvalidHeaderCharsTest, is_field_value) {
  10557. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  10558. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  10559. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  10560. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  10561. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  10562. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  10563. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  10564. EXPECT_TRUE(detail::fields::is_field_value(""));
  10565. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  10566. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  10567. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  10568. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  10569. EXPECT_TRUE(detail::fields::is_field_value("0"));
  10570. }
  10571. TEST(InvalidHeaderCharsTest, OnServer) {
  10572. Server svr;
  10573. svr.Get("/test_name", [&](const Request &req, Response &res) {
  10574. std::string header = "Not Set";
  10575. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10576. res.set_header(header, "value");
  10577. res.set_content("Page Content Page Content", "text/plain");
  10578. });
  10579. svr.Get("/test_value", [&](const Request &req, Response &res) {
  10580. std::string header = "Not Set";
  10581. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10582. res.set_header("X-Test", header);
  10583. res.set_content("Page Content Page Content", "text/plain");
  10584. });
  10585. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10586. auto se = detail::scope_exit([&] {
  10587. svr.stop();
  10588. thread.join();
  10589. ASSERT_FALSE(svr.is_running());
  10590. });
  10591. svr.wait_until_ready();
  10592. Client cli(HOST, PORT);
  10593. {
  10594. auto res = cli.Get(
  10595. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10596. ASSERT_TRUE(res);
  10597. EXPECT_EQ("Page Content Page Content", res->body);
  10598. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10599. }
  10600. {
  10601. auto res = cli.Get(
  10602. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10603. ASSERT_TRUE(res);
  10604. EXPECT_EQ("Page Content Page Content", res->body);
  10605. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10606. }
  10607. }
  10608. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  10609. auto handled = false;
  10610. Server svr;
  10611. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10612. thread t = thread([&] { svr.listen(HOST, PORT); });
  10613. auto se = detail::scope_exit([&] {
  10614. svr.stop();
  10615. t.join();
  10616. ASSERT_FALSE(svr.is_running());
  10617. ASSERT_FALSE(handled);
  10618. });
  10619. svr.wait_until_ready();
  10620. auto req = "POST /test HTTP/1.1\r\n"
  10621. "Content-Length: x\r\n"
  10622. "\r\n";
  10623. std::string response;
  10624. ASSERT_TRUE(send_request(1, req, &response));
  10625. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10626. response.substr(0, response.find("\r\n")));
  10627. }
  10628. #ifndef _WIN32
  10629. TEST(Expect100ContinueTest, ServerClosesConnection) {
  10630. static constexpr char reject[] = "Unauthorized";
  10631. static constexpr char accept[] = "Upload accepted";
  10632. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  10633. Server svr;
  10634. svr.set_expect_100_continue_handler(
  10635. [](const Request & /*req*/, Response &res) {
  10636. res.status = StatusCode::Unauthorized_401;
  10637. res.set_content(reject, "text/plain");
  10638. return res.status;
  10639. });
  10640. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  10641. res.set_content(accept, "text/plain");
  10642. });
  10643. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10644. auto se = detail::scope_exit([&] {
  10645. svr.stop();
  10646. thread.join();
  10647. ASSERT_FALSE(svr.is_running());
  10648. });
  10649. svr.wait_until_ready();
  10650. {
  10651. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  10652. curl_easy_init(), &curl_easy_cleanup};
  10653. ASSERT_NE(curl, nullptr);
  10654. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  10655. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  10656. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  10657. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  10658. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  10659. &curl_slist_free_all};
  10660. ASSERT_NE(list, nullptr);
  10661. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  10662. struct read_data {
  10663. size_t read_size;
  10664. size_t total_size;
  10665. } data = {0, total_size};
  10666. using read_callback_t =
  10667. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10668. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  10669. void *userdata) -> size_t {
  10670. read_data *data = (read_data *)userdata;
  10671. if (!userdata || data->read_size >= data->total_size) { return 0; }
  10672. std::fill_n(ptr, size * nmemb, 'A');
  10673. data->read_size += size * nmemb;
  10674. return size * nmemb;
  10675. };
  10676. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  10677. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  10678. std::vector<char> buffer;
  10679. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  10680. using write_callback_t =
  10681. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10682. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  10683. void *userdata) -> size_t {
  10684. std::vector<char> *buffer = (std::vector<char> *)userdata;
  10685. buffer->reserve(buffer->size() + size * nmemb + 1);
  10686. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  10687. return size * nmemb;
  10688. };
  10689. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  10690. {
  10691. const auto res = curl_easy_perform(curl.get());
  10692. ASSERT_EQ(res, CURLE_OK);
  10693. }
  10694. {
  10695. auto response_code = long{};
  10696. const auto res =
  10697. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  10698. ASSERT_EQ(res, CURLE_OK);
  10699. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  10700. }
  10701. {
  10702. auto dl = curl_off_t{};
  10703. const auto res =
  10704. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  10705. ASSERT_EQ(res, CURLE_OK);
  10706. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  10707. }
  10708. {
  10709. buffer.push_back('\0');
  10710. ASSERT_STRCASEEQ(buffer.data(), reject);
  10711. }
  10712. }
  10713. }
  10714. #endif
  10715. template <typename S, typename C>
  10716. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  10717. svr.Get("/stream", [&](const Request &, Response &res) {
  10718. auto data = new std::string("01234567890123456789");
  10719. res.set_content_provider(
  10720. data->size(), "text/plain",
  10721. [&, data](size_t offset, size_t length, DataSink &sink) {
  10722. const size_t DATA_CHUNK_SIZE = 4;
  10723. const auto &d = *data;
  10724. std::this_thread::sleep_for(std::chrono::seconds(1));
  10725. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  10726. return true;
  10727. },
  10728. [data](bool success) {
  10729. EXPECT_FALSE(success);
  10730. delete data;
  10731. });
  10732. });
  10733. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  10734. auto i = new size_t(0);
  10735. res.set_content_provider(
  10736. "text/plain",
  10737. [i](size_t, DataSink &sink) {
  10738. if (*i < 5) {
  10739. std::this_thread::sleep_for(std::chrono::seconds(1));
  10740. sink.write("abcd", 4);
  10741. (*i)++;
  10742. } else {
  10743. sink.done();
  10744. }
  10745. return true;
  10746. },
  10747. [i](bool success) {
  10748. EXPECT_FALSE(success);
  10749. delete i;
  10750. });
  10751. });
  10752. svr.Get("/chunked", [&](const Request &, Response &res) {
  10753. auto i = new size_t(0);
  10754. res.set_chunked_content_provider(
  10755. "text/plain",
  10756. [i](size_t, DataSink &sink) {
  10757. if (*i < 5) {
  10758. std::this_thread::sleep_for(std::chrono::seconds(1));
  10759. sink.os << "abcd";
  10760. (*i)++;
  10761. } else {
  10762. sink.done();
  10763. }
  10764. return true;
  10765. },
  10766. [i](bool success) {
  10767. EXPECT_FALSE(success);
  10768. delete i;
  10769. });
  10770. });
  10771. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10772. auto se = detail::scope_exit([&] {
  10773. svr.stop();
  10774. listen_thread.join();
  10775. ASSERT_FALSE(svr.is_running());
  10776. });
  10777. svr.wait_until_ready();
  10778. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  10779. {
  10780. auto start = std::chrono::steady_clock::now();
  10781. auto res = cli.Get("/stream");
  10782. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10783. std::chrono::steady_clock::now() - start)
  10784. .count();
  10785. ASSERT_FALSE(res);
  10786. EXPECT_EQ(Error::Read, res.error());
  10787. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10788. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10789. }
  10790. {
  10791. auto start = std::chrono::steady_clock::now();
  10792. auto res = cli.Get("/stream_without_length");
  10793. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10794. std::chrono::steady_clock::now() - start)
  10795. .count();
  10796. ASSERT_FALSE(res);
  10797. EXPECT_EQ(Error::Read, res.error());
  10798. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10799. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10800. }
  10801. {
  10802. auto start = std::chrono::steady_clock::now();
  10803. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  10804. EXPECT_EQ("abcd", string(data, data_length));
  10805. return true;
  10806. });
  10807. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10808. std::chrono::steady_clock::now() - start)
  10809. .count();
  10810. ASSERT_FALSE(res);
  10811. EXPECT_EQ(Error::Read, res.error());
  10812. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10813. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10814. }
  10815. }
  10816. TEST(MaxTimeoutTest, ContentStream) {
  10817. time_t timeout = 2000;
  10818. time_t threshold = 200;
  10819. Server svr;
  10820. Client cli("localhost", PORT);
  10821. max_timeout_test(svr, cli, timeout, threshold);
  10822. }
  10823. #ifdef CPPHTTPLIB_SSL_ENABLED
  10824. TEST(MaxTimeoutTest, ContentStreamSSL) {
  10825. time_t timeout = 2000;
  10826. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  10827. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10828. SSLClient cli("localhost", PORT);
  10829. cli.enable_server_certificate_verification(false);
  10830. max_timeout_test(svr, cli, timeout, threshold);
  10831. }
  10832. #endif
  10833. class EventDispatcher {
  10834. public:
  10835. EventDispatcher() {}
  10836. bool wait_event(DataSink *sink) {
  10837. unique_lock<mutex> lk(m_);
  10838. int id = id_;
  10839. // Wait with timeout to prevent hanging if client disconnects
  10840. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  10841. [&] { return cid_ == id; })) {
  10842. return false; // Timeout occurred
  10843. }
  10844. sink->write(message_.data(), message_.size());
  10845. return true;
  10846. }
  10847. void send_event(const string &message) {
  10848. lock_guard<mutex> lk(m_);
  10849. cid_ = id_++;
  10850. message_ = message;
  10851. cv_.notify_all();
  10852. }
  10853. private:
  10854. mutex m_;
  10855. condition_variable cv_;
  10856. atomic_int id_{0};
  10857. atomic_int cid_{-1};
  10858. string message_;
  10859. };
  10860. TEST(ClientInThreadTest, Issue2068) {
  10861. EventDispatcher ed;
  10862. Server svr;
  10863. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  10864. res.set_chunked_content_provider("text/event-stream",
  10865. [&](size_t /*offset*/, DataSink &sink) {
  10866. return ed.wait_event(&sink);
  10867. });
  10868. });
  10869. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10870. svr.wait_until_ready();
  10871. thread event_thread([&] {
  10872. int id = 0;
  10873. while (svr.is_running()) {
  10874. this_thread::sleep_for(chrono::milliseconds(500));
  10875. std::stringstream ss;
  10876. ss << "data: " << id << "\n\n";
  10877. ed.send_event(ss.str());
  10878. id++;
  10879. }
  10880. });
  10881. auto se = detail::scope_exit([&] {
  10882. svr.stop();
  10883. listen_thread.join();
  10884. event_thread.join();
  10885. ASSERT_FALSE(svr.is_running());
  10886. });
  10887. {
  10888. auto client = detail::make_unique<Client>(HOST, PORT);
  10889. client->set_read_timeout(std::chrono::minutes(10));
  10890. std::atomic<bool> stop{false};
  10891. std::thread t([&] {
  10892. client->Get("/event1",
  10893. [&](const char *, size_t) -> bool { return !stop; });
  10894. });
  10895. std::this_thread::sleep_for(std::chrono::seconds(2));
  10896. stop = true;
  10897. client->stop();
  10898. t.join();
  10899. // Reset client after thread has finished
  10900. client.reset();
  10901. }
  10902. }
  10903. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  10904. auto handled = false;
  10905. Server svr;
  10906. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10907. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10908. auto se = detail::scope_exit([&] {
  10909. svr.stop();
  10910. t.join();
  10911. ASSERT_FALSE(svr.is_running());
  10912. ASSERT_FALSE(handled);
  10913. });
  10914. svr.wait_until_ready();
  10915. // Two Content-Length headers with different values — must be rejected
  10916. auto req = "POST /test HTTP/1.1\r\n"
  10917. "Content-Length: 5\r\n"
  10918. "Content-Length: 10\r\n"
  10919. "\r\n"
  10920. "hello";
  10921. std::string response;
  10922. ASSERT_TRUE(send_request(1, req, &response));
  10923. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10924. response.substr(0, response.find("\r\n")));
  10925. }
  10926. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  10927. auto handled = false;
  10928. Server svr;
  10929. svr.Post("/test", [&](const Request &, Response &res) {
  10930. handled = true;
  10931. res.set_content("ok", "text/plain");
  10932. });
  10933. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10934. auto se = detail::scope_exit([&] {
  10935. svr.stop();
  10936. t.join();
  10937. ASSERT_FALSE(svr.is_running());
  10938. ASSERT_TRUE(handled);
  10939. });
  10940. svr.wait_until_ready();
  10941. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  10942. auto req = "POST /test HTTP/1.1\r\n"
  10943. "Content-Length: 5\r\n"
  10944. "Content-Length: 5\r\n"
  10945. "\r\n"
  10946. "hello";
  10947. std::string response;
  10948. ASSERT_TRUE(send_request(1, req, &response));
  10949. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  10950. }
  10951. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  10952. Server svr;
  10953. svr.Get("/", [](const Request &req, Response &res) {
  10954. EXPECT_EQ(2U, req.trailers.size());
  10955. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  10956. // Denied
  10957. EXPECT_FALSE(req.has_trailer("Content-Length"));
  10958. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  10959. // Accepted
  10960. EXPECT_TRUE(req.has_trailer("X-Hello"));
  10961. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  10962. EXPECT_TRUE(req.has_trailer("X-World"));
  10963. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  10964. res.set_content("ok", "text/plain");
  10965. });
  10966. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10967. auto se = detail::scope_exit([&] {
  10968. svr.stop();
  10969. t.join();
  10970. ASSERT_FALSE(svr.is_running());
  10971. });
  10972. svr.wait_until_ready();
  10973. const std::string req = "GET / HTTP/1.1\r\n"
  10974. "Transfer-Encoding: chunked\r\n"
  10975. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  10976. "\r\n"
  10977. "0\r\n"
  10978. "Content-Length: 10\r\n"
  10979. "Host: internal.local\r\n"
  10980. "Content-Type: malicious/content\r\n"
  10981. "Cookie: any\r\n"
  10982. "Set-Cookie: any\r\n"
  10983. "X-Forwarded-For: attacker.com\r\n"
  10984. "X-Real-Ip: 1.1.1.1\r\n"
  10985. "X-Hello: hello\r\n"
  10986. "X-World: world\r\n"
  10987. "\r\n";
  10988. std::string res;
  10989. ASSERT_TRUE(send_request(1, req, &res));
  10990. }
  10991. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  10992. Server svr;
  10993. std::string observed_remote_addr;
  10994. std::string observed_xff;
  10995. svr.Get("/ip", [&](const Request &req, Response &res) {
  10996. observed_remote_addr = req.remote_addr;
  10997. observed_xff = req.get_header_value("X-Forwarded-For");
  10998. res.set_content("ok", "text/plain");
  10999. });
  11000. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11001. auto se = detail::scope_exit([&] {
  11002. svr.stop();
  11003. t.join();
  11004. ASSERT_FALSE(svr.is_running());
  11005. });
  11006. svr.wait_until_ready();
  11007. Client cli(HOST, PORT);
  11008. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  11009. ASSERT_TRUE(res);
  11010. EXPECT_EQ(StatusCode::OK_200, res->status);
  11011. EXPECT_EQ(observed_xff, "203.0.113.66");
  11012. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11013. observed_remote_addr == "127.0.0.1");
  11014. }
  11015. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  11016. Server svr;
  11017. svr.set_trusted_proxies({"203.0.113.66"});
  11018. std::string observed_remote_addr;
  11019. std::string observed_xff;
  11020. svr.Get("/ip", [&](const Request &req, Response &res) {
  11021. observed_remote_addr = req.remote_addr;
  11022. observed_xff = req.get_header_value("X-Forwarded-For");
  11023. res.set_content("ok", "text/plain");
  11024. });
  11025. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11026. auto se = detail::scope_exit([&] {
  11027. svr.stop();
  11028. t.join();
  11029. ASSERT_FALSE(svr.is_running());
  11030. });
  11031. svr.wait_until_ready();
  11032. Client cli(HOST, PORT);
  11033. auto res = cli.Get("/ip");
  11034. ASSERT_TRUE(res);
  11035. EXPECT_EQ(StatusCode::OK_200, res->status);
  11036. EXPECT_EQ(observed_xff, "");
  11037. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11038. observed_remote_addr == "127.0.0.1");
  11039. }
  11040. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  11041. Server svr;
  11042. svr.set_trusted_proxies({"203.0.113.66"});
  11043. std::string observed_remote_addr;
  11044. std::string observed_xff;
  11045. svr.Get("/ip", [&](const Request &req, Response &res) {
  11046. observed_remote_addr = req.remote_addr;
  11047. observed_xff = req.get_header_value("X-Forwarded-For");
  11048. res.set_content("ok", "text/plain");
  11049. });
  11050. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11051. auto se = detail::scope_exit([&] {
  11052. svr.stop();
  11053. t.join();
  11054. ASSERT_FALSE(svr.is_running());
  11055. });
  11056. svr.wait_until_ready();
  11057. Client cli(HOST, PORT);
  11058. auto res =
  11059. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  11060. ASSERT_TRUE(res);
  11061. EXPECT_EQ(StatusCode::OK_200, res->status);
  11062. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  11063. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11064. }
  11065. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  11066. Server svr;
  11067. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  11068. std::string observed_remote_addr;
  11069. std::string observed_xff;
  11070. svr.Get("/ip", [&](const Request &req, Response &res) {
  11071. observed_remote_addr = req.remote_addr;
  11072. observed_xff = req.get_header_value("X-Forwarded-For");
  11073. res.set_content("ok", "text/plain");
  11074. });
  11075. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11076. auto se = detail::scope_exit([&] {
  11077. svr.stop();
  11078. t.join();
  11079. ASSERT_FALSE(svr.is_running());
  11080. });
  11081. svr.wait_until_ready();
  11082. Client cli(HOST, PORT);
  11083. auto res = cli.Get(
  11084. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11085. ASSERT_TRUE(res);
  11086. EXPECT_EQ(StatusCode::OK_200, res->status);
  11087. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11088. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11089. }
  11090. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  11091. Server svr;
  11092. svr.set_trusted_proxies({"192.0.2.45"});
  11093. std::string observed_remote_addr;
  11094. std::string observed_xff;
  11095. svr.Get("/ip", [&](const Request &req, Response &res) {
  11096. observed_remote_addr = req.remote_addr;
  11097. observed_xff = req.get_header_value("X-Forwarded-For");
  11098. res.set_content("ok", "text/plain");
  11099. });
  11100. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11101. auto se = detail::scope_exit([&] {
  11102. svr.stop();
  11103. t.join();
  11104. ASSERT_FALSE(svr.is_running());
  11105. });
  11106. svr.wait_until_ready();
  11107. Client cli(HOST, PORT);
  11108. auto res =
  11109. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  11110. ASSERT_TRUE(res);
  11111. EXPECT_EQ(StatusCode::OK_200, res->status);
  11112. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  11113. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11114. }
  11115. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  11116. Server svr;
  11117. svr.set_trusted_proxies({"192.0.2.45"});
  11118. std::string observed_remote_addr;
  11119. std::string observed_xff;
  11120. svr.Get("/ip", [&](const Request &req, Response &res) {
  11121. observed_remote_addr = req.remote_addr;
  11122. observed_xff = req.get_header_value("X-Forwarded-For");
  11123. res.set_content("ok", "text/plain");
  11124. });
  11125. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11126. auto se = detail::scope_exit([&] {
  11127. svr.stop();
  11128. t.join();
  11129. ASSERT_FALSE(svr.is_running());
  11130. });
  11131. svr.wait_until_ready();
  11132. Client cli(HOST, PORT);
  11133. auto res = cli.Get(
  11134. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11135. ASSERT_TRUE(res);
  11136. EXPECT_EQ(StatusCode::OK_200, res->status);
  11137. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11138. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11139. }
  11140. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  11141. Server svr;
  11142. svr.set_trusted_proxies({"192.0.2.45"});
  11143. std::string observed_remote_addr;
  11144. std::string observed_xff;
  11145. svr.Get("/ip", [&](const Request &req, Response &res) {
  11146. observed_remote_addr = req.remote_addr;
  11147. observed_xff = req.get_header_value("X-Forwarded-For");
  11148. res.set_content("ok", "text/plain");
  11149. });
  11150. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11151. auto se = detail::scope_exit([&] {
  11152. svr.stop();
  11153. t.join();
  11154. ASSERT_FALSE(svr.is_running());
  11155. });
  11156. svr.wait_until_ready();
  11157. std::string raw_req =
  11158. "GET /ip HTTP/1.1\r\n"
  11159. "Host: localhost\r\n"
  11160. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  11161. "Connection: close\r\n"
  11162. "\r\n";
  11163. std::string out;
  11164. ASSERT_TRUE(send_request(5, raw_req, &out));
  11165. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11166. // Header parser trims surrounding whitespace of the header value
  11167. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  11168. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11169. }
  11170. #ifndef _WIN32
  11171. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  11172. Server svr;
  11173. svr.Post("/post", [&](const Request &req, Response &res) {
  11174. res.set_content(req.body, "text/plain");
  11175. });
  11176. svr.Put("/put", [&](const Request &req, Response &res) {
  11177. res.set_content(req.body, "text/plain");
  11178. });
  11179. svr.Patch("/patch", [&](const Request &req, Response &res) {
  11180. res.set_content(req.body, "text/plain");
  11181. });
  11182. svr.Delete("/delete", [&](const Request &req, Response &res) {
  11183. res.set_content(req.body, "text/plain");
  11184. });
  11185. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11186. auto se = detail::scope_exit([&] {
  11187. svr.stop();
  11188. t.join();
  11189. ASSERT_FALSE(svr.is_running());
  11190. });
  11191. svr.wait_until_ready();
  11192. std::string resp;
  11193. // POST without Content-Length
  11194. ASSERT_TRUE(send_request(5,
  11195. "POST /post HTTP/1.1\r\n"
  11196. "Host: localhost\r\n"
  11197. "Connection: close\r\n"
  11198. "\r\n",
  11199. &resp));
  11200. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11201. // PUT without Content-Length
  11202. resp.clear();
  11203. ASSERT_TRUE(send_request(5,
  11204. "PUT /put HTTP/1.1\r\n"
  11205. "Host: localhost\r\n"
  11206. "Connection: close\r\n"
  11207. "\r\n",
  11208. &resp));
  11209. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11210. // PATCH without Content-Length
  11211. resp.clear();
  11212. ASSERT_TRUE(send_request(5,
  11213. "PATCH /patch HTTP/1.1\r\n"
  11214. "Host: localhost\r\n"
  11215. "Connection: close\r\n"
  11216. "\r\n",
  11217. &resp));
  11218. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11219. // DELETE without Content-Length
  11220. resp.clear();
  11221. ASSERT_TRUE(send_request(5,
  11222. "DELETE /delete HTTP/1.1\r\n"
  11223. "Host: localhost\r\n"
  11224. "Connection: close\r\n"
  11225. "\r\n",
  11226. &resp));
  11227. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11228. }
  11229. #endif
  11230. //==============================================================================
  11231. // open_stream() Tests
  11232. //==============================================================================
  11233. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  11234. std::string result;
  11235. char buf[8192];
  11236. ssize_t n;
  11237. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11238. result.append(buf, static_cast<size_t>(n));
  11239. }
  11240. return result;
  11241. }
  11242. // Mock stream for unit tests
  11243. class MockStream : public Stream {
  11244. public:
  11245. std::string data;
  11246. size_t pos = 0;
  11247. ssize_t error_after = -1; // -1 = no error
  11248. explicit MockStream(const std::string &d, ssize_t err = -1)
  11249. : data(d), error_after(err) {}
  11250. bool is_readable() const override { return true; }
  11251. bool wait_readable() const override { return true; }
  11252. bool wait_writable() const override { return true; }
  11253. ssize_t read(char *ptr, size_t size) override {
  11254. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  11255. if (pos >= data.size()) return 0;
  11256. size_t limit =
  11257. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  11258. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  11259. std::memcpy(ptr, data.data() + pos, to_read);
  11260. pos += to_read;
  11261. return static_cast<ssize_t>(to_read);
  11262. }
  11263. ssize_t write(const char *, size_t) override { return -1; }
  11264. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  11265. ip = "127.0.0.1";
  11266. port = 0;
  11267. }
  11268. void get_local_ip_and_port(std::string &ip, int &port) const override {
  11269. ip = "127.0.0.1";
  11270. port = 0;
  11271. }
  11272. socket_t socket() const override { return INVALID_SOCKET; }
  11273. time_t duration() const override { return 0; }
  11274. };
  11275. TEST(StreamHandleTest, Basic) {
  11276. ClientImpl::StreamHandle handle;
  11277. EXPECT_FALSE(handle.is_valid());
  11278. handle.response = detail::make_unique<Response>();
  11279. handle.error = Error::Connection;
  11280. EXPECT_FALSE(handle.is_valid());
  11281. handle.error = Error::Success;
  11282. EXPECT_TRUE(handle.is_valid());
  11283. }
  11284. TEST(BodyReaderTest, Basic) {
  11285. MockStream stream("Hello, World!");
  11286. detail::BodyReader reader;
  11287. reader.stream = &stream;
  11288. reader.content_length = 13;
  11289. char buf[32];
  11290. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  11291. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  11292. EXPECT_TRUE(reader.eof);
  11293. }
  11294. TEST(BodyReaderTest, NoStream) {
  11295. detail::BodyReader reader;
  11296. char buf[32];
  11297. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11298. EXPECT_EQ(Error::Connection, reader.last_error);
  11299. }
  11300. TEST(BodyReaderTest, Error) {
  11301. MockStream stream("Hello, World!", 5);
  11302. detail::BodyReader reader;
  11303. reader.stream = &stream;
  11304. reader.content_length = 13;
  11305. char buf[32];
  11306. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  11307. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11308. EXPECT_EQ(Error::Read, reader.last_error);
  11309. }
  11310. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  11311. // Mock-based StreamHandle tests relying on private internals are removed.
  11312. class OpenStreamTest : public ::testing::Test {
  11313. protected:
  11314. void SetUp() override {
  11315. svr_.Get("/hello", [](const Request &, Response &res) {
  11316. res.set_content("Hello World!", "text/plain");
  11317. });
  11318. svr_.Get("/large", [](const Request &, Response &res) {
  11319. res.set_content(std::string(10000, 'X'), "text/plain");
  11320. });
  11321. svr_.Get("/chunked", [](const Request &, Response &res) {
  11322. res.set_chunked_content_provider("text/plain",
  11323. [](size_t offset, DataSink &sink) {
  11324. if (offset < 15) {
  11325. sink.write("chunk", 5);
  11326. return true;
  11327. }
  11328. sink.done();
  11329. return true;
  11330. });
  11331. });
  11332. svr_.Get("/compressible", [](const Request &, Response &res) {
  11333. res.set_chunked_content_provider("text/plain", [](size_t offset,
  11334. DataSink &sink) {
  11335. if (offset < 100 * 1024) {
  11336. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  11337. sink.write(chunk.data(), chunk.size());
  11338. return true;
  11339. }
  11340. sink.done();
  11341. return true;
  11342. });
  11343. });
  11344. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  11345. [](const Request & /*req*/, Response &res) {
  11346. auto i = new int(0);
  11347. res.set_header("Trailer", "Content-Length, X-Allowed");
  11348. res.set_chunked_content_provider(
  11349. "text/plain",
  11350. [i](size_t /*offset*/, DataSink &sink) {
  11351. switch (*i) {
  11352. case 0: sink.os << "123"; break;
  11353. case 1: sink.os << "456"; break;
  11354. case 2: sink.os << "789"; break;
  11355. case 3: {
  11356. sink.done_with_trailer(
  11357. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  11358. } break;
  11359. }
  11360. (*i)++;
  11361. return true;
  11362. },
  11363. [i](bool success) {
  11364. EXPECT_TRUE(success);
  11365. delete i;
  11366. });
  11367. });
  11368. // Echo headers endpoint for header-related tests
  11369. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  11370. std::string body;
  11371. for (const auto &h : req.headers) {
  11372. body.append(h.first);
  11373. body.push_back(':');
  11374. body.append(h.second);
  11375. body.push_back('\n');
  11376. }
  11377. res.set_content(body, "text/plain");
  11378. });
  11379. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  11380. std::string body;
  11381. for (const auto &h : req.headers) {
  11382. body.append(h.first);
  11383. body.push_back(':');
  11384. body.append(h.second);
  11385. body.push_back('\n');
  11386. }
  11387. res.set_content(body, "text/plain");
  11388. });
  11389. port_ = svr_.bind_to_any_port("127.0.0.1");
  11390. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11391. svr_.wait_until_ready();
  11392. }
  11393. void TearDown() override {
  11394. svr_.stop();
  11395. if (thread_.joinable()) thread_.join();
  11396. }
  11397. Server svr_;
  11398. std::thread thread_;
  11399. int port_ = 0;
  11400. };
  11401. TEST_F(OpenStreamTest, Basic) {
  11402. Client cli("127.0.0.1", port_);
  11403. auto handle = cli.open_stream("GET", "/hello");
  11404. EXPECT_TRUE(handle.is_valid());
  11405. EXPECT_EQ("Hello World!", read_all(handle));
  11406. }
  11407. TEST_F(OpenStreamTest, SmallBuffer) {
  11408. Client cli("127.0.0.1", port_);
  11409. auto handle = cli.open_stream("GET", "/hello");
  11410. std::string result;
  11411. char buf[4];
  11412. ssize_t n;
  11413. while ((n = handle.read(buf, sizeof(buf))) > 0)
  11414. result.append(buf, static_cast<size_t>(n));
  11415. EXPECT_EQ("Hello World!", result);
  11416. }
  11417. TEST_F(OpenStreamTest, DefaultHeaders) {
  11418. Client cli("127.0.0.1", port_);
  11419. // open_stream GET should include Host, User-Agent and Accept-Encoding
  11420. {
  11421. auto handle = cli.open_stream("GET", "/echo-headers");
  11422. ASSERT_TRUE(handle.is_valid());
  11423. auto body = read_all(handle);
  11424. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  11425. std::string::npos);
  11426. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  11427. std::string::npos);
  11428. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  11429. }
  11430. // open_stream POST with body and no explicit content_type should NOT add
  11431. // text/plain Content-Type (behavior differs from non-streaming path), but
  11432. // should include Content-Length
  11433. {
  11434. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  11435. ASSERT_TRUE(handle.is_valid());
  11436. auto body = read_all(handle);
  11437. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  11438. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  11439. }
  11440. // open_stream POST with explicit Content-Type should preserve it
  11441. {
  11442. auto handle = cli.open_stream("POST", "/echo-headers", {},
  11443. {{"Content-Type", "application/custom"}},
  11444. "{}", "application/custom");
  11445. ASSERT_TRUE(handle.is_valid());
  11446. auto body = read_all(handle);
  11447. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  11448. }
  11449. // User-specified User-Agent must not be overwritten for stream API
  11450. {
  11451. auto handle = cli.open_stream("GET", "/echo-headers", {},
  11452. {{"User-Agent", "MyAgent/1.2"}});
  11453. ASSERT_TRUE(handle.is_valid());
  11454. auto body = read_all(handle);
  11455. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  11456. }
  11457. }
  11458. TEST_F(OpenStreamTest, Large) {
  11459. Client cli("127.0.0.1", port_);
  11460. auto handle = cli.open_stream("GET", "/large");
  11461. EXPECT_EQ(10000u, read_all(handle).size());
  11462. }
  11463. TEST_F(OpenStreamTest, ConnectionError) {
  11464. Client cli("127.0.0.1", 9999);
  11465. auto handle = cli.open_stream("GET", "/hello");
  11466. EXPECT_FALSE(handle.is_valid());
  11467. }
  11468. TEST_F(OpenStreamTest, Chunked) {
  11469. Client cli("127.0.0.1", port_);
  11470. auto handle = cli.open_stream("GET", "/chunked");
  11471. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11472. "Transfer-Encoding") == "chunked");
  11473. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  11474. }
  11475. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  11476. Client cli("127.0.0.1", port_);
  11477. auto handle =
  11478. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  11479. ASSERT_TRUE(handle.is_valid());
  11480. // Consume body to allow trailers to be received/parsed
  11481. auto body = read_all(handle);
  11482. // Explicitly parse trailers (ensure trailers are available for assertion)
  11483. handle.parse_trailers_if_needed();
  11484. EXPECT_EQ(std::string("123456789"), body);
  11485. // The response should include a Trailer header declaring both names
  11486. ASSERT_TRUE(handle.response);
  11487. EXPECT_TRUE(handle.response->has_header("Trailer"));
  11488. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  11489. handle.response->get_header_value("Trailer"));
  11490. // Prohibited trailer must not be present
  11491. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  11492. // Allowed trailer should be present
  11493. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  11494. EXPECT_EQ(std::string("yes"),
  11495. handle.response->get_trailer_value("X-Allowed"));
  11496. // Verify trailers are NOT present as regular headers
  11497. EXPECT_EQ(std::string(""),
  11498. handle.response->get_header_value("Content-Length"));
  11499. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  11500. }
  11501. static std::thread serve_single_response(int port,
  11502. const std::string &response) {
  11503. return std::thread([port, response] {
  11504. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11505. default_socket_options(srv);
  11506. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11507. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11508. sockaddr_in addr{};
  11509. addr.sin_family = AF_INET;
  11510. addr.sin_port = htons(static_cast<uint16_t>(port));
  11511. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11512. int opt = 1;
  11513. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11514. #ifdef _WIN32
  11515. reinterpret_cast<const char *>(&opt),
  11516. #else
  11517. &opt,
  11518. #endif
  11519. sizeof(opt));
  11520. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11521. ::listen(srv, 1);
  11522. sockaddr_in cli_addr{};
  11523. socklen_t cli_len = sizeof(cli_addr);
  11524. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11525. if (cli != INVALID_SOCKET) {
  11526. char buf[4096];
  11527. ::recv(cli, buf, sizeof(buf), 0);
  11528. ::send(cli,
  11529. #ifdef _WIN32
  11530. static_cast<const char *>(response.c_str()),
  11531. static_cast<int>(response.size()),
  11532. #else
  11533. response.c_str(), response.size(),
  11534. #endif
  11535. 0);
  11536. detail::close_socket(cli);
  11537. }
  11538. detail::close_socket(srv);
  11539. });
  11540. }
  11541. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  11542. #ifndef _WIN32
  11543. signal(SIGPIPE, SIG_IGN);
  11544. #endif
  11545. auto server_thread =
  11546. serve_single_response(PORT + 2, "HTTP/1.1 200 OK\r\n"
  11547. "Content-Type: text/plain\r\n"
  11548. "Content-Length: not-a-number\r\n"
  11549. "Connection: close\r\n"
  11550. "\r\n"
  11551. "hello");
  11552. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11553. Client cli("127.0.0.1", PORT + 2);
  11554. auto handle = cli.open_stream("GET", "/");
  11555. EXPECT_FALSE(handle.is_valid());
  11556. server_thread.join();
  11557. }
  11558. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  11559. #ifndef _WIN32
  11560. signal(SIGPIPE, SIG_IGN);
  11561. #endif
  11562. auto server_thread = serve_single_response(
  11563. PORT + 2, "HTTP/1.1 200 OK\r\n"
  11564. "Content-Type: text/plain\r\n"
  11565. "Content-Length: 99999999999999999999999999\r\n"
  11566. "Connection: close\r\n"
  11567. "\r\n"
  11568. "hello");
  11569. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11570. // Before the fix, std::stoull would throw std::out_of_range here and
  11571. // crash the process. After the fix, strtoull silently clamps to
  11572. // ULLONG_MAX so the stream opens without crashing. The important thing
  11573. // is that the process does NOT terminate.
  11574. Client cli("127.0.0.1", PORT + 2);
  11575. auto handle = cli.open_stream("GET", "/");
  11576. EXPECT_TRUE(handle.is_valid());
  11577. server_thread.join();
  11578. }
  11579. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11580. TEST_F(OpenStreamTest, Gzip) {
  11581. Client cli("127.0.0.1", port_);
  11582. auto handle = cli.open_stream("GET", "/compressible", {},
  11583. {{"Accept-Encoding", "gzip"}});
  11584. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  11585. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11586. }
  11587. #endif
  11588. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11589. TEST_F(OpenStreamTest, Brotli) {
  11590. Client cli("127.0.0.1", port_);
  11591. auto handle =
  11592. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  11593. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  11594. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11595. }
  11596. #endif
  11597. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11598. TEST_F(OpenStreamTest, Zstd) {
  11599. Client cli("127.0.0.1", port_);
  11600. auto handle = cli.open_stream("GET", "/compressible", {},
  11601. {{"Accept-Encoding", "zstd"}});
  11602. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  11603. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11604. }
  11605. #endif
  11606. #ifdef CPPHTTPLIB_SSL_ENABLED
  11607. class SSLOpenStreamTest : public ::testing::Test {
  11608. protected:
  11609. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  11610. void SetUp() override {
  11611. svr_.Get("/hello", [](const Request &, Response &res) {
  11612. res.set_content("Hello SSL World!", "text/plain");
  11613. });
  11614. svr_.Get("/chunked", [](const Request &, Response &res) {
  11615. res.set_chunked_content_provider("text/plain",
  11616. [](size_t offset, DataSink &sink) {
  11617. if (offset < 15) {
  11618. sink.write("chunk", 5);
  11619. return true;
  11620. }
  11621. sink.done();
  11622. return true;
  11623. });
  11624. });
  11625. svr_.Post("/echo", [](const Request &req, Response &res) {
  11626. res.set_content(req.body, req.get_header_value("Content-Type"));
  11627. });
  11628. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  11629. std::string body = req.body;
  11630. res.set_chunked_content_provider(
  11631. "text/plain", [body](size_t offset, DataSink &sink) {
  11632. if (offset < body.size()) {
  11633. sink.write(body.data() + offset, body.size() - offset);
  11634. }
  11635. sink.done();
  11636. return true;
  11637. });
  11638. });
  11639. port_ = svr_.bind_to_any_port("127.0.0.1");
  11640. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11641. svr_.wait_until_ready();
  11642. }
  11643. void TearDown() override {
  11644. svr_.stop();
  11645. if (thread_.joinable()) thread_.join();
  11646. }
  11647. SSLServer svr_;
  11648. std::thread thread_;
  11649. int port_ = 0;
  11650. };
  11651. TEST_F(SSLOpenStreamTest, Basic) {
  11652. SSLClient cli("127.0.0.1", port_);
  11653. cli.enable_server_certificate_verification(false);
  11654. auto handle = cli.open_stream("GET", "/hello");
  11655. ASSERT_TRUE(handle.is_valid());
  11656. EXPECT_EQ("Hello SSL World!", read_all(handle));
  11657. }
  11658. TEST_F(SSLOpenStreamTest, Chunked) {
  11659. SSLClient cli("127.0.0.1", port_);
  11660. cli.enable_server_certificate_verification(false);
  11661. auto handle = cli.open_stream("GET", "/chunked");
  11662. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11663. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11664. "Transfer-Encoding") == "chunked");
  11665. auto body = read_all(handle);
  11666. EXPECT_EQ("chunkchunkchunk", body);
  11667. }
  11668. TEST_F(SSLOpenStreamTest, Post) {
  11669. SSLClient cli("127.0.0.1", port_);
  11670. cli.enable_server_certificate_verification(false);
  11671. auto handle =
  11672. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  11673. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11674. EXPECT_EQ(200, handle.response->status);
  11675. auto body = read_all(handle);
  11676. EXPECT_EQ("Hello SSL POST", body);
  11677. }
  11678. TEST_F(SSLOpenStreamTest, PostChunked) {
  11679. SSLClient cli("127.0.0.1", port_);
  11680. cli.enable_server_certificate_verification(false);
  11681. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  11682. "Chunked SSL Data", "text/plain");
  11683. ASSERT_TRUE(handle.is_valid());
  11684. EXPECT_EQ(200, handle.response->status);
  11685. auto body = read_all(handle);
  11686. EXPECT_EQ("Chunked SSL Data", body);
  11687. }
  11688. #endif // CPPHTTPLIB_SSL_ENABLED
  11689. //==============================================================================
  11690. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  11691. // results for various scenarios.
  11692. //==============================================================================
  11693. TEST(ParityTest, GetVsOpenStream) {
  11694. Server svr;
  11695. const std::string path = "/parity";
  11696. const std::string content = "Parity test content: hello world";
  11697. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11698. res.set_content(content, "text/plain");
  11699. });
  11700. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11701. auto se = detail::scope_exit([&] {
  11702. svr.stop();
  11703. t.join();
  11704. ASSERT_FALSE(svr.is_running());
  11705. });
  11706. svr.wait_until_ready();
  11707. Client cli(HOST, PORT);
  11708. // Non-stream path
  11709. auto r1 = cli.Get(path);
  11710. ASSERT_TRUE(r1);
  11711. EXPECT_EQ(StatusCode::OK_200, r1->status);
  11712. // Stream path
  11713. auto h = cli.open_stream("GET", path);
  11714. ASSERT_TRUE(h.is_valid());
  11715. EXPECT_EQ(r1->body, read_all(h));
  11716. }
  11717. // Helper to compress data with provided compressor type T
  11718. template <typename Compressor>
  11719. static std::string compress_payload_for_parity(const std::string &in) {
  11720. std::string out;
  11721. Compressor compressor;
  11722. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  11723. [&](const char *data, size_t n) {
  11724. out.append(data, n);
  11725. return true;
  11726. });
  11727. EXPECT_TRUE(ok);
  11728. return out;
  11729. }
  11730. // Helper function for compression parity tests
  11731. template <typename Compressor>
  11732. static void test_compression_parity(const std::string &original,
  11733. const std::string &path,
  11734. const std::string &encoding) {
  11735. const std::string compressed =
  11736. compress_payload_for_parity<Compressor>(original);
  11737. Server svr;
  11738. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11739. res.set_content(compressed, "application/octet-stream");
  11740. res.set_header("Content-Encoding", encoding);
  11741. });
  11742. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  11743. auto se = detail::scope_exit([&] {
  11744. svr.stop();
  11745. t.join();
  11746. ASSERT_FALSE(svr.is_running());
  11747. });
  11748. svr.wait_until_ready();
  11749. Client cli(HOST, PORT);
  11750. // Non-streaming
  11751. {
  11752. auto res = cli.Get(path);
  11753. ASSERT_TRUE(res);
  11754. EXPECT_EQ(StatusCode::OK_200, res->status);
  11755. EXPECT_EQ(original, res->body);
  11756. }
  11757. // Streaming
  11758. {
  11759. auto h = cli.open_stream("GET", path);
  11760. ASSERT_TRUE(h.is_valid());
  11761. EXPECT_EQ(original, read_all(h));
  11762. }
  11763. }
  11764. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11765. TEST(ParityTest, Gzip) {
  11766. test_compression_parity<detail::gzip_compressor>(
  11767. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  11768. }
  11769. #endif
  11770. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11771. TEST(ParityTest, Brotli) {
  11772. test_compression_parity<detail::brotli_compressor>(
  11773. "Hello, brotli parity test payload", "/parity-br", "br");
  11774. }
  11775. #endif
  11776. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11777. TEST(ParityTest, Zstd) {
  11778. test_compression_parity<detail::zstd_compressor>(
  11779. "Zstandard parity test payload", "/parity-zstd", "zstd");
  11780. }
  11781. #endif
  11782. //==============================================================================
  11783. // New Stream API Tests
  11784. //==============================================================================
  11785. inline std::string read_body(httplib::stream::Result &result) {
  11786. std::string body;
  11787. while (result.next()) {
  11788. body.append(result.data(), result.size());
  11789. }
  11790. return body;
  11791. }
  11792. TEST(ClientConnectionTest, Basic) {
  11793. httplib::ClientConnection conn;
  11794. EXPECT_FALSE(conn.is_open());
  11795. conn.sock = 1;
  11796. EXPECT_TRUE(conn.is_open());
  11797. httplib::ClientConnection conn2(std::move(conn));
  11798. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  11799. conn2.sock = INVALID_SOCKET;
  11800. }
  11801. // Unified test server for all stream::* tests
  11802. class StreamApiTest : public ::testing::Test {
  11803. protected:
  11804. void SetUp() override {
  11805. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11806. res.set_content("Hello World!", "text/plain");
  11807. });
  11808. svr_.Get("/echo-params",
  11809. [](const httplib::Request &req, httplib::Response &res) {
  11810. std::string r;
  11811. for (const auto &p : req.params) {
  11812. if (!r.empty()) r += "&";
  11813. r += p.first + "=" + p.second;
  11814. }
  11815. res.set_content(r, "text/plain");
  11816. });
  11817. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11818. res.set_content(req.body, req.get_header_value("Content-Type"));
  11819. });
  11820. svr_.Post("/echo-headers",
  11821. [](const httplib::Request &req, httplib::Response &res) {
  11822. std::string r;
  11823. for (const auto &h : req.headers)
  11824. r += h.first + ": " + h.second + "\n";
  11825. res.set_content(r, "text/plain");
  11826. });
  11827. svr_.Post("/echo-params",
  11828. [](const httplib::Request &req, httplib::Response &res) {
  11829. std::string r = "params:";
  11830. for (const auto &p : req.params)
  11831. r += p.first + "=" + p.second + ";";
  11832. res.set_content(r + " body:" + req.body, "text/plain");
  11833. });
  11834. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  11835. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  11836. });
  11837. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11838. res.set_content("PUT:" + req.body, "text/plain");
  11839. });
  11840. svr_.Patch("/echo",
  11841. [](const httplib::Request &req, httplib::Response &res) {
  11842. res.set_content("PATCH:" + req.body, "text/plain");
  11843. });
  11844. svr_.Delete(
  11845. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  11846. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  11847. "text/plain");
  11848. });
  11849. svr_.Get("/head-test",
  11850. [](const httplib::Request &, httplib::Response &res) {
  11851. res.set_content("body for HEAD", "text/plain");
  11852. });
  11853. svr_.Options("/options",
  11854. [](const httplib::Request &, httplib::Response &res) {
  11855. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  11856. });
  11857. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  11858. svr_.wait_until_ready();
  11859. }
  11860. void TearDown() override {
  11861. svr_.stop();
  11862. if (thread_.joinable()) thread_.join();
  11863. }
  11864. httplib::Server svr_;
  11865. std::thread thread_;
  11866. };
  11867. // stream::Get tests
  11868. TEST_F(StreamApiTest, GetBasic) {
  11869. httplib::Client cli(HOST, PORT);
  11870. auto result = httplib::stream::Get(cli, "/hello");
  11871. ASSERT_TRUE(result.is_valid());
  11872. EXPECT_EQ(200, result.status());
  11873. EXPECT_EQ("Hello World!", read_body(result));
  11874. }
  11875. TEST_F(StreamApiTest, GetWithParams) {
  11876. httplib::Client cli(HOST, PORT);
  11877. httplib::Params params{{"foo", "bar"}};
  11878. auto result = httplib::stream::Get(cli, "/echo-params", params);
  11879. ASSERT_TRUE(result.is_valid());
  11880. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  11881. }
  11882. TEST_F(StreamApiTest, GetConnectionError) {
  11883. httplib::Client cli(HOST, 9999);
  11884. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  11885. }
  11886. TEST_F(StreamApiTest, Get404) {
  11887. httplib::Client cli(HOST, PORT);
  11888. auto result = httplib::stream::Get(cli, "/nonexistent");
  11889. EXPECT_TRUE(result.is_valid());
  11890. EXPECT_EQ(404, result.status());
  11891. }
  11892. // stream::Post tests
  11893. TEST_F(StreamApiTest, PostBasic) {
  11894. httplib::Client cli(HOST, PORT);
  11895. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  11896. "application/json");
  11897. ASSERT_TRUE(result.is_valid());
  11898. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  11899. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  11900. }
  11901. TEST_F(StreamApiTest, PostWithHeaders) {
  11902. httplib::Client cli(HOST, PORT);
  11903. httplib::Headers headers{{"X-Custom", "value"}};
  11904. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  11905. "text/plain");
  11906. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  11907. }
  11908. TEST_F(StreamApiTest, PostWithParams) {
  11909. httplib::Client cli(HOST, PORT);
  11910. httplib::Params params{{"k", "v"}};
  11911. auto result =
  11912. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  11913. auto body = read_body(result);
  11914. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  11915. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  11916. }
  11917. TEST_F(StreamApiTest, PostLarge) {
  11918. httplib::Client cli(HOST, PORT);
  11919. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  11920. size_t total = 0;
  11921. while (result.next()) {
  11922. total += result.size();
  11923. }
  11924. EXPECT_EQ(100u * 1024u, total);
  11925. }
  11926. // stream::Put/Patch tests
  11927. TEST_F(StreamApiTest, PutAndPatch) {
  11928. httplib::Client cli(HOST, PORT);
  11929. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  11930. EXPECT_EQ("PUT:test", read_body(put));
  11931. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  11932. EXPECT_EQ("PATCH:test", read_body(patch));
  11933. }
  11934. // stream::Delete tests
  11935. TEST_F(StreamApiTest, Delete) {
  11936. httplib::Client cli(HOST, PORT);
  11937. auto del1 = httplib::stream::Delete(cli, "/resource");
  11938. EXPECT_EQ("Deleted", read_body(del1));
  11939. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  11940. EXPECT_EQ("Deleted:data", read_body(del2));
  11941. }
  11942. // stream::Head/Options tests
  11943. TEST_F(StreamApiTest, HeadAndOptions) {
  11944. httplib::Client cli(HOST, PORT);
  11945. auto head = httplib::stream::Head(cli, "/head-test");
  11946. EXPECT_TRUE(head.is_valid());
  11947. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  11948. auto opts = httplib::stream::Options(cli, "/options");
  11949. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  11950. }
  11951. // SSL stream::* tests
  11952. #ifdef CPPHTTPLIB_SSL_ENABLED
  11953. class SSLStreamApiTest : public ::testing::Test {
  11954. protected:
  11955. void SetUp() override {
  11956. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11957. res.set_content("Hello SSL!", "text/plain");
  11958. });
  11959. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11960. res.set_content(req.body, "text/plain");
  11961. });
  11962. port_ = svr_.bind_to_any_port("127.0.0.1");
  11963. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11964. svr_.wait_until_ready();
  11965. }
  11966. void TearDown() override {
  11967. svr_.stop();
  11968. if (thread_.joinable()) thread_.join();
  11969. }
  11970. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  11971. std::thread thread_;
  11972. int port_ = 0;
  11973. };
  11974. TEST_F(SSLStreamApiTest, GetAndPost) {
  11975. httplib::SSLClient cli("127.0.0.1", port_);
  11976. cli.enable_server_certificate_verification(false);
  11977. auto get = httplib::stream::Get(cli, "/hello");
  11978. EXPECT_EQ("Hello SSL!", read_body(get));
  11979. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  11980. EXPECT_EQ("test", read_body(post));
  11981. }
  11982. #endif
  11983. // Tests for Error::Timeout and Error::ConnectionClosed error types
  11984. // These errors are set in SocketStream/SSLSocketStream and propagated through
  11985. // BodyReader
  11986. TEST(ErrorHandlingTest, StreamReadTimeout) {
  11987. // Test that read timeout during streaming is detected
  11988. // Use a large content-length response where server delays mid-stream
  11989. Server svr;
  11990. svr.Get("/slow-stream", [](const Request &, Response &res) {
  11991. // Send a large response with delay in the middle
  11992. res.set_content_provider(
  11993. 1000, // content_length
  11994. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  11995. if (offset < 100) {
  11996. // Send first 100 bytes immediately
  11997. std::string data(100, 'A');
  11998. sink.write(data.c_str(), data.size());
  11999. return true;
  12000. }
  12001. // Then delay longer than client timeout
  12002. std::this_thread::sleep_for(std::chrono::seconds(3));
  12003. std::string data(900, 'B');
  12004. sink.write(data.c_str(), data.size());
  12005. return true;
  12006. });
  12007. });
  12008. auto port = 8091;
  12009. std::thread t([&]() { svr.listen("localhost", port); });
  12010. svr.wait_until_ready();
  12011. Client cli("localhost", port);
  12012. cli.set_read_timeout(1, 0); // 1 second timeout
  12013. auto handle = cli.open_stream("GET", "/slow-stream");
  12014. ASSERT_TRUE(handle.is_valid());
  12015. char buf[256];
  12016. ssize_t total = 0;
  12017. ssize_t n;
  12018. bool got_error = false;
  12019. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12020. total += n;
  12021. }
  12022. if (n < 0) {
  12023. got_error = true;
  12024. // Should be timeout or read error
  12025. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12026. handle.get_read_error() == Error::Read)
  12027. << "Actual error: " << to_string(handle.get_read_error());
  12028. }
  12029. // Either we got an error, or we got less data than expected
  12030. EXPECT_TRUE(got_error || total < 1000)
  12031. << "Expected timeout but got all " << total << " bytes";
  12032. svr.stop();
  12033. t.join();
  12034. }
  12035. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  12036. // Test connection closed detection via BodyReader
  12037. Server svr;
  12038. std::atomic<bool> close_now{false};
  12039. svr.Get("/will-close", [&](const Request &, Response &res) {
  12040. res.set_content_provider(
  12041. 10000, // Large content_length that we won't fully send
  12042. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12043. if (offset < 100) {
  12044. std::string data(100, 'X');
  12045. sink.write(data.c_str(), data.size());
  12046. return true;
  12047. }
  12048. // Wait for signal then abort
  12049. while (!close_now) {
  12050. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12051. }
  12052. return false; // Abort - server will close connection
  12053. });
  12054. });
  12055. auto port = 8092;
  12056. std::thread t([&]() { svr.listen("localhost", port); });
  12057. svr.wait_until_ready();
  12058. Client cli("localhost", port);
  12059. auto handle = cli.open_stream("GET", "/will-close");
  12060. ASSERT_TRUE(handle.is_valid());
  12061. char buf[256];
  12062. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12063. EXPECT_GT(n, 0) << "First read should succeed";
  12064. // Signal server to close
  12065. close_now = true;
  12066. // Keep reading until error or EOF
  12067. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12068. // Keep reading
  12069. }
  12070. // Should get an error since content_length wasn't satisfied
  12071. if (n < 0) {
  12072. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12073. handle.get_read_error() == Error::Read)
  12074. << "Actual error: " << to_string(handle.get_read_error());
  12075. }
  12076. svr.stop();
  12077. t.join();
  12078. }
  12079. #ifdef CPPHTTPLIB_SSL_ENABLED
  12080. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  12081. // Test that read timeout during SSL streaming is detected
  12082. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12083. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12084. res.set_content_provider(
  12085. 1000, "text/plain",
  12086. [](size_t offset, size_t /*length*/, DataSink &sink) {
  12087. if (offset < 100) {
  12088. std::string data(100, 'A');
  12089. sink.write(data.c_str(), data.size());
  12090. return true;
  12091. }
  12092. std::this_thread::sleep_for(std::chrono::seconds(3));
  12093. std::string data(900, 'B');
  12094. sink.write(data.c_str(), data.size());
  12095. return true;
  12096. });
  12097. });
  12098. auto port = 8093;
  12099. std::thread t([&]() { svr.listen("localhost", port); });
  12100. svr.wait_until_ready();
  12101. SSLClient cli("localhost", port);
  12102. cli.enable_server_certificate_verification(false);
  12103. cli.set_read_timeout(1, 0); // 1 second timeout
  12104. auto handle = cli.open_stream("GET", "/slow-stream");
  12105. ASSERT_TRUE(handle.is_valid());
  12106. char buf[256];
  12107. ssize_t total = 0;
  12108. ssize_t n;
  12109. bool got_error = false;
  12110. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12111. total += n;
  12112. }
  12113. if (n < 0) {
  12114. got_error = true;
  12115. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12116. handle.get_read_error() == Error::Read)
  12117. << "Actual error: " << to_string(handle.get_read_error());
  12118. }
  12119. EXPECT_TRUE(got_error || total < 1000)
  12120. << "Expected timeout but got all " << total << " bytes";
  12121. svr.stop();
  12122. t.join();
  12123. }
  12124. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  12125. // Test SSL connection closed detection
  12126. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12127. std::atomic<bool> close_now{false};
  12128. svr.Get("/will-close", [&](const Request &, Response &res) {
  12129. res.set_content_provider(
  12130. 10000, "text/plain",
  12131. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12132. if (offset < 100) {
  12133. std::string data(100, 'X');
  12134. sink.write(data.c_str(), data.size());
  12135. return true;
  12136. }
  12137. while (!close_now) {
  12138. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12139. }
  12140. return false;
  12141. });
  12142. });
  12143. auto port = 8094;
  12144. std::thread t([&]() { svr.listen("localhost", port); });
  12145. svr.wait_until_ready();
  12146. SSLClient cli("localhost", port);
  12147. cli.enable_server_certificate_verification(false);
  12148. auto handle = cli.open_stream("GET", "/will-close");
  12149. ASSERT_TRUE(handle.is_valid());
  12150. char buf[256];
  12151. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12152. EXPECT_GT(n, 0);
  12153. // Signal server to close
  12154. close_now = true;
  12155. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12156. // Keep reading
  12157. }
  12158. if (n < 0) {
  12159. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12160. handle.get_read_error() == Error::Read)
  12161. << "Actual error: " << to_string(handle.get_read_error());
  12162. }
  12163. svr.stop();
  12164. t.join();
  12165. }
  12166. #endif
  12167. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  12168. using namespace httplib;
  12169. // Create a test file
  12170. const char *fname = "etag_testfile.txt";
  12171. const char *content = "etag-content";
  12172. {
  12173. std::ofstream ofs(fname);
  12174. ofs << content;
  12175. ASSERT_TRUE(ofs.good());
  12176. }
  12177. Server svr;
  12178. svr.set_mount_point("/static", ".");
  12179. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12180. svr.wait_until_ready();
  12181. Client cli(HOST, PORT);
  12182. // First request: should get 200 with ETag header
  12183. auto res1 = cli.Get("/static/etag_testfile.txt");
  12184. ASSERT_TRUE(res1);
  12185. ASSERT_EQ(200, res1->status);
  12186. ASSERT_TRUE(res1->has_header("ETag"));
  12187. std::string etag = res1->get_header_value("ETag");
  12188. EXPECT_FALSE(etag.empty());
  12189. // Verify ETag format: W/"hex-hex"
  12190. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  12191. EXPECT_EQ('W', etag[0]);
  12192. EXPECT_EQ('/', etag[1]);
  12193. EXPECT_EQ('"', etag[2]);
  12194. EXPECT_EQ('"', etag.back());
  12195. // Exact match: expect 304 Not Modified
  12196. Headers h2 = {{"If-None-Match", etag}};
  12197. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  12198. ASSERT_TRUE(res2);
  12199. EXPECT_EQ(304, res2->status);
  12200. // Wildcard match: expect 304 Not Modified
  12201. Headers h3 = {{"If-None-Match", "*"}};
  12202. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  12203. ASSERT_TRUE(res3);
  12204. EXPECT_EQ(304, res3->status);
  12205. // Non-matching ETag: expect 200
  12206. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  12207. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  12208. ASSERT_TRUE(res4);
  12209. EXPECT_EQ(200, res4->status);
  12210. // Multiple ETags with one matching: expect 304
  12211. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  12212. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  12213. ASSERT_TRUE(res5);
  12214. EXPECT_EQ(304, res5->status);
  12215. svr.stop();
  12216. t.join();
  12217. std::remove(fname);
  12218. }
  12219. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  12220. using namespace httplib;
  12221. Server svr;
  12222. svr.set_mount_point("/static", ".");
  12223. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12224. svr.wait_until_ready();
  12225. Client cli(HOST, PORT);
  12226. // Send If-None-Match: * to a non-existent file
  12227. Headers h = {{"If-None-Match", "*"}};
  12228. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  12229. ASSERT_TRUE(res);
  12230. EXPECT_EQ(404, res->status);
  12231. svr.stop();
  12232. t.join();
  12233. }
  12234. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  12235. using namespace httplib;
  12236. // Create a test file
  12237. const char *fname = "etag_boundary_testfile.txt";
  12238. const char *content = "boundary-test";
  12239. {
  12240. std::ofstream ofs(fname);
  12241. ofs << content;
  12242. ASSERT_TRUE(ofs.good());
  12243. }
  12244. Server svr;
  12245. svr.set_mount_point("/static", ".");
  12246. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12247. svr.wait_until_ready();
  12248. Client cli(HOST, PORT);
  12249. // Get the actual ETag
  12250. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  12251. ASSERT_TRUE(res1);
  12252. ASSERT_EQ(200, res1->status);
  12253. ASSERT_TRUE(res1->has_header("ETag"));
  12254. std::string etag = res1->get_header_value("ETag");
  12255. // Test 1: Very long ETag value (longer than actual ETag)
  12256. // Should NOT match and return 200 (not trigger out-of-bounds read)
  12257. Headers h1 = {{"If-None-Match", "W/"
  12258. "\"very-long-etag-value-that-is-much-longer-"
  12259. "than-the-actual-etag-value\""}};
  12260. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  12261. ASSERT_TRUE(res2);
  12262. EXPECT_EQ(200, res2->status); // Should not match
  12263. // Test 2: Long string followed by wildcard
  12264. // Should match on "*" and return 304 (without out-of-bounds read on the long
  12265. // string)
  12266. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  12267. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  12268. ASSERT_TRUE(res3);
  12269. EXPECT_EQ(304, res3->status); // Should match on "*"
  12270. // Test 3: Wildcard followed by long string
  12271. // Should match on "*" immediately and return 304
  12272. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  12273. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  12274. ASSERT_TRUE(res4);
  12275. EXPECT_EQ(304, res4->status); // Should match on "*"
  12276. // Test 4: Multiple long non-matching values
  12277. // Should NOT match and return 200 (test that all comparisons are safe)
  12278. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  12279. "W/\"second-long-non-matching-value\", "
  12280. "W/\"third-long-non-matching-value\""}};
  12281. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  12282. ASSERT_TRUE(res5);
  12283. EXPECT_EQ(200, res5->status); // Should not match
  12284. // Test 5: Single character that is not "*" (edge case)
  12285. Headers h5 = {{"If-None-Match", "X"}};
  12286. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  12287. ASSERT_TRUE(res6);
  12288. EXPECT_EQ(200, res6->status); // Should not match
  12289. svr.stop();
  12290. t.join();
  12291. std::remove(fname);
  12292. }
  12293. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  12294. using namespace httplib;
  12295. // Create a test file
  12296. const char *fname = "ims_testfile.txt";
  12297. const char *content = "if-modified-since-test";
  12298. {
  12299. std::ofstream ofs(fname);
  12300. ofs << content;
  12301. ASSERT_TRUE(ofs.good());
  12302. }
  12303. Server svr;
  12304. svr.set_mount_point("/static", ".");
  12305. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12306. svr.wait_until_ready();
  12307. Client cli(HOST, PORT);
  12308. // First request: should get 200 with Last-Modified header
  12309. auto res1 = cli.Get("/static/ims_testfile.txt");
  12310. ASSERT_TRUE(res1);
  12311. ASSERT_EQ(200, res1->status);
  12312. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12313. std::string last_modified = res1->get_header_value("Last-Modified");
  12314. EXPECT_FALSE(last_modified.empty());
  12315. // If-Modified-Since with same time: expect 304
  12316. Headers h2 = {{"If-Modified-Since", last_modified}};
  12317. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  12318. ASSERT_TRUE(res2);
  12319. EXPECT_EQ(304, res2->status);
  12320. // If-Modified-Since with future time: expect 304
  12321. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12322. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  12323. ASSERT_TRUE(res3);
  12324. EXPECT_EQ(304, res3->status);
  12325. // If-Modified-Since with past time: expect 200
  12326. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12327. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  12328. ASSERT_TRUE(res4);
  12329. EXPECT_EQ(200, res4->status);
  12330. // If-None-Match takes precedence over If-Modified-Since
  12331. // (send matching ETag with old If-Modified-Since -> should still be 304)
  12332. ASSERT_TRUE(res1->has_header("ETag"));
  12333. std::string etag = res1->get_header_value("ETag");
  12334. Headers h5 = {{"If-None-Match", etag},
  12335. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12336. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  12337. ASSERT_TRUE(res5);
  12338. EXPECT_EQ(304, res5->status);
  12339. svr.stop();
  12340. t.join();
  12341. std::remove(fname);
  12342. }
  12343. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  12344. using namespace httplib;
  12345. Server svr;
  12346. // Endpoint that returns compressible content
  12347. svr.Get("/compressible", [](const Request &, Response &res) {
  12348. // Return a large enough body to trigger compression
  12349. std::string body(1000, 'a');
  12350. res.set_content(body, "text/plain");
  12351. });
  12352. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12353. svr.wait_until_ready();
  12354. Client cli(HOST, PORT);
  12355. // Request with gzip support: should get Vary header when compressed
  12356. cli.set_compress(true);
  12357. auto res1 = cli.Get("/compressible");
  12358. ASSERT_TRUE(res1);
  12359. EXPECT_EQ(200, res1->status);
  12360. // If Content-Encoding is set, Vary should also be set
  12361. if (res1->has_header("Content-Encoding")) {
  12362. EXPECT_TRUE(res1->has_header("Vary"));
  12363. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  12364. }
  12365. // Request without Accept-Encoding header: should not have compression
  12366. Headers h_no_compress;
  12367. auto res2 = cli.Get("/compressible", h_no_compress);
  12368. ASSERT_TRUE(res2);
  12369. EXPECT_EQ(200, res2->status);
  12370. // Verify Vary header is present when compression is applied
  12371. // (the exact behavior depends on server configuration)
  12372. svr.stop();
  12373. t.join();
  12374. }
  12375. TEST(ETagTest, IfRangeWithETag) {
  12376. using namespace httplib;
  12377. // Create a test file with known content
  12378. const char *fname = "if_range_testfile.txt";
  12379. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  12380. {
  12381. std::ofstream ofs(fname);
  12382. ofs << content;
  12383. ASSERT_TRUE(ofs.good());
  12384. }
  12385. Server svr;
  12386. svr.set_mount_point("/static", ".");
  12387. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12388. svr.wait_until_ready();
  12389. Client cli(HOST, PORT);
  12390. // First request: get ETag
  12391. auto res1 = cli.Get("/static/if_range_testfile.txt");
  12392. ASSERT_TRUE(res1);
  12393. ASSERT_EQ(200, res1->status);
  12394. ASSERT_TRUE(res1->has_header("ETag"));
  12395. std::string etag = res1->get_header_value("ETag");
  12396. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  12397. // Since our server generates weak ETags (W/"..."), If-Range with our
  12398. // ETag should NOT result in partial content - it should return full content.
  12399. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  12400. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  12401. ASSERT_TRUE(res2);
  12402. // Weak ETag in If-Range -> full content (200), not partial (206)
  12403. EXPECT_EQ(200, res2->status);
  12404. EXPECT_EQ(content, res2->body);
  12405. EXPECT_FALSE(res2->has_header("Content-Range"));
  12406. // Range request with non-matching If-Range (ETag): should get 200 (full
  12407. // content)
  12408. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  12409. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  12410. ASSERT_TRUE(res3);
  12411. EXPECT_EQ(200, res3->status);
  12412. EXPECT_EQ(content, res3->body);
  12413. EXPECT_FALSE(res3->has_header("Content-Range"));
  12414. // Range request with strong ETag (hypothetical - our server doesn't generate
  12415. // strong ETags, but if client sends a strong ETag that doesn't match, it
  12416. // should return full content)
  12417. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  12418. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  12419. ASSERT_TRUE(res4);
  12420. EXPECT_EQ(200, res4->status);
  12421. EXPECT_EQ(content, res4->body);
  12422. EXPECT_FALSE(res4->has_header("Content-Range"));
  12423. svr.stop();
  12424. t.join();
  12425. std::remove(fname);
  12426. }
  12427. TEST(ETagTest, IfRangeWithDate) {
  12428. using namespace httplib;
  12429. // Create a test file
  12430. const char *fname = "if_range_date_testfile.txt";
  12431. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  12432. {
  12433. std::ofstream ofs(fname);
  12434. ofs << content;
  12435. ASSERT_TRUE(ofs.good());
  12436. }
  12437. Server svr;
  12438. svr.set_mount_point("/static", ".");
  12439. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12440. svr.wait_until_ready();
  12441. Client cli(HOST, PORT);
  12442. // First request: get Last-Modified
  12443. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  12444. ASSERT_TRUE(res1);
  12445. ASSERT_EQ(200, res1->status);
  12446. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12447. std::string last_modified = res1->get_header_value("Last-Modified");
  12448. // Range request with matching If-Range (date): should get 206
  12449. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  12450. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  12451. ASSERT_TRUE(res2);
  12452. EXPECT_EQ(206, res2->status);
  12453. EXPECT_EQ("FGHIJ", res2->body);
  12454. // Range request with old If-Range date: should get 200 (full content)
  12455. Headers h3 = {{"Range", "bytes=5-9"},
  12456. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12457. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  12458. ASSERT_TRUE(res3);
  12459. EXPECT_EQ(200, res3->status);
  12460. EXPECT_EQ(content, res3->body);
  12461. // Range request with future If-Range date: should get 206
  12462. Headers h4 = {{"Range", "bytes=0-4"},
  12463. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12464. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  12465. ASSERT_TRUE(res4);
  12466. EXPECT_EQ(206, res4->status);
  12467. EXPECT_EQ("ABCDE", res4->body);
  12468. svr.stop();
  12469. t.join();
  12470. std::remove(fname);
  12471. }
  12472. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  12473. using namespace httplib;
  12474. const char *fname = "etag_malformed.txt";
  12475. const char *content = "malformed-etag";
  12476. {
  12477. std::ofstream ofs(fname);
  12478. ofs << content;
  12479. ASSERT_TRUE(ofs.good());
  12480. }
  12481. Server svr;
  12482. svr.set_mount_point("/static", ".");
  12483. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12484. svr.wait_until_ready();
  12485. Client cli(HOST, PORT);
  12486. // baseline: should get 200 and an ETag
  12487. auto res1 = cli.Get("/static/etag_malformed.txt");
  12488. ASSERT_TRUE(res1);
  12489. ASSERT_EQ(200, res1->status);
  12490. ASSERT_TRUE(res1->has_header("ETag"));
  12491. // Malformed ETag value (missing quotes) should be treated as non-matching
  12492. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  12493. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  12494. ASSERT_TRUE(res_bad);
  12495. EXPECT_EQ(200, res_bad->status);
  12496. // Whitespace-only header value should be considered invalid / non-matching
  12497. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  12498. "Host: localhost\r\n"
  12499. "If-None-Match: \r\n"
  12500. "Connection: close\r\n"
  12501. "\r\n";
  12502. std::string out;
  12503. ASSERT_TRUE(send_request(5, raw_req, &out));
  12504. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12505. svr.stop();
  12506. t.join();
  12507. std::remove(fname);
  12508. }
  12509. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  12510. using namespace httplib;
  12511. const char *fname = "ims_invalid_format.txt";
  12512. const char *content = "ims-bad-format";
  12513. {
  12514. std::ofstream ofs(fname);
  12515. ofs << content;
  12516. ASSERT_TRUE(ofs.good());
  12517. }
  12518. Server svr;
  12519. svr.set_mount_point("/static", ".");
  12520. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12521. svr.wait_until_ready();
  12522. Client cli(HOST, PORT);
  12523. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  12524. ASSERT_TRUE(res1);
  12525. ASSERT_EQ(200, res1->status);
  12526. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12527. // If-Modified-Since with invalid format should not result in 304
  12528. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  12529. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  12530. ASSERT_TRUE(res_bad);
  12531. EXPECT_EQ(200, res_bad->status);
  12532. // If-Range with invalid date format should be treated as mismatch -> full
  12533. // content (200)
  12534. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  12535. {"If-Range", "invalid-date"}};
  12536. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  12537. ASSERT_TRUE(res_ifrange);
  12538. EXPECT_EQ(200, res_ifrange->status);
  12539. svr.stop();
  12540. t.join();
  12541. std::remove(fname);
  12542. }
  12543. TEST(ETagTest, IfRangeWithMalformedETag) {
  12544. using namespace httplib;
  12545. const char *fname = "ifrange_malformed.txt";
  12546. const std::string content = "0123456789";
  12547. {
  12548. std::ofstream ofs(fname);
  12549. ofs << content;
  12550. ASSERT_TRUE(ofs.good());
  12551. }
  12552. Server svr;
  12553. svr.set_mount_point("/static", ".");
  12554. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12555. svr.wait_until_ready();
  12556. Client cli(HOST, PORT);
  12557. // First request: get ETag
  12558. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  12559. ASSERT_TRUE(res1);
  12560. ASSERT_EQ(200, res1->status);
  12561. ASSERT_TRUE(res1->has_header("ETag"));
  12562. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  12563. // full content (200)
  12564. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  12565. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  12566. ASSERT_TRUE(res2);
  12567. EXPECT_EQ(200, res2->status);
  12568. EXPECT_EQ(content, res2->body);
  12569. svr.stop();
  12570. t.join();
  12571. std::remove(fname);
  12572. }
  12573. TEST(ETagTest, ExtremeLargeDateValues) {
  12574. using namespace httplib;
  12575. const char *fname = "ims_extreme_date.txt";
  12576. const char *content = "ims-extreme-date";
  12577. {
  12578. std::ofstream ofs(fname);
  12579. ofs << content;
  12580. ASSERT_TRUE(ofs.good());
  12581. }
  12582. Server svr;
  12583. svr.set_mount_point("/static", ".");
  12584. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12585. svr.wait_until_ready();
  12586. Client cli(HOST, PORT);
  12587. auto res1 = cli.Get(std::string("/static/") + fname);
  12588. ASSERT_TRUE(res1);
  12589. ASSERT_EQ(200, res1->status);
  12590. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12591. // Extremely large year that may overflow date parsing routines.
  12592. Headers h_large_date = {
  12593. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12594. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  12595. ASSERT_TRUE(res_bad);
  12596. // Expect server to treat this as invalid/mismatch and return full content
  12597. EXPECT_EQ(200, res_bad->status);
  12598. // If-Range with extremely large date should be treated as mismatch -> full
  12599. // content (200)
  12600. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  12601. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12602. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  12603. ASSERT_TRUE(res_ifrange);
  12604. EXPECT_EQ(200, res_ifrange->status);
  12605. svr.stop();
  12606. t.join();
  12607. std::remove(fname);
  12608. }
  12609. TEST(ETagTest, NegativeFileModificationTime) {
  12610. using namespace httplib;
  12611. const char *fname = "ims_negative_mtime.txt";
  12612. const std::string content = "negative-mtime";
  12613. {
  12614. std::ofstream ofs(fname);
  12615. ofs << content;
  12616. ASSERT_TRUE(ofs.good());
  12617. }
  12618. // Try to set file mtime to a negative value. This may fail on some
  12619. // platforms/filesystems; if it fails, the test will still verify server
  12620. // behaves safely by performing a regular conditional request.
  12621. #if defined(__APPLE__) || defined(__linux__)
  12622. bool set_negative = false;
  12623. do {
  12624. struct timeval times[2];
  12625. // access time: now
  12626. times[0].tv_sec = time(nullptr);
  12627. times[0].tv_usec = 0;
  12628. // modification time: negative (e.g., -1)
  12629. times[1].tv_sec = -1;
  12630. times[1].tv_usec = 0;
  12631. if (utimes(fname, times) == 0) { set_negative = true; }
  12632. } while (0);
  12633. #else
  12634. bool set_negative = false;
  12635. #endif
  12636. Server svr;
  12637. svr.set_mount_point("/static", ".");
  12638. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12639. svr.wait_until_ready();
  12640. Client cli(HOST, PORT);
  12641. auto res1 = cli.Get(std::string("/static/") + fname);
  12642. ASSERT_TRUE(res1);
  12643. ASSERT_EQ(200, res1->status);
  12644. bool has_last_modified = res1->has_header("Last-Modified");
  12645. std::string last_modified;
  12646. if (has_last_modified) {
  12647. last_modified = res1->get_header_value("Last-Modified");
  12648. }
  12649. if (set_negative) {
  12650. // If we successfully set a negative mtime, ensure server returns a
  12651. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  12652. // with an old date and ensure server handles it without crash.
  12653. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  12654. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  12655. ASSERT_TRUE(res2);
  12656. // Behavior may vary; at minimum ensure server responds (200 or 304).
  12657. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  12658. } else {
  12659. // Could not set negative mtime on this platform; fall back to verifying
  12660. // that normal invalid/malformed dates are treated safely (non-304).
  12661. Headers h_bad_date = {
  12662. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12663. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  12664. ASSERT_TRUE(res_bad);
  12665. EXPECT_EQ(200, res_bad->status);
  12666. }
  12667. svr.stop();
  12668. t.join();
  12669. std::remove(fname);
  12670. }
  12671. //==============================================================================
  12672. // SSE Parsing Tests
  12673. //==============================================================================
  12674. class SSEParsingTest : public ::testing::Test {
  12675. protected:
  12676. // Test helper that mimics SSE parsing behavior
  12677. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  12678. int &retry_ms) {
  12679. // Blank line signals end of event
  12680. if (line.empty() || line == "\r") { return true; }
  12681. // Lines starting with ':' are comments (ignored)
  12682. if (!line.empty() && line[0] == ':') { return false; }
  12683. // Find the colon separator
  12684. auto colon_pos = line.find(':');
  12685. if (colon_pos == std::string::npos) {
  12686. // Line with no colon is treated as field name with empty value
  12687. return false;
  12688. }
  12689. std::string field = line.substr(0, colon_pos);
  12690. std::string value;
  12691. // Value starts after colon, skip optional single space
  12692. if (colon_pos + 1 < line.size()) {
  12693. size_t value_start = colon_pos + 1;
  12694. if (line[value_start] == ' ') { value_start++; }
  12695. value = line.substr(value_start);
  12696. // Remove trailing \r if present
  12697. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  12698. }
  12699. // Handle known fields
  12700. if (field == "event") {
  12701. msg.event = value;
  12702. } else if (field == "data") {
  12703. // Multiple data lines are concatenated with newlines
  12704. if (!msg.data.empty()) { msg.data += "\n"; }
  12705. msg.data += value;
  12706. } else if (field == "id") {
  12707. // Empty id is valid (clears the last event ID)
  12708. msg.id = value;
  12709. } else if (field == "retry") {
  12710. // Parse retry interval in milliseconds
  12711. {
  12712. int v = 0;
  12713. auto res =
  12714. detail::from_chars(value.data(), value.data() + value.size(), v);
  12715. if (res.ec == std::errc{}) { retry_ms = v; }
  12716. }
  12717. }
  12718. // Unknown fields are ignored per SSE spec
  12719. return false;
  12720. }
  12721. };
  12722. // Test: Single-line data
  12723. TEST_F(SSEParsingTest, SingleLineData) {
  12724. sse::SSEMessage msg;
  12725. int retry_ms = 3000;
  12726. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  12727. EXPECT_EQ(msg.data, "hello");
  12728. EXPECT_EQ(msg.event, "message");
  12729. // Blank line ends event
  12730. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12731. }
  12732. // Test: Multi-line data
  12733. TEST_F(SSEParsingTest, MultiLineData) {
  12734. sse::SSEMessage msg;
  12735. int retry_ms = 3000;
  12736. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  12737. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  12738. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  12739. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  12740. }
  12741. // Test: Custom event types
  12742. TEST_F(SSEParsingTest, CustomEventType) {
  12743. sse::SSEMessage msg;
  12744. int retry_ms = 3000;
  12745. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  12746. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  12747. EXPECT_EQ(msg.event, "update");
  12748. EXPECT_EQ(msg.data, "payload");
  12749. }
  12750. // Test: Event ID handling
  12751. TEST_F(SSEParsingTest, EventIdHandling) {
  12752. sse::SSEMessage msg;
  12753. int retry_ms = 3000;
  12754. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  12755. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  12756. EXPECT_EQ(msg.id, "12345");
  12757. }
  12758. // Test: Empty event ID (clears last event ID)
  12759. TEST_F(SSEParsingTest, EmptyEventId) {
  12760. sse::SSEMessage msg;
  12761. msg.id = "previous";
  12762. int retry_ms = 3000;
  12763. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  12764. EXPECT_EQ(msg.id, "");
  12765. }
  12766. // Test: Retry field parsing
  12767. TEST_F(SSEParsingTest, RetryFieldParsing) {
  12768. sse::SSEMessage msg;
  12769. int retry_ms = 3000;
  12770. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  12771. EXPECT_EQ(retry_ms, 5000);
  12772. }
  12773. // Test: Invalid retry value
  12774. TEST_F(SSEParsingTest, InvalidRetryValue) {
  12775. sse::SSEMessage msg;
  12776. int retry_ms = 3000;
  12777. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  12778. EXPECT_EQ(retry_ms, 3000); // Unchanged
  12779. }
  12780. // Test: Comments (lines starting with :)
  12781. TEST_F(SSEParsingTest, CommentsIgnored) {
  12782. sse::SSEMessage msg;
  12783. int retry_ms = 3000;
  12784. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  12785. EXPECT_EQ(msg.data, "");
  12786. EXPECT_EQ(msg.event, "message");
  12787. }
  12788. // Test: Colon in value
  12789. TEST_F(SSEParsingTest, ColonInValue) {
  12790. sse::SSEMessage msg;
  12791. int retry_ms = 3000;
  12792. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  12793. EXPECT_EQ(msg.data, "hello:world:test");
  12794. }
  12795. // Test: Line with no colon (field name only)
  12796. TEST_F(SSEParsingTest, FieldNameOnly) {
  12797. sse::SSEMessage msg;
  12798. int retry_ms = 3000;
  12799. // According to SSE spec, this is treated as field name with empty value
  12800. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  12801. // Since we don't recognize "data" without colon, data should be empty
  12802. EXPECT_EQ(msg.data, "");
  12803. }
  12804. // Test: Trailing \r handling
  12805. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  12806. sse::SSEMessage msg;
  12807. int retry_ms = 3000;
  12808. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  12809. EXPECT_EQ(msg.data, "hello");
  12810. }
  12811. // Test: Unknown fields ignored
  12812. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  12813. sse::SSEMessage msg;
  12814. int retry_ms = 3000;
  12815. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  12816. EXPECT_EQ(msg.data, "");
  12817. EXPECT_EQ(msg.event, "message");
  12818. }
  12819. // Test: Space after colon is optional
  12820. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  12821. sse::SSEMessage msg1, msg2;
  12822. int retry_ms = 3000;
  12823. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  12824. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  12825. EXPECT_EQ(msg1.data, "hello");
  12826. EXPECT_EQ(msg2.data, "hello");
  12827. }
  12828. // Test: SSEMessage clear
  12829. TEST_F(SSEParsingTest, MessageClear) {
  12830. sse::SSEMessage msg;
  12831. msg.event = "custom";
  12832. msg.data = "some data";
  12833. msg.id = "123";
  12834. msg.clear();
  12835. EXPECT_EQ(msg.event, "message");
  12836. EXPECT_EQ(msg.data, "");
  12837. EXPECT_EQ(msg.id, "");
  12838. }
  12839. // Test: Complete event parsing
  12840. TEST_F(SSEParsingTest, CompleteEventParsing) {
  12841. sse::SSEMessage msg;
  12842. int retry_ms = 3000;
  12843. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  12844. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  12845. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  12846. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  12847. // Blank line ends event
  12848. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12849. EXPECT_EQ(msg.event, "notification");
  12850. EXPECT_EQ(msg.id, "evt-42");
  12851. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  12852. EXPECT_EQ(retry_ms, 1000);
  12853. }
  12854. //==============================================================================
  12855. // Integration Tests with Server
  12856. //==============================================================================
  12857. class SSEIntegrationTest : public ::testing::Test {
  12858. protected:
  12859. void SetUp() override {
  12860. stop_server_.store(false);
  12861. events_.clear();
  12862. server_ = httplib::detail::make_unique<Server>();
  12863. setup_server();
  12864. start_server();
  12865. }
  12866. void TearDown() override {
  12867. stop_server_.store(true);
  12868. event_cv_.notify_all();
  12869. server_->stop();
  12870. if (server_thread_.joinable()) { server_thread_.join(); }
  12871. }
  12872. void setup_server() {
  12873. // Simple SSE endpoint
  12874. server_->Get("/events", [this](const Request &req, Response &res) {
  12875. auto last_id = req.get_header_value("Last-Event-ID");
  12876. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  12877. res.set_chunked_content_provider(
  12878. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  12879. std::unique_lock<std::mutex> lock(event_mutex_);
  12880. if (event_cv_.wait_for(
  12881. lock, std::chrono::milliseconds(200), [this] {
  12882. return !events_.empty() || stop_server_.load();
  12883. })) {
  12884. if (stop_server_.load()) { return false; }
  12885. if (!events_.empty()) {
  12886. std::string event = events_.front();
  12887. events_.erase(events_.begin());
  12888. sink.write(event.data(), event.size());
  12889. return true;
  12890. }
  12891. }
  12892. return !stop_server_.load();
  12893. });
  12894. });
  12895. // Endpoint that returns error
  12896. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  12897. res.status = 500;
  12898. res.set_content("Internal Server Error", "text/plain");
  12899. });
  12900. // Endpoint for custom event types
  12901. server_->Get("/custom-events", [](const Request &, Response &res) {
  12902. res.set_chunked_content_provider(
  12903. "text/event-stream", [](size_t offset, DataSink &sink) {
  12904. if (offset == 0) {
  12905. std::string event = "event: update\ndata: updated\n\n"
  12906. "event: delete\ndata: deleted\n\n";
  12907. sink.write(event.data(), event.size());
  12908. }
  12909. return false; // End stream after sending
  12910. });
  12911. });
  12912. }
  12913. void start_server() {
  12914. port_ = server_->bind_to_any_port(HOST);
  12915. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  12916. // Wait for server to start
  12917. while (!server_->is_running()) {
  12918. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12919. }
  12920. }
  12921. int get_port() const { return port_; }
  12922. void send_event(const std::string &event) {
  12923. std::lock_guard<std::mutex> lock(event_mutex_);
  12924. events_.push_back(event);
  12925. event_cv_.notify_all();
  12926. }
  12927. std::unique_ptr<Server> server_;
  12928. std::thread server_thread_;
  12929. std::mutex event_mutex_;
  12930. std::condition_variable event_cv_;
  12931. std::vector<std::string> events_;
  12932. std::atomic<bool> stop_server_{false};
  12933. std::string last_received_event_id_;
  12934. int port_ = 0;
  12935. };
  12936. // Test: Successful connection and on_open callback
  12937. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  12938. // Add a simple endpoint that sends one event and closes
  12939. server_->Get("/simple-event", [](const Request &, Response &res) {
  12940. res.set_chunked_content_provider(
  12941. "text/event-stream", [](size_t offset, DataSink &sink) {
  12942. if (offset == 0) {
  12943. std::string event = "data: hello\n\n";
  12944. sink.write(event.data(), event.size());
  12945. }
  12946. return false; // Close stream after sending
  12947. });
  12948. });
  12949. Client client("localhost", get_port());
  12950. sse::SSEClient sse(client, "/simple-event");
  12951. std::atomic<bool> open_called{false};
  12952. std::atomic<bool> message_received{false};
  12953. sse.on_open([&open_called]() { open_called.store(true); });
  12954. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  12955. if (msg.data == "hello") { message_received.store(true); }
  12956. });
  12957. sse.set_reconnect_interval(100);
  12958. sse.set_max_reconnect_attempts(1);
  12959. // Start async
  12960. sse.start_async();
  12961. // Wait for message to be processed
  12962. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12963. sse.stop();
  12964. EXPECT_TRUE(open_called.load());
  12965. EXPECT_TRUE(message_received.load());
  12966. }
  12967. // Test: on_message callback
  12968. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  12969. // Endpoint that sends multiple events then closes
  12970. server_->Get("/multi-event", [](const Request &, Response &res) {
  12971. res.set_chunked_content_provider(
  12972. "text/event-stream", [](size_t offset, DataSink &sink) {
  12973. if (offset == 0) {
  12974. std::string events = "data: message1\n\ndata: message2\n\n";
  12975. sink.write(events.data(), events.size());
  12976. }
  12977. return false;
  12978. });
  12979. });
  12980. Client client("localhost", get_port());
  12981. sse::SSEClient sse(client, "/multi-event");
  12982. std::vector<std::string> received_messages;
  12983. std::mutex messages_mutex;
  12984. sse.on_message([&](const sse::SSEMessage &msg) {
  12985. std::lock_guard<std::mutex> lock(messages_mutex);
  12986. received_messages.push_back(msg.data);
  12987. });
  12988. sse.set_reconnect_interval(100);
  12989. sse.set_max_reconnect_attempts(1);
  12990. sse.start_async();
  12991. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12992. sse.stop();
  12993. std::lock_guard<std::mutex> lock(messages_mutex);
  12994. EXPECT_GE(received_messages.size(), 2u);
  12995. if (received_messages.size() >= 2) {
  12996. EXPECT_EQ(received_messages[0], "message1");
  12997. EXPECT_EQ(received_messages[1], "message2");
  12998. }
  12999. }
  13000. // Test: on_event for specific types
  13001. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  13002. Client client("localhost", get_port());
  13003. sse::SSEClient sse(client, "/custom-events");
  13004. std::atomic<bool> update_received{false};
  13005. std::atomic<bool> delete_received{false};
  13006. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  13007. if (msg.data == "updated") { update_received.store(true); }
  13008. });
  13009. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  13010. if (msg.data == "deleted") { delete_received.store(true); }
  13011. });
  13012. sse.set_max_reconnect_attempts(1);
  13013. sse.start_async();
  13014. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  13015. sse.stop();
  13016. EXPECT_TRUE(update_received.load());
  13017. EXPECT_TRUE(delete_received.load());
  13018. }
  13019. // Test: on_error callback on connection failure
  13020. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  13021. // Connect to a non-existent port
  13022. Client client("localhost", 59999);
  13023. sse::SSEClient sse(client, "/events");
  13024. std::atomic<bool> error_called{false};
  13025. Error received_error = Error::Success;
  13026. sse.on_error([&](Error err) {
  13027. error_called.store(true);
  13028. received_error = err;
  13029. });
  13030. sse.set_reconnect_interval(50);
  13031. sse.set_max_reconnect_attempts(1);
  13032. sse.start_async();
  13033. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13034. sse.stop();
  13035. EXPECT_TRUE(error_called.load());
  13036. EXPECT_NE(received_error, Error::Success);
  13037. }
  13038. // Test: Last-Event-ID header sent on reconnect
  13039. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  13040. // Endpoint that sends event with ID
  13041. server_->Get("/event-with-id", [](const Request &, Response &res) {
  13042. res.set_chunked_content_provider(
  13043. "text/event-stream", [](size_t offset, DataSink &sink) {
  13044. if (offset == 0) {
  13045. std::string event = "id: evt-123\ndata: test\n\n";
  13046. sink.write(event.data(), event.size());
  13047. }
  13048. return false;
  13049. });
  13050. });
  13051. Client client("localhost", get_port());
  13052. sse::SSEClient sse(client, "/event-with-id");
  13053. std::atomic<bool> id_received{false};
  13054. sse.on_message([&](const sse::SSEMessage &msg) {
  13055. if (!msg.id.empty()) { id_received.store(true); }
  13056. });
  13057. sse.set_reconnect_interval(100);
  13058. sse.set_max_reconnect_attempts(1);
  13059. sse.start_async();
  13060. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13061. sse.stop();
  13062. EXPECT_TRUE(id_received.load());
  13063. EXPECT_EQ(sse.last_event_id(), "evt-123");
  13064. }
  13065. // Test: Manual stop
  13066. TEST_F(SSEIntegrationTest, ManualStop) {
  13067. // Endpoint that sends one event and stays open briefly
  13068. std::atomic<bool> handler_running{true};
  13069. server_->Get("/stay-open", [&handler_running](const Request &,
  13070. Response &res) {
  13071. res.set_chunked_content_provider(
  13072. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  13073. if (offset == 0) {
  13074. std::string event = "data: connected\n\n";
  13075. sink.write(event.data(), event.size());
  13076. }
  13077. // Keep connection open while handler_running is true
  13078. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  13079. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13080. }
  13081. return false;
  13082. });
  13083. });
  13084. Client client("localhost", get_port());
  13085. sse::SSEClient sse(client, "/stay-open");
  13086. std::atomic<bool> connected{false};
  13087. sse.on_open([&connected]() { connected.store(true); });
  13088. sse.set_reconnect_interval(100);
  13089. sse.set_max_reconnect_attempts(1);
  13090. sse.start_async();
  13091. // Wait for connection to establish
  13092. for (int i = 0; i < 20 && !connected.load(); ++i) {
  13093. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13094. }
  13095. EXPECT_TRUE(connected.load());
  13096. EXPECT_TRUE(sse.is_connected());
  13097. // Signal handler to stop
  13098. handler_running.store(false);
  13099. // Stop SSE client
  13100. sse.stop();
  13101. EXPECT_FALSE(sse.is_connected());
  13102. }
  13103. // Test: SSEClient with custom headers
  13104. TEST_F(SSEIntegrationTest, CustomHeaders) {
  13105. // Setup a server endpoint that checks for custom header
  13106. std::atomic<bool> header_received{false};
  13107. server_->Get("/header-check", [&](const Request &req, Response &res) {
  13108. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  13109. header_received.store(true);
  13110. }
  13111. res.set_chunked_content_provider("text/event-stream",
  13112. [](size_t, DataSink &) { return false; });
  13113. });
  13114. Client client("localhost", get_port());
  13115. Headers headers = {{"X-Custom-Header", "custom-value"}};
  13116. sse::SSEClient sse(client, "/header-check", headers);
  13117. sse.set_max_reconnect_attempts(1);
  13118. sse.start_async();
  13119. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13120. sse.stop();
  13121. EXPECT_TRUE(header_received.load());
  13122. }
  13123. // Test: Reconnect interval configuration
  13124. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  13125. Client client("localhost", get_port());
  13126. sse::SSEClient sse(client, "/events");
  13127. auto &result = sse.set_reconnect_interval(500);
  13128. // Builder pattern should return reference to self
  13129. EXPECT_EQ(&result, &sse);
  13130. }
  13131. // Test: Max reconnect attempts
  13132. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  13133. // Connect to non-existent port to force reconnects
  13134. Client client("localhost", 59998);
  13135. sse::SSEClient sse(client, "/events");
  13136. std::atomic<int> error_count{0};
  13137. sse.on_error([&](Error) { error_count.fetch_add(1); });
  13138. sse.set_reconnect_interval(50);
  13139. sse.set_max_reconnect_attempts(2);
  13140. auto start = std::chrono::steady_clock::now();
  13141. sse.start(); // Blocking call
  13142. auto end = std::chrono::steady_clock::now();
  13143. // Should have stopped after 2 failed attempts
  13144. EXPECT_GE(error_count.load(), 2);
  13145. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  13146. auto duration =
  13147. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  13148. #ifdef _WIN32
  13149. // Windows is much slower for socket connection failures
  13150. EXPECT_LT(duration.count(), 7000);
  13151. #else
  13152. EXPECT_LT(duration.count(), 1000);
  13153. #endif
  13154. }
  13155. // Test: Multi-line data in integration
  13156. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  13157. // Endpoint with multi-line data
  13158. server_->Get("/multiline-data", [](const Request &, Response &res) {
  13159. res.set_chunked_content_provider(
  13160. "text/event-stream", [](size_t offset, DataSink &sink) {
  13161. if (offset == 0) {
  13162. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  13163. sink.write(event.data(), event.size());
  13164. }
  13165. return false;
  13166. });
  13167. });
  13168. Client client("localhost", get_port());
  13169. sse::SSEClient sse(client, "/multiline-data");
  13170. std::string received_data;
  13171. std::mutex data_mutex;
  13172. sse.on_message([&](const sse::SSEMessage &msg) {
  13173. std::lock_guard<std::mutex> lock(data_mutex);
  13174. received_data = msg.data;
  13175. });
  13176. sse.set_reconnect_interval(100);
  13177. sse.set_max_reconnect_attempts(1);
  13178. sse.start_async();
  13179. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13180. sse.stop();
  13181. std::lock_guard<std::mutex> lock(data_mutex);
  13182. EXPECT_EQ(received_data, "line1\nline2\nline3");
  13183. }
  13184. // Test: Auto-reconnect after server disconnection
  13185. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  13186. std::atomic<int> connection_count{0};
  13187. std::atomic<int> message_count{0};
  13188. // Endpoint that sends one event and closes, forcing reconnect
  13189. server_->Get("/reconnect-test",
  13190. [&connection_count](const Request &, Response &res) {
  13191. connection_count.fetch_add(1);
  13192. res.set_chunked_content_provider(
  13193. "text/event-stream", [](size_t offset, DataSink &sink) {
  13194. if (offset == 0) {
  13195. std::string event = "data: hello\n\n";
  13196. sink.write(event.data(), event.size());
  13197. }
  13198. return false; // Close connection after sending
  13199. });
  13200. });
  13201. Client client("localhost", get_port());
  13202. sse::SSEClient sse(client, "/reconnect-test");
  13203. sse.on_message([&message_count](const sse::SSEMessage &) {
  13204. message_count.fetch_add(1);
  13205. });
  13206. sse.set_reconnect_interval(100);
  13207. sse.set_max_reconnect_attempts(3);
  13208. sse.start_async();
  13209. // Wait long enough for multiple reconnects
  13210. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13211. sse.stop();
  13212. // Should have connected multiple times (initial + reconnects)
  13213. EXPECT_GE(connection_count.load(), 2);
  13214. // Should have received messages from multiple connections
  13215. EXPECT_GE(message_count.load(), 2);
  13216. }
  13217. // Test: Last-Event-ID sent on reconnect
  13218. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  13219. std::atomic<int> connection_count{0};
  13220. std::vector<std::string> received_last_event_ids;
  13221. std::mutex id_mutex;
  13222. // Endpoint that checks Last-Event-ID header and sends event with ID
  13223. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  13224. int conn = connection_count.fetch_add(1);
  13225. // Capture the Last-Event-ID header from each connection
  13226. {
  13227. std::lock_guard<std::mutex> lock(id_mutex);
  13228. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  13229. }
  13230. res.set_chunked_content_provider(
  13231. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  13232. if (offset == 0) {
  13233. std::string event =
  13234. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  13235. sink.write(event.data(), event.size());
  13236. }
  13237. return false;
  13238. });
  13239. });
  13240. Client client("localhost", get_port());
  13241. sse::SSEClient sse(client, "/reconnect-with-id");
  13242. sse.set_reconnect_interval(100);
  13243. sse.set_max_reconnect_attempts(3);
  13244. sse.start_async();
  13245. // Wait for at least 2 connections
  13246. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13247. sse.stop();
  13248. // Verify behavior
  13249. std::lock_guard<std::mutex> lock(id_mutex);
  13250. EXPECT_GE(received_last_event_ids.size(), 2u);
  13251. // First connection should have no Last-Event-ID
  13252. if (!received_last_event_ids.empty()) {
  13253. EXPECT_EQ(received_last_event_ids[0], "");
  13254. }
  13255. // Second connection should have Last-Event-ID from first connection
  13256. if (received_last_event_ids.size() >= 2) {
  13257. EXPECT_EQ(received_last_event_ids[1], "event-0");
  13258. }
  13259. }
  13260. TEST(Issue2318Test, EmptyHostString) {
  13261. {
  13262. httplib::Client cli_empty("", PORT);
  13263. auto res = cli_empty.Get("/");
  13264. ASSERT_FALSE(res);
  13265. EXPECT_EQ(httplib::Error::Connection, res.error());
  13266. }
  13267. {
  13268. httplib::Client cli(" ", PORT);
  13269. auto res = cli.Get("/");
  13270. ASSERT_FALSE(res);
  13271. EXPECT_EQ(httplib::Error::Connection, res.error());
  13272. }
  13273. }
  13274. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13275. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  13276. Server svr;
  13277. // Set a small payload limit (1KB)
  13278. svr.set_payload_max_length(1024);
  13279. svr.Post("/test", [&](const Request &req, Response &res) {
  13280. res.set_content("Body size: " + std::to_string(req.body.size()),
  13281. "text/plain");
  13282. });
  13283. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13284. auto se = detail::scope_exit([&] {
  13285. svr.stop();
  13286. listen_thread.join();
  13287. });
  13288. svr.wait_until_ready();
  13289. // Create data that compresses well but exceeds limit when decompressed
  13290. // 8KB of repeated null bytes compresses to a very small size
  13291. std::string original_data(8 * 1024, '\0');
  13292. // Compress the data using gzip
  13293. std::string compressed_data;
  13294. detail::gzip_compressor compressor;
  13295. compressor.compress(original_data.data(), original_data.size(), true,
  13296. [&](const char *data, size_t size) {
  13297. compressed_data.append(data, size);
  13298. return true;
  13299. });
  13300. // Verify compression worked (compressed should be much smaller)
  13301. ASSERT_LT(compressed_data.size(), original_data.size());
  13302. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  13303. // Send compressed data with Content-Encoding: gzip
  13304. Client cli(HOST, PORT);
  13305. Headers headers = {{"Content-Encoding", "gzip"}};
  13306. auto res =
  13307. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  13308. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  13309. ASSERT_TRUE(res);
  13310. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13311. }
  13312. #endif
  13313. // ============================================================================
  13314. // OpenSSL-Specific Tests
  13315. // ============================================================================
  13316. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13317. X509 *readCertificate(const std::string &strFileName) {
  13318. std::ifstream inStream(strFileName);
  13319. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  13320. std::istreambuf_iterator<char>());
  13321. if (strCertPEM.empty()) return (nullptr);
  13322. BIO *pbCert = BIO_new(BIO_s_mem());
  13323. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  13324. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  13325. BIO_free(pbCert);
  13326. return (pCert);
  13327. }
  13328. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  13329. std::ifstream inStream(strFileName);
  13330. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  13331. std::istreambuf_iterator<char>());
  13332. if (strPrivateKeyPEM.empty()) return (nullptr);
  13333. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  13334. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  13335. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  13336. BIO_free(pbPrivKey);
  13337. return (pPrivateKey);
  13338. }
  13339. TEST(BindServerTest, UpdateCerts) {
  13340. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13341. int port = svr.bind_to_any_port("0.0.0.0");
  13342. ASSERT_TRUE(svr.is_valid());
  13343. ASSERT_TRUE(port > 0);
  13344. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13345. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13346. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13347. ASSERT_TRUE(cert != nullptr);
  13348. ASSERT_TRUE(ca_cert != nullptr);
  13349. ASSERT_TRUE(key != nullptr);
  13350. X509_STORE *cert_store = X509_STORE_new();
  13351. X509_STORE_add_cert(cert_store, ca_cert);
  13352. // svr.update_certs(cert, key, cert_store); // deprecated
  13353. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13354. CLIENT_CA_CERT_FILE);
  13355. ASSERT_TRUE(svr.is_valid());
  13356. svr.stop();
  13357. X509_STORE_free(cert_store);
  13358. X509_free(cert);
  13359. X509_free(ca_cert);
  13360. EVP_PKEY_free(key);
  13361. }
  13362. // Test that SSLServer(X509*, EVP_PKEY*, X509_STORE*) constructor sets
  13363. // client CA list correctly for TLS handshake
  13364. TEST(SSLClientServerTest, X509ConstructorSetsClientCAList) {
  13365. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13366. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13367. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13368. ASSERT_TRUE(cert != nullptr);
  13369. ASSERT_TRUE(ca_cert != nullptr);
  13370. ASSERT_TRUE(key != nullptr);
  13371. X509_STORE *cert_store = X509_STORE_new();
  13372. X509_STORE_add_cert(cert_store, ca_cert);
  13373. // Use X509-based constructor (deprecated but should still work correctly)
  13374. #pragma GCC diagnostic push
  13375. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  13376. SSLServer svr(cert, key, cert_store);
  13377. #pragma GCC diagnostic pop
  13378. ASSERT_TRUE(svr.is_valid());
  13379. // Verify that client CA list is set in SSL_CTX
  13380. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13381. ASSERT_TRUE(ssl_ctx != nullptr);
  13382. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13383. ASSERT_TRUE(ca_list != nullptr);
  13384. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13385. X509_free(cert);
  13386. X509_free(ca_cert);
  13387. EVP_PKEY_free(key);
  13388. }
  13389. // Test that update_certs() updates client CA list correctly
  13390. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  13391. // Start with file-based constructor
  13392. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13393. ASSERT_TRUE(svr.is_valid());
  13394. // Initially no client CA list should be set
  13395. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13396. ASSERT_TRUE(ssl_ctx != nullptr);
  13397. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  13398. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  13399. EXPECT_EQ(0, count_before);
  13400. // Now update with client CA (PEM string)
  13401. std::string cert_pem, key_pem, ca_pem;
  13402. read_file(SERVER_CERT_FILE, cert_pem);
  13403. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13404. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13405. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  13406. ASSERT_TRUE(svr.is_valid());
  13407. // Now client CA list should be set
  13408. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  13409. ASSERT_TRUE(ca_list_after != nullptr);
  13410. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  13411. }
  13412. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  13413. // Test that the file-path SSLServer constructor properly sets the client CA
  13414. // list that is sent to clients during the TLS handshake (CertificateRequest)
  13415. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13416. ASSERT_TRUE(svr.is_valid());
  13417. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13418. ASSERT_TRUE(ssl_ctx != nullptr);
  13419. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13420. ASSERT_TRUE(ca_list != nullptr);
  13421. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13422. }
  13423. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  13424. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  13425. // prepare large data
  13426. std::random_device seed_gen;
  13427. std::mt19937 random(seed_gen());
  13428. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  13429. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  13430. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  13431. // server
  13432. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13433. ASSERT_TRUE(svr.is_valid());
  13434. svr.Post("/binary", [&](const Request &req, Response &res) {
  13435. EXPECT_EQ(large_size_byte, req.body.size());
  13436. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  13437. res.set_content(req.body, "application/octet-stream");
  13438. });
  13439. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  13440. auto se = detail::scope_exit([&] {
  13441. svr.stop();
  13442. listen_thread.join();
  13443. ASSERT_FALSE(svr.is_running());
  13444. });
  13445. svr.wait_until_ready();
  13446. // client POST
  13447. SSLClient cli("localhost", PORT);
  13448. cli.enable_server_certificate_verification(false);
  13449. cli.set_read_timeout(std::chrono::seconds(100));
  13450. cli.set_write_timeout(std::chrono::seconds(100));
  13451. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  13452. large_size_byte, "application/octet-stream");
  13453. // compare
  13454. EXPECT_EQ(StatusCode::OK_200, res->status);
  13455. EXPECT_EQ(large_size_byte, res->body.size());
  13456. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  13457. }
  13458. #endif
  13459. // ============================================================================
  13460. // MbedTLS-Specific Tests
  13461. // ============================================================================
  13462. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  13463. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  13464. using namespace httplib::tls;
  13465. // Track if callback was invoked
  13466. bool callback_invoked = false;
  13467. // The callback receives void* ctx which is actually MbedTlsContext*
  13468. // We can access the mbedtls_ssl_config via the context
  13469. auto setup_callback = [&callback_invoked](void *ctx) {
  13470. callback_invoked = true;
  13471. // Cast to MbedTlsContext* to access the ssl config
  13472. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  13473. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  13474. // Use static variables to hold certificate data (simplified for test)
  13475. static mbedtls_x509_crt own_cert;
  13476. static mbedtls_pk_context own_key;
  13477. static mbedtls_x509_crt ca_chain;
  13478. static bool initialized = false;
  13479. if (!initialized) {
  13480. mbedtls_x509_crt_init(&own_cert);
  13481. mbedtls_pk_init(&own_key);
  13482. mbedtls_x509_crt_init(&ca_chain);
  13483. // Load server certificate
  13484. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  13485. return false;
  13486. }
  13487. // Load server private key
  13488. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  13489. #if MBEDTLS_VERSION_MAJOR >= 3
  13490. ,
  13491. mbedtls_ctr_drbg_random, nullptr
  13492. #endif
  13493. ) != 0) {
  13494. return false;
  13495. }
  13496. // Load CA chain for client verification
  13497. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  13498. return false;
  13499. }
  13500. initialized = true;
  13501. }
  13502. // Configure the SSL config
  13503. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  13504. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  13505. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  13506. // Set minimum TLS version using mbedTLS native API
  13507. #if MBEDTLS_VERSION_MAJOR >= 3
  13508. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  13509. #else
  13510. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  13511. MBEDTLS_SSL_MINOR_VERSION_3);
  13512. #endif
  13513. return true;
  13514. };
  13515. SSLServer svr(setup_callback);
  13516. ASSERT_TRUE(svr.is_valid());
  13517. ASSERT_TRUE(callback_invoked);
  13518. svr.Get("/test", [&](const Request &req, Response &res) {
  13519. res.set_content("test", "text/plain");
  13520. auto cert = req.peer_cert();
  13521. ASSERT_TRUE(static_cast<bool>(cert));
  13522. auto common_name = cert.subject_cn();
  13523. EXPECT_EQ("Common Name", common_name);
  13524. });
  13525. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13526. auto se = detail::scope_exit([&] {
  13527. svr.stop();
  13528. t.join();
  13529. ASSERT_FALSE(svr.is_running());
  13530. });
  13531. svr.wait_until_ready();
  13532. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13533. cli.enable_server_certificate_verification(false);
  13534. cli.set_connection_timeout(30);
  13535. auto res = cli.Get("/test");
  13536. ASSERT_TRUE(res);
  13537. ASSERT_EQ(StatusCode::OK_200, res->status);
  13538. }
  13539. #endif
  13540. // WebSocket Tests
  13541. TEST(WebSocketTest, RSVBitsMustBeZero) {
  13542. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  13543. // defining the meaning of these bits has been negotiated.
  13544. auto make_frame = [](uint8_t first_byte) {
  13545. std::string frame;
  13546. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  13547. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  13548. frame += "Hello";
  13549. return frame;
  13550. };
  13551. // RSV1 set (0x40)
  13552. {
  13553. detail::BufferStream strm;
  13554. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  13555. ws::Opcode opcode;
  13556. std::string payload;
  13557. bool fin;
  13558. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13559. false, 1024));
  13560. }
  13561. // RSV2 set (0x20)
  13562. {
  13563. detail::BufferStream strm;
  13564. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  13565. ws::Opcode opcode;
  13566. std::string payload;
  13567. bool fin;
  13568. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13569. false, 1024));
  13570. }
  13571. // RSV3 set (0x10)
  13572. {
  13573. detail::BufferStream strm;
  13574. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  13575. ws::Opcode opcode;
  13576. std::string payload;
  13577. bool fin;
  13578. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13579. false, 1024));
  13580. }
  13581. // No RSV bits set - should succeed
  13582. {
  13583. detail::BufferStream strm;
  13584. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  13585. ws::Opcode opcode;
  13586. std::string payload;
  13587. bool fin;
  13588. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13589. false, 1024));
  13590. EXPECT_EQ(ws::Opcode::Text, opcode);
  13591. EXPECT_EQ("Hello", payload);
  13592. EXPECT_TRUE(fin);
  13593. }
  13594. }
  13595. TEST(WebSocketTest, ControlFrameValidation) {
  13596. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  13597. // payload length <= 125.
  13598. // Ping with FIN=0 - must be rejected
  13599. {
  13600. detail::BufferStream strm;
  13601. std::string frame;
  13602. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  13603. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13604. strm.write(frame.data(), frame.size());
  13605. ws::Opcode opcode;
  13606. std::string payload;
  13607. bool fin;
  13608. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13609. false, 1024));
  13610. }
  13611. // Close with FIN=0 - must be rejected
  13612. {
  13613. detail::BufferStream strm;
  13614. std::string frame;
  13615. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  13616. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13617. strm.write(frame.data(), frame.size());
  13618. ws::Opcode opcode;
  13619. std::string payload;
  13620. bool fin;
  13621. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13622. false, 1024));
  13623. }
  13624. // Ping with payload_len=126 (extended length) - must be rejected
  13625. {
  13626. detail::BufferStream strm;
  13627. std::string frame;
  13628. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13629. frame += static_cast<char>(126); // payload_len=126 (>125)
  13630. frame += static_cast<char>(0x00); // extended length high byte
  13631. frame += static_cast<char>(126); // extended length low byte
  13632. frame += std::string(126, 'x');
  13633. strm.write(frame.data(), frame.size());
  13634. ws::Opcode opcode;
  13635. std::string payload;
  13636. bool fin;
  13637. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13638. false, 1024));
  13639. }
  13640. // Ping with FIN=1 and payload_len=125 - should succeed
  13641. {
  13642. detail::BufferStream strm;
  13643. std::string frame;
  13644. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13645. frame += static_cast<char>(125); // payload_len=125
  13646. frame += std::string(125, 'x');
  13647. strm.write(frame.data(), frame.size());
  13648. ws::Opcode opcode;
  13649. std::string payload;
  13650. bool fin;
  13651. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13652. false, 1024));
  13653. EXPECT_EQ(ws::Opcode::Ping, opcode);
  13654. EXPECT_EQ(125u, payload.size());
  13655. EXPECT_TRUE(fin);
  13656. }
  13657. }
  13658. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  13659. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  13660. // length MUST be 0.
  13661. // MSB set - must be rejected
  13662. {
  13663. detail::BufferStream strm;
  13664. std::string frame;
  13665. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13666. frame += static_cast<char>(127); // 64-bit extended length
  13667. frame += static_cast<char>(0x80); // MSB set (invalid)
  13668. frame += std::string(7, '\0'); // remaining 7 bytes of length
  13669. strm.write(frame.data(), frame.size());
  13670. ws::Opcode opcode;
  13671. std::string payload;
  13672. bool fin;
  13673. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13674. false, 1024));
  13675. }
  13676. // MSB clear - should pass length parsing (will be rejected by max_len,
  13677. // but that's a different check; use a small length to verify)
  13678. {
  13679. detail::BufferStream strm;
  13680. std::string frame;
  13681. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13682. frame += static_cast<char>(127); // 64-bit extended length
  13683. frame += std::string(7, '\0'); // high bytes = 0
  13684. frame += static_cast<char>(0x03); // length = 3
  13685. frame += "abc";
  13686. strm.write(frame.data(), frame.size());
  13687. ws::Opcode opcode;
  13688. std::string payload;
  13689. bool fin;
  13690. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13691. false, 1024));
  13692. EXPECT_EQ(ws::Opcode::Text, opcode);
  13693. EXPECT_EQ("abc", payload);
  13694. }
  13695. }
  13696. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  13697. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  13698. // Valid UTF-8
  13699. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  13700. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  13701. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  13702. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  13703. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  13704. // Invalid UTF-8
  13705. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  13706. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  13707. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  13708. EXPECT_FALSE(
  13709. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  13710. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  13711. }
  13712. TEST(WebSocketTest, ConnectAndDisconnect) {
  13713. Server svr;
  13714. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  13715. std::string msg;
  13716. while (ws.read(msg)) {}
  13717. });
  13718. auto port = svr.bind_to_any_port(HOST);
  13719. std::thread t([&]() { svr.listen_after_bind(); });
  13720. svr.wait_until_ready();
  13721. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  13722. ASSERT_TRUE(client.connect());
  13723. EXPECT_TRUE(client.is_open());
  13724. client.close();
  13725. EXPECT_FALSE(client.is_open());
  13726. svr.stop();
  13727. t.join();
  13728. }
  13729. TEST(WebSocketTest, ValidURL) {
  13730. ws::WebSocketClient ws1("ws://localhost:8080/path");
  13731. EXPECT_TRUE(ws1.is_valid());
  13732. ws::WebSocketClient ws2("ws://example.com/path");
  13733. EXPECT_TRUE(ws2.is_valid());
  13734. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  13735. EXPECT_TRUE(ws3.is_valid());
  13736. #ifdef CPPHTTPLIB_SSL_ENABLED
  13737. ws::WebSocketClient wss1("wss://example.com/path");
  13738. EXPECT_TRUE(wss1.is_valid());
  13739. ws::WebSocketClient wss2("wss://example.com:443/path");
  13740. EXPECT_TRUE(wss2.is_valid());
  13741. #endif
  13742. }
  13743. TEST(WebSocketTest, InvalidURL) {
  13744. // No scheme
  13745. ws::WebSocketClient ws1("localhost:8080/path");
  13746. EXPECT_FALSE(ws1.is_valid());
  13747. // No path
  13748. ws::WebSocketClient ws2("ws://localhost:8080");
  13749. EXPECT_FALSE(ws2.is_valid());
  13750. // Empty string
  13751. ws::WebSocketClient ws3("");
  13752. EXPECT_FALSE(ws3.is_valid());
  13753. // Missing host
  13754. ws::WebSocketClient ws4("ws://:8080/path");
  13755. EXPECT_FALSE(ws4.is_valid());
  13756. // Port number overflow — should not crash
  13757. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  13758. EXPECT_FALSE(ws5.is_valid());
  13759. // Port out of range
  13760. ws::WebSocketClient ws6("ws://localhost:99999/path");
  13761. EXPECT_FALSE(ws6.is_valid());
  13762. }
  13763. TEST(WebSocketTest, UnsupportedScheme) {
  13764. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13765. ws::WebSocketClient ws1("http://localhost:8080/path");
  13766. EXPECT_FALSE(ws1.is_valid());
  13767. ws::WebSocketClient ws2("https://localhost:8080/path");
  13768. EXPECT_FALSE(ws2.is_valid());
  13769. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  13770. EXPECT_FALSE(ws3.is_valid());
  13771. #else
  13772. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  13773. std::invalid_argument);
  13774. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  13775. std::invalid_argument);
  13776. #endif
  13777. }
  13778. TEST(WebSocketTest, ConnectWhenInvalid) {
  13779. ws::WebSocketClient ws("not a valid url");
  13780. EXPECT_FALSE(ws.is_valid());
  13781. EXPECT_FALSE(ws.connect());
  13782. }
  13783. TEST(WebSocketTest, DefaultPort) {
  13784. ws::WebSocketClient ws1("ws://example.com/path");
  13785. EXPECT_TRUE(ws1.is_valid());
  13786. // ws:// defaults to port 80 (verified by successful parse)
  13787. #ifdef CPPHTTPLIB_SSL_ENABLED
  13788. ws::WebSocketClient ws2("wss://example.com/path");
  13789. EXPECT_TRUE(ws2.is_valid());
  13790. // wss:// defaults to port 443 (verified by successful parse)
  13791. #endif
  13792. }
  13793. TEST(WebSocketTest, IPv6LiteralAddress) {
  13794. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  13795. EXPECT_TRUE(ws1.is_valid());
  13796. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  13797. EXPECT_TRUE(ws2.is_valid());
  13798. }
  13799. TEST(WebSocketTest, ComplexPath) {
  13800. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  13801. EXPECT_TRUE(ws1.is_valid());
  13802. ws::WebSocketClient ws2("ws://localhost:8080/");
  13803. EXPECT_TRUE(ws2.is_valid());
  13804. }
  13805. class WebSocketIntegrationTest : public ::testing::Test {
  13806. protected:
  13807. void SetUp() override {
  13808. server_ = httplib::detail::make_unique<Server>();
  13809. setup_server();
  13810. start_server();
  13811. }
  13812. void TearDown() override {
  13813. server_->stop();
  13814. if (server_thread_.joinable()) { server_thread_.join(); }
  13815. }
  13816. void setup_server() {
  13817. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  13818. std::string msg;
  13819. ws::ReadResult ret;
  13820. while ((ret = ws.read(msg))) {
  13821. if (ret == ws::Binary) {
  13822. ws.send(msg.data(), msg.size());
  13823. } else {
  13824. ws.send(msg);
  13825. }
  13826. }
  13827. });
  13828. server_->WebSocket("/ws-echo-string",
  13829. [](const Request &, ws::WebSocket &ws) {
  13830. std::string msg;
  13831. while (ws.read(msg)) {
  13832. ws.send("echo: " + msg);
  13833. }
  13834. });
  13835. server_->WebSocket(
  13836. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  13837. // Echo back request metadata
  13838. ws.send("path:" + req.path);
  13839. ws.send("header:" + req.get_header_value("X-Test-Header"));
  13840. std::string msg;
  13841. while (ws.read(msg)) {}
  13842. });
  13843. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  13844. std::string msg;
  13845. ws.read(msg); // wait for a message
  13846. ws.close();
  13847. });
  13848. server_->WebSocket("/ws-close-status",
  13849. [](const Request &, ws::WebSocket &ws) {
  13850. std::string msg;
  13851. ws.read(msg); // wait for a message
  13852. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  13853. });
  13854. server_->WebSocket(
  13855. "/ws-subprotocol",
  13856. [](const Request &, ws::WebSocket &ws) {
  13857. std::string msg;
  13858. while (ws.read(msg)) {
  13859. ws.send(msg);
  13860. }
  13861. },
  13862. [](const std::vector<std::string> &protocols) -> std::string {
  13863. for (const auto &p : protocols) {
  13864. if (p == "graphql-ws") { return p; }
  13865. }
  13866. return "";
  13867. });
  13868. }
  13869. void start_server() {
  13870. port_ = server_->bind_to_any_port(HOST);
  13871. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13872. server_->wait_until_ready();
  13873. }
  13874. std::unique_ptr<Server> server_;
  13875. std::thread server_thread_;
  13876. int port_ = 0;
  13877. };
  13878. TEST_F(WebSocketIntegrationTest, TextEcho) {
  13879. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13880. "/ws-echo");
  13881. ASSERT_TRUE(client.connect());
  13882. ASSERT_TRUE(client.is_open());
  13883. ASSERT_TRUE(client.send("Hello WebSocket"));
  13884. std::string msg;
  13885. EXPECT_EQ(ws::Text, client.read(msg));
  13886. EXPECT_EQ("Hello WebSocket", msg);
  13887. client.close();
  13888. }
  13889. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  13890. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13891. "/ws-echo");
  13892. ASSERT_TRUE(client.connect());
  13893. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  13894. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  13895. std::string msg;
  13896. EXPECT_EQ(ws::Binary, client.read(msg));
  13897. EXPECT_EQ(binary_data, msg);
  13898. client.close();
  13899. }
  13900. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  13901. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13902. "/ws-echo");
  13903. ASSERT_TRUE(client.connect());
  13904. for (int i = 0; i < 10; i++) {
  13905. auto text = "message " + std::to_string(i);
  13906. ASSERT_TRUE(client.send(text));
  13907. std::string msg;
  13908. ASSERT_TRUE(client.read(msg));
  13909. EXPECT_EQ(text, msg);
  13910. }
  13911. client.close();
  13912. }
  13913. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  13914. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13915. "/ws-close");
  13916. ASSERT_TRUE(client.connect());
  13917. // Send a message to trigger the server to close
  13918. ASSERT_TRUE(client.send("trigger close"));
  13919. // The server will close, so read should return false
  13920. std::string msg;
  13921. EXPECT_FALSE(client.read(msg));
  13922. EXPECT_FALSE(client.is_open());
  13923. }
  13924. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  13925. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13926. "/ws-echo");
  13927. ASSERT_TRUE(client.connect());
  13928. // 128KB message
  13929. std::string large_data(128 * 1024, 'X');
  13930. ASSERT_TRUE(client.send(large_data));
  13931. std::string msg;
  13932. ASSERT_TRUE(client.read(msg));
  13933. EXPECT_EQ(large_data, msg);
  13934. client.close();
  13935. }
  13936. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  13937. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13938. "/ws-echo");
  13939. ASSERT_TRUE(client.connect());
  13940. const int num_threads = 4;
  13941. std::vector<std::thread> threads;
  13942. std::atomic<int> send_count{0};
  13943. for (int t = 0; t < num_threads; t++) {
  13944. threads.emplace_back([&client, &send_count, t]() {
  13945. for (int i = 0; i < 5; i++) {
  13946. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  13947. if (client.send(text)) { send_count++; }
  13948. }
  13949. });
  13950. }
  13951. for (auto &th : threads) {
  13952. th.join();
  13953. }
  13954. int received = 0;
  13955. std::string msg;
  13956. while (received < send_count.load()) {
  13957. if (!client.read(msg)) { break; }
  13958. received++;
  13959. }
  13960. EXPECT_EQ(send_count.load(), received);
  13961. client.close();
  13962. }
  13963. TEST_F(WebSocketIntegrationTest, ReadString) {
  13964. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13965. "/ws-echo-string");
  13966. ASSERT_TRUE(client.connect());
  13967. ASSERT_TRUE(client.send("hello"));
  13968. std::string msg;
  13969. ASSERT_TRUE(client.read(msg));
  13970. EXPECT_EQ("echo: hello", msg);
  13971. ASSERT_TRUE(client.send("world"));
  13972. ASSERT_TRUE(client.read(msg));
  13973. EXPECT_EQ("echo: world", msg);
  13974. client.close();
  13975. }
  13976. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  13977. Headers headers = {{"X-Test-Header", "test-value"}};
  13978. ws::WebSocketClient client(
  13979. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  13980. ASSERT_TRUE(client.connect());
  13981. std::string msg;
  13982. ASSERT_TRUE(client.read(msg));
  13983. EXPECT_EQ("path:/ws-request-info", msg);
  13984. ASSERT_TRUE(client.read(msg));
  13985. EXPECT_EQ("header:test-value", msg);
  13986. client.close();
  13987. }
  13988. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  13989. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13990. "/ws-echo");
  13991. client.set_read_timeout(1, 0); // 1 second
  13992. ASSERT_TRUE(client.connect());
  13993. // Don't send anything — server echo handler waits for a message,
  13994. // so read() should time out and return false.
  13995. std::string msg;
  13996. EXPECT_FALSE(client.read(msg));
  13997. }
  13998. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  13999. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14000. "/ws-echo");
  14001. client.set_read_timeout(5, 0);
  14002. ASSERT_TRUE(client.connect());
  14003. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14004. // The server should reject it and close the connection.
  14005. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  14006. client.send(oversized);
  14007. // The server's read() should have failed due to payload limit,
  14008. // so our read() should return false (connection closed).
  14009. std::string msg;
  14010. EXPECT_FALSE(client.read(msg));
  14011. }
  14012. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  14013. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14014. "/ws-echo");
  14015. client.set_read_timeout(10, 0);
  14016. ASSERT_TRUE(client.connect());
  14017. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14018. // This should succeed.
  14019. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  14020. ASSERT_TRUE(client.send(at_limit));
  14021. std::string msg;
  14022. ASSERT_TRUE(client.read(msg));
  14023. EXPECT_EQ(at_limit.size(), msg.size());
  14024. client.close();
  14025. }
  14026. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  14027. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14028. "/nonexistent");
  14029. EXPECT_FALSE(client.connect());
  14030. EXPECT_FALSE(client.is_open());
  14031. }
  14032. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  14033. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14034. "/ws-echo");
  14035. ASSERT_TRUE(client.connect());
  14036. ASSERT_TRUE(client.send(""));
  14037. std::string msg;
  14038. EXPECT_EQ(ws::Text, client.read(msg));
  14039. EXPECT_EQ("", msg);
  14040. client.close();
  14041. }
  14042. TEST_F(WebSocketIntegrationTest, Reconnect) {
  14043. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14044. "/ws-echo");
  14045. // First connection
  14046. ASSERT_TRUE(client.connect());
  14047. ASSERT_TRUE(client.send("first"));
  14048. std::string msg;
  14049. ASSERT_TRUE(client.read(msg));
  14050. EXPECT_EQ("first", msg);
  14051. client.close();
  14052. EXPECT_FALSE(client.is_open());
  14053. // Reconnect using the same client object
  14054. ASSERT_TRUE(client.connect());
  14055. ASSERT_TRUE(client.is_open());
  14056. ASSERT_TRUE(client.send("second"));
  14057. ASSERT_TRUE(client.read(msg));
  14058. EXPECT_EQ("second", msg);
  14059. client.close();
  14060. }
  14061. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  14062. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14063. "/ws-close-status");
  14064. ASSERT_TRUE(client.connect());
  14065. // Trigger the server to close with GoingAway status
  14066. ASSERT_TRUE(client.send("trigger"));
  14067. // read() should return false after receiving the close frame
  14068. std::string msg;
  14069. EXPECT_FALSE(client.read(msg));
  14070. EXPECT_FALSE(client.is_open());
  14071. }
  14072. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  14073. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14074. "/ws-echo");
  14075. ASSERT_TRUE(client.connect());
  14076. client.close(ws::CloseStatus::GoingAway, "client leaving");
  14077. EXPECT_FALSE(client.is_open());
  14078. }
  14079. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  14080. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  14081. ws::WebSocketClient client(
  14082. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14083. ASSERT_TRUE(client.connect());
  14084. // Server should have selected graphql-ws
  14085. EXPECT_EQ("graphql-ws", client.subprotocol());
  14086. client.close();
  14087. }
  14088. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  14089. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  14090. ws::WebSocketClient client(
  14091. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14092. ASSERT_TRUE(client.connect());
  14093. // Server should not have selected any subprotocol
  14094. EXPECT_TRUE(client.subprotocol().empty());
  14095. client.close();
  14096. }
  14097. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  14098. // Connect without requesting any subprotocol
  14099. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14100. "/ws-subprotocol");
  14101. ASSERT_TRUE(client.connect());
  14102. EXPECT_TRUE(client.subprotocol().empty());
  14103. client.close();
  14104. }
  14105. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  14106. Server svr;
  14107. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  14108. if (!req.has_header("Authorization")) {
  14109. res.status = StatusCode::Unauthorized_401;
  14110. res.set_content("Unauthorized", "text/plain");
  14111. return Server::HandlerResponse::Handled;
  14112. }
  14113. return Server::HandlerResponse::Unhandled;
  14114. });
  14115. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14116. std::string msg;
  14117. while (ws.read(msg)) {
  14118. ws.send(msg);
  14119. }
  14120. });
  14121. auto port = svr.bind_to_any_port("localhost");
  14122. std::thread t([&]() { svr.listen_after_bind(); });
  14123. svr.wait_until_ready();
  14124. // Without Authorization header - should be rejected before upgrade
  14125. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  14126. EXPECT_FALSE(client1.connect());
  14127. // With Authorization header - should succeed
  14128. Headers headers = {{"Authorization", "Bearer token123"}};
  14129. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  14130. headers);
  14131. ASSERT_TRUE(client2.connect());
  14132. ASSERT_TRUE(client2.send("hello"));
  14133. std::string msg;
  14134. ASSERT_TRUE(client2.read(msg));
  14135. EXPECT_EQ("hello", msg);
  14136. client2.close();
  14137. svr.stop();
  14138. t.join();
  14139. }
  14140. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14141. class WebSocketSSLIntegrationTest : public ::testing::Test {
  14142. protected:
  14143. void SetUp() override {
  14144. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  14145. SERVER_PRIVATE_KEY_FILE);
  14146. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14147. std::string msg;
  14148. ws::ReadResult ret;
  14149. while ((ret = ws.read(msg))) {
  14150. if (ret == ws::Binary) {
  14151. ws.send(msg.data(), msg.size());
  14152. } else {
  14153. ws.send(msg);
  14154. }
  14155. }
  14156. });
  14157. port_ = server_->bind_to_any_port(HOST);
  14158. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14159. server_->wait_until_ready();
  14160. }
  14161. void TearDown() override {
  14162. server_->stop();
  14163. if (server_thread_.joinable()) { server_thread_.join(); }
  14164. }
  14165. std::unique_ptr<SSLServer> server_;
  14166. std::thread server_thread_;
  14167. int port_ = 0;
  14168. };
  14169. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  14170. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  14171. "/ws-echo");
  14172. client.enable_server_certificate_verification(false);
  14173. ASSERT_TRUE(client.connect());
  14174. ASSERT_TRUE(client.is_open());
  14175. ASSERT_TRUE(client.send("Hello WSS"));
  14176. std::string msg;
  14177. EXPECT_EQ(ws::Text, client.read(msg));
  14178. EXPECT_EQ("Hello WSS", msg);
  14179. client.close();
  14180. }
  14181. #endif