test.cc 529 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #if __cplusplus >= 202002L
  28. inline std::string u8_to_string(const char8_t *s) {
  29. return std::string(reinterpret_cast<const char *>(s));
  30. }
  31. #define U8(x) u8_to_string(u8##x)
  32. #else
  33. #define U8(x) u8##x
  34. #endif
  35. #define SERVER_CERT_FILE "./cert.pem"
  36. #define SERVER_CERT2_FILE "./cert2.pem"
  37. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  38. #define CA_CERT_FILE "./ca-bundle.crt"
  39. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  40. #define CLIENT_CA_CERT_DIR "."
  41. #define CLIENT_CERT_FILE "./client.cert.pem"
  42. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  43. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  44. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  45. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  46. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  47. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  48. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  49. using namespace std;
  50. using namespace httplib;
  51. const char *HOST = "localhost";
  52. static int get_base_port() {
  53. const char *shard = getenv("GTEST_SHARD_INDEX");
  54. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  55. }
  56. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  57. // New standalone tests MUST use svr.bind_to_any_port() instead.
  58. const int PORT = get_base_port();
  59. const string LONG_QUERY_VALUE = string(25000, '@');
  60. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  61. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  62. const string TOO_LONG_QUERY_URL =
  63. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  64. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  65. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  66. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  67. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  68. return file.name == key;
  69. });
  70. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  71. return *it;
  72. #else
  73. if (it != items.end()) { return *it; }
  74. throw std::runtime_error("invalid multipart form data name error");
  75. #endif
  76. }
  77. static void read_file(const std::string &path, std::string &out) {
  78. std::ifstream fs(path, std::ios_base::binary);
  79. if (!fs) {
  80. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  81. return;
  82. #else
  83. throw std::runtime_error("File not found: " + path);
  84. #endif
  85. }
  86. fs.seekg(0, std::ios_base::end);
  87. auto size = fs.tellg();
  88. fs.seekg(0);
  89. out.resize(static_cast<size_t>(size));
  90. fs.read(&out[0], static_cast<std::streamsize>(size));
  91. }
  92. class UnixSocketTest : public ::testing::Test {
  93. protected:
  94. void TearDown() override { std::remove(pathname_.c_str()); }
  95. void client_GET(const std::string &addr) {
  96. httplib::Client cli{addr};
  97. cli.set_address_family(AF_UNIX);
  98. ASSERT_TRUE(cli.is_valid());
  99. const auto &result = cli.Get(pattern_);
  100. ASSERT_TRUE(result) << "error: " << result.error();
  101. const auto &resp = result.value();
  102. EXPECT_EQ(resp.status, StatusCode::OK_200);
  103. EXPECT_EQ(resp.body, content_);
  104. }
  105. static std::string make_sock_path() {
  106. const char *shard = getenv("GTEST_SHARD_INDEX");
  107. return shard ? std::string("./httplib-server-") + shard + ".sock"
  108. : "./httplib-server.sock";
  109. }
  110. const std::string pathname_{make_sock_path()};
  111. const std::string pattern_{"/hi"};
  112. const std::string content_{"Hello World!"};
  113. };
  114. TEST_F(UnixSocketTest, pathname) {
  115. httplib::Server svr;
  116. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  117. res.set_content(content_, "text/plain");
  118. });
  119. std::thread t{[&] {
  120. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  121. }};
  122. auto se = detail::scope_exit([&] {
  123. svr.stop();
  124. t.join();
  125. ASSERT_FALSE(svr.is_running());
  126. });
  127. svr.wait_until_ready();
  128. ASSERT_TRUE(svr.is_running());
  129. client_GET(pathname_);
  130. }
  131. #if defined(__linux__) || \
  132. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  133. TEST_F(UnixSocketTest, PeerPid) {
  134. httplib::Server svr;
  135. std::string remote_port_val;
  136. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  137. res.set_content(content_, "text/plain");
  138. remote_port_val = std::to_string(req.remote_port);
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  152. }
  153. #endif
  154. #ifdef __linux__
  155. TEST_F(UnixSocketTest, abstract) {
  156. constexpr char svr_path[]{"\x00httplib-server.sock"};
  157. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  158. httplib::Server svr;
  159. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  160. res.set_content(content_, "text/plain");
  161. });
  162. std::thread t{[&] {
  163. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  164. }};
  165. auto se = detail::scope_exit([&] {
  166. svr.stop();
  167. t.join();
  168. ASSERT_FALSE(svr.is_running());
  169. });
  170. svr.wait_until_ready();
  171. ASSERT_TRUE(svr.is_running());
  172. client_GET(abstract_addr);
  173. }
  174. #endif
  175. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  176. httplib::Server svr;
  177. std::string received_host_header;
  178. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  179. // Capture the Host header sent by the client
  180. auto host_iter = req.headers.find("Host");
  181. if (host_iter != req.headers.end()) {
  182. received_host_header = host_iter->second;
  183. }
  184. res.set_content(content_, "text/plain");
  185. });
  186. std::thread t{[&] {
  187. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  188. }};
  189. auto se = detail::scope_exit([&] {
  190. svr.stop();
  191. t.join();
  192. ASSERT_FALSE(svr.is_running());
  193. });
  194. svr.wait_until_ready();
  195. ASSERT_TRUE(svr.is_running());
  196. // Test that Host header is automatically set to "localhost" for Unix socket
  197. // connections
  198. httplib::Client cli{pathname_};
  199. cli.set_address_family(AF_UNIX);
  200. ASSERT_TRUE(cli.is_valid());
  201. const auto &result = cli.Get(pattern_);
  202. ASSERT_TRUE(result) << "error: " << result.error();
  203. const auto &resp = result.value();
  204. EXPECT_EQ(resp.status, StatusCode::OK_200);
  205. EXPECT_EQ(resp.body, content_);
  206. // Verify that Host header was automatically set to "localhost"
  207. EXPECT_EQ(received_host_header, "localhost");
  208. }
  209. #ifndef _WIN32
  210. TEST(SocketStream, wait_writable_UNIX) {
  211. int fds[2];
  212. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  213. const auto asSocketStream = [&](socket_t fd,
  214. std::function<bool(Stream &)> func) {
  215. return detail::process_client_socket(
  216. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  217. };
  218. asSocketStream(fds[0], [&](Stream &s0) {
  219. EXPECT_EQ(s0.socket(), fds[0]);
  220. EXPECT_TRUE(s0.wait_writable());
  221. EXPECT_TRUE(s0.is_peer_alive());
  222. EXPECT_EQ(0, close(fds[1]));
  223. EXPECT_FALSE(s0.is_peer_alive());
  224. return true;
  225. });
  226. EXPECT_EQ(0, close(fds[0]));
  227. }
  228. TEST(SocketStream, wait_writable_INET) {
  229. sockaddr_in addr;
  230. memset(&addr, 0, sizeof(addr));
  231. addr.sin_family = AF_INET;
  232. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  233. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  234. int disconnected_svr_sock = -1;
  235. std::thread svr{[&] {
  236. const int s = socket(AF_INET, SOCK_STREAM, 0);
  237. ASSERT_LE(0, s);
  238. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  239. ASSERT_EQ(0, listen(s, 1));
  240. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  241. ASSERT_EQ(0, close(s));
  242. }};
  243. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  244. std::thread cli{[&] {
  245. const int s = socket(AF_INET, SOCK_STREAM, 0);
  246. ASSERT_LE(0, s);
  247. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  248. ASSERT_EQ(0, close(s));
  249. }};
  250. cli.join();
  251. svr.join();
  252. ASSERT_NE(disconnected_svr_sock, -1);
  253. const auto asSocketStream = [&](socket_t fd,
  254. std::function<bool(Stream &)> func) {
  255. return detail::process_client_socket(
  256. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  257. };
  258. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  259. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  260. // wait_writable() returns true because select_write() only checks if the
  261. // send buffer has space. Peer disconnection is detected later by send().
  262. EXPECT_TRUE(ss.wait_writable());
  263. return true;
  264. });
  265. ASSERT_EQ(0, close(disconnected_svr_sock));
  266. }
  267. #endif // #ifndef _WIN32
  268. TEST(ClientTest, MoveConstructible) {
  269. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  270. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  271. }
  272. TEST(ClientTest, MoveAssignable) {
  273. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  274. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  275. }
  276. #ifdef _WIN32
  277. TEST(StartupTest, WSAStartup) {
  278. WSADATA wsaData;
  279. int ret = WSAStartup(0x0002, &wsaData);
  280. ASSERT_EQ(0, ret);
  281. }
  282. #endif
  283. TEST(DecodePathTest, PercentCharacter) {
  284. EXPECT_EQ(
  285. decode_path_component(
  286. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  287. U8("descrip=Gastos áéíóúñÑ 6"));
  288. }
  289. TEST(DecodePathTest, PercentCharacterNUL) {
  290. string expected;
  291. expected.push_back('x');
  292. expected.push_back('\0');
  293. expected.push_back('x');
  294. EXPECT_EQ(decode_path_component("x%00x"), expected);
  295. }
  296. TEST(DecodePathTest, UnicodeEncoding) {
  297. // %u0041 = 'A' (1-byte UTF-8)
  298. EXPECT_EQ("A", decode_path_component("%u0041"));
  299. // %u00E9 = 'é' (2-byte UTF-8)
  300. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  301. // %u3042 = 'あ' (3-byte UTF-8)
  302. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  303. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  304. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  305. // %uD800 = surrogate (invalid, silently dropped)
  306. EXPECT_EQ("", decode_path_component("%uD800"));
  307. }
  308. TEST(SanitizeFilenameTest, VariousPatterns) {
  309. // Path traversal
  310. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  311. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  312. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  313. // Normal and edge cases
  314. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  315. EXPECT_EQ("filename.txt",
  316. httplib::sanitize_filename("/path/to/filename.txt"));
  317. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  318. EXPECT_EQ("", httplib::sanitize_filename(".."));
  319. EXPECT_EQ("", httplib::sanitize_filename(""));
  320. // Null bytes stripped
  321. EXPECT_EQ("safe.txt",
  322. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  323. // Whitespace-only rejected
  324. EXPECT_EQ("", httplib::sanitize_filename(" "));
  325. }
  326. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  327. string unescapedCharacters = "-_.!~*'()";
  328. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  329. }
  330. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  331. string reservedCharacters = ";,/?:@&=+$";
  332. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  333. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  334. }
  335. TEST(ClientQueryOrder, PreserveOrder) {
  336. // This test reproduces Issue #2259: client may reorder query parameters
  337. // when sending a GET request. The expected behavior is that the client
  338. // preserves the original query string order when the caller supplied it
  339. // as part of the path.
  340. Server svr;
  341. svr.Get("/", [&](const Request &req, Response &res) {
  342. // Echo back the raw target so the test can assert ordering
  343. res.set_content(req.target, "text/plain");
  344. });
  345. std::thread t{[&] { svr.listen(HOST, PORT); }};
  346. auto se = detail::scope_exit([&] {
  347. svr.stop();
  348. t.join();
  349. ASSERT_FALSE(svr.is_running());
  350. });
  351. svr.wait_until_ready();
  352. Client cli(HOST, PORT);
  353. ASSERT_TRUE(cli.is_valid());
  354. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  355. auto res = cli.Get(original);
  356. ASSERT_TRUE(res);
  357. // Expect the echoed target to exactly match the original path (order
  358. // preserved)
  359. EXPECT_EQ(res->body, original);
  360. }
  361. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  362. string chineseCharacters = U8("中国語");
  363. string russianCharacters = U8("дом");
  364. string brazilianCharacters = U8("óculos");
  365. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  366. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  367. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  368. "%D0%B4%D0%BE%D0%BC");
  369. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  370. }
  371. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  372. string unescapedCharacters = "-_.!~*'()";
  373. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  374. }
  375. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  376. string reservedCharacters = ";,/?:@&=+$";
  377. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  378. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  379. }
  380. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  381. string chineseCharacters = U8("中国語");
  382. string russianCharacters = U8("дом");
  383. string brazilianCharacters = U8("óculos");
  384. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  385. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  386. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  387. "%D0%B4%D0%BE%D0%BC");
  388. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  389. }
  390. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  391. // Issue #2082 use case: encoding path component with ampersand
  392. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  393. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  394. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  395. }
  396. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  397. string unescapedCharacters = "-_.!~*'()";
  398. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  399. }
  400. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  401. string reservedCharacters = ";,/?:@&=+$#";
  402. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  403. }
  404. TEST(EncodeUriTest, TestUTF8Characters) {
  405. string chineseCharacters = U8("中国語");
  406. string russianCharacters = U8("дом");
  407. string brazilianCharacters = U8("óculos");
  408. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  409. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  410. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  411. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  412. }
  413. TEST(EncodeUriTest, TestCompleteUri) {
  414. string uri =
  415. "https://example.com/path/to/resource?query=value&param=test#fragment";
  416. EXPECT_EQ(
  417. httplib::encode_uri(uri),
  418. "https://example.com/path/to/resource?query=value&param=test#fragment");
  419. }
  420. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  421. string uri =
  422. "https://example.com/path with spaces/file name.html?q=hello world";
  423. EXPECT_EQ(httplib::encode_uri(uri),
  424. "https://example.com/path%20with%20spaces/"
  425. "file%20name.html?q=hello%20world");
  426. }
  427. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  428. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  429. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  430. }
  431. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  432. string unescapedCharacters = "-_.!~*'()";
  433. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  434. }
  435. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  436. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  437. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  438. string encodedBrazilian = "%C3%B3culos";
  439. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  440. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  441. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  442. }
  443. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  444. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  445. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  446. "Piri Tommy Villiers - on & on");
  447. }
  448. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  449. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  450. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  451. }
  452. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  453. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  454. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  455. }
  456. TEST(DecodeUriTest, TestUTF8Characters) {
  457. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  458. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  459. string encodedBrazilian = "%C3%B3culos";
  460. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  461. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  462. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  463. }
  464. TEST(DecodeUriTest, TestCompleteUri) {
  465. string encodedUri = "https://example.com/path%20with%20spaces/"
  466. "file%20name.html?q=hello%20world";
  467. EXPECT_EQ(
  468. httplib::decode_uri(encodedUri),
  469. "https://example.com/path with spaces/file name.html?q=hello world");
  470. }
  471. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  472. string original =
  473. "https://example.com/path with spaces/file name.html?q=hello world";
  474. string encoded = httplib::encode_uri(original);
  475. string decoded = httplib::decode_uri(encoded);
  476. EXPECT_EQ(decoded, original);
  477. }
  478. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  479. string original = "Piri Tommy Villiers - on & on";
  480. string encoded = httplib::encode_uri_component(original);
  481. string decoded = httplib::decode_uri_component(encoded);
  482. EXPECT_EQ(decoded, original);
  483. }
  484. TEST(TrimTests, TrimStringTests) {
  485. EXPECT_EQ("abc", detail::trim_copy("abc"));
  486. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  487. EXPECT_TRUE(detail::trim_copy("").empty());
  488. }
  489. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  490. // Simple case without quality values
  491. std::vector<std::string> result1;
  492. EXPECT_TRUE(detail::parse_accept_header(
  493. "text/html,application/json,text/plain", result1));
  494. EXPECT_EQ(result1.size(), 3U);
  495. EXPECT_EQ(result1[0], "text/html");
  496. EXPECT_EQ(result1[1], "application/json");
  497. EXPECT_EQ(result1[2], "text/plain");
  498. // With quality values
  499. std::vector<std::string> result2;
  500. EXPECT_TRUE(detail::parse_accept_header(
  501. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  502. EXPECT_EQ(result2.size(), 3U);
  503. EXPECT_EQ(result2[0], "application/json"); // highest q value
  504. EXPECT_EQ(result2[1], "text/html");
  505. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  506. }
  507. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  508. // Mixed with and without quality values
  509. std::vector<std::string> result;
  510. EXPECT_TRUE(detail::parse_accept_header(
  511. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  512. EXPECT_EQ(result.size(), 3U);
  513. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  514. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  515. EXPECT_EQ(result[2], "application/json"); // q=0.5
  516. }
  517. TEST(ParseAcceptHeaderTest, EdgeCases) {
  518. // Empty header
  519. std::vector<std::string> empty_result;
  520. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  521. EXPECT_TRUE(empty_result.empty());
  522. // Single type
  523. std::vector<std::string> single_result;
  524. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  525. EXPECT_EQ(single_result.size(), 1U);
  526. EXPECT_EQ(single_result[0], "application/json");
  527. // Wildcard types
  528. std::vector<std::string> wildcard_result;
  529. EXPECT_TRUE(detail::parse_accept_header(
  530. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  531. EXPECT_EQ(wildcard_result.size(), 3U);
  532. EXPECT_EQ(wildcard_result[0], "application/json");
  533. EXPECT_EQ(wildcard_result[1], "text/*");
  534. EXPECT_EQ(wildcard_result[2], "*/*");
  535. }
  536. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  537. // Common browser Accept header
  538. std::vector<std::string> browser_result;
  539. EXPECT_TRUE(
  540. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  541. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  542. browser_result));
  543. EXPECT_EQ(browser_result.size(), 6U);
  544. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  545. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  546. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  547. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  548. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  549. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  550. // API client header
  551. std::vector<std::string> api_result;
  552. EXPECT_TRUE(detail::parse_accept_header(
  553. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  554. api_result));
  555. EXPECT_EQ(api_result.size(), 3U);
  556. EXPECT_EQ(api_result[0], "application/json");
  557. EXPECT_EQ(api_result[1], "application/xml");
  558. EXPECT_EQ(api_result[2], "text/plain");
  559. }
  560. TEST(ParseAcceptHeaderTest, SpecialCases) {
  561. // Quality value with 3 decimal places
  562. std::vector<std::string> decimal_result;
  563. EXPECT_TRUE(detail::parse_accept_header(
  564. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  565. EXPECT_EQ(decimal_result.size(), 2U);
  566. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  567. EXPECT_EQ(decimal_result[1], "text/html");
  568. // Zero quality (should still be included but with lowest priority)
  569. std::vector<std::string> zero_q_result;
  570. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  571. zero_q_result));
  572. EXPECT_EQ(zero_q_result.size(), 2U);
  573. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  574. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  575. // No spaces around commas
  576. std::vector<std::string> no_space_result;
  577. EXPECT_TRUE(detail::parse_accept_header(
  578. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  579. no_space_result));
  580. EXPECT_EQ(no_space_result.size(), 3U);
  581. EXPECT_EQ(no_space_result[0], "text/html");
  582. EXPECT_EQ(no_space_result[1], "application/json");
  583. EXPECT_EQ(no_space_result[2], "text/plain");
  584. }
  585. TEST(ParseAcceptHeaderTest, InvalidCases) {
  586. std::vector<std::string> result;
  587. // Invalid quality value (> 1.0)
  588. EXPECT_FALSE(
  589. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  590. // Invalid quality value (< 0.0)
  591. EXPECT_FALSE(
  592. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  593. // Invalid quality value (not a number)
  594. EXPECT_FALSE(detail::parse_accept_header(
  595. "text/html;q=invalid,application/json", result));
  596. // Empty quality value
  597. EXPECT_FALSE(
  598. detail::parse_accept_header("text/html;q=,application/json", result));
  599. // Invalid media type format (no slash and not wildcard)
  600. EXPECT_FALSE(
  601. detail::parse_accept_header("invalidtype,application/json", result));
  602. // Empty media type
  603. result.clear();
  604. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  605. // Only commas
  606. result.clear();
  607. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  608. // Valid cases should still work
  609. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  610. EXPECT_EQ(result.size(), 1U);
  611. EXPECT_EQ(result[0], "*/*");
  612. EXPECT_TRUE(detail::parse_accept_header("*", result));
  613. EXPECT_EQ(result.size(), 1U);
  614. EXPECT_EQ(result[0], "*");
  615. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  616. EXPECT_EQ(result.size(), 1U);
  617. EXPECT_EQ(result[0], "text/*");
  618. }
  619. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  620. Server svr;
  621. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  622. EXPECT_EQ(req.accept_content_types.size(), 3U);
  623. EXPECT_EQ(req.accept_content_types[0], "application/json");
  624. EXPECT_EQ(req.accept_content_types[1], "text/html");
  625. EXPECT_EQ(req.accept_content_types[2], "*/*");
  626. res.set_content("ok", "text/plain");
  627. });
  628. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  629. EXPECT_TRUE(false);
  630. res.set_content("bad request", "text/plain");
  631. });
  632. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  633. auto se = detail::scope_exit([&] {
  634. svr.stop();
  635. listen_thread.join();
  636. ASSERT_FALSE(svr.is_running());
  637. });
  638. svr.wait_until_ready();
  639. Client cli("localhost", PORT);
  640. {
  641. auto res =
  642. cli.Get("/accept_ok",
  643. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  644. ASSERT_TRUE(res);
  645. EXPECT_EQ(StatusCode::OK_200, res->status);
  646. }
  647. {
  648. auto res = cli.Get("/accept_bad_request",
  649. {{"Accept", "text/html;q=abc,application/json"}});
  650. ASSERT_TRUE(res);
  651. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  652. }
  653. }
  654. TEST(DivideTest, DivideStringTests) {
  655. auto divide = [](const std::string &str, char d) {
  656. std::string lhs;
  657. std::string rhs;
  658. detail::divide(str, d,
  659. [&](const char *lhs_data, std::size_t lhs_size,
  660. const char *rhs_data, std::size_t rhs_size) {
  661. lhs.assign(lhs_data, lhs_size);
  662. rhs.assign(rhs_data, rhs_size);
  663. });
  664. return std::make_pair(std::move(lhs), std::move(rhs));
  665. };
  666. {
  667. const auto res = divide("", '=');
  668. EXPECT_EQ(res.first, "");
  669. EXPECT_EQ(res.second, "");
  670. }
  671. {
  672. const auto res = divide("=", '=');
  673. EXPECT_EQ(res.first, "");
  674. EXPECT_EQ(res.second, "");
  675. }
  676. {
  677. const auto res = divide(" ", '=');
  678. EXPECT_EQ(res.first, " ");
  679. EXPECT_EQ(res.second, "");
  680. }
  681. {
  682. const auto res = divide("a", '=');
  683. EXPECT_EQ(res.first, "a");
  684. EXPECT_EQ(res.second, "");
  685. }
  686. {
  687. const auto res = divide("a=", '=');
  688. EXPECT_EQ(res.first, "a");
  689. EXPECT_EQ(res.second, "");
  690. }
  691. {
  692. const auto res = divide("=b", '=');
  693. EXPECT_EQ(res.first, "");
  694. EXPECT_EQ(res.second, "b");
  695. }
  696. {
  697. const auto res = divide("a=b", '=');
  698. EXPECT_EQ(res.first, "a");
  699. EXPECT_EQ(res.second, "b");
  700. }
  701. {
  702. const auto res = divide("a=b=", '=');
  703. EXPECT_EQ(res.first, "a");
  704. EXPECT_EQ(res.second, "b=");
  705. }
  706. {
  707. const auto res = divide("a=b=c", '=');
  708. EXPECT_EQ(res.first, "a");
  709. EXPECT_EQ(res.second, "b=c");
  710. }
  711. }
  712. TEST(SplitTest, ParseQueryString) {
  713. string s = "key1=val1&key2=val2&key3=val3";
  714. Params dic;
  715. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  716. [&](const char *b, const char *e) {
  717. string key, val;
  718. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  719. if (key.empty()) {
  720. key.assign(b2, e2);
  721. } else {
  722. val.assign(b2, e2);
  723. }
  724. });
  725. dic.emplace(key, val);
  726. });
  727. EXPECT_EQ("val1", dic.find("key1")->second);
  728. EXPECT_EQ("val2", dic.find("key2")->second);
  729. EXPECT_EQ("val3", dic.find("key3")->second);
  730. }
  731. TEST(SplitTest, ParseInvalidQueryTests) {
  732. {
  733. string s = " ";
  734. Params dict;
  735. detail::parse_query_text(s, dict);
  736. EXPECT_TRUE(dict.empty());
  737. }
  738. {
  739. string s = " = =";
  740. Params dict;
  741. detail::parse_query_text(s, dict);
  742. EXPECT_TRUE(dict.empty());
  743. }
  744. }
  745. TEST(ParseQueryTest, ParseQueryString) {
  746. {
  747. std::string s = "key1=val1&key2=val2&key3=val3";
  748. Params dic;
  749. detail::parse_query_text(s, dic);
  750. EXPECT_EQ("val1", dic.find("key1")->second);
  751. EXPECT_EQ("val2", dic.find("key2")->second);
  752. EXPECT_EQ("val3", dic.find("key3")->second);
  753. }
  754. {
  755. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  756. Params dic;
  757. detail::parse_query_text(s, dic);
  758. EXPECT_EQ("", dic.find("key1")->second);
  759. EXPECT_EQ("val1", dic.find("key2")->second);
  760. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  761. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  762. }
  763. }
  764. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  765. Params dic;
  766. EXPECT_EQ(detail::params_to_query_str(dic), "");
  767. dic.emplace("key1", "val1");
  768. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  769. dic.emplace("key2", "val2");
  770. dic.emplace("key3", "val3");
  771. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  772. }
  773. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  774. string content_type = "multipart/form-data; boundary=something";
  775. string boundary;
  776. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  777. EXPECT_TRUE(ret);
  778. EXPECT_EQ(boundary, "something");
  779. }
  780. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  781. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  782. string boundary;
  783. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  784. EXPECT_TRUE(ret);
  785. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  786. }
  787. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  788. string content_type =
  789. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  790. string boundary;
  791. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  792. EXPECT_TRUE(ret);
  793. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  794. }
  795. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  796. string content_type =
  797. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  798. string boundary;
  799. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  800. EXPECT_TRUE(ret);
  801. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  802. }
  803. TEST(GetHeaderValueTest, DefaultValue) {
  804. Headers headers = {{"Dummy", "Dummy"}};
  805. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  806. EXPECT_STREQ("text/plain", val);
  807. }
  808. TEST(GetHeaderValueTest, DefaultValueInt) {
  809. Headers headers = {{"Dummy", "Dummy"}};
  810. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  811. EXPECT_EQ(100ull, val);
  812. }
  813. TEST(GetHeaderValueTest, RegularValue) {
  814. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  815. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  816. EXPECT_STREQ("text/html", val);
  817. }
  818. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  819. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  820. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  821. EXPECT_STREQ("text/html", val);
  822. }
  823. TEST(GetHeaderValueTest, SetContent) {
  824. Response res;
  825. res.set_content("html", "text/html");
  826. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  827. res.set_content("text", "text/plain");
  828. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  829. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  830. }
  831. TEST(GetHeaderValueTest, RegularValueInt) {
  832. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  833. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  834. EXPECT_EQ(100ull, val);
  835. }
  836. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  837. Headers headers = {{"Content-Length", "x"}};
  838. auto is_invalid_value = false;
  839. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  840. is_invalid_value);
  841. EXPECT_EQ(0ull, val);
  842. EXPECT_TRUE(is_invalid_value);
  843. }
  844. TEST(GetHeaderValueTest, Range) {
  845. {
  846. Headers headers = {make_range_header({{1, -1}})};
  847. auto val = detail::get_header_value(headers, "Range", 0, 0);
  848. EXPECT_STREQ("bytes=1-", val);
  849. }
  850. {
  851. Headers headers = {make_range_header({{-1, 1}})};
  852. auto val = detail::get_header_value(headers, "Range", 0, 0);
  853. EXPECT_STREQ("bytes=-1", val);
  854. }
  855. {
  856. Headers headers = {make_range_header({{1, 10}})};
  857. auto val = detail::get_header_value(headers, "Range", 0, 0);
  858. EXPECT_STREQ("bytes=1-10", val);
  859. }
  860. {
  861. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  862. auto val = detail::get_header_value(headers, "Range", 0, 0);
  863. EXPECT_STREQ("bytes=1-10, 100-", val);
  864. }
  865. {
  866. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  867. auto val = detail::get_header_value(headers, "Range", 0, 0);
  868. EXPECT_STREQ("bytes=1-10, 100-200", val);
  869. }
  870. {
  871. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  872. auto val = detail::get_header_value(headers, "Range", 0, 0);
  873. EXPECT_STREQ("bytes=0-0, -1", val);
  874. }
  875. }
  876. TEST(ParseHeaderValueTest, Range) {
  877. {
  878. Ranges ranges;
  879. auto ret = detail::parse_range_header("bytes=1-", ranges);
  880. EXPECT_TRUE(ret);
  881. EXPECT_EQ(1u, ranges.size());
  882. EXPECT_EQ(1u, ranges[0].first);
  883. EXPECT_EQ(-1, ranges[0].second);
  884. }
  885. {
  886. Ranges ranges;
  887. auto ret = detail::parse_range_header("bytes=-1", ranges);
  888. EXPECT_TRUE(ret);
  889. EXPECT_EQ(1u, ranges.size());
  890. EXPECT_EQ(-1, ranges[0].first);
  891. EXPECT_EQ(1u, ranges[0].second);
  892. }
  893. {
  894. Ranges ranges;
  895. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  896. EXPECT_TRUE(ret);
  897. EXPECT_EQ(1u, ranges.size());
  898. EXPECT_EQ(1u, ranges[0].first);
  899. EXPECT_EQ(10u, ranges[0].second);
  900. }
  901. {
  902. Ranges ranges;
  903. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  904. EXPECT_FALSE(ret);
  905. }
  906. {
  907. Ranges ranges;
  908. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  909. EXPECT_TRUE(ret);
  910. EXPECT_EQ(2u, ranges.size());
  911. EXPECT_EQ(1u, ranges[0].first);
  912. EXPECT_EQ(10u, ranges[0].second);
  913. EXPECT_EQ(100u, ranges[1].first);
  914. EXPECT_EQ(-1, ranges[1].second);
  915. }
  916. {
  917. Ranges ranges;
  918. auto ret =
  919. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  920. EXPECT_TRUE(ret);
  921. EXPECT_EQ(3u, ranges.size());
  922. EXPECT_EQ(1u, ranges[0].first);
  923. EXPECT_EQ(10u, ranges[0].second);
  924. EXPECT_EQ(100u, ranges[1].first);
  925. EXPECT_EQ(200u, ranges[1].second);
  926. EXPECT_EQ(300u, ranges[2].first);
  927. EXPECT_EQ(400u, ranges[2].second);
  928. }
  929. {
  930. Ranges ranges;
  931. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  932. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  933. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  934. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  935. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  936. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  937. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  938. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  939. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  940. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  941. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  942. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  943. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  944. EXPECT_TRUE(ranges.empty());
  945. }
  946. }
  947. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  948. Request req;
  949. req.set_header("Accept-Encoding", "gzip");
  950. Response res;
  951. res.set_header("Content-Type", "text/plain");
  952. auto ret = detail::encoding_type(req, res);
  953. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  954. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  955. #else
  956. EXPECT_TRUE(ret == detail::EncodingType::None);
  957. #endif
  958. }
  959. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  960. Request req;
  961. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  962. Response res;
  963. res.set_header("Content-Type", "text/plain");
  964. auto ret = detail::encoding_type(req, res);
  965. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  966. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  967. #elif CPPHTTPLIB_ZLIB_SUPPORT
  968. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  969. #elif CPPHTTPLIB_ZSTD_SUPPORT
  970. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  971. #else
  972. EXPECT_TRUE(ret == detail::EncodingType::None);
  973. #endif
  974. }
  975. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  976. Request req;
  977. req.set_header("Accept-Encoding",
  978. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  979. Response res;
  980. res.set_header("Content-Type", "text/plain");
  981. auto ret = detail::encoding_type(req, res);
  982. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  983. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  984. #elif CPPHTTPLIB_ZLIB_SUPPORT
  985. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  986. #elif CPPHTTPLIB_ZSTD_SUPPORT
  987. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  988. #else
  989. EXPECT_TRUE(ret == detail::EncodingType::None);
  990. #endif
  991. }
  992. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  993. // All supported encodings rejected with q=0 should return None
  994. Request req;
  995. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  996. Response res;
  997. res.set_header("Content-Type", "text/plain");
  998. auto ret = detail::encoding_type(req, res);
  999. EXPECT_TRUE(ret == detail::EncodingType::None);
  1000. }
  1001. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1002. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1003. Request req;
  1004. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1005. Response res;
  1006. res.set_header("Content-Type", "text/plain");
  1007. auto ret = detail::encoding_type(req, res);
  1008. EXPECT_TRUE(ret == detail::EncodingType::None);
  1009. }
  1010. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1011. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1012. Request req;
  1013. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1014. Response res;
  1015. res.set_header("Content-Type", "text/plain");
  1016. auto ret = detail::encoding_type(req, res);
  1017. EXPECT_TRUE(ret == detail::EncodingType::None);
  1018. }
  1019. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1020. // RFC 7231: Accept-Encoding values are case-insensitive
  1021. Request req;
  1022. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1023. Response res;
  1024. res.set_header("Content-Type", "text/plain");
  1025. auto ret = detail::encoding_type(req, res);
  1026. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1027. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1028. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1029. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1030. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1031. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1032. #else
  1033. EXPECT_TRUE(ret == detail::EncodingType::None);
  1034. #endif
  1035. }
  1036. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1037. // q value should determine priority, not hardcoded order
  1038. Request req;
  1039. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1040. Response res;
  1041. res.set_header("Content-Type", "text/plain");
  1042. auto ret = detail::encoding_type(req, res);
  1043. // gzip has highest q=1.0, so it should be selected even though
  1044. // br and zstd are also supported
  1045. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1046. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1047. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1048. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1049. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1050. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1051. #else
  1052. EXPECT_TRUE(ret == detail::EncodingType::None);
  1053. #endif
  1054. }
  1055. TEST(BufferStreamTest, read) {
  1056. detail::BufferStream strm1;
  1057. Stream &strm = strm1;
  1058. EXPECT_EQ(5, strm.write("hello"));
  1059. char buf[512];
  1060. EXPECT_EQ(2, strm.read(buf, 2));
  1061. EXPECT_EQ('h', buf[0]);
  1062. EXPECT_EQ('e', buf[1]);
  1063. EXPECT_EQ(2, strm.read(buf, 2));
  1064. EXPECT_EQ('l', buf[0]);
  1065. EXPECT_EQ('l', buf[1]);
  1066. EXPECT_EQ(1, strm.read(buf, 1));
  1067. EXPECT_EQ('o', buf[0]);
  1068. EXPECT_EQ(0, strm.read(buf, 1));
  1069. }
  1070. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1071. auto host = "www.httpwatch.com";
  1072. auto ip = hosted_at(host);
  1073. EXPECT_EQ("23.96.13.243", ip);
  1074. std::vector<std::string> addrs;
  1075. hosted_at(host, addrs);
  1076. EXPECT_EQ(1u, addrs.size());
  1077. }
  1078. #if 0 // It depends on each test environment...
  1079. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1080. auto host = "www.youtube.com";
  1081. std::vector<std::string> addrs;
  1082. hosted_at(host, addrs);
  1083. EXPECT_EQ(20u, addrs.size());
  1084. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1085. EXPECT_TRUE(it != addrs.end());
  1086. }
  1087. #endif
  1088. class ChunkedEncodingTest : public ::testing::Test {
  1089. protected:
  1090. ChunkedEncodingTest()
  1091. : cli_(HOST, PORT)
  1092. #ifdef CPPHTTPLIB_SSL_ENABLED
  1093. ,
  1094. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1095. #endif
  1096. {
  1097. cli_.set_connection_timeout(2);
  1098. #ifdef CPPHTTPLIB_SSL_ENABLED
  1099. cli_.enable_server_certificate_verification(false);
  1100. #endif
  1101. }
  1102. virtual void SetUp() {
  1103. read_file("./image.jpg", image_data_);
  1104. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1105. res.set_content("Hello World!", "text/plain");
  1106. });
  1107. svr_.Get(
  1108. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1109. res.set_chunked_content_provider(
  1110. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1111. size_t remaining = image_data_.size() - offset;
  1112. if (remaining == 0) {
  1113. sink.done();
  1114. } else {
  1115. constexpr size_t CHUNK_SIZE = 1024;
  1116. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1117. sink.write(&image_data_[offset], send_size);
  1118. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1119. }
  1120. return true;
  1121. });
  1122. });
  1123. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1124. svr_.wait_until_ready();
  1125. }
  1126. virtual void TearDown() {
  1127. svr_.stop();
  1128. if (!request_threads_.empty()) {
  1129. std::this_thread::sleep_for(std::chrono::seconds(1));
  1130. for (auto &t : request_threads_) {
  1131. t.join();
  1132. }
  1133. }
  1134. t_.join();
  1135. }
  1136. #ifdef CPPHTTPLIB_SSL_ENABLED
  1137. SSLClient cli_;
  1138. SSLServer svr_;
  1139. #else
  1140. Client cli_;
  1141. Server svr_;
  1142. #endif
  1143. thread t_;
  1144. std::vector<thread> request_threads_;
  1145. std::string image_data_;
  1146. };
  1147. TEST_F(ChunkedEncodingTest, NormalGet) {
  1148. auto res = cli_.Get("/chunked");
  1149. ASSERT_TRUE(res);
  1150. std::string out;
  1151. read_file("./image.jpg", out);
  1152. EXPECT_EQ(StatusCode::OK_200, res->status);
  1153. EXPECT_EQ(out, res->body);
  1154. }
  1155. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1156. std::string body;
  1157. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1158. body.append(data, data_length);
  1159. return true;
  1160. });
  1161. ASSERT_TRUE(res);
  1162. std::string out;
  1163. read_file("./image.jpg", out);
  1164. EXPECT_EQ(StatusCode::OK_200, res->status);
  1165. EXPECT_EQ(out, body);
  1166. }
  1167. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1168. std::string body;
  1169. auto res = cli_.Get(
  1170. "/chunked",
  1171. [&](const Response &response) {
  1172. EXPECT_EQ(StatusCode::OK_200, response.status);
  1173. return true;
  1174. },
  1175. [&](const char *data, size_t data_length) {
  1176. body.append(data, data_length);
  1177. return true;
  1178. });
  1179. ASSERT_TRUE(res);
  1180. std::string out;
  1181. read_file("./image.jpg", out);
  1182. EXPECT_EQ(StatusCode::OK_200, res->status);
  1183. EXPECT_EQ(out, body);
  1184. }
  1185. TEST(RangeTest, FromHTTPBin_Online) {
  1186. auto host = "httpbingo.org";
  1187. auto path = std::string{"/range/32"};
  1188. #ifdef CPPHTTPLIB_SSL_ENABLED
  1189. auto port = 443;
  1190. SSLClient cli(host, port);
  1191. #else
  1192. auto port = 80;
  1193. Client cli(host, port);
  1194. #endif
  1195. cli.set_connection_timeout(5);
  1196. {
  1197. auto res = cli.Get(path);
  1198. ASSERT_TRUE(res);
  1199. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1200. EXPECT_EQ(StatusCode::OK_200, res->status);
  1201. }
  1202. {
  1203. Headers headers = {make_range_header({{1, -1}})};
  1204. auto res = cli.Get(path, headers);
  1205. ASSERT_TRUE(res);
  1206. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1207. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1208. }
  1209. {
  1210. Headers headers = {make_range_header({{1, 10}})};
  1211. auto res = cli.Get(path, headers);
  1212. ASSERT_TRUE(res);
  1213. EXPECT_EQ("bcdefghijk", res->body);
  1214. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1215. }
  1216. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1217. // entire resource, while the original httpbin returned 200. Both are
  1218. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1219. {
  1220. Headers headers = {make_range_header({{0, 31}})};
  1221. auto res = cli.Get(path, headers);
  1222. ASSERT_TRUE(res);
  1223. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1224. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1225. res->status == StatusCode::PartialContent_206);
  1226. }
  1227. {
  1228. Headers headers = {make_range_header({{0, -1}})};
  1229. auto res = cli.Get(path, headers);
  1230. ASSERT_TRUE(res);
  1231. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1232. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1233. res->status == StatusCode::PartialContent_206);
  1234. }
  1235. // go-httpbin returns 206 with clamped range for over-range requests,
  1236. // while the original httpbin returned 416. Both behaviors are observed
  1237. // in real servers, so we only verify the request succeeds.
  1238. {
  1239. Headers headers = {make_range_header({{0, 32}})};
  1240. auto res = cli.Get(path, headers);
  1241. ASSERT_TRUE(res);
  1242. }
  1243. }
  1244. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1245. auto host = "unresolvableaddress.local";
  1246. auto path = std::string{"/"};
  1247. #ifdef CPPHTTPLIB_SSL_ENABLED
  1248. auto port = 443;
  1249. SSLClient cli(host, port);
  1250. #else
  1251. auto port = 80;
  1252. Client cli(host, port);
  1253. #endif
  1254. cli.set_connection_timeout(1);
  1255. {
  1256. auto res = cli.Get(path);
  1257. ASSERT_FALSE(res);
  1258. }
  1259. std::this_thread::sleep_for(std::chrono::seconds(8));
  1260. }
  1261. TEST(ConnectionErrorTest, InvalidHost) {
  1262. auto host = "-abcde.com";
  1263. #ifdef CPPHTTPLIB_SSL_ENABLED
  1264. auto port = 443;
  1265. SSLClient cli(host, port);
  1266. #else
  1267. auto port = 80;
  1268. Client cli(host, port);
  1269. #endif
  1270. cli.set_connection_timeout(std::chrono::seconds(2));
  1271. auto res = cli.Get("/");
  1272. ASSERT_TRUE(!res);
  1273. EXPECT_EQ(Error::Connection, res.error());
  1274. }
  1275. TEST(ConnectionErrorTest, InvalidHost2) {
  1276. auto host = "httpcan.org/";
  1277. #ifdef CPPHTTPLIB_SSL_ENABLED
  1278. SSLClient cli(host);
  1279. #else
  1280. Client cli(host);
  1281. #endif
  1282. cli.set_connection_timeout(std::chrono::seconds(2));
  1283. auto res = cli.Get("/");
  1284. ASSERT_TRUE(!res);
  1285. EXPECT_EQ(Error::Connection, res.error());
  1286. }
  1287. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1288. auto host = "httpcan.org/";
  1289. #ifdef CPPHTTPLIB_SSL_ENABLED
  1290. SSLClient cli(host);
  1291. #else
  1292. Client cli(host);
  1293. #endif
  1294. cli.set_connection_timeout(std::chrono::seconds(2));
  1295. auto res = cli.Get("/");
  1296. ASSERT_TRUE(!res);
  1297. stringstream s;
  1298. s << "error code: " << res.error();
  1299. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1300. }
  1301. TEST(ConnectionErrorTest, InvalidPort) {
  1302. auto host = "localhost";
  1303. auto port = 44380;
  1304. #ifdef CPPHTTPLIB_SSL_ENABLED
  1305. SSLClient cli(host, port);
  1306. #else
  1307. Client cli(host, port);
  1308. #endif
  1309. cli.set_connection_timeout(std::chrono::seconds(2));
  1310. auto res = cli.Get("/");
  1311. ASSERT_TRUE(!res);
  1312. EXPECT_TRUE(Error::Connection == res.error() ||
  1313. Error::ConnectionTimeout == res.error());
  1314. }
  1315. TEST(ConnectionErrorTest, Timeout_Online) {
  1316. auto host = "google.com";
  1317. #ifdef CPPHTTPLIB_SSL_ENABLED
  1318. auto port = 44380;
  1319. SSLClient cli(host, port);
  1320. #else
  1321. auto port = 8080;
  1322. Client cli(host, port);
  1323. #endif
  1324. cli.set_connection_timeout(std::chrono::seconds(2));
  1325. // only probe one address type so that the error reason
  1326. // correlates to the timed-out IPv4, not the unsupported
  1327. // IPv6 connection attempt
  1328. cli.set_address_family(AF_INET);
  1329. auto res = cli.Get("/");
  1330. ASSERT_TRUE(!res);
  1331. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1332. }
  1333. TEST(CancelTest, NoCancel_Online) {
  1334. auto host = "httpbingo.org";
  1335. auto path = std::string{"/range/32"};
  1336. #ifdef CPPHTTPLIB_SSL_ENABLED
  1337. auto port = 443;
  1338. SSLClient cli(host, port);
  1339. #else
  1340. auto port = 80;
  1341. Client cli(host, port);
  1342. #endif
  1343. cli.set_connection_timeout(std::chrono::seconds(5));
  1344. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1345. ASSERT_TRUE(res);
  1346. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1347. EXPECT_EQ(StatusCode::OK_200, res->status);
  1348. }
  1349. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1350. // Use /bytes with a large payload so that the DownloadProgress callback
  1351. // (which only fires for Content-Length responses) is invoked before the
  1352. // entire body is received, giving cancellation a chance to fire.
  1353. auto host = "httpbingo.org";
  1354. auto path = std::string{"/bytes/524288"};
  1355. #ifdef CPPHTTPLIB_SSL_ENABLED
  1356. auto port = 443;
  1357. SSLClient cli(host, port);
  1358. #else
  1359. auto port = 80;
  1360. Client cli(host, port);
  1361. #endif
  1362. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1363. cli.set_connection_timeout(std::chrono::seconds(5));
  1364. ASSERT_TRUE(!res);
  1365. EXPECT_EQ(Error::Canceled, res.error());
  1366. }
  1367. TEST(CancelTest, WithCancelLargePayload_Online) {
  1368. auto host = "httpbingo.org";
  1369. auto path = std::string{"/bytes/524288"};
  1370. #ifdef CPPHTTPLIB_SSL_ENABLED
  1371. auto port = 443;
  1372. SSLClient cli(host, port);
  1373. #else
  1374. auto port = 80;
  1375. Client cli(host, port);
  1376. #endif
  1377. cli.set_connection_timeout(std::chrono::seconds(5));
  1378. uint32_t count = 0;
  1379. auto res =
  1380. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1381. ASSERT_TRUE(!res);
  1382. EXPECT_EQ(Error::Canceled, res.error());
  1383. }
  1384. TEST(CancelTest, NoCancelPost) {
  1385. Server svr;
  1386. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1387. res.set_content("Hello World!", "text/plain");
  1388. });
  1389. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1390. auto se = detail::scope_exit([&] {
  1391. svr.stop();
  1392. thread.join();
  1393. ASSERT_FALSE(svr.is_running());
  1394. });
  1395. svr.wait_until_ready();
  1396. Client cli(HOST, PORT);
  1397. cli.set_connection_timeout(std::chrono::seconds(5));
  1398. auto res =
  1399. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1400. "application/json", [](uint64_t, uint64_t) { return true; });
  1401. ASSERT_TRUE(res);
  1402. EXPECT_EQ("Hello World!", res->body);
  1403. EXPECT_EQ(StatusCode::OK_200, res->status);
  1404. }
  1405. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1406. Server svr;
  1407. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1408. res.set_content("Hello World!", "text/plain");
  1409. });
  1410. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1411. auto se = detail::scope_exit([&] {
  1412. svr.stop();
  1413. thread.join();
  1414. ASSERT_FALSE(svr.is_running());
  1415. });
  1416. svr.wait_until_ready();
  1417. Client cli(HOST, PORT);
  1418. cli.set_connection_timeout(std::chrono::seconds(5));
  1419. auto res =
  1420. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1421. "application/json", [](uint64_t, uint64_t) { return false; });
  1422. ASSERT_TRUE(!res);
  1423. EXPECT_EQ(Error::Canceled, res.error());
  1424. }
  1425. TEST(CancelTest, WithCancelLargePayloadPost) {
  1426. Server svr;
  1427. svr.set_payload_max_length(200 * 1024 * 1024);
  1428. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1429. res.set_content(LARGE_DATA, "text/plain");
  1430. });
  1431. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1432. auto se = detail::scope_exit([&] {
  1433. svr.stop();
  1434. thread.join();
  1435. ASSERT_FALSE(svr.is_running());
  1436. });
  1437. svr.wait_until_ready();
  1438. Client cli(HOST, PORT);
  1439. cli.set_payload_max_length(200 * 1024 * 1024);
  1440. cli.set_connection_timeout(std::chrono::seconds(5));
  1441. auto res =
  1442. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1443. "application/json", [](uint64_t, uint64_t) { return false; });
  1444. ASSERT_TRUE(!res);
  1445. EXPECT_EQ(Error::Canceled, res.error());
  1446. }
  1447. TEST(CancelTest, NoCancelPut) {
  1448. Server svr;
  1449. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1450. res.set_content("Hello World!", "text/plain");
  1451. });
  1452. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1453. auto se = detail::scope_exit([&] {
  1454. svr.stop();
  1455. thread.join();
  1456. ASSERT_FALSE(svr.is_running());
  1457. });
  1458. svr.wait_until_ready();
  1459. Client cli(HOST, PORT);
  1460. cli.set_connection_timeout(std::chrono::seconds(5));
  1461. auto res =
  1462. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1463. "application/json", [](uint64_t, uint64_t) { return true; });
  1464. ASSERT_TRUE(res);
  1465. EXPECT_EQ("Hello World!", res->body);
  1466. EXPECT_EQ(StatusCode::OK_200, res->status);
  1467. }
  1468. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1469. Server svr;
  1470. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1471. res.set_content("Hello World!", "text/plain");
  1472. });
  1473. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1474. auto se = detail::scope_exit([&] {
  1475. svr.stop();
  1476. thread.join();
  1477. ASSERT_FALSE(svr.is_running());
  1478. });
  1479. svr.wait_until_ready();
  1480. Client cli(HOST, PORT);
  1481. cli.set_connection_timeout(std::chrono::seconds(5));
  1482. auto res =
  1483. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1484. "application/json", [](uint64_t, uint64_t) { return false; });
  1485. ASSERT_TRUE(!res);
  1486. EXPECT_EQ(Error::Canceled, res.error());
  1487. }
  1488. TEST(CancelTest, WithCancelLargePayloadPut) {
  1489. Server svr;
  1490. svr.set_payload_max_length(200 * 1024 * 1024);
  1491. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1492. res.set_content(LARGE_DATA, "text/plain");
  1493. });
  1494. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1495. auto se = detail::scope_exit([&] {
  1496. svr.stop();
  1497. thread.join();
  1498. ASSERT_FALSE(svr.is_running());
  1499. });
  1500. svr.wait_until_ready();
  1501. Client cli(HOST, PORT);
  1502. cli.set_payload_max_length(200 * 1024 * 1024);
  1503. cli.set_connection_timeout(std::chrono::seconds(5));
  1504. auto res =
  1505. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1506. "application/json", [](uint64_t, uint64_t) { return false; });
  1507. ASSERT_TRUE(!res);
  1508. EXPECT_EQ(Error::Canceled, res.error());
  1509. }
  1510. TEST(CancelTest, NoCancelPatch) {
  1511. Server svr;
  1512. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1513. res.set_content("Hello World!", "text/plain");
  1514. });
  1515. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1516. auto se = detail::scope_exit([&] {
  1517. svr.stop();
  1518. thread.join();
  1519. ASSERT_FALSE(svr.is_running());
  1520. });
  1521. svr.wait_until_ready();
  1522. Client cli(HOST, PORT);
  1523. cli.set_connection_timeout(std::chrono::seconds(5));
  1524. auto res =
  1525. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1526. "application/json", [](uint64_t, uint64_t) { return true; });
  1527. ASSERT_TRUE(res);
  1528. EXPECT_EQ("Hello World!", res->body);
  1529. EXPECT_EQ(StatusCode::OK_200, res->status);
  1530. }
  1531. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1532. Server svr;
  1533. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1534. res.set_content("Hello World!", "text/plain");
  1535. });
  1536. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1537. auto se = detail::scope_exit([&] {
  1538. svr.stop();
  1539. thread.join();
  1540. ASSERT_FALSE(svr.is_running());
  1541. });
  1542. svr.wait_until_ready();
  1543. Client cli(HOST, PORT);
  1544. cli.set_connection_timeout(std::chrono::seconds(5));
  1545. auto res =
  1546. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1547. "application/json", [](uint64_t, uint64_t) { return false; });
  1548. ASSERT_TRUE(!res);
  1549. EXPECT_EQ(Error::Canceled, res.error());
  1550. }
  1551. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1552. Server svr;
  1553. svr.set_payload_max_length(200 * 1024 * 1024);
  1554. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1555. res.set_content(LARGE_DATA, "text/plain");
  1556. });
  1557. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1558. auto se = detail::scope_exit([&] {
  1559. svr.stop();
  1560. thread.join();
  1561. ASSERT_FALSE(svr.is_running());
  1562. });
  1563. svr.wait_until_ready();
  1564. Client cli(HOST, PORT);
  1565. cli.set_payload_max_length(200 * 1024 * 1024);
  1566. cli.set_connection_timeout(std::chrono::seconds(5));
  1567. auto res =
  1568. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1569. "application/json", [](uint64_t, uint64_t) { return false; });
  1570. ASSERT_TRUE(!res);
  1571. EXPECT_EQ(Error::Canceled, res.error());
  1572. }
  1573. TEST(CancelTest, NoCancelDelete) {
  1574. Server svr;
  1575. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1576. res.set_content("Hello World!", "text/plain");
  1577. });
  1578. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1579. auto se = detail::scope_exit([&] {
  1580. svr.stop();
  1581. thread.join();
  1582. ASSERT_FALSE(svr.is_running());
  1583. });
  1584. svr.wait_until_ready();
  1585. Client cli(HOST, PORT);
  1586. cli.set_connection_timeout(std::chrono::seconds(5));
  1587. auto res =
  1588. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1589. "application/json", [](uint64_t, uint64_t) { return true; });
  1590. ASSERT_TRUE(res);
  1591. EXPECT_EQ("Hello World!", res->body);
  1592. EXPECT_EQ(StatusCode::OK_200, res->status);
  1593. }
  1594. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1595. Server svr;
  1596. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1597. res.set_content("Hello World!", "text/plain");
  1598. });
  1599. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1600. auto se = detail::scope_exit([&] {
  1601. svr.stop();
  1602. thread.join();
  1603. ASSERT_FALSE(svr.is_running());
  1604. });
  1605. svr.wait_until_ready();
  1606. Client cli(HOST, PORT);
  1607. cli.set_connection_timeout(std::chrono::seconds(5));
  1608. auto res =
  1609. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1610. "application/json", [](uint64_t, uint64_t) { return false; });
  1611. ASSERT_TRUE(!res);
  1612. EXPECT_EQ(Error::Canceled, res.error());
  1613. }
  1614. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1615. Server svr;
  1616. svr.set_payload_max_length(200 * 1024 * 1024);
  1617. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1618. res.set_content(LARGE_DATA, "text/plain");
  1619. });
  1620. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1621. auto se = detail::scope_exit([&] {
  1622. svr.stop();
  1623. thread.join();
  1624. ASSERT_FALSE(svr.is_running());
  1625. });
  1626. svr.wait_until_ready();
  1627. Client cli(HOST, PORT);
  1628. cli.set_payload_max_length(200 * 1024 * 1024);
  1629. cli.set_connection_timeout(std::chrono::seconds(5));
  1630. auto res =
  1631. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1632. "application/json", [](uint64_t, uint64_t) { return false; });
  1633. ASSERT_TRUE(!res);
  1634. EXPECT_EQ(Error::Canceled, res.error());
  1635. }
  1636. static std::string remove_whitespace(const std::string &input) {
  1637. std::string output;
  1638. output.reserve(input.size());
  1639. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1640. [](unsigned char c) { return !std::isspace(c); });
  1641. return output;
  1642. }
  1643. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1644. auto host = "httpbingo.org";
  1645. auto path = std::string{"/basic-auth/hello/world"};
  1646. #ifdef CPPHTTPLIB_SSL_ENABLED
  1647. auto port = 443;
  1648. SSLClient cli(host, port);
  1649. #else
  1650. auto port = 80;
  1651. Client cli(host, port);
  1652. #endif
  1653. {
  1654. auto res = cli.Get(path);
  1655. ASSERT_TRUE(res);
  1656. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1657. }
  1658. {
  1659. auto res =
  1660. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1661. ASSERT_TRUE(res);
  1662. auto body = remove_whitespace(res->body);
  1663. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1664. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1665. EXPECT_EQ(StatusCode::OK_200, res->status);
  1666. }
  1667. {
  1668. cli.set_basic_auth("hello", "world");
  1669. auto res = cli.Get(path);
  1670. ASSERT_TRUE(res);
  1671. auto body = remove_whitespace(res->body);
  1672. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1673. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1674. EXPECT_EQ(StatusCode::OK_200, res->status);
  1675. }
  1676. {
  1677. cli.set_basic_auth("hello", "bad");
  1678. auto res = cli.Get(path);
  1679. ASSERT_TRUE(res);
  1680. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1681. }
  1682. {
  1683. cli.set_basic_auth("bad", "world");
  1684. auto res = cli.Get(path);
  1685. ASSERT_TRUE(res);
  1686. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1687. }
  1688. }
  1689. #ifdef CPPHTTPLIB_SSL_ENABLED
  1690. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1691. auto host = "httpbingo.org";
  1692. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1693. auto paths = std::vector<std::string>{
  1694. "/digest-auth/auth/hello/world/MD5",
  1695. "/digest-auth/auth/hello/world/SHA-256",
  1696. };
  1697. auto port = 443;
  1698. SSLClient cli(host, port);
  1699. {
  1700. auto res = cli.Get(unauth_path);
  1701. ASSERT_TRUE(res);
  1702. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1703. }
  1704. {
  1705. cli.set_digest_auth("hello", "world");
  1706. for (const auto &path : paths) {
  1707. auto res = cli.Get(path.c_str());
  1708. ASSERT_TRUE(res);
  1709. auto body = remove_whitespace(res->body);
  1710. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1711. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1712. EXPECT_EQ(StatusCode::OK_200, res->status);
  1713. }
  1714. cli.set_digest_auth("hello", "bad");
  1715. for (const auto &path : paths) {
  1716. auto res = cli.Get(path.c_str());
  1717. ASSERT_TRUE(res);
  1718. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1719. }
  1720. }
  1721. }
  1722. #endif
  1723. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1724. auto host = "google.com";
  1725. auto another_host = "example.com";
  1726. auto wrong_ip = "0.0.0.0";
  1727. #ifdef CPPHTTPLIB_SSL_ENABLED
  1728. SSLClient cli(host);
  1729. #else
  1730. Client cli(host);
  1731. #endif
  1732. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1733. auto res = cli.Get("/");
  1734. ASSERT_TRUE(res);
  1735. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1736. }
  1737. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1738. auto host = "google.com";
  1739. auto wrong_ip = "0.0.0.0";
  1740. #ifdef CPPHTTPLIB_SSL_ENABLED
  1741. SSLClient cli(host);
  1742. #else
  1743. Client cli(host);
  1744. #endif
  1745. cli.set_hostname_addr_map({{host, wrong_ip}});
  1746. auto res = cli.Get("/");
  1747. ASSERT_TRUE(!res);
  1748. EXPECT_EQ(Error::Connection, res.error());
  1749. }
  1750. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1751. auto host = "httpbingo.org";
  1752. auto path = std::string{"/absolute-redirect/3"};
  1753. #ifdef CPPHTTPLIB_SSL_ENABLED
  1754. SSLClient cli(host);
  1755. #else
  1756. Client cli(host);
  1757. #endif
  1758. cli.set_follow_location(true);
  1759. auto res = cli.Get(path);
  1760. ASSERT_TRUE(res);
  1761. EXPECT_EQ(StatusCode::OK_200, res->status);
  1762. }
  1763. TEST(RedirectTest, Redirect_Online) {
  1764. auto host = "httpbingo.org";
  1765. auto path = std::string{"/redirect/3"};
  1766. #ifdef CPPHTTPLIB_SSL_ENABLED
  1767. SSLClient cli(host);
  1768. #else
  1769. Client cli(host);
  1770. #endif
  1771. cli.set_follow_location(true);
  1772. auto res = cli.Get(path);
  1773. ASSERT_TRUE(res);
  1774. EXPECT_EQ(StatusCode::OK_200, res->status);
  1775. }
  1776. TEST(RelativeRedirectTest, Redirect_Online) {
  1777. auto host = "httpbingo.org";
  1778. auto path = std::string{"/relative-redirect/3"};
  1779. #ifdef CPPHTTPLIB_SSL_ENABLED
  1780. SSLClient cli(host);
  1781. #else
  1782. Client cli(host);
  1783. #endif
  1784. cli.set_follow_location(true);
  1785. auto res = cli.Get(path);
  1786. ASSERT_TRUE(res);
  1787. EXPECT_EQ(StatusCode::OK_200, res->status);
  1788. }
  1789. TEST(TooManyRedirectTest, Redirect_Online) {
  1790. auto host = "httpbingo.org";
  1791. auto path = std::string{"/redirect/21"};
  1792. #ifdef CPPHTTPLIB_SSL_ENABLED
  1793. SSLClient cli(host);
  1794. #else
  1795. Client cli(host);
  1796. #endif
  1797. cli.set_follow_location(true);
  1798. auto res = cli.Get(path);
  1799. ASSERT_TRUE(!res);
  1800. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1801. }
  1802. #ifdef CPPHTTPLIB_SSL_ENABLED
  1803. TEST(YahooRedirectTest, Redirect_Online) {
  1804. Client cli("yahoo.com");
  1805. auto res = cli.Get("/");
  1806. ASSERT_TRUE(res);
  1807. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1808. cli.set_follow_location(true);
  1809. res = cli.Get("/");
  1810. ASSERT_TRUE(res);
  1811. EXPECT_EQ(StatusCode::OK_200, res->status);
  1812. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1813. }
  1814. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1815. #define REDIR_HOST "httpbingo.org"
  1816. #define REDIR_PATH "/redirect-to"
  1817. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1818. SSLClient cli(REDIR_HOST);
  1819. cli.set_follow_location(true);
  1820. auto res =
  1821. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1822. ASSERT_TRUE(res);
  1823. EXPECT_EQ(StatusCode::OK_200, res->status);
  1824. }
  1825. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1826. SSLClient cli(REDIR_HOST);
  1827. cli.set_follow_location(true);
  1828. Params params;
  1829. params.emplace("url", "http://example.com");
  1830. params.emplace("status_code", "302");
  1831. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1832. ASSERT_TRUE(res);
  1833. EXPECT_EQ(StatusCode::OK_200, res->status);
  1834. }
  1835. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1836. SSLClient cli(REDIR_HOST);
  1837. cli.set_follow_location(true);
  1838. Params params;
  1839. params.emplace("url", "http://example.com");
  1840. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1841. ASSERT_TRUE(res);
  1842. EXPECT_EQ(StatusCode::OK_200, res->status);
  1843. }
  1844. TEST(UrlWithSpace, Redirect_Online) {
  1845. SSLClient cli("edge.forgecdn.net");
  1846. cli.set_follow_location(true);
  1847. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1848. ASSERT_TRUE(res);
  1849. EXPECT_EQ(StatusCode::OK_200, res->status);
  1850. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1851. }
  1852. #endif
  1853. #if !defined(_WIN32) && !defined(_WIN64)
  1854. TEST(ReceiveSignals, Signal) {
  1855. auto setupSignalHandlers = []() {
  1856. struct sigaction act;
  1857. sigemptyset(&act.sa_mask);
  1858. act.sa_flags = SA_SIGINFO;
  1859. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1860. switch (sig) {
  1861. case SIGINT:
  1862. default: break;
  1863. }
  1864. };
  1865. ::sigaction(SIGINT, &act, nullptr);
  1866. };
  1867. Server svr;
  1868. int port = 0;
  1869. auto thread = std::thread([&]() {
  1870. setupSignalHandlers();
  1871. port = svr.bind_to_any_port(HOST);
  1872. svr.listen_after_bind();
  1873. });
  1874. auto se = detail::scope_exit([&] {
  1875. svr.stop();
  1876. thread.join();
  1877. ASSERT_FALSE(svr.is_running());
  1878. });
  1879. svr.wait_until_ready();
  1880. ASSERT_TRUE(svr.is_running());
  1881. pthread_kill(thread.native_handle(), SIGINT);
  1882. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1883. ASSERT_TRUE(svr.is_running());
  1884. }
  1885. #endif
  1886. TEST(RedirectToDifferentPort, Redirect) {
  1887. Server svr1;
  1888. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1889. res.set_content("Hello World!", "text/plain");
  1890. });
  1891. int svr1_port = 0;
  1892. auto thread1 = std::thread([&]() {
  1893. svr1_port = svr1.bind_to_any_port(HOST);
  1894. svr1.listen_after_bind();
  1895. });
  1896. Server svr2;
  1897. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1898. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1899. });
  1900. int svr2_port = 0;
  1901. auto thread2 = std::thread([&]() {
  1902. svr2_port = svr2.bind_to_any_port(HOST);
  1903. svr2.listen_after_bind();
  1904. });
  1905. auto se = detail::scope_exit([&] {
  1906. svr2.stop();
  1907. thread2.join();
  1908. svr1.stop();
  1909. thread1.join();
  1910. ASSERT_FALSE(svr2.is_running());
  1911. ASSERT_FALSE(svr1.is_running());
  1912. });
  1913. svr1.wait_until_ready();
  1914. svr2.wait_until_ready();
  1915. Client cli("localhost", svr2_port);
  1916. cli.set_follow_location(true);
  1917. auto res = cli.Get("/2");
  1918. ASSERT_TRUE(res);
  1919. EXPECT_EQ(StatusCode::OK_200, res->status);
  1920. EXPECT_EQ("Hello World!", res->body);
  1921. }
  1922. static void
  1923. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  1924. Server svr1;
  1925. std::string captured_authorization;
  1926. svr1.Get("/target", [&](const Request &req, Response &res) {
  1927. captured_authorization = req.get_header_value("Authorization");
  1928. res.set_content("OK", "text/plain");
  1929. });
  1930. int svr1_port = 0;
  1931. auto thread1 = std::thread([&]() {
  1932. svr1_port = svr1.bind_to_any_port(HOST);
  1933. svr1.listen_after_bind();
  1934. });
  1935. Server svr2;
  1936. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  1937. res.set_redirect(
  1938. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  1939. });
  1940. int svr2_port = 0;
  1941. auto thread2 = std::thread([&]() {
  1942. svr2_port = svr2.bind_to_any_port(HOST);
  1943. svr2.listen_after_bind();
  1944. });
  1945. auto se = detail::scope_exit([&] {
  1946. svr2.stop();
  1947. thread2.join();
  1948. svr1.stop();
  1949. thread1.join();
  1950. ASSERT_FALSE(svr2.is_running());
  1951. ASSERT_FALSE(svr1.is_running());
  1952. });
  1953. svr1.wait_until_ready();
  1954. svr2.wait_until_ready();
  1955. Client cli("localhost", svr2_port);
  1956. cli.set_follow_location(true);
  1957. set_auth(cli);
  1958. auto res = cli.Get("/redir");
  1959. ASSERT_TRUE(res);
  1960. EXPECT_EQ(StatusCode::OK_200, res->status);
  1961. // RFC 9110: credentials MUST NOT be forwarded to a different host
  1962. EXPECT_TRUE(captured_authorization.empty());
  1963. }
  1964. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  1965. TestDoNotForwardCredentialsOnRedirect(
  1966. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  1967. }
  1968. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  1969. TestDoNotForwardCredentialsOnRedirect(
  1970. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  1971. }
  1972. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  1973. Server svr;
  1974. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  1975. // Port number that overflows int — should not crash
  1976. res.set_redirect("http://localhost:99999999999999999999/target");
  1977. });
  1978. auto port = svr.bind_to_any_port(HOST);
  1979. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  1980. auto se = detail::scope_exit([&] {
  1981. svr.stop();
  1982. thread.join();
  1983. ASSERT_FALSE(svr.is_running());
  1984. });
  1985. svr.wait_until_ready();
  1986. Client cli(HOST, port);
  1987. cli.set_follow_location(true);
  1988. auto res = cli.Get("/redir");
  1989. // Should fail gracefully, not crash (no valid response due to bad port)
  1990. EXPECT_FALSE(res);
  1991. }
  1992. TEST(RedirectFromPageWithContent, Redirect) {
  1993. Server svr;
  1994. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1995. res.set_content("___", "text/plain");
  1996. res.set_redirect("/2");
  1997. });
  1998. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1999. res.set_content("Hello World!", "text/plain");
  2000. });
  2001. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2002. auto se = detail::scope_exit([&] {
  2003. svr.stop();
  2004. th.join();
  2005. ASSERT_FALSE(svr.is_running());
  2006. });
  2007. svr.wait_until_ready();
  2008. {
  2009. Client cli("localhost", PORT);
  2010. cli.set_follow_location(true);
  2011. std::string body;
  2012. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2013. body.append(data, data_length);
  2014. return true;
  2015. });
  2016. ASSERT_TRUE(res);
  2017. EXPECT_EQ(StatusCode::OK_200, res->status);
  2018. EXPECT_EQ("Hello World!", body);
  2019. }
  2020. {
  2021. Client cli("localhost", PORT);
  2022. std::string body;
  2023. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2024. body.append(data, data_length);
  2025. return true;
  2026. });
  2027. ASSERT_TRUE(res);
  2028. EXPECT_EQ(StatusCode::Found_302, res->status);
  2029. EXPECT_EQ("___", body);
  2030. }
  2031. }
  2032. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2033. Server svr;
  2034. auto port_str = std::to_string(PORT);
  2035. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2036. auto expected_host = "[::1]:" + port_str;
  2037. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2038. res.set_content("___", "text/plain");
  2039. // res.set_redirect("/2");
  2040. res.set_redirect(redirect_url);
  2041. });
  2042. svr.Get("/2", [&](const Request &req, Response &res) {
  2043. auto host_header = req.headers.find("Host");
  2044. ASSERT_TRUE(host_header != req.headers.end());
  2045. EXPECT_EQ(expected_host, host_header->second);
  2046. res.set_content("Hello World!", "text/plain");
  2047. });
  2048. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2049. auto se = detail::scope_exit([&] {
  2050. svr.stop();
  2051. th.join();
  2052. ASSERT_FALSE(svr.is_running());
  2053. });
  2054. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2055. // actually starts anything, so the condition !svr.is_running() will
  2056. // always remain true, and the loop never stops.
  2057. // This basically counts how many milliseconds have passed since the
  2058. // call to svr.listen(), and if after 5 seconds nothing started yet
  2059. // aborts the test.
  2060. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2061. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2062. ASSERT_LT(milliseconds, 5000U);
  2063. }
  2064. {
  2065. Client cli("::1", PORT);
  2066. cli.set_follow_location(true);
  2067. std::string body;
  2068. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2069. body.append(data, data_length);
  2070. return true;
  2071. });
  2072. ASSERT_TRUE(res);
  2073. EXPECT_EQ(StatusCode::OK_200, res->status);
  2074. EXPECT_EQ("Hello World!", body);
  2075. }
  2076. {
  2077. Client cli("::1", PORT);
  2078. std::string body;
  2079. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2080. body.append(data, data_length);
  2081. return true;
  2082. });
  2083. ASSERT_TRUE(res);
  2084. EXPECT_EQ(StatusCode::Found_302, res->status);
  2085. EXPECT_EQ("___", body);
  2086. }
  2087. }
  2088. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2089. Server svr;
  2090. svr.Get("/foo", [](const Request &req, Response &res) {
  2091. auto a = req.params.find("a");
  2092. if (a != req.params.end()) {
  2093. res.set_content((*a).second, "text/plain");
  2094. res.status = StatusCode::OK_200;
  2095. } else {
  2096. res.status = StatusCode::BadRequest_400;
  2097. }
  2098. });
  2099. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2100. auto se = detail::scope_exit([&] {
  2101. svr.stop();
  2102. thread.join();
  2103. ASSERT_FALSE(svr.is_running());
  2104. });
  2105. svr.wait_until_ready();
  2106. {
  2107. Client cli(HOST, PORT);
  2108. cli.set_path_encode(false);
  2109. auto res = cli.Get("/foo?a=explicitly+encoded");
  2110. ASSERT_TRUE(res);
  2111. EXPECT_EQ(StatusCode::OK_200, res->status);
  2112. // This expects it back with a space, as the `+` won't have been
  2113. // url-encoded, and server-side the params get decoded turning `+`
  2114. // into spaces.
  2115. EXPECT_EQ("explicitly encoded", res->body);
  2116. }
  2117. }
  2118. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2119. Server svr;
  2120. svr.Get("/", [](const Request &req, Response &) {
  2121. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2122. });
  2123. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2124. auto se = detail::scope_exit([&] {
  2125. svr.stop();
  2126. thread.join();
  2127. ASSERT_FALSE(svr.is_running());
  2128. });
  2129. svr.wait_until_ready();
  2130. {
  2131. Client cli(HOST, PORT);
  2132. cli.set_path_encode(false);
  2133. auto res = cli.Get("/?something=%0A");
  2134. ASSERT_TRUE(res);
  2135. EXPECT_EQ(StatusCode::OK_200, res->status);
  2136. }
  2137. }
  2138. TEST(BindServerTest, BindDualStack) {
  2139. Server svr;
  2140. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2141. res.set_content("Hello World!", "text/plain");
  2142. });
  2143. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2144. auto se = detail::scope_exit([&] {
  2145. svr.stop();
  2146. thread.join();
  2147. ASSERT_FALSE(svr.is_running());
  2148. });
  2149. svr.wait_until_ready();
  2150. {
  2151. Client cli("127.0.0.1", PORT);
  2152. auto res = cli.Get("/1");
  2153. ASSERT_TRUE(res);
  2154. EXPECT_EQ(StatusCode::OK_200, res->status);
  2155. EXPECT_EQ("Hello World!", res->body);
  2156. }
  2157. {
  2158. Client cli("::1", PORT);
  2159. auto res = cli.Get("/1");
  2160. ASSERT_TRUE(res);
  2161. EXPECT_EQ(StatusCode::OK_200, res->status);
  2162. EXPECT_EQ("Hello World!", res->body);
  2163. }
  2164. }
  2165. TEST(BindServerTest, BindAndListenSeparately) {
  2166. Server svr;
  2167. int port = svr.bind_to_any_port("0.0.0.0");
  2168. ASSERT_TRUE(svr.is_valid());
  2169. ASSERT_TRUE(port > 0);
  2170. svr.stop();
  2171. }
  2172. #ifdef CPPHTTPLIB_SSL_ENABLED
  2173. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2174. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2175. CLIENT_CA_CERT_DIR);
  2176. int port = svr.bind_to_any_port("0.0.0.0");
  2177. ASSERT_TRUE(svr.is_valid());
  2178. ASSERT_TRUE(port > 0);
  2179. svr.stop();
  2180. }
  2181. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2182. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2183. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2184. int port = svr.bind_to_any_port("0.0.0.0");
  2185. ASSERT_TRUE(svr.is_valid());
  2186. ASSERT_TRUE(port > 0);
  2187. svr.stop();
  2188. }
  2189. TEST(BindServerTest, UpdateCertsPem) {
  2190. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2191. int port = svr.bind_to_any_port("0.0.0.0");
  2192. ASSERT_TRUE(svr.is_valid());
  2193. ASSERT_TRUE(port > 0);
  2194. // Read PEM files
  2195. std::string cert_pem, key_pem, ca_pem;
  2196. read_file(SERVER_CERT_FILE, cert_pem);
  2197. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2198. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2199. // Update server certificates using PEM API
  2200. ASSERT_TRUE(
  2201. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2202. ASSERT_TRUE(svr.is_valid());
  2203. svr.stop();
  2204. }
  2205. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2206. // Start server with client CA (enables client auth)
  2207. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2208. ASSERT_TRUE(svr.is_valid());
  2209. bool handler_called = false;
  2210. svr.Get("/test", [&](const Request &req, Response &res) {
  2211. handler_called = true;
  2212. // Verify client certificate is present
  2213. auto cert = req.peer_cert();
  2214. EXPECT_TRUE(static_cast<bool>(cert));
  2215. res.set_content("ok", "text/plain");
  2216. });
  2217. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2218. auto se = detail::scope_exit([&] {
  2219. svr.stop();
  2220. t.join();
  2221. ASSERT_FALSE(svr.is_running());
  2222. });
  2223. svr.wait_until_ready();
  2224. // Read PEM files
  2225. std::string cert_pem, key_pem, ca_pem;
  2226. read_file(SERVER_CERT_FILE, cert_pem);
  2227. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2228. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2229. // Update server certificates and client CA using PEM API while server running
  2230. ASSERT_TRUE(
  2231. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2232. // Connect with client certificate
  2233. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2234. cli.enable_server_certificate_verification(false);
  2235. cli.set_connection_timeout(30);
  2236. auto res = cli.Get("/test");
  2237. ASSERT_TRUE(res);
  2238. ASSERT_EQ(StatusCode::OK_200, res->status);
  2239. ASSERT_TRUE(handler_called);
  2240. EXPECT_EQ("ok", res->body);
  2241. }
  2242. #endif
  2243. TEST(ErrorHandlerTest, ContentLength) {
  2244. Server svr;
  2245. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2246. res.status = StatusCode::OK_200;
  2247. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2248. "text/html"); // <= Content-Length still 13
  2249. });
  2250. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2251. res.set_content("Hello World!\n", "text/plain");
  2252. res.status = 524;
  2253. });
  2254. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2255. auto se = detail::scope_exit([&] {
  2256. svr.stop();
  2257. thread.join();
  2258. ASSERT_FALSE(svr.is_running());
  2259. });
  2260. svr.wait_until_ready();
  2261. {
  2262. Client cli(HOST, PORT);
  2263. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2264. ASSERT_TRUE(res);
  2265. EXPECT_EQ(StatusCode::OK_200, 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. }
  2271. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2272. TEST(ExceptionTest, WithoutExceptionHandler) {
  2273. Server svr;
  2274. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2275. throw std::runtime_error("exception...");
  2276. });
  2277. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2278. throw std::runtime_error("exception\r\n...");
  2279. });
  2280. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2281. auto se = detail::scope_exit([&] {
  2282. svr.stop();
  2283. listen_thread.join();
  2284. ASSERT_FALSE(svr.is_running());
  2285. });
  2286. svr.wait_until_ready();
  2287. Client cli("localhost", PORT);
  2288. {
  2289. auto res = cli.Get("/exception");
  2290. ASSERT_TRUE(res);
  2291. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2292. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2293. }
  2294. {
  2295. auto res = cli.Get("/unknown");
  2296. ASSERT_TRUE(res);
  2297. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2298. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2299. }
  2300. }
  2301. TEST(ExceptionTest, WithExceptionHandler) {
  2302. Server svr;
  2303. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2304. std::exception_ptr ep) {
  2305. EXPECT_FALSE(ep == nullptr);
  2306. try {
  2307. std::rethrow_exception(ep);
  2308. } catch (std::exception &e) {
  2309. EXPECT_EQ("abc", std::string(e.what()));
  2310. } catch (...) {}
  2311. res.status = StatusCode::InternalServerError_500;
  2312. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2313. "text/html"); // <= Content-Length still 13 at this point
  2314. });
  2315. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2316. res.set_content("Hello World!\n", "text/plain");
  2317. throw std::runtime_error("abc");
  2318. });
  2319. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2320. auto se = detail::scope_exit([&] {
  2321. svr.stop();
  2322. thread.join();
  2323. ASSERT_FALSE(svr.is_running());
  2324. });
  2325. svr.wait_until_ready();
  2326. for (size_t i = 0; i < 10; i++) {
  2327. Client cli(HOST, PORT);
  2328. for (size_t j = 0; j < 100; j++) {
  2329. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2330. ASSERT_TRUE(res);
  2331. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2332. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2333. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2334. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2335. }
  2336. cli.set_keep_alive(true);
  2337. for (size_t j = 0; j < 100; j++) {
  2338. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2339. ASSERT_TRUE(res);
  2340. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2341. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2342. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2343. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2344. }
  2345. }
  2346. }
  2347. TEST(ExceptionTest, AndErrorHandler) {
  2348. Server svr;
  2349. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2350. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2351. });
  2352. svr.set_exception_handler(
  2353. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2354. EXPECT_FALSE(ep == nullptr);
  2355. try {
  2356. std::rethrow_exception(ep);
  2357. } catch (std::exception &e) {
  2358. res.set_content(e.what(), "text/html");
  2359. } catch (...) {}
  2360. res.status = StatusCode::InternalServerError_500;
  2361. });
  2362. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2363. throw std::runtime_error("EXCEPTION");
  2364. });
  2365. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2366. res.set_content("ERROR", "text/html");
  2367. res.status = StatusCode::InternalServerError_500;
  2368. });
  2369. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2370. auto se = detail::scope_exit([&] {
  2371. svr.stop();
  2372. thread.join();
  2373. ASSERT_FALSE(svr.is_running());
  2374. });
  2375. svr.wait_until_ready();
  2376. Client cli(HOST, PORT);
  2377. {
  2378. auto res = cli.Get("/exception");
  2379. ASSERT_TRUE(res);
  2380. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2381. EXPECT_EQ("EXCEPTION", res->body);
  2382. }
  2383. {
  2384. auto res = cli.Get("/error");
  2385. ASSERT_TRUE(res);
  2386. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2387. EXPECT_EQ("ERROR", res->body);
  2388. }
  2389. {
  2390. auto res = cli.Get("/invalid");
  2391. ASSERT_TRUE(res);
  2392. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2393. EXPECT_EQ("NOT_FOUND", res->body);
  2394. }
  2395. }
  2396. #endif
  2397. TEST(NoContentTest, ContentLength) {
  2398. Server svr;
  2399. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2400. res.status = StatusCode::NoContent_204;
  2401. });
  2402. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2403. auto se = detail::scope_exit([&] {
  2404. svr.stop();
  2405. thread.join();
  2406. ASSERT_FALSE(svr.is_running());
  2407. });
  2408. svr.wait_until_ready();
  2409. {
  2410. Client cli(HOST, PORT);
  2411. auto res = cli.Get("/hi");
  2412. ASSERT_TRUE(res);
  2413. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2414. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2415. }
  2416. }
  2417. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2418. #ifdef CPPHTTPLIB_SSL_ENABLED
  2419. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2420. ASSERT_TRUE(svr.is_valid());
  2421. #else
  2422. Server svr;
  2423. #endif
  2424. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2425. if (req.path == "/routing_handler") {
  2426. res.set_header("PRE_ROUTING", "on");
  2427. res.set_content("Routing Handler", "text/plain");
  2428. return httplib::Server::HandlerResponse::Handled;
  2429. }
  2430. return httplib::Server::HandlerResponse::Unhandled;
  2431. });
  2432. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2433. res.set_content("Error", "text/html");
  2434. });
  2435. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2436. if (req.path == "/routing_handler") {
  2437. res.set_header("POST_ROUTING", "on");
  2438. }
  2439. });
  2440. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2441. res.set_content("Hello World!\n", "text/plain");
  2442. });
  2443. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2444. auto se = detail::scope_exit([&] {
  2445. svr.stop();
  2446. thread.join();
  2447. ASSERT_FALSE(svr.is_running());
  2448. });
  2449. svr.wait_until_ready();
  2450. {
  2451. #ifdef CPPHTTPLIB_SSL_ENABLED
  2452. SSLClient cli(HOST, PORT);
  2453. cli.enable_server_certificate_verification(false);
  2454. #else
  2455. Client cli(HOST, PORT);
  2456. #endif
  2457. auto res = cli.Get("/routing_handler");
  2458. ASSERT_TRUE(res);
  2459. EXPECT_EQ(StatusCode::OK_200, res->status);
  2460. EXPECT_EQ("Routing Handler", res->body);
  2461. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2462. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2463. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2464. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2465. }
  2466. {
  2467. #ifdef CPPHTTPLIB_SSL_ENABLED
  2468. SSLClient cli(HOST, PORT);
  2469. cli.enable_server_certificate_verification(false);
  2470. #else
  2471. Client cli(HOST, PORT);
  2472. #endif
  2473. auto res = cli.Get("/hi");
  2474. ASSERT_TRUE(res);
  2475. EXPECT_EQ(StatusCode::OK_200, res->status);
  2476. EXPECT_EQ("Hello World!\n", res->body);
  2477. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2478. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2479. }
  2480. {
  2481. #ifdef CPPHTTPLIB_SSL_ENABLED
  2482. SSLClient cli(HOST, PORT);
  2483. cli.enable_server_certificate_verification(false);
  2484. #else
  2485. Client cli(HOST, PORT);
  2486. #endif
  2487. auto res = cli.Get("/aaa");
  2488. ASSERT_TRUE(res);
  2489. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2490. EXPECT_EQ("Error", res->body);
  2491. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2492. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2493. }
  2494. }
  2495. TEST(RequestHandlerTest, PreRequestHandler) {
  2496. auto route_path = "/user/:user";
  2497. Server svr;
  2498. svr.Get("/hi", [](const Request &, Response &res) {
  2499. res.set_content("hi", "text/plain");
  2500. });
  2501. svr.Get(route_path, [](const Request &req, Response &res) {
  2502. res.set_content(req.path_params.at("user"), "text/plain");
  2503. });
  2504. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2505. if (req.matched_route == route_path) {
  2506. auto user = req.path_params.at("user");
  2507. if (user != "john") {
  2508. res.status = StatusCode::Forbidden_403;
  2509. res.set_content("error", "text/html");
  2510. return Server::HandlerResponse::Handled;
  2511. }
  2512. }
  2513. return Server::HandlerResponse::Unhandled;
  2514. });
  2515. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2516. auto se = detail::scope_exit([&] {
  2517. svr.stop();
  2518. thread.join();
  2519. ASSERT_FALSE(svr.is_running());
  2520. });
  2521. svr.wait_until_ready();
  2522. Client cli(HOST, PORT);
  2523. {
  2524. auto res = cli.Get("/hi");
  2525. ASSERT_TRUE(res);
  2526. EXPECT_EQ(StatusCode::OK_200, res->status);
  2527. EXPECT_EQ("hi", res->body);
  2528. }
  2529. {
  2530. auto res = cli.Get("/user/john");
  2531. ASSERT_TRUE(res);
  2532. EXPECT_EQ(StatusCode::OK_200, res->status);
  2533. EXPECT_EQ("john", res->body);
  2534. }
  2535. {
  2536. auto res = cli.Get("/user/invalid-user");
  2537. ASSERT_TRUE(res);
  2538. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2539. EXPECT_EQ("error", res->body);
  2540. }
  2541. }
  2542. TEST(AnyTest, BasicOperations) {
  2543. // Default construction
  2544. httplib::any a;
  2545. EXPECT_FALSE(a.has_value());
  2546. // Value construction and any_cast (pointer form, noexcept)
  2547. httplib::any b(42);
  2548. EXPECT_TRUE(b.has_value());
  2549. auto *p = httplib::any_cast<int>(&b);
  2550. ASSERT_NE(nullptr, p);
  2551. EXPECT_EQ(42, *p);
  2552. // Type mismatch → nullptr
  2553. auto *q = httplib::any_cast<std::string>(&b);
  2554. EXPECT_EQ(nullptr, q);
  2555. // any_cast (value form) succeeds
  2556. EXPECT_EQ(42, httplib::any_cast<int>(b));
  2557. // any_cast (value form) throws on type mismatch
  2558. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2559. EXPECT_THROW(httplib::any_cast<std::string>(b), httplib::bad_any_cast);
  2560. #endif
  2561. // Copy
  2562. httplib::any c = b;
  2563. EXPECT_EQ(42, httplib::any_cast<int>(c));
  2564. // Move
  2565. httplib::any d = std::move(c);
  2566. EXPECT_EQ(42, httplib::any_cast<int>(d));
  2567. // Assignment with different type
  2568. b = std::string("hello");
  2569. EXPECT_EQ("hello", httplib::any_cast<std::string>(b));
  2570. // Reset
  2571. b.reset();
  2572. EXPECT_FALSE(b.has_value());
  2573. }
  2574. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2575. struct AuthCtx {
  2576. std::string user_id;
  2577. };
  2578. Server svr;
  2579. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2580. res.user_data["auth"] = AuthCtx{"alice"};
  2581. return Server::HandlerResponse::Unhandled;
  2582. });
  2583. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2584. auto *ctx = httplib::any_cast<AuthCtx>(&res.user_data["auth"]);
  2585. ASSERT_NE(nullptr, ctx);
  2586. res.set_content("Hello " + ctx->user_id, "text/plain");
  2587. });
  2588. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2589. auto se = detail::scope_exit([&] {
  2590. svr.stop();
  2591. thread.join();
  2592. ASSERT_FALSE(svr.is_running());
  2593. });
  2594. svr.wait_until_ready();
  2595. Client cli(HOST, PORT);
  2596. auto res = cli.Get("/me");
  2597. ASSERT_TRUE(res);
  2598. EXPECT_EQ(StatusCode::OK_200, res->status);
  2599. EXPECT_EQ("Hello alice", res->body);
  2600. }
  2601. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2602. struct RoleCtx {
  2603. std::string role;
  2604. };
  2605. Server svr;
  2606. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2607. res.user_data["role"] = RoleCtx{"admin"};
  2608. return Server::HandlerResponse::Unhandled;
  2609. });
  2610. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2611. auto *ctx = httplib::any_cast<RoleCtx>(&res.user_data["role"]);
  2612. ASSERT_NE(nullptr, ctx);
  2613. res.set_content(ctx->role, "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. Client cli(HOST, PORT);
  2623. auto res = cli.Get("/role");
  2624. ASSERT_TRUE(res);
  2625. EXPECT_EQ(StatusCode::OK_200, res->status);
  2626. EXPECT_EQ("admin", res->body);
  2627. }
  2628. TEST(InvalidFormatTest, StatusCode) {
  2629. Server svr;
  2630. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2631. res.set_content("Hello World!\n", "text/plain");
  2632. res.status = 9999; // Status should be a three-digit code...
  2633. });
  2634. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2635. auto se = detail::scope_exit([&] {
  2636. svr.stop();
  2637. thread.join();
  2638. ASSERT_FALSE(svr.is_running());
  2639. });
  2640. svr.wait_until_ready();
  2641. {
  2642. Client cli(HOST, PORT);
  2643. auto res = cli.Get("/hi");
  2644. ASSERT_FALSE(res);
  2645. }
  2646. }
  2647. TEST(URLFragmentTest, WithFragment) {
  2648. Server svr;
  2649. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2650. EXPECT_TRUE(req.target == "/hi");
  2651. });
  2652. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2653. auto se = detail::scope_exit([&] {
  2654. svr.stop();
  2655. thread.join();
  2656. ASSERT_FALSE(svr.is_running());
  2657. });
  2658. svr.wait_until_ready();
  2659. {
  2660. Client cli(HOST, PORT);
  2661. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2662. EXPECT_TRUE(res);
  2663. EXPECT_EQ(StatusCode::OK_200, res->status);
  2664. res = cli.Get("/hi%23key1=val1=key2=val2");
  2665. EXPECT_TRUE(res);
  2666. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2667. }
  2668. }
  2669. TEST(HeaderWriter, SetHeaderWriter) {
  2670. Server svr;
  2671. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2672. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2673. return detail::write_headers(strm, hdrs);
  2674. });
  2675. svr.Get("/hi", [](const Request &req, Response &res) {
  2676. auto it = req.headers.find("CustomClientHeader");
  2677. EXPECT_TRUE(it != req.headers.end());
  2678. EXPECT_EQ(it->second, "CustomClientValue");
  2679. res.set_content("Hello World!\n", "text/plain");
  2680. });
  2681. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2682. auto se = detail::scope_exit([&] {
  2683. svr.stop();
  2684. thread.join();
  2685. ASSERT_FALSE(svr.is_running());
  2686. });
  2687. svr.wait_until_ready();
  2688. {
  2689. Client cli(HOST, PORT);
  2690. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2691. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2692. return detail::write_headers(strm, hdrs);
  2693. });
  2694. auto res = cli.Get("/hi");
  2695. EXPECT_TRUE(res);
  2696. EXPECT_EQ(StatusCode::OK_200, res->status);
  2697. auto it = res->headers.find("CustomServerHeader");
  2698. EXPECT_TRUE(it != res->headers.end());
  2699. EXPECT_EQ(it->second, "CustomServerValue");
  2700. }
  2701. }
  2702. class ServerTest : public ::testing::Test {
  2703. protected:
  2704. ServerTest()
  2705. : cli_(HOST, PORT)
  2706. #ifdef CPPHTTPLIB_SSL_ENABLED
  2707. ,
  2708. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2709. #endif
  2710. {
  2711. #ifdef CPPHTTPLIB_SSL_ENABLED
  2712. cli_.enable_server_certificate_verification(false);
  2713. #endif
  2714. // Allow LARGE_DATA (100MB) responses
  2715. cli_.set_payload_max_length(200 * 1024 * 1024);
  2716. }
  2717. virtual void SetUp() {
  2718. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2719. svr_.set_payload_max_length(200 * 1024 * 1024);
  2720. svr_.set_mount_point("/", "./www");
  2721. svr_.set_mount_point("/mount", "./www2");
  2722. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2723. svr_.Get("/hi",
  2724. [&](const Request & /*req*/, Response &res) {
  2725. res.set_content("Hello World!", "text/plain");
  2726. })
  2727. .Get("/file_content",
  2728. [&](const Request & /*req*/, Response &res) {
  2729. res.set_file_content("./www/dir/test.html");
  2730. })
  2731. .Get("/file_content_with_content_type",
  2732. [&](const Request & /*req*/, Response &res) {
  2733. res.set_file_content("./www/file", "text/plain");
  2734. })
  2735. .Get("/invalid_file_content",
  2736. [&](const Request & /*req*/, Response &res) {
  2737. res.set_file_content("./www/dir/invalid_file_path");
  2738. })
  2739. .Get("/http_response_splitting",
  2740. [&](const Request & /*req*/, Response &res) {
  2741. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2742. EXPECT_EQ(0U, res.headers.size());
  2743. EXPECT_FALSE(res.has_header("a"));
  2744. res.set_header("a", "1\nSet-Cookie: a=1");
  2745. EXPECT_EQ(0U, res.headers.size());
  2746. EXPECT_FALSE(res.has_header("a"));
  2747. res.set_header("a", "1\rSet-Cookie: a=1");
  2748. EXPECT_EQ(0U, res.headers.size());
  2749. EXPECT_FALSE(res.has_header("a"));
  2750. res.set_header("a\r\nb", "0");
  2751. EXPECT_EQ(0U, res.headers.size());
  2752. EXPECT_FALSE(res.has_header("a"));
  2753. res.set_header("a\rb", "0");
  2754. EXPECT_EQ(0U, res.headers.size());
  2755. EXPECT_FALSE(res.has_header("a"));
  2756. res.set_header("a\nb", "0");
  2757. EXPECT_EQ(0U, res.headers.size());
  2758. EXPECT_FALSE(res.has_header("a"));
  2759. res.set_redirect("1\r\nSet-Cookie: a=1");
  2760. EXPECT_EQ(0U, res.headers.size());
  2761. EXPECT_FALSE(res.has_header("Location"));
  2762. })
  2763. .Get("/slow",
  2764. [&](const Request & /*req*/, Response &res) {
  2765. std::this_thread::sleep_for(std::chrono::seconds(2));
  2766. res.set_content("slow", "text/plain");
  2767. })
  2768. #if 0
  2769. .Post("/slowpost",
  2770. [&](const Request & /*req*/, Response &res) {
  2771. std::this_thread::sleep_for(std::chrono::seconds(2));
  2772. res.set_content("slow", "text/plain");
  2773. })
  2774. #endif
  2775. .Get("/remote_addr",
  2776. [&](const Request &req, Response &res) {
  2777. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2778. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2779. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2780. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2781. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2782. #endif
  2783. res.set_content(req.remote_addr, "text/plain");
  2784. })
  2785. .Get("/local_addr",
  2786. [&](const Request &req, Response &res) {
  2787. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2788. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2789. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2790. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2791. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2792. #endif
  2793. auto local_addr = req.local_addr;
  2794. auto local_port = std::to_string(req.local_port);
  2795. res.set_content(local_addr.append(":").append(local_port),
  2796. "text/plain");
  2797. })
  2798. .Get("/endwith%",
  2799. [&](const Request & /*req*/, Response &res) {
  2800. res.set_content("Hello World!", "text/plain");
  2801. })
  2802. .Get("/a\\+\\+b",
  2803. [&](const Request &req, Response &res) {
  2804. ASSERT_TRUE(req.has_param("a +b"));
  2805. auto val = req.get_param_value("a +b");
  2806. res.set_content(val, "text/plain");
  2807. })
  2808. .Get("/", [&](const Request & /*req*/,
  2809. Response &res) { res.set_redirect("/hi"); })
  2810. .Post("/1",
  2811. [](const Request & /*req*/, Response &res) {
  2812. res.set_redirect("/2", StatusCode::SeeOther_303);
  2813. })
  2814. .Get("/2",
  2815. [](const Request & /*req*/, Response &res) {
  2816. res.set_content("redirected.", "text/plain");
  2817. res.status = StatusCode::OK_200;
  2818. })
  2819. .Post("/person",
  2820. [&](const Request &req, Response &res) {
  2821. if (req.has_param("name") && req.has_param("note")) {
  2822. persons_[req.get_param_value("name")] =
  2823. req.get_param_value("note");
  2824. } else {
  2825. res.status = StatusCode::BadRequest_400;
  2826. }
  2827. })
  2828. .Put("/person",
  2829. [&](const Request &req, Response &res) {
  2830. if (req.has_param("name") && req.has_param("note")) {
  2831. persons_[req.get_param_value("name")] =
  2832. req.get_param_value("note");
  2833. } else {
  2834. res.status = StatusCode::BadRequest_400;
  2835. }
  2836. })
  2837. .Get("/person/(.*)",
  2838. [&](const Request &req, Response &res) {
  2839. string name = req.matches[1];
  2840. if (persons_.find(name) != persons_.end()) {
  2841. auto note = persons_[name];
  2842. res.set_content(note, "text/plain");
  2843. } else {
  2844. res.status = StatusCode::NotFound_404;
  2845. }
  2846. })
  2847. .Delete("/person",
  2848. [&](const Request &req, Response &res) {
  2849. if (req.has_param("name")) {
  2850. string name = req.get_param_value("name");
  2851. if (persons_.find(name) != persons_.end()) {
  2852. persons_.erase(name);
  2853. res.set_content("DELETED", "text/plain");
  2854. } else {
  2855. res.status = StatusCode::NotFound_404;
  2856. }
  2857. } else {
  2858. res.status = StatusCode::BadRequest_400;
  2859. }
  2860. })
  2861. .Post("/x-www-form-urlencoded-json",
  2862. [&](const Request &req, Response &res) {
  2863. auto json = req.get_param_value("json");
  2864. ASSERT_EQ(JSON_DATA, json);
  2865. res.set_content(json, "appliation/json");
  2866. res.status = StatusCode::OK_200;
  2867. })
  2868. .Get("/streamed-chunked",
  2869. [&](const Request & /*req*/, Response &res) {
  2870. res.set_chunked_content_provider(
  2871. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2872. sink.os << "123";
  2873. sink.os << "456";
  2874. sink.os << "789";
  2875. sink.done();
  2876. return true;
  2877. });
  2878. })
  2879. .Get("/streamed-chunked-with-prohibited-trailer",
  2880. [&](const Request & /*req*/, Response &res) {
  2881. auto i = new int(0);
  2882. // Declare both a prohibited trailer (Content-Length) and an
  2883. // allowed one
  2884. res.set_header("Trailer", "Content-Length, X-Allowed");
  2885. res.set_chunked_content_provider(
  2886. "text/plain",
  2887. [i](size_t /*offset*/, DataSink &sink) {
  2888. switch (*i) {
  2889. case 0: sink.os << "123"; break;
  2890. case 1: sink.os << "456"; break;
  2891. case 2: sink.os << "789"; break;
  2892. case 3: {
  2893. sink.done_with_trailer(
  2894. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2895. } break;
  2896. }
  2897. (*i)++;
  2898. return true;
  2899. },
  2900. [i](bool success) {
  2901. EXPECT_TRUE(success);
  2902. delete i;
  2903. });
  2904. })
  2905. .Get("/streamed-chunked2",
  2906. [&](const Request & /*req*/, Response &res) {
  2907. auto i = new int(0);
  2908. res.set_chunked_content_provider(
  2909. "text/plain",
  2910. [i](size_t /*offset*/, DataSink &sink) {
  2911. switch (*i) {
  2912. case 0: sink.os << "123"; break;
  2913. case 1: sink.os << "456"; break;
  2914. case 2: sink.os << "789"; break;
  2915. case 3: sink.done(); break;
  2916. }
  2917. (*i)++;
  2918. return true;
  2919. },
  2920. [i](bool success) {
  2921. EXPECT_TRUE(success);
  2922. delete i;
  2923. });
  2924. })
  2925. .Get("/streamed-chunked-with-trailer",
  2926. [&](const Request & /*req*/, Response &res) {
  2927. auto i = new int(0);
  2928. res.set_header("Trailer", "Dummy1, Dummy2");
  2929. res.set_chunked_content_provider(
  2930. "text/plain",
  2931. [i](size_t /*offset*/, DataSink &sink) {
  2932. switch (*i) {
  2933. case 0: sink.os << "123"; break;
  2934. case 1: sink.os << "456"; break;
  2935. case 2: sink.os << "789"; break;
  2936. case 3: {
  2937. sink.done_with_trailer(
  2938. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2939. } break;
  2940. }
  2941. (*i)++;
  2942. return true;
  2943. },
  2944. [i](bool success) {
  2945. EXPECT_TRUE(success);
  2946. delete i;
  2947. });
  2948. })
  2949. .Get("/streamed",
  2950. [&](const Request & /*req*/, Response &res) {
  2951. res.set_content_provider(
  2952. 6, "text/plain",
  2953. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2954. sink.os << (offset < 3 ? "a" : "b");
  2955. return true;
  2956. });
  2957. })
  2958. .Get("/streamed-with-range",
  2959. [&](const Request &req, Response &res) {
  2960. auto data = new std::string("abcdefg");
  2961. res.set_content_provider(
  2962. data->size(), "text/plain",
  2963. [data](size_t offset, size_t length, DataSink &sink) {
  2964. size_t DATA_CHUNK_SIZE = 4;
  2965. const auto &d = *data;
  2966. auto out_len =
  2967. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2968. auto ret =
  2969. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2970. EXPECT_TRUE(ret);
  2971. return true;
  2972. },
  2973. [data, &req](bool success) {
  2974. EXPECT_EQ(success, !req.has_param("error"));
  2975. delete data;
  2976. });
  2977. })
  2978. .Get("/streamed-cancel",
  2979. [&](const Request & /*req*/, Response &res) {
  2980. res.set_content_provider(
  2981. size_t(-1), "text/plain",
  2982. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2983. sink.os << "data_chunk";
  2984. return true;
  2985. });
  2986. })
  2987. .Get("/regex-with-delimiter",
  2988. [&](const Request &req, Response & /*res*/) {
  2989. ASSERT_TRUE(req.has_param("key"));
  2990. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2991. })
  2992. .Get("/with-range",
  2993. [&](const Request & /*req*/, Response &res) {
  2994. res.set_content("abcdefg", "text/plain");
  2995. })
  2996. .Get("/test-start-time",
  2997. [&](const Request &req, Response & /*res*/) {
  2998. EXPECT_NE(req.start_time_,
  2999. std::chrono::steady_clock::time_point::min());
  3000. })
  3001. .Get("/with-range-customized-response",
  3002. [&](const Request & /*req*/, Response &res) {
  3003. res.status = StatusCode::BadRequest_400;
  3004. res.set_content(JSON_DATA, "application/json");
  3005. })
  3006. .Post("/chunked",
  3007. [&](const Request &req, Response & /*res*/) {
  3008. EXPECT_EQ(req.body, "dechunked post body");
  3009. })
  3010. .Post("/large-chunked",
  3011. [&](const Request &req, Response & /*res*/) {
  3012. std::string expected(6 * 30 * 1024u, 'a');
  3013. EXPECT_EQ(req.body, expected);
  3014. })
  3015. .Post("/multipart",
  3016. [&](const Request &req, Response & /*res*/) {
  3017. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3018. req.form.get_field_count("text2") +
  3019. req.form.get_field_count("file3") +
  3020. req.form.get_field_count("file4"));
  3021. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3022. req.form.get_file_count("file2"));
  3023. ASSERT_TRUE(!req.form.has_file("???"));
  3024. ASSERT_TRUE(!req.form.has_field("???"));
  3025. ASSERT_TRUE(req.body.empty());
  3026. {
  3027. const auto &text = req.form.get_field("text1");
  3028. EXPECT_EQ("text default", text);
  3029. }
  3030. {
  3031. const auto &text = req.form.get_field("text2");
  3032. EXPECT_EQ("aωb", text);
  3033. }
  3034. {
  3035. const auto &file = req.form.get_file("file1");
  3036. EXPECT_EQ("hello.txt", file.filename);
  3037. EXPECT_EQ("text/plain", file.content_type);
  3038. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3039. }
  3040. {
  3041. const auto &file = req.form.get_file("file2");
  3042. EXPECT_EQ("world.json", file.filename);
  3043. EXPECT_EQ("application/json", file.content_type);
  3044. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3045. }
  3046. {
  3047. const auto &text = req.form.get_field("file3");
  3048. EXPECT_EQ(0u, text.size());
  3049. }
  3050. {
  3051. const auto &text = req.form.get_field("file4");
  3052. EXPECT_EQ(0u, text.size());
  3053. }
  3054. })
  3055. .Post("/multipart/multi_file_values",
  3056. [&](const Request &req, Response & /*res*/) {
  3057. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3058. req.form.get_field_count("multi_text1"));
  3059. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3060. ASSERT_TRUE(!req.form.has_file("???"));
  3061. ASSERT_TRUE(!req.form.has_field("???"));
  3062. ASSERT_TRUE(req.body.empty());
  3063. {
  3064. const auto &text = req.form.get_field("text");
  3065. EXPECT_EQ("default text", text);
  3066. }
  3067. {
  3068. const auto &text1_values = req.form.get_fields("multi_text1");
  3069. EXPECT_EQ(2u, text1_values.size());
  3070. EXPECT_EQ("aaaaa", text1_values[0]);
  3071. EXPECT_EQ("bbbbb", text1_values[1]);
  3072. }
  3073. {
  3074. const auto &file1_values = req.form.get_files("multi_file1");
  3075. EXPECT_EQ(2u, file1_values.size());
  3076. auto file1 = file1_values[0];
  3077. EXPECT_EQ(file1.filename, "hello.txt");
  3078. EXPECT_EQ(file1.content_type, "text/plain");
  3079. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3080. auto file2 = file1_values[1];
  3081. EXPECT_EQ(file2.filename, "world.json");
  3082. EXPECT_EQ(file2.content_type, "application/json");
  3083. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3084. }
  3085. })
  3086. .Post("/empty",
  3087. [&](const Request &req, Response &res) {
  3088. EXPECT_EQ(req.body, "");
  3089. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3090. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3091. res.set_content("empty", "text/plain");
  3092. })
  3093. .Post("/empty-no-content-type",
  3094. [&](const Request &req, Response &res) {
  3095. EXPECT_EQ(req.body, "");
  3096. EXPECT_FALSE(req.has_header("Content-Type"));
  3097. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3098. res.set_content("empty-no-content-type", "text/plain");
  3099. })
  3100. .Post("/path-only",
  3101. [&](const Request &req, Response &res) {
  3102. EXPECT_EQ(req.body, "");
  3103. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3104. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3105. res.set_content("path-only", "text/plain");
  3106. })
  3107. .Post("/path-headers-only",
  3108. [&](const Request &req, Response &res) {
  3109. EXPECT_EQ(req.body, "");
  3110. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3111. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3112. EXPECT_EQ("world", req.get_header_value("hello"));
  3113. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3114. res.set_content("path-headers-only", "text/plain");
  3115. })
  3116. .Post("/post-large",
  3117. [&](const Request &req, Response &res) {
  3118. EXPECT_EQ(req.body, LARGE_DATA);
  3119. res.set_content(req.body, "text/plain");
  3120. })
  3121. .Post("/post-loopback",
  3122. [&](const Request &, Response &res,
  3123. ContentReader const &content_reader) {
  3124. std::string body;
  3125. content_reader([&](const char *data, size_t data_length) {
  3126. body.append(data, data_length);
  3127. return true;
  3128. });
  3129. res.set_content(body, "text/plain");
  3130. })
  3131. .Put("/put-loopback",
  3132. [&](const Request &, Response &res,
  3133. ContentReader const &content_reader) {
  3134. std::string body;
  3135. content_reader([&](const char *data, size_t data_length) {
  3136. body.append(data, data_length);
  3137. return true;
  3138. });
  3139. res.set_content(body, "text/plain");
  3140. })
  3141. .Patch("/patch-loopback",
  3142. [&](const Request &, Response &res,
  3143. ContentReader const &content_reader) {
  3144. std::string body;
  3145. content_reader([&](const char *data, size_t data_length) {
  3146. body.append(data, data_length);
  3147. return true;
  3148. });
  3149. res.set_content(body, "text/plain");
  3150. })
  3151. .Put("/empty-no-content-type",
  3152. [&](const Request &req, Response &res) {
  3153. EXPECT_EQ(req.body, "");
  3154. EXPECT_FALSE(req.has_header("Content-Type"));
  3155. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3156. res.set_content("empty-no-content-type", "text/plain");
  3157. })
  3158. .Put("/put",
  3159. [&](const Request &req, Response &res) {
  3160. EXPECT_EQ(req.body, "PUT");
  3161. res.set_content(req.body, "text/plain");
  3162. })
  3163. .Put("/put-large",
  3164. [&](const Request &req, Response &res) {
  3165. EXPECT_EQ(req.body, LARGE_DATA);
  3166. res.set_content(req.body, "text/plain");
  3167. })
  3168. .Patch("/patch",
  3169. [&](const Request &req, Response &res) {
  3170. EXPECT_EQ(req.body, "PATCH");
  3171. res.set_content(req.body, "text/plain");
  3172. })
  3173. .Delete("/delete",
  3174. [&](const Request & /*req*/, Response &res) {
  3175. res.set_content("DELETE", "text/plain");
  3176. })
  3177. .Delete("/delete-body",
  3178. [&](const Request &req, Response &res) {
  3179. EXPECT_EQ(req.body, "content");
  3180. res.set_content(req.body, "text/plain");
  3181. })
  3182. .Options(R"(\*)",
  3183. [&](const Request & /*req*/, Response &res) {
  3184. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3185. })
  3186. .Get("/request-target",
  3187. [&](const Request &req, Response & /*res*/) {
  3188. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3189. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3190. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3191. })
  3192. .Get("/long-query-value",
  3193. [&](const Request &req, Response & /*res*/) {
  3194. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3195. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3196. })
  3197. .Get("/too-long-query-value",
  3198. [&](const Request &req, Response & /*res*/) {
  3199. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3200. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3201. })
  3202. .Get("/array-param",
  3203. [&](const Request &req, Response & /*res*/) {
  3204. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3205. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3206. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3207. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3208. })
  3209. .Post("/validate-no-multiple-headers",
  3210. [&](const Request &req, Response & /*res*/) {
  3211. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3212. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3213. })
  3214. .Post("/content_receiver",
  3215. [&](const Request &req, Response &res,
  3216. const ContentReader &content_reader) {
  3217. if (req.is_multipart_form_data()) {
  3218. std::vector<FormData> items;
  3219. content_reader(
  3220. [&](const FormData &file) {
  3221. items.push_back(file);
  3222. return true;
  3223. },
  3224. [&](const char *data, size_t data_length) {
  3225. items.back().content.append(data, data_length);
  3226. return true;
  3227. });
  3228. EXPECT_EQ(5u, items.size());
  3229. {
  3230. const auto &file = get_file_value(items, "text1");
  3231. EXPECT_TRUE(file.filename.empty());
  3232. EXPECT_EQ("text default", file.content);
  3233. }
  3234. {
  3235. const auto &file = get_file_value(items, "text2");
  3236. EXPECT_TRUE(file.filename.empty());
  3237. EXPECT_EQ("aωb", file.content);
  3238. }
  3239. {
  3240. const auto &file = get_file_value(items, "file1");
  3241. EXPECT_EQ("hello.txt", file.filename);
  3242. EXPECT_EQ("text/plain", file.content_type);
  3243. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3244. }
  3245. {
  3246. const auto &file = get_file_value(items, "file2");
  3247. EXPECT_EQ("world.json", file.filename);
  3248. EXPECT_EQ("application/json", file.content_type);
  3249. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3250. }
  3251. {
  3252. const auto &file = get_file_value(items, "file3");
  3253. EXPECT_TRUE(file.filename.empty());
  3254. EXPECT_EQ("application/octet-stream", file.content_type);
  3255. EXPECT_EQ(0u, file.content.size());
  3256. }
  3257. } else {
  3258. std::string body;
  3259. content_reader([&](const char *data, size_t data_length) {
  3260. EXPECT_EQ(7U, data_length);
  3261. body.append(data, data_length);
  3262. return true;
  3263. });
  3264. EXPECT_EQ(body, "content");
  3265. res.set_content(body, "text/plain");
  3266. }
  3267. })
  3268. .Put("/content_receiver",
  3269. [&](const Request & /*req*/, Response &res,
  3270. const ContentReader &content_reader) {
  3271. std::string body;
  3272. content_reader([&](const char *data, size_t data_length) {
  3273. body.append(data, data_length);
  3274. return true;
  3275. });
  3276. EXPECT_EQ(body, "content");
  3277. res.set_content(body, "text/plain");
  3278. })
  3279. .Patch("/content_receiver",
  3280. [&](const Request & /*req*/, Response &res,
  3281. const ContentReader &content_reader) {
  3282. std::string body;
  3283. content_reader([&](const char *data, size_t data_length) {
  3284. body.append(data, data_length);
  3285. return true;
  3286. });
  3287. EXPECT_EQ(body, "content");
  3288. res.set_content(body, "text/plain");
  3289. })
  3290. .Post("/query-string-and-body",
  3291. [&](const Request &req, Response & /*res*/) {
  3292. ASSERT_TRUE(req.has_param("key"));
  3293. EXPECT_EQ(req.get_param_value("key"), "value");
  3294. EXPECT_EQ(req.body, "content");
  3295. })
  3296. .Get("/last-request",
  3297. [&](const Request &req, Response & /*res*/) {
  3298. EXPECT_EQ("close", req.get_header_value("Connection"));
  3299. })
  3300. .Get(R"(/redirect/(\d+))",
  3301. [&](const Request &req, Response &res) {
  3302. auto num = std::stoi(req.matches[1]) + 1;
  3303. std::string url = "/redirect/" + std::to_string(num);
  3304. res.set_redirect(url);
  3305. })
  3306. .Post("/binary",
  3307. [&](const Request &req, Response &res) {
  3308. EXPECT_EQ(4U, req.body.size());
  3309. EXPECT_EQ("application/octet-stream",
  3310. req.get_header_value("Content-Type"));
  3311. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3312. res.set_content(req.body, "application/octet-stream");
  3313. })
  3314. .Put("/binary",
  3315. [&](const Request &req, Response &res) {
  3316. EXPECT_EQ(4U, req.body.size());
  3317. EXPECT_EQ("application/octet-stream",
  3318. req.get_header_value("Content-Type"));
  3319. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3320. res.set_content(req.body, "application/octet-stream");
  3321. })
  3322. .Patch("/binary",
  3323. [&](const Request &req, Response &res) {
  3324. EXPECT_EQ(4U, req.body.size());
  3325. EXPECT_EQ("application/octet-stream",
  3326. req.get_header_value("Content-Type"));
  3327. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3328. res.set_content(req.body, "application/octet-stream");
  3329. })
  3330. .Delete("/binary",
  3331. [&](const Request &req, Response &res) {
  3332. EXPECT_EQ(4U, req.body.size());
  3333. EXPECT_EQ("application/octet-stream",
  3334. req.get_header_value("Content-Type"));
  3335. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3336. res.set_content(req.body, "application/octet-stream");
  3337. })
  3338. .Get("/issue1772",
  3339. [&](const Request & /*req*/, Response &res) {
  3340. res.status = 401;
  3341. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3342. })
  3343. .Delete("/issue609",
  3344. [](const httplib::Request &, httplib::Response &res,
  3345. const httplib::ContentReader &) {
  3346. res.set_content("ok", "text/plain");
  3347. })
  3348. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3349. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3350. .Get("/compress",
  3351. [&](const Request & /*req*/, Response &res) {
  3352. res.set_content(
  3353. "12345678901234567890123456789012345678901234567890123456789"
  3354. "01234567890123456789012345678901234567890",
  3355. "text/plain");
  3356. })
  3357. .Get("/compress-with-charset",
  3358. [&](const Request & /*req*/, Response &res) {
  3359. res.set_content(
  3360. "12345678901234567890123456789012345678901234567890123456789"
  3361. "01234567890123456789012345678901234567890",
  3362. "application/json; charset=utf-8");
  3363. })
  3364. .Get("/nocompress",
  3365. [&](const Request & /*req*/, Response &res) {
  3366. res.set_content(
  3367. "12345678901234567890123456789012345678901234567890123456789"
  3368. "01234567890123456789012345678901234567890",
  3369. "application/octet-stream");
  3370. })
  3371. .Post("/compress-multipart",
  3372. [&](const Request &req, Response & /*res*/) {
  3373. EXPECT_EQ(2u, req.form.fields.size());
  3374. ASSERT_TRUE(!req.form.has_field("???"));
  3375. {
  3376. const auto &text = req.form.get_field("key1");
  3377. EXPECT_EQ("test", text);
  3378. }
  3379. {
  3380. const auto &text = req.form.get_field("key2");
  3381. EXPECT_EQ("--abcdefg123", text);
  3382. }
  3383. })
  3384. #endif
  3385. ;
  3386. persons_["john"] = "programmer";
  3387. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3388. svr_.wait_until_ready();
  3389. }
  3390. virtual void TearDown() {
  3391. svr_.stop();
  3392. if (!request_threads_.empty()) {
  3393. std::this_thread::sleep_for(std::chrono::seconds(1));
  3394. for (auto &t : request_threads_) {
  3395. t.join();
  3396. }
  3397. }
  3398. t_.join();
  3399. }
  3400. map<string, string> persons_;
  3401. #ifdef CPPHTTPLIB_SSL_ENABLED
  3402. SSLClient cli_;
  3403. SSLServer svr_;
  3404. #else
  3405. Client cli_;
  3406. Server svr_;
  3407. #endif
  3408. thread t_;
  3409. std::vector<thread> request_threads_;
  3410. };
  3411. TEST_F(ServerTest, GetMethod200) {
  3412. auto res = cli_.Get("/hi");
  3413. ASSERT_TRUE(res);
  3414. EXPECT_EQ("HTTP/1.1", res->version);
  3415. EXPECT_EQ(StatusCode::OK_200, res->status);
  3416. EXPECT_EQ("OK", res->reason);
  3417. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3418. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3419. EXPECT_EQ("Hello World!", res->body);
  3420. }
  3421. TEST_F(ServerTest, GetEmptyFile) {
  3422. auto res = cli_.Get("/empty_file");
  3423. ASSERT_TRUE(res);
  3424. EXPECT_EQ(StatusCode::OK_200, res->status);
  3425. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3426. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3427. EXPECT_EQ("", res->body);
  3428. }
  3429. TEST_F(ServerTest, GetFileContent) {
  3430. auto res = cli_.Get("/file_content");
  3431. ASSERT_TRUE(res);
  3432. EXPECT_EQ(StatusCode::OK_200, res->status);
  3433. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3434. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3435. EXPECT_EQ("test.html", res->body);
  3436. }
  3437. TEST_F(ServerTest, GetFileContentWithRange) {
  3438. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3439. ASSERT_TRUE(res);
  3440. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3441. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3442. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3443. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3444. EXPECT_EQ("est", res->body);
  3445. }
  3446. TEST_F(ServerTest, GetFileContentWithContentType) {
  3447. auto res = cli_.Get("/file_content_with_content_type");
  3448. ASSERT_TRUE(res);
  3449. EXPECT_EQ(StatusCode::OK_200, res->status);
  3450. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3451. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3452. EXPECT_EQ("file\n", res->body);
  3453. }
  3454. TEST_F(ServerTest, GetInvalidFileContent) {
  3455. auto res = cli_.Get("/invalid_file_content");
  3456. ASSERT_TRUE(res);
  3457. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3458. }
  3459. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3460. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3461. ASSERT_TRUE(res);
  3462. EXPECT_EQ("HTTP/1.1", res->version);
  3463. EXPECT_EQ(StatusCode::OK_200, res->status);
  3464. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3465. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3466. EXPECT_EQ("Hello World!", res->body);
  3467. }
  3468. TEST_F(ServerTest, GetMethod302) {
  3469. auto res = cli_.Get("/");
  3470. ASSERT_TRUE(res);
  3471. EXPECT_EQ(StatusCode::Found_302, res->status);
  3472. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3473. }
  3474. TEST_F(ServerTest, GetMethod302Redirect) {
  3475. cli_.set_follow_location(true);
  3476. auto res = cli_.Get("/");
  3477. ASSERT_TRUE(res);
  3478. EXPECT_EQ(StatusCode::OK_200, res->status);
  3479. EXPECT_EQ("Hello World!", res->body);
  3480. EXPECT_EQ("/hi", res->location);
  3481. }
  3482. TEST_F(ServerTest, GetMethod404) {
  3483. auto res = cli_.Get("/invalid");
  3484. ASSERT_TRUE(res);
  3485. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3486. }
  3487. TEST_F(ServerTest, HeadMethod200) {
  3488. auto res = cli_.Head("/hi");
  3489. ASSERT_TRUE(res);
  3490. EXPECT_EQ(StatusCode::OK_200, res->status);
  3491. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3492. EXPECT_TRUE(res->body.empty());
  3493. }
  3494. TEST_F(ServerTest, HeadMethod200Static) {
  3495. auto res = cli_.Head("/mount/dir/index.html");
  3496. ASSERT_TRUE(res);
  3497. EXPECT_EQ(StatusCode::OK_200, res->status);
  3498. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3499. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3500. EXPECT_TRUE(res->body.empty());
  3501. }
  3502. TEST_F(ServerTest, HeadMethod404) {
  3503. auto res = cli_.Head("/invalid");
  3504. ASSERT_TRUE(res);
  3505. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3506. EXPECT_TRUE(res->body.empty());
  3507. }
  3508. TEST_F(ServerTest, GetMethodPersonJohn) {
  3509. auto res = cli_.Get("/person/john");
  3510. ASSERT_TRUE(res);
  3511. EXPECT_EQ(StatusCode::OK_200, res->status);
  3512. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3513. EXPECT_EQ("programmer", res->body);
  3514. }
  3515. TEST_F(ServerTest, PostMethod1) {
  3516. auto res = cli_.Get("/person/john1");
  3517. ASSERT_TRUE(res);
  3518. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3519. res = cli_.Post("/person", "name=john1&note=coder",
  3520. "application/x-www-form-urlencoded");
  3521. ASSERT_TRUE(res);
  3522. ASSERT_EQ(StatusCode::OK_200, res->status);
  3523. res = cli_.Get("/person/john1");
  3524. ASSERT_TRUE(res);
  3525. ASSERT_EQ(StatusCode::OK_200, res->status);
  3526. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3527. ASSERT_EQ("coder", res->body);
  3528. }
  3529. TEST_F(ServerTest, PostMethod2) {
  3530. auto res = cli_.Get("/person/john2");
  3531. ASSERT_TRUE(res);
  3532. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3533. Params params;
  3534. params.emplace("name", "john2");
  3535. params.emplace("note", "coder");
  3536. res = cli_.Post("/person", params);
  3537. ASSERT_TRUE(res);
  3538. ASSERT_EQ(StatusCode::OK_200, res->status);
  3539. res = cli_.Get("/person/john2");
  3540. ASSERT_TRUE(res);
  3541. ASSERT_EQ(StatusCode::OK_200, res->status);
  3542. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3543. ASSERT_EQ("coder", res->body);
  3544. }
  3545. TEST_F(ServerTest, PutMethod3) {
  3546. auto res = cli_.Get("/person/john3");
  3547. ASSERT_TRUE(res);
  3548. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3549. Params params;
  3550. params.emplace("name", "john3");
  3551. params.emplace("note", "coder");
  3552. res = cli_.Put("/person", params);
  3553. ASSERT_TRUE(res);
  3554. ASSERT_EQ(StatusCode::OK_200, res->status);
  3555. res = cli_.Get("/person/john3");
  3556. ASSERT_TRUE(res);
  3557. ASSERT_EQ(StatusCode::OK_200, res->status);
  3558. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3559. ASSERT_EQ("coder", res->body);
  3560. }
  3561. TEST_F(ServerTest, DeleteMethod1) {
  3562. auto res = cli_.Get("/person/john4");
  3563. ASSERT_TRUE(res);
  3564. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3565. Params params;
  3566. params.emplace("name", "john4");
  3567. params.emplace("note", "coder");
  3568. res = cli_.Post("/person", params);
  3569. ASSERT_TRUE(res);
  3570. ASSERT_EQ(StatusCode::OK_200, res->status);
  3571. res = cli_.Get("/person/john4");
  3572. ASSERT_TRUE(res);
  3573. ASSERT_EQ(StatusCode::OK_200, res->status);
  3574. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3575. ASSERT_EQ("coder", res->body);
  3576. Params delete_params;
  3577. delete_params.emplace("name", "john4");
  3578. res = cli_.Delete("/person", delete_params);
  3579. ASSERT_TRUE(res);
  3580. ASSERT_EQ(StatusCode::OK_200, res->status);
  3581. ASSERT_EQ("DELETED", res->body);
  3582. res = cli_.Get("/person/john4");
  3583. ASSERT_TRUE(res);
  3584. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3585. }
  3586. TEST_F(ServerTest, DeleteMethod2) {
  3587. auto res = cli_.Get("/person/john5");
  3588. ASSERT_TRUE(res);
  3589. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3590. Params params;
  3591. params.emplace("name", "john5");
  3592. params.emplace("note", "developer");
  3593. res = cli_.Post("/person", params);
  3594. ASSERT_TRUE(res);
  3595. ASSERT_EQ(StatusCode::OK_200, res->status);
  3596. res = cli_.Get("/person/john5");
  3597. ASSERT_TRUE(res);
  3598. ASSERT_EQ(StatusCode::OK_200, res->status);
  3599. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3600. ASSERT_EQ("developer", res->body);
  3601. Params delete_params;
  3602. delete_params.emplace("name", "john5");
  3603. Headers headers;
  3604. headers.emplace("Custom-Header", "test-value");
  3605. res = cli_.Delete("/person", headers, delete_params);
  3606. ASSERT_TRUE(res);
  3607. ASSERT_EQ(StatusCode::OK_200, res->status);
  3608. ASSERT_EQ("DELETED", res->body);
  3609. res = cli_.Get("/person/john5");
  3610. ASSERT_TRUE(res);
  3611. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3612. }
  3613. TEST_F(ServerTest, DeleteMethod3) {
  3614. auto res = cli_.Get("/person/john6");
  3615. ASSERT_TRUE(res);
  3616. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3617. Params params;
  3618. params.emplace("name", "john6");
  3619. params.emplace("note", "tester");
  3620. res = cli_.Post("/person", params);
  3621. ASSERT_TRUE(res);
  3622. ASSERT_EQ(StatusCode::OK_200, res->status);
  3623. res = cli_.Get("/person/john6");
  3624. ASSERT_TRUE(res);
  3625. ASSERT_EQ(StatusCode::OK_200, res->status);
  3626. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3627. ASSERT_EQ("tester", res->body);
  3628. Params delete_params;
  3629. delete_params.emplace("name", "john6");
  3630. Headers headers;
  3631. headers.emplace("Custom-Header", "test-value");
  3632. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3633. ASSERT_TRUE(res);
  3634. ASSERT_EQ(StatusCode::OK_200, res->status);
  3635. ASSERT_EQ("DELETED", res->body);
  3636. res = cli_.Get("/person/john6");
  3637. ASSERT_TRUE(res);
  3638. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3639. }
  3640. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3641. Params params;
  3642. params.emplace("json", JSON_DATA);
  3643. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3644. ASSERT_TRUE(res);
  3645. ASSERT_EQ(StatusCode::OK_200, res->status);
  3646. ASSERT_EQ(JSON_DATA, res->body);
  3647. }
  3648. TEST_F(ServerTest, PostEmptyContent) {
  3649. auto res = cli_.Post("/empty", "", "text/plain");
  3650. ASSERT_TRUE(res);
  3651. ASSERT_EQ(StatusCode::OK_200, res->status);
  3652. ASSERT_EQ("empty", res->body);
  3653. }
  3654. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3655. auto res = cli_.Post("/empty-no-content-type");
  3656. ASSERT_TRUE(res);
  3657. ASSERT_EQ(StatusCode::OK_200, res->status);
  3658. ASSERT_EQ("empty-no-content-type", res->body);
  3659. }
  3660. TEST_F(ServerTest, PostPathOnly) {
  3661. auto res = cli_.Post("/path-only");
  3662. ASSERT_TRUE(res);
  3663. ASSERT_EQ(StatusCode::OK_200, res->status);
  3664. ASSERT_EQ("path-only", res->body);
  3665. }
  3666. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3667. auto res = cli_.Post("/path-headers-only",
  3668. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3669. ASSERT_TRUE(res);
  3670. ASSERT_EQ(StatusCode::OK_200, res->status);
  3671. ASSERT_EQ("path-headers-only", res->body);
  3672. }
  3673. TEST_F(ServerTest, PostLarge) {
  3674. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3675. ASSERT_TRUE(res);
  3676. ASSERT_EQ(StatusCode::OK_200, res->status);
  3677. EXPECT_EQ(LARGE_DATA, res->body);
  3678. }
  3679. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3680. auto res = cli_.Put("/empty-no-content-type");
  3681. ASSERT_TRUE(res);
  3682. ASSERT_EQ(StatusCode::OK_200, res->status);
  3683. ASSERT_EQ("empty-no-content-type", res->body);
  3684. }
  3685. TEST_F(ServerTest, GetMethodDir) {
  3686. auto res = cli_.Get("/dir/");
  3687. ASSERT_TRUE(res);
  3688. EXPECT_EQ(StatusCode::OK_200, res->status);
  3689. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3690. auto body = R"(<html>
  3691. <head>
  3692. </head>
  3693. <body>
  3694. <a href="/dir/test.html">Test</a>
  3695. <a href="/hi">hi</a>
  3696. </body>
  3697. </html>
  3698. )";
  3699. EXPECT_EQ(body, res->body);
  3700. }
  3701. TEST_F(ServerTest, GetMethodDirTest) {
  3702. auto res = cli_.Get("/dir/test.html");
  3703. ASSERT_TRUE(res);
  3704. EXPECT_EQ(StatusCode::OK_200, res->status);
  3705. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3706. EXPECT_EQ("test.html", res->body);
  3707. }
  3708. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3709. auto res = cli_.Get("/dir/../dir/test.html");
  3710. ASSERT_TRUE(res);
  3711. EXPECT_EQ(StatusCode::OK_200, res->status);
  3712. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3713. EXPECT_EQ("test.html", res->body);
  3714. }
  3715. TEST_F(ServerTest, GetMethodInvalidPath) {
  3716. auto res = cli_.Get("/dir/../test.html");
  3717. ASSERT_TRUE(res);
  3718. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3719. }
  3720. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3721. auto res = cli_.Get("/../www/dir/test.html");
  3722. ASSERT_TRUE(res);
  3723. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3724. }
  3725. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3726. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3727. ASSERT_TRUE(res);
  3728. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3729. }
  3730. TEST_F(ServerTest, GetMethodDirMountTest) {
  3731. auto res = cli_.Get("/mount/dir/test.html");
  3732. ASSERT_TRUE(res);
  3733. EXPECT_EQ(StatusCode::OK_200, res->status);
  3734. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3735. EXPECT_EQ("test.html", res->body);
  3736. }
  3737. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3738. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3739. ASSERT_TRUE(res);
  3740. EXPECT_EQ(StatusCode::OK_200, res->status);
  3741. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3742. EXPECT_EQ("test.html", res->body);
  3743. }
  3744. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3745. auto res = cli_.Get("/mount/dir/../test.html");
  3746. ASSERT_TRUE(res);
  3747. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3748. }
  3749. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3750. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3751. ASSERT_TRUE(res);
  3752. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3753. }
  3754. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3755. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3756. ASSERT_TRUE(res);
  3757. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3758. }
  3759. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3760. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3761. ASSERT_TRUE(res);
  3762. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3763. }
  3764. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3765. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3766. ASSERT_TRUE(res);
  3767. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3768. }
  3769. TEST_F(ServerTest, PostMethod303) {
  3770. auto res = cli_.Post("/1", "body", "text/plain");
  3771. ASSERT_TRUE(res);
  3772. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3773. EXPECT_EQ("/2", res->get_header_value("Location"));
  3774. }
  3775. TEST_F(ServerTest, PostMethod303Redirect) {
  3776. cli_.set_follow_location(true);
  3777. auto res = cli_.Post("/1", "body", "text/plain");
  3778. ASSERT_TRUE(res);
  3779. EXPECT_EQ(StatusCode::OK_200, res->status);
  3780. EXPECT_EQ("redirected.", res->body);
  3781. EXPECT_EQ("/2", res->location);
  3782. }
  3783. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3784. auto res = cli_.Get("/dir/test.abcde");
  3785. ASSERT_TRUE(res);
  3786. EXPECT_EQ(StatusCode::OK_200, res->status);
  3787. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3788. EXPECT_EQ("abcde", res->body);
  3789. }
  3790. TEST_F(ServerTest, StaticFileRange) {
  3791. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3792. ASSERT_TRUE(res);
  3793. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3794. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3795. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3796. EXPECT_EQ(true, res->has_header("Content-Range"));
  3797. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3798. EXPECT_EQ(std::string("cd"), res->body);
  3799. }
  3800. TEST_F(ServerTest, StaticFileRanges) {
  3801. auto res =
  3802. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3803. ASSERT_TRUE(res);
  3804. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3805. EXPECT_TRUE(
  3806. res->get_header_value("Content-Type")
  3807. .find(
  3808. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3809. 0);
  3810. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3811. }
  3812. TEST_F(ServerTest, StaticFileRangeHead) {
  3813. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3814. ASSERT_TRUE(res);
  3815. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3816. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3817. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3818. EXPECT_EQ(true, res->has_header("Content-Range"));
  3819. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3820. }
  3821. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3822. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3823. ASSERT_TRUE(res);
  3824. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3825. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3826. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3827. EXPECT_EQ(true, res->has_header("Content-Range"));
  3828. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3829. res->get_header_value("Content-Range"));
  3830. EXPECT_EQ("LAST\n", res->body);
  3831. }
  3832. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3833. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3834. ASSERT_TRUE(res);
  3835. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3836. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3837. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3838. EXPECT_EQ(true, res->has_header("Content-Range"));
  3839. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3840. }
  3841. TEST_F(ServerTest, StaticFileBigFile) {
  3842. auto res = cli_.Get("/dir/1MB.txt");
  3843. ASSERT_TRUE(res);
  3844. EXPECT_EQ(StatusCode::OK_200, res->status);
  3845. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3846. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3847. }
  3848. TEST_F(ServerTest, InvalidBaseDirMount) {
  3849. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3850. }
  3851. TEST_F(ServerTest, Binary) {
  3852. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3853. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3854. "application/octet-stream");
  3855. ASSERT_TRUE(res);
  3856. ASSERT_EQ(StatusCode::OK_200, res->status);
  3857. ASSERT_EQ(4U, res->body.size());
  3858. res = cli_.Put("/binary", binary.data(), binary.size(),
  3859. "application/octet-stream");
  3860. ASSERT_TRUE(res);
  3861. ASSERT_EQ(StatusCode::OK_200, res->status);
  3862. ASSERT_EQ(4U, res->body.size());
  3863. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3864. "application/octet-stream");
  3865. ASSERT_TRUE(res);
  3866. ASSERT_EQ(StatusCode::OK_200, res->status);
  3867. ASSERT_EQ(4U, res->body.size());
  3868. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3869. "application/octet-stream");
  3870. ASSERT_TRUE(res);
  3871. ASSERT_EQ(StatusCode::OK_200, res->status);
  3872. ASSERT_EQ(4U, res->body.size());
  3873. }
  3874. TEST_F(ServerTest, BinaryString) {
  3875. auto binary = std::string("\x00\x01\x02\x03", 4);
  3876. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3877. ASSERT_TRUE(res);
  3878. ASSERT_EQ(StatusCode::OK_200, res->status);
  3879. ASSERT_EQ(4U, res->body.size());
  3880. res = cli_.Put("/binary", binary, "application/octet-stream");
  3881. ASSERT_TRUE(res);
  3882. ASSERT_EQ(StatusCode::OK_200, res->status);
  3883. ASSERT_EQ(4U, res->body.size());
  3884. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3885. ASSERT_TRUE(res);
  3886. ASSERT_EQ(StatusCode::OK_200, res->status);
  3887. ASSERT_EQ(4U, res->body.size());
  3888. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3889. ASSERT_TRUE(res);
  3890. ASSERT_EQ(StatusCode::OK_200, res->status);
  3891. ASSERT_EQ(4U, res->body.size());
  3892. }
  3893. TEST_F(ServerTest, EmptyRequest) {
  3894. auto res = cli_.Get("");
  3895. ASSERT_TRUE(!res);
  3896. EXPECT_EQ(Error::Connection, res.error());
  3897. }
  3898. TEST_F(ServerTest, LongRequest) {
  3899. std::string request;
  3900. for (size_t i = 0; i < 545; i++) {
  3901. request += "/TooLongRequest";
  3902. }
  3903. request += "OK";
  3904. auto res = cli_.Get(request.c_str());
  3905. ASSERT_TRUE(res);
  3906. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3907. }
  3908. TEST_F(ServerTest, TooLongRequest) {
  3909. std::string request;
  3910. for (size_t i = 0; i < 546; i++) {
  3911. request += "/TooLongRequest";
  3912. }
  3913. request += "_NG";
  3914. auto start = std::chrono::high_resolution_clock::now();
  3915. cli_.set_keep_alive(true);
  3916. auto res = cli_.Get(request.c_str());
  3917. auto end = std::chrono::high_resolution_clock::now();
  3918. auto elapsed =
  3919. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3920. .count();
  3921. ASSERT_TRUE(res);
  3922. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3923. EXPECT_LE(elapsed, 1000);
  3924. EXPECT_EQ("close", res->get_header_value("Connection"));
  3925. EXPECT_FALSE(cli_.is_socket_open());
  3926. }
  3927. TEST_F(ServerTest, AlmostTooLongRequest) {
  3928. // test for #2046 - URI length check shouldn't include other content on req
  3929. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3930. // leading /, space, HTTP/1.1)
  3931. std::string request =
  3932. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3933. auto res = cli_.Get(request.c_str());
  3934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3935. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3936. }
  3937. TEST_F(ServerTest, LongHeader) {
  3938. Request req;
  3939. req.method = "GET";
  3940. req.path = "/hi";
  3941. std::string host_and_port;
  3942. host_and_port += HOST;
  3943. host_and_port += ":";
  3944. host_and_port += std::to_string(PORT);
  3945. req.headers.emplace("Host", host_and_port.c_str());
  3946. req.headers.emplace("Accept", "*/*");
  3947. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3948. req.headers.emplace(
  3949. "Header-Name",
  3950. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  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. auto res = std::make_shared<Response>();
  3980. auto error = Error::Success;
  3981. auto ret = cli_.send(req, *res, error);
  3982. ASSERT_TRUE(ret);
  3983. EXPECT_EQ(StatusCode::OK_200, res->status);
  3984. }
  3985. TEST_F(ServerTest, LongQueryValue) {
  3986. auto start = std::chrono::high_resolution_clock::now();
  3987. cli_.set_keep_alive(true);
  3988. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3989. auto end = std::chrono::high_resolution_clock::now();
  3990. auto elapsed =
  3991. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3992. .count();
  3993. ASSERT_TRUE(res);
  3994. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3995. EXPECT_LE(elapsed, 1000);
  3996. EXPECT_EQ("close", res->get_header_value("Connection"));
  3997. EXPECT_FALSE(cli_.is_socket_open());
  3998. }
  3999. TEST_F(ServerTest, TooLongQueryValue) {
  4000. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4001. ASSERT_FALSE(res);
  4002. EXPECT_EQ(Error::Read, res.error());
  4003. }
  4004. TEST_F(ServerTest, TooLongHeader) {
  4005. Request req;
  4006. req.method = "GET";
  4007. req.path = "/hi";
  4008. std::string host_and_port;
  4009. host_and_port += HOST;
  4010. host_and_port += ":";
  4011. host_and_port += std::to_string(PORT);
  4012. req.headers.emplace("Host", host_and_port.c_str());
  4013. req.headers.emplace("Accept", "*/*");
  4014. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4015. req.headers.emplace(
  4016. "Header-Name",
  4017. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4018. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4019. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4020. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4021. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4022. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4023. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4024. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4025. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4026. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4027. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4028. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4029. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4030. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4031. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4032. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4033. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4034. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4035. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4036. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4037. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4038. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4039. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4040. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4041. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4042. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4043. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4044. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4045. "@@@@@@@@@@@@@@@@@");
  4046. auto res = std::make_shared<Response>();
  4047. auto error = Error::Success;
  4048. auto ret = cli_.send(req, *res, error);
  4049. ASSERT_TRUE(ret);
  4050. EXPECT_EQ(StatusCode::OK_200, res->status);
  4051. }
  4052. TEST_F(ServerTest, HeaderCountAtLimit) {
  4053. // Test with headers just under the 100 limit
  4054. httplib::Headers headers;
  4055. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4056. // This should keep us just under the 100 header limit
  4057. for (int i = 0; i < 95; i++) {
  4058. std::string name = "X-Test-Header-" + std::to_string(i);
  4059. std::string value = "value" + std::to_string(i);
  4060. headers.emplace(name, value);
  4061. }
  4062. // This should work fine as we're under the limit
  4063. auto res = cli_.Get("/hi", headers);
  4064. EXPECT_TRUE(res);
  4065. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4066. }
  4067. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4068. // Test with many headers to exceed the 100 limit
  4069. httplib::Headers headers;
  4070. // Add 150 headers to definitely exceed the 100 limit
  4071. for (int i = 0; i < 150; i++) {
  4072. std::string name = "X-Test-Header-" + std::to_string(i);
  4073. std::string value = "value" + std::to_string(i);
  4074. headers.emplace(name, value);
  4075. }
  4076. // This should fail due to exceeding header count limit
  4077. cli_.set_keep_alive(true);
  4078. auto res = cli_.Get("/hi", headers);
  4079. // The server should respond with 400 Bad Request
  4080. ASSERT_TRUE(res);
  4081. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4082. EXPECT_EQ("close", res->get_header_value("Connection"));
  4083. EXPECT_FALSE(cli_.is_socket_open());
  4084. }
  4085. TEST_F(ServerTest, PercentEncoding) {
  4086. auto res = cli_.Get("/e%6edwith%");
  4087. ASSERT_TRUE(res);
  4088. EXPECT_EQ(StatusCode::OK_200, res->status);
  4089. }
  4090. TEST_F(ServerTest, PercentEncodingUnicode) {
  4091. auto res = cli_.Get("/e%u006edwith%");
  4092. ASSERT_TRUE(res);
  4093. EXPECT_EQ(StatusCode::OK_200, res->status);
  4094. }
  4095. TEST_F(ServerTest, InvalidPercentEncoding) {
  4096. auto res = cli_.Get("/%endwith%");
  4097. ASSERT_TRUE(res);
  4098. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4099. }
  4100. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4101. auto res = cli_.Get("/%uendwith%");
  4102. ASSERT_TRUE(res);
  4103. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4104. }
  4105. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4106. auto res = cli_.Get("/hello?aaa=bbb%");
  4107. ASSERT_TRUE(res);
  4108. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4109. }
  4110. TEST_F(ServerTest, PlusSignEncoding) {
  4111. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4112. ASSERT_TRUE(res);
  4113. EXPECT_EQ(StatusCode::OK_200, res->status);
  4114. EXPECT_EQ("a +b", res->body);
  4115. }
  4116. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4117. // This test simulates a potential DoS attack using many headers
  4118. // to verify our security fix prevents memory exhaustion
  4119. httplib::Headers attack_headers;
  4120. // Attempt to add many headers like an attacker would (200 headers to far
  4121. // exceed limit)
  4122. for (int i = 0; i < 200; i++) {
  4123. std::string name = "X-Attack-Header-" + std::to_string(i);
  4124. std::string value = "attack_payload_" + std::to_string(i);
  4125. attack_headers.emplace(name, value);
  4126. }
  4127. // Try to POST with excessive headers
  4128. cli_.set_keep_alive(true);
  4129. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4130. // Should either fail or return 400 Bad Request due to security limit
  4131. if (res) {
  4132. // If we get a response, it should be 400 Bad Request
  4133. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4134. EXPECT_EQ("close", res->get_header_value("Connection"));
  4135. }
  4136. EXPECT_FALSE(cli_.is_socket_open());
  4137. }
  4138. TEST_F(ServerTest, MultipartFormData) {
  4139. UploadFormDataItems items = {
  4140. {"text1", "text default", "", ""},
  4141. {"text2", "aωb", "", ""},
  4142. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4143. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4144. {"file3", "", "", "application/octet-stream"},
  4145. {"file4", "", "", " application/json tmp-string "}};
  4146. auto res = cli_.Post("/multipart", items);
  4147. ASSERT_TRUE(res);
  4148. EXPECT_EQ(StatusCode::OK_200, res->status);
  4149. }
  4150. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4151. UploadFormDataItems items = {
  4152. {"text", "default text", "", ""},
  4153. {"multi_text1", "aaaaa", "", ""},
  4154. {"multi_text1", "bbbbb", "", ""},
  4155. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4156. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4157. "application/json"},
  4158. };
  4159. auto res = cli_.Post("/multipart/multi_file_values", items);
  4160. ASSERT_TRUE(res);
  4161. EXPECT_EQ(StatusCode::OK_200, res->status);
  4162. }
  4163. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4164. auto res = cli_.Get("/hi");
  4165. ASSERT_TRUE(res);
  4166. EXPECT_EQ(StatusCode::OK_200, res->status);
  4167. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4168. EXPECT_EQ("Hello World!", res->body);
  4169. }
  4170. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4171. Request req;
  4172. req.method = "POST";
  4173. req.path = "/chunked";
  4174. std::string host_and_port;
  4175. host_and_port += HOST;
  4176. host_and_port += ":";
  4177. host_and_port += std::to_string(PORT);
  4178. req.headers.emplace("Host", host_and_port.c_str());
  4179. req.headers.emplace("Accept", "*/*");
  4180. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4181. req.headers.emplace("Content-Type", "text/plain");
  4182. req.headers.emplace("Content-Length", "0");
  4183. req.headers.emplace(
  4184. "Transfer-Encoding",
  4185. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4186. // Client does not chunk, so make a chunked body manually.
  4187. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4188. auto res = std::make_shared<Response>();
  4189. auto error = Error::Success;
  4190. auto ret = cli_.send(req, *res, error);
  4191. ASSERT_TRUE(ret);
  4192. EXPECT_EQ(StatusCode::OK_200, res->status);
  4193. }
  4194. TEST_F(ServerTest, GetStreamed2) {
  4195. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4196. ASSERT_TRUE(res);
  4197. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4198. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4199. EXPECT_EQ(true, res->has_header("Content-Range"));
  4200. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4201. EXPECT_EQ(std::string("ab"), res->body);
  4202. }
  4203. TEST_F(ServerTest, GetStreamed) {
  4204. auto res = cli_.Get("/streamed");
  4205. ASSERT_TRUE(res);
  4206. EXPECT_EQ(StatusCode::OK_200, res->status);
  4207. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4208. EXPECT_EQ(std::string("aaabbb"), res->body);
  4209. }
  4210. TEST_F(ServerTest, GetStreamedWithRange1) {
  4211. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4212. ASSERT_TRUE(res);
  4213. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4214. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4215. EXPECT_EQ(true, res->has_header("Content-Range"));
  4216. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4217. EXPECT_EQ(std::string("def"), res->body);
  4218. }
  4219. TEST_F(ServerTest, GetStreamedWithRange2) {
  4220. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4221. ASSERT_TRUE(res);
  4222. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4223. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4224. EXPECT_EQ(true, res->has_header("Content-Range"));
  4225. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4226. EXPECT_EQ(std::string("bcdefg"), res->body);
  4227. }
  4228. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4229. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4230. ASSERT_TRUE(res);
  4231. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4232. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4233. EXPECT_EQ(true, res->has_header("Content-Range"));
  4234. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4235. EXPECT_EQ(std::string("efg"), res->body);
  4236. }
  4237. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4238. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4239. ASSERT_TRUE(res);
  4240. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4241. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4242. EXPECT_EQ(false, res->has_header("Content-Range"));
  4243. EXPECT_EQ(0U, res->body.size());
  4244. }
  4245. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4246. auto res = cli_.Get("/streamed-with-range",
  4247. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4248. "92233720368547758079223372036854775807"}});
  4249. ASSERT_TRUE(res);
  4250. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4251. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4252. EXPECT_EQ(false, res->has_header("Content-Range"));
  4253. EXPECT_EQ(0U, res->body.size());
  4254. }
  4255. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4256. auto res = cli_.Get(
  4257. "/with-range",
  4258. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4259. {"Accept-Encoding", ""}});
  4260. ASSERT_TRUE(res);
  4261. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4262. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4263. EXPECT_EQ(true, res->has_header("Content-Range"));
  4264. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4265. EXPECT_EQ(std::string("abcdefg"), res->body);
  4266. }
  4267. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4268. auto res = cli_.Get("/with-range", {
  4269. {"Range", "bytes=0-"},
  4270. {"Accept-Encoding", ""},
  4271. });
  4272. ASSERT_TRUE(res);
  4273. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4274. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4275. EXPECT_EQ(true, res->has_header("Content-Range"));
  4276. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4277. EXPECT_EQ(std::string("abcdefg"), res->body);
  4278. }
  4279. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4280. auto res =
  4281. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4282. ASSERT_TRUE(res);
  4283. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4284. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4285. EXPECT_EQ(false, res->has_header("Content-Range"));
  4286. EXPECT_EQ(267U, res->body.size());
  4287. // Check that both range contents are present
  4288. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4289. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4290. // Check that Content-Range headers are present for both ranges
  4291. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4292. std::string::npos);
  4293. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4294. std::string::npos);
  4295. }
  4296. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4297. Ranges ranges;
  4298. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4299. ranges.emplace_back(0, -1);
  4300. }
  4301. auto res =
  4302. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4303. ASSERT_TRUE(res);
  4304. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4305. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4306. EXPECT_EQ(false, res->has_header("Content-Range"));
  4307. EXPECT_EQ(0U, res->body.size());
  4308. }
  4309. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4310. auto res =
  4311. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4312. ASSERT_TRUE(res);
  4313. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4314. EXPECT_EQ(5U, res->body.size());
  4315. // Check that overlapping ranges are coalesced into a single range
  4316. EXPECT_EQ("bcdef", res->body);
  4317. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4318. // Should be single range, not multipart
  4319. EXPECT_TRUE(res->has_header("Content-Range"));
  4320. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4321. }
  4322. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4323. auto res =
  4324. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4325. ASSERT_TRUE(res);
  4326. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4327. EXPECT_EQ(268U, res->body.size());
  4328. // Check that both range contents are present
  4329. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4330. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4331. // Check that Content-Range headers are present for both ranges
  4332. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4333. std::string::npos);
  4334. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4335. std::string::npos);
  4336. }
  4337. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4338. auto res =
  4339. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4340. ASSERT_TRUE(res);
  4341. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4342. EXPECT_EQ(269U, res->body.size());
  4343. // Check that both duplicate range contents are present
  4344. size_t first_abc = res->body.find("abc\r\n");
  4345. EXPECT_TRUE(first_abc != std::string::npos);
  4346. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4347. EXPECT_TRUE(second_abc != std::string::npos);
  4348. // Check that Content-Range headers are present for both ranges
  4349. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4350. EXPECT_TRUE(first_range != std::string::npos);
  4351. size_t second_range =
  4352. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4353. EXPECT_TRUE(second_range != std::string::npos);
  4354. }
  4355. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4356. auto res = cli_.Get("/streamed-with-range?error",
  4357. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4358. ASSERT_TRUE(res);
  4359. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4360. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4361. EXPECT_EQ(false, res->has_header("Content-Range"));
  4362. EXPECT_EQ(0U, res->body.size());
  4363. }
  4364. TEST_F(ServerTest, GetStreamedEndless) {
  4365. uint64_t offset = 0;
  4366. auto res = cli_.Get("/streamed-cancel",
  4367. [&](const char * /*data*/, uint64_t data_length) {
  4368. if (offset < 100) {
  4369. offset += data_length;
  4370. return true;
  4371. }
  4372. return false;
  4373. });
  4374. ASSERT_TRUE(!res);
  4375. EXPECT_EQ(Error::Canceled, res.error());
  4376. }
  4377. TEST_F(ServerTest, ClientStop) {
  4378. std::atomic_size_t count{4};
  4379. std::vector<std::thread> threads;
  4380. for (auto i = count.load(); i != 0; --i) {
  4381. threads.emplace_back([&]() {
  4382. auto res = cli_.Get("/streamed-cancel",
  4383. [&](const char *, uint64_t) { return true; });
  4384. --count;
  4385. ASSERT_TRUE(!res);
  4386. EXPECT_TRUE(res.error() == Error::Canceled ||
  4387. res.error() == Error::Read || res.error() == Error::Write);
  4388. });
  4389. }
  4390. std::this_thread::sleep_for(std::chrono::seconds(2));
  4391. while (count != 0) {
  4392. cli_.stop();
  4393. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4394. }
  4395. for (auto &t : threads) {
  4396. t.join();
  4397. }
  4398. }
  4399. TEST_F(ServerTest, GetWithRange1) {
  4400. auto res = cli_.Get("/with-range", {
  4401. make_range_header({{3, 5}}),
  4402. {"Accept-Encoding", ""},
  4403. });
  4404. ASSERT_TRUE(res);
  4405. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4406. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4407. EXPECT_EQ(true, res->has_header("Content-Range"));
  4408. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4409. EXPECT_EQ(std::string("def"), res->body);
  4410. }
  4411. TEST_F(ServerTest, GetWithRange2) {
  4412. auto res = cli_.Get("/with-range", {
  4413. make_range_header({{1, -1}}),
  4414. {"Accept-Encoding", ""},
  4415. });
  4416. ASSERT_TRUE(res);
  4417. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4418. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4419. EXPECT_EQ(true, res->has_header("Content-Range"));
  4420. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4421. EXPECT_EQ(std::string("bcdefg"), res->body);
  4422. }
  4423. TEST_F(ServerTest, GetWithRange3) {
  4424. auto res = cli_.Get("/with-range", {
  4425. make_range_header({{0, 0}}),
  4426. {"Accept-Encoding", ""},
  4427. });
  4428. ASSERT_TRUE(res);
  4429. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4430. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4431. EXPECT_EQ(true, res->has_header("Content-Range"));
  4432. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4433. EXPECT_EQ(std::string("a"), res->body);
  4434. }
  4435. TEST_F(ServerTest, GetWithRange4) {
  4436. auto res = cli_.Get("/with-range", {
  4437. make_range_header({{-1, 2}}),
  4438. {"Accept-Encoding", ""},
  4439. });
  4440. ASSERT_TRUE(res);
  4441. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4442. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4443. EXPECT_EQ(true, res->has_header("Content-Range"));
  4444. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4445. EXPECT_EQ(std::string("fg"), res->body);
  4446. }
  4447. TEST_F(ServerTest, GetWithRange5) {
  4448. auto res = cli_.Get("/with-range", {
  4449. make_range_header({{0, 5}}),
  4450. {"Accept-Encoding", ""},
  4451. });
  4452. ASSERT_TRUE(res);
  4453. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4454. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4455. EXPECT_EQ(true, res->has_header("Content-Range"));
  4456. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4457. EXPECT_EQ(std::string("abcdef"), res->body);
  4458. }
  4459. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4460. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4461. ASSERT_TRUE(res);
  4462. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4463. }
  4464. TEST_F(ServerTest, GetWithRangeMultipart) {
  4465. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4466. ASSERT_TRUE(res);
  4467. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4468. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4469. EXPECT_EQ(false, res->has_header("Content-Range"));
  4470. EXPECT_EQ(267U, res->body.size());
  4471. }
  4472. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4473. auto res =
  4474. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4475. ASSERT_TRUE(res);
  4476. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4477. }
  4478. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4479. auto res = cli_.Get("/with-range-customized-response",
  4480. {{make_range_header({{1, 2}})}});
  4481. ASSERT_TRUE(res);
  4482. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4483. EXPECT_EQ(true, res->has_header("Content-Length"));
  4484. EXPECT_EQ(false, res->has_header("Content-Range"));
  4485. EXPECT_EQ(JSON_DATA, res->body);
  4486. }
  4487. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4488. auto res = cli_.Get("/with-range-customized-response",
  4489. {{make_range_header({{1, 2}, {4, 5}})}});
  4490. ASSERT_TRUE(res);
  4491. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4492. EXPECT_EQ(true, res->has_header("Content-Length"));
  4493. EXPECT_EQ(false, res->has_header("Content-Range"));
  4494. EXPECT_EQ(JSON_DATA, res->body);
  4495. }
  4496. TEST_F(ServerTest, Issue1772) {
  4497. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4498. ASSERT_TRUE(res);
  4499. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4500. }
  4501. TEST_F(ServerTest, Issue609) {
  4502. auto res = cli_.Delete("/issue609");
  4503. ASSERT_TRUE(res);
  4504. EXPECT_EQ(StatusCode::OK_200, res->status);
  4505. EXPECT_EQ(std::string("ok"), res->body);
  4506. }
  4507. TEST_F(ServerTest, GetStreamedChunked) {
  4508. auto res = cli_.Get("/streamed-chunked");
  4509. ASSERT_TRUE(res);
  4510. EXPECT_EQ(StatusCode::OK_200, res->status);
  4511. EXPECT_EQ(std::string("123456789"), res->body);
  4512. }
  4513. TEST_F(ServerTest, GetStreamedChunked2) {
  4514. auto res = cli_.Get("/streamed-chunked2");
  4515. ASSERT_TRUE(res);
  4516. EXPECT_EQ(StatusCode::OK_200, res->status);
  4517. EXPECT_EQ(std::string("123456789"), res->body);
  4518. }
  4519. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4520. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4521. ASSERT_TRUE(res);
  4522. EXPECT_EQ(StatusCode::OK_200, res->status);
  4523. EXPECT_EQ(std::string("123456789"), res->body);
  4524. EXPECT_TRUE(res->has_header("Trailer"));
  4525. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4526. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4527. // Trailers are now stored separately from headers (security fix)
  4528. EXPECT_EQ(2U, res->trailers.size());
  4529. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4530. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4531. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4532. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4533. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4534. // Verify trailers are NOT in headers (security verification)
  4535. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4536. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4537. }
  4538. TEST_F(ServerTest, LargeChunkedPost) {
  4539. Request req;
  4540. req.method = "POST";
  4541. req.path = "/large-chunked";
  4542. std::string host_and_port;
  4543. host_and_port += HOST;
  4544. host_and_port += ":";
  4545. host_and_port += std::to_string(PORT);
  4546. req.headers.emplace("Host", host_and_port.c_str());
  4547. req.headers.emplace("Accept", "*/*");
  4548. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4549. req.headers.emplace("Content-Type", "text/plain");
  4550. req.headers.emplace("Content-Length", "0");
  4551. req.headers.emplace("Transfer-Encoding", "chunked");
  4552. std::string long_string(30 * 1024u, 'a');
  4553. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4554. // Attempt to make a large enough post to exceed OS buffers, to test that
  4555. // the server handles short reads if the full chunk data isn't available.
  4556. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4557. auto res = std::make_shared<Response>();
  4558. auto error = Error::Success;
  4559. auto ret = cli_.send(req, *res, error);
  4560. ASSERT_TRUE(ret);
  4561. EXPECT_EQ(StatusCode::OK_200, res->status);
  4562. }
  4563. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4564. auto res = cli_.Get("/remote_addr");
  4565. ASSERT_TRUE(res);
  4566. EXPECT_EQ(StatusCode::OK_200, res->status);
  4567. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4568. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4569. }
  4570. TEST_F(ServerTest, GetMethodLocalAddr) {
  4571. auto res = cli_.Get("/local_addr");
  4572. ASSERT_TRUE(res);
  4573. EXPECT_EQ(StatusCode::OK_200, res->status);
  4574. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4575. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4576. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4577. }
  4578. TEST_F(ServerTest, HTTPResponseSplitting) {
  4579. auto res = cli_.Get("/http_response_splitting");
  4580. ASSERT_TRUE(res);
  4581. EXPECT_EQ(StatusCode::OK_200, res->status);
  4582. }
  4583. TEST_F(ServerTest, SlowRequest) {
  4584. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4585. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4586. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4587. }
  4588. #if 0
  4589. TEST_F(ServerTest, SlowPost) {
  4590. char buffer[64 * 1024];
  4591. memset(buffer, 0x42, sizeof(buffer));
  4592. auto res = cli_.Post(
  4593. "/slowpost", 64 * 1024 * 1024,
  4594. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4595. auto ret = sink.write(buffer, sizeof(buffer));
  4596. EXPECT_TRUE(ret);
  4597. return true;
  4598. },
  4599. "text/plain");
  4600. ASSERT_TRUE(res);
  4601. EXPECT_EQ(StatusCode::OK_200, res->status);
  4602. }
  4603. TEST_F(ServerTest, SlowPostFail) {
  4604. char buffer[64 * 1024];
  4605. memset(buffer, 0x42, sizeof(buffer));
  4606. cli_.set_write_timeout(std::chrono::seconds(0));
  4607. auto res = cli_.Post(
  4608. "/slowpost", 64 * 1024 * 1024,
  4609. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4610. sink.write(buffer, sizeof(buffer));
  4611. return true;
  4612. },
  4613. "text/plain");
  4614. ASSERT_TRUE(!res);
  4615. EXPECT_EQ(Error::Write, res.error());
  4616. }
  4617. #endif
  4618. TEST_F(ServerTest, Put) {
  4619. auto res = cli_.Put("/put", "PUT", "text/plain");
  4620. ASSERT_TRUE(res);
  4621. EXPECT_EQ(StatusCode::OK_200, res->status);
  4622. EXPECT_EQ("PUT", res->body);
  4623. }
  4624. TEST_F(ServerTest, PutWithContentProvider) {
  4625. auto res = cli_.Put(
  4626. "/put", 3,
  4627. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4628. sink.os << "PUT";
  4629. return true;
  4630. },
  4631. "text/plain");
  4632. ASSERT_TRUE(res);
  4633. EXPECT_EQ(StatusCode::OK_200, res->status);
  4634. EXPECT_EQ("PUT", res->body);
  4635. }
  4636. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4637. auto res = cli_.Post(
  4638. "/post", 42,
  4639. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4640. return false;
  4641. },
  4642. "text/plain");
  4643. ASSERT_TRUE(!res);
  4644. EXPECT_EQ(Error::Canceled, res.error());
  4645. }
  4646. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4647. auto res = cli_.Put(
  4648. "/put",
  4649. [](size_t /*offset*/, DataSink &sink) {
  4650. sink.os << "PUT";
  4651. sink.done();
  4652. return true;
  4653. },
  4654. "text/plain");
  4655. ASSERT_TRUE(res);
  4656. EXPECT_EQ(StatusCode::OK_200, res->status);
  4657. EXPECT_EQ("PUT", res->body);
  4658. }
  4659. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4660. auto res = cli_.Post(
  4661. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4662. "text/plain");
  4663. ASSERT_TRUE(!res);
  4664. EXPECT_EQ(Error::Canceled, res.error());
  4665. }
  4666. TEST_F(ServerTest, PostLoopBack) {
  4667. std::string body;
  4668. auto res = cli_.Post(
  4669. "/post-loopback", 9,
  4670. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4671. EXPECT_EQ(9u, length);
  4672. sink.write("123", 3);
  4673. sink.write("456", 3);
  4674. sink.write("789", 3);
  4675. return true;
  4676. },
  4677. "text/plain",
  4678. [&body](const char *data, size_t data_length) {
  4679. body.append(data, data_length);
  4680. return true;
  4681. });
  4682. ASSERT_TRUE(res);
  4683. EXPECT_EQ(StatusCode::OK_200, res->status);
  4684. EXPECT_EQ("123456789", body);
  4685. }
  4686. TEST_F(ServerTest, PutLoopBack) {
  4687. std::string body;
  4688. auto res = cli_.Put(
  4689. "/put-loopback", 9,
  4690. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4691. EXPECT_EQ(9u, length);
  4692. sink.write("123", 3);
  4693. sink.write("456", 3);
  4694. sink.write("789", 3);
  4695. return true;
  4696. },
  4697. "text/plain",
  4698. [&body](const char *data, size_t data_length) {
  4699. body.append(data, data_length);
  4700. return true;
  4701. });
  4702. ASSERT_TRUE(res);
  4703. EXPECT_EQ(StatusCode::OK_200, res->status);
  4704. EXPECT_EQ("123456789", body);
  4705. }
  4706. TEST_F(ServerTest, PatchLoopBack) {
  4707. std::string body;
  4708. auto res = cli_.Patch(
  4709. "/patch-loopback", 9,
  4710. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4711. EXPECT_EQ(9u, length);
  4712. sink.write("123", 3);
  4713. sink.write("456", 3);
  4714. sink.write("789", 3);
  4715. return true;
  4716. },
  4717. "text/plain",
  4718. [&body](const char *data, size_t data_length) {
  4719. body.append(data, data_length);
  4720. return true;
  4721. });
  4722. ASSERT_TRUE(res);
  4723. EXPECT_EQ(StatusCode::OK_200, res->status);
  4724. EXPECT_EQ("123456789", body);
  4725. }
  4726. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4727. std::string body;
  4728. auto res = cli_.Post(
  4729. "/post-loopback",
  4730. [](size_t /*offset*/, DataSink &sink) {
  4731. sink.write("123", 3);
  4732. sink.write("456", 3);
  4733. sink.write("789", 3);
  4734. sink.done();
  4735. return true;
  4736. },
  4737. "text/plain",
  4738. [&body](const char *data, size_t data_length) {
  4739. body.append(data, data_length);
  4740. return true;
  4741. });
  4742. ASSERT_TRUE(res);
  4743. EXPECT_EQ(StatusCode::OK_200, res->status);
  4744. EXPECT_EQ("123456789", body);
  4745. }
  4746. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4747. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4748. cli_.set_compress(true);
  4749. auto res = cli_.Put(
  4750. "/put", 3,
  4751. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4752. sink.os << "PUT";
  4753. return true;
  4754. },
  4755. "text/plain");
  4756. ASSERT_TRUE(res);
  4757. EXPECT_EQ(StatusCode::OK_200, res->status);
  4758. EXPECT_EQ("PUT", res->body);
  4759. }
  4760. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4761. cli_.set_compress(true);
  4762. auto res = cli_.Post(
  4763. "/post", 42,
  4764. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4765. return false;
  4766. },
  4767. "text/plain");
  4768. ASSERT_TRUE(!res);
  4769. EXPECT_EQ(Error::Canceled, res.error());
  4770. }
  4771. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4772. cli_.set_compress(true);
  4773. auto res = cli_.Put(
  4774. "/put",
  4775. [](size_t /*offset*/, DataSink &sink) {
  4776. sink.os << "PUT";
  4777. sink.done();
  4778. return true;
  4779. },
  4780. "text/plain");
  4781. ASSERT_TRUE(res);
  4782. EXPECT_EQ(StatusCode::OK_200, res->status);
  4783. EXPECT_EQ("PUT", res->body);
  4784. }
  4785. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4786. cli_.set_compress(true);
  4787. auto res = cli_.Post(
  4788. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4789. "text/plain");
  4790. ASSERT_TRUE(!res);
  4791. EXPECT_EQ(Error::Canceled, res.error());
  4792. }
  4793. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4794. cli_.set_compress(true);
  4795. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4796. ASSERT_TRUE(res);
  4797. EXPECT_EQ(StatusCode::OK_200, res->status);
  4798. EXPECT_EQ(LARGE_DATA, res->body);
  4799. }
  4800. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4801. #ifdef CPPHTTPLIB_SSL_ENABLED
  4802. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4803. Client cli(s.c_str());
  4804. cli.enable_server_certificate_verification(false);
  4805. #else
  4806. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4807. Client cli(s.c_str());
  4808. #endif
  4809. cli.set_compress(true);
  4810. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4811. ASSERT_TRUE(res);
  4812. EXPECT_EQ(StatusCode::OK_200, res->status);
  4813. EXPECT_EQ(LARGE_DATA, res->body);
  4814. // The compressed size should be less than a 10th of the original. May vary
  4815. // depending on the zlib library.
  4816. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4817. static_cast<uint64_t>(10 * 1024 * 1024));
  4818. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4819. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  4820. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  4821. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4822. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4823. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  4824. #endif
  4825. }
  4826. TEST_F(ServerTest, PutContentWithDeflate) {
  4827. cli_.set_compress(false);
  4828. Headers headers;
  4829. headers.emplace("Content-Encoding", "deflate");
  4830. // PUT in deflate format:
  4831. auto res = cli_.Put("/put", headers,
  4832. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4833. ASSERT_TRUE(res);
  4834. EXPECT_EQ(StatusCode::OK_200, res->status);
  4835. EXPECT_EQ("PUT", res->body);
  4836. }
  4837. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4838. Headers headers;
  4839. headers.emplace("Accept-Encoding", "gzip, deflate");
  4840. auto res = cli_.Get("/streamed-chunked", headers);
  4841. ASSERT_TRUE(res);
  4842. EXPECT_EQ(StatusCode::OK_200, res->status);
  4843. EXPECT_EQ(std::string("123456789"), res->body);
  4844. }
  4845. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4846. Headers headers;
  4847. headers.emplace("Accept-Encoding", "gzip, deflate");
  4848. auto res = cli_.Get("/streamed-chunked2", headers);
  4849. ASSERT_TRUE(res);
  4850. EXPECT_EQ(StatusCode::OK_200, res->status);
  4851. EXPECT_EQ(std::string("123456789"), res->body);
  4852. }
  4853. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4854. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4855. ASSERT_TRUE(res);
  4856. EXPECT_EQ(StatusCode::OK_200, res->status);
  4857. }
  4858. TEST(GzipDecompressor, ChunkedDecompression) {
  4859. std::string data;
  4860. for (size_t i = 0; i < 32 * 1024; ++i) {
  4861. data.push_back(static_cast<char>('a' + i % 26));
  4862. }
  4863. std::string compressed_data;
  4864. {
  4865. httplib::detail::gzip_compressor compressor;
  4866. bool result = compressor.compress(
  4867. data.data(), data.size(),
  4868. /*last=*/true,
  4869. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4870. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4871. compressed_data_size);
  4872. return true;
  4873. });
  4874. ASSERT_TRUE(result);
  4875. }
  4876. std::string decompressed_data;
  4877. {
  4878. httplib::detail::gzip_decompressor decompressor;
  4879. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4880. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4881. size_t chunk_size = 130;
  4882. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4883. chunk_begin += chunk_size) {
  4884. size_t current_chunk_size =
  4885. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4886. bool result = decompressor.decompress(
  4887. compressed_data.data() + chunk_begin, current_chunk_size,
  4888. [&](const char *decompressed_data_chunk,
  4889. size_t decompressed_data_chunk_size) {
  4890. decompressed_data.insert(decompressed_data.size(),
  4891. decompressed_data_chunk,
  4892. decompressed_data_chunk_size);
  4893. return true;
  4894. });
  4895. ASSERT_TRUE(result);
  4896. }
  4897. }
  4898. ASSERT_EQ(data, decompressed_data);
  4899. }
  4900. TEST(GzipDecompressor, DeflateDecompression) {
  4901. std::string original_text = "Raw deflate without gzip";
  4902. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4903. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4904. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4905. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4906. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4907. std::string decompressed_data;
  4908. {
  4909. httplib::detail::gzip_decompressor decompressor;
  4910. bool result = decompressor.decompress(
  4911. compressed_data.data(), compressed_data.size(),
  4912. [&](const char *decompressed_data_chunk,
  4913. size_t decompressed_data_chunk_size) {
  4914. decompressed_data.insert(decompressed_data.size(),
  4915. decompressed_data_chunk,
  4916. decompressed_data_chunk_size);
  4917. return true;
  4918. });
  4919. ASSERT_TRUE(result);
  4920. }
  4921. ASSERT_EQ(original_text, decompressed_data);
  4922. }
  4923. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4924. std::string original_text = "Raw deflate without gzip";
  4925. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4926. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4927. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4928. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4929. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4930. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4931. std::string decompressed_data;
  4932. {
  4933. httplib::detail::gzip_decompressor decompressor;
  4934. bool result = decompressor.decompress(
  4935. compressed_data.data(), compressed_data.size(),
  4936. [&](const char *decompressed_data_chunk,
  4937. size_t decompressed_data_chunk_size) {
  4938. decompressed_data.insert(decompressed_data.size(),
  4939. decompressed_data_chunk,
  4940. decompressed_data_chunk_size);
  4941. return true;
  4942. });
  4943. ASSERT_TRUE(result);
  4944. }
  4945. ASSERT_EQ(original_text, decompressed_data);
  4946. }
  4947. #endif
  4948. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4949. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4950. Headers headers;
  4951. headers.emplace("Accept-Encoding", "br");
  4952. auto res = cli_.Get("/streamed-chunked", headers);
  4953. ASSERT_TRUE(res);
  4954. EXPECT_EQ(StatusCode::OK_200, res->status);
  4955. EXPECT_EQ(std::string("123456789"), res->body);
  4956. }
  4957. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4958. Headers headers;
  4959. headers.emplace("Accept-Encoding", "br");
  4960. auto res = cli_.Get("/streamed-chunked2", headers);
  4961. ASSERT_TRUE(res);
  4962. EXPECT_EQ(StatusCode::OK_200, res->status);
  4963. EXPECT_EQ(std::string("123456789"), res->body);
  4964. }
  4965. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  4966. cli_.set_compress(true);
  4967. auto res = cli_.Put(
  4968. "/put", 3,
  4969. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4970. sink.os << "PUT";
  4971. return true;
  4972. },
  4973. "text/plain");
  4974. ASSERT_TRUE(res);
  4975. EXPECT_EQ(StatusCode::OK_200, res->status);
  4976. EXPECT_EQ("PUT", res->body);
  4977. }
  4978. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  4979. cli_.set_compress(true);
  4980. auto res = cli_.Put(
  4981. "/put",
  4982. [](size_t /*offset*/, DataSink &sink) {
  4983. sink.os << "PUT";
  4984. sink.done();
  4985. return true;
  4986. },
  4987. "text/plain");
  4988. ASSERT_TRUE(res);
  4989. EXPECT_EQ(StatusCode::OK_200, res->status);
  4990. EXPECT_EQ("PUT", res->body);
  4991. }
  4992. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  4993. cli_.set_compress(true);
  4994. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4995. ASSERT_TRUE(res);
  4996. EXPECT_EQ(StatusCode::OK_200, res->status);
  4997. EXPECT_EQ(LARGE_DATA, res->body);
  4998. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  4999. }
  5000. #endif
  5001. TEST_F(ServerTest, Patch) {
  5002. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5003. ASSERT_TRUE(res);
  5004. EXPECT_EQ(StatusCode::OK_200, res->status);
  5005. EXPECT_EQ("PATCH", res->body);
  5006. }
  5007. TEST_F(ServerTest, Delete) {
  5008. auto res = cli_.Delete("/delete");
  5009. ASSERT_TRUE(res);
  5010. EXPECT_EQ(StatusCode::OK_200, res->status);
  5011. EXPECT_EQ("DELETE", res->body);
  5012. }
  5013. TEST_F(ServerTest, DeleteContentReceiver) {
  5014. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5015. ASSERT_TRUE(res);
  5016. EXPECT_EQ(StatusCode::OK_200, res->status);
  5017. EXPECT_EQ("content", res->body);
  5018. }
  5019. TEST_F(ServerTest, Options) {
  5020. auto res = cli_.Options("*");
  5021. ASSERT_TRUE(res);
  5022. EXPECT_EQ(StatusCode::OK_200, res->status);
  5023. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5024. EXPECT_TRUE(res->body.empty());
  5025. }
  5026. TEST_F(ServerTest, URL) {
  5027. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5028. ASSERT_TRUE(res);
  5029. EXPECT_EQ(StatusCode::OK_200, res->status);
  5030. }
  5031. TEST_F(ServerTest, ArrayParam) {
  5032. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5033. ASSERT_TRUE(res);
  5034. EXPECT_EQ(StatusCode::OK_200, res->status);
  5035. }
  5036. TEST_F(ServerTest, NoMultipleHeaders) {
  5037. Headers headers = {{"Content-Length", "5"}};
  5038. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5039. "text/plain");
  5040. ASSERT_TRUE(res);
  5041. EXPECT_EQ(StatusCode::OK_200, res->status);
  5042. }
  5043. TEST_F(ServerTest, PostContentReceiver) {
  5044. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5045. ASSERT_TRUE(res);
  5046. ASSERT_EQ(StatusCode::OK_200, res->status);
  5047. ASSERT_EQ("content", res->body);
  5048. }
  5049. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5050. UploadFormDataItems items = {
  5051. {"text1", "text default", "", ""},
  5052. {"text2", "aωb", "", ""},
  5053. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5054. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5055. {"file3", "", "", "application/octet-stream"},
  5056. };
  5057. auto res = cli_.Post("/content_receiver", items);
  5058. ASSERT_TRUE(res);
  5059. EXPECT_EQ(StatusCode::OK_200, res->status);
  5060. }
  5061. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5062. UploadFormDataItems items = {
  5063. {"text1", "text default", "", ""},
  5064. {"text2", "aωb", "", ""},
  5065. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5066. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5067. {"file3", "", "", "application/octet-stream"},
  5068. };
  5069. auto boundary = std::string("+++++");
  5070. std::string body;
  5071. for (const auto &item : items) {
  5072. body += "--" + boundary + "\r\n";
  5073. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5074. if (!item.filename.empty()) {
  5075. body += "; filename=\"" + item.filename + "\"";
  5076. }
  5077. body += "\r\n";
  5078. if (!item.content_type.empty()) {
  5079. body += "Content-Type: " + item.content_type + "\r\n";
  5080. }
  5081. body += "\r\n";
  5082. body += item.content + "\r\n";
  5083. }
  5084. body += "--" + boundary + "--\r\n";
  5085. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5086. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5087. ASSERT_TRUE(res);
  5088. EXPECT_EQ(StatusCode::OK_200, res->status);
  5089. }
  5090. TEST_F(ServerTest, PostContentReceiverGzip) {
  5091. cli_.set_compress(true);
  5092. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5093. ASSERT_TRUE(res);
  5094. ASSERT_EQ(StatusCode::OK_200, res->status);
  5095. ASSERT_EQ("content", res->body);
  5096. }
  5097. TEST_F(ServerTest, PutContentReceiver) {
  5098. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5099. ASSERT_TRUE(res);
  5100. ASSERT_EQ(StatusCode::OK_200, res->status);
  5101. ASSERT_EQ("content", res->body);
  5102. }
  5103. TEST_F(ServerTest, PatchContentReceiver) {
  5104. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5105. ASSERT_TRUE(res);
  5106. ASSERT_EQ(StatusCode::OK_200, res->status);
  5107. ASSERT_EQ("content", res->body);
  5108. }
  5109. template <typename ClientType>
  5110. void TestWithHeadersAndContentReceiver(
  5111. ClientType &cli,
  5112. std::function<Result(ClientType &, const std::string &, const Headers &,
  5113. const std::string &, const std::string &,
  5114. ContentReceiver, DownloadProgress)>
  5115. request_func) {
  5116. Headers headers;
  5117. headers.emplace("X-Custom-Header", "test-value");
  5118. std::string received_body;
  5119. auto res = request_func(
  5120. cli, "/content_receiver", headers, "content", "application/json",
  5121. [&](const char *data, size_t data_length) {
  5122. received_body.append(data, data_length);
  5123. return true;
  5124. },
  5125. nullptr);
  5126. ASSERT_TRUE(res);
  5127. EXPECT_EQ(StatusCode::OK_200, res->status);
  5128. EXPECT_EQ("content", received_body);
  5129. }
  5130. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5131. #ifdef CPPHTTPLIB_SSL_ENABLED
  5132. using ClientT = SSLClient;
  5133. #else
  5134. using ClientT = Client;
  5135. #endif
  5136. TestWithHeadersAndContentReceiver<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, PutWithHeadersAndContentReceiver) {
  5144. #ifdef CPPHTTPLIB_SSL_ENABLED
  5145. using ClientT = SSLClient;
  5146. #else
  5147. using ClientT = Client;
  5148. #endif
  5149. TestWithHeadersAndContentReceiver<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, PatchWithHeadersAndContentReceiver) {
  5157. #ifdef CPPHTTPLIB_SSL_ENABLED
  5158. using ClientT = SSLClient;
  5159. #else
  5160. using ClientT = Client;
  5161. #endif
  5162. TestWithHeadersAndContentReceiver<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 TestWithHeadersAndContentReceiverWithProgress(
  5171. ClientType &cli,
  5172. std::function<Result(ClientType &, const std::string &, const Headers &,
  5173. const std::string &, const std::string &,
  5174. ContentReceiver, DownloadProgress)>
  5175. request_func) {
  5176. Headers headers;
  5177. headers.emplace("X-Test-Header", "progress-test");
  5178. std::string received_body;
  5179. auto progress_called = false;
  5180. auto res = request_func(
  5181. cli, "/content_receiver", headers, "content", "text/plain",
  5182. [&](const char *data, size_t data_length) {
  5183. received_body.append(data, data_length);
  5184. return true;
  5185. },
  5186. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5187. progress_called = true;
  5188. return true;
  5189. });
  5190. ASSERT_TRUE(res);
  5191. EXPECT_EQ(StatusCode::OK_200, res->status);
  5192. EXPECT_EQ("content", received_body);
  5193. EXPECT_TRUE(progress_called);
  5194. }
  5195. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5196. #ifdef CPPHTTPLIB_SSL_ENABLED
  5197. using ClientT = SSLClient;
  5198. #else
  5199. using ClientT = Client;
  5200. #endif
  5201. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5202. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5203. const std::string &body, const std::string &content_type,
  5204. ContentReceiver receiver, DownloadProgress progress) {
  5205. return cli.Post(path, headers, body, content_type, receiver, progress);
  5206. });
  5207. }
  5208. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5209. #ifdef CPPHTTPLIB_SSL_ENABLED
  5210. using ClientT = SSLClient;
  5211. #else
  5212. using ClientT = Client;
  5213. #endif
  5214. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5215. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5216. const std::string &body, const std::string &content_type,
  5217. ContentReceiver receiver, DownloadProgress progress) {
  5218. return cli.Put(path, headers, body, content_type, receiver, progress);
  5219. });
  5220. }
  5221. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5222. #ifdef CPPHTTPLIB_SSL_ENABLED
  5223. using ClientT = SSLClient;
  5224. #else
  5225. using ClientT = Client;
  5226. #endif
  5227. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5228. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5229. const std::string &body, const std::string &content_type,
  5230. ContentReceiver receiver, DownloadProgress progress) {
  5231. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5232. });
  5233. }
  5234. template <typename ClientType>
  5235. void TestWithHeadersAndContentReceiverError(
  5236. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5237. const Headers &, const std::string &,
  5238. const std::string &, ContentReceiver)>
  5239. request_func) {
  5240. Headers headers;
  5241. headers.emplace("X-Error-Test", "true");
  5242. std::string received_body;
  5243. auto receiver_failed = false;
  5244. auto res =
  5245. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5246. [&](const char *data, size_t data_length) {
  5247. received_body.append(data, data_length);
  5248. receiver_failed = true;
  5249. return false;
  5250. });
  5251. ASSERT_FALSE(res);
  5252. EXPECT_TRUE(receiver_failed);
  5253. }
  5254. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5255. #ifdef CPPHTTPLIB_SSL_ENABLED
  5256. using ClientT = SSLClient;
  5257. #else
  5258. using ClientT = Client;
  5259. #endif
  5260. TestWithHeadersAndContentReceiverError<ClientT>(
  5261. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5262. const std::string &body, const std::string &content_type,
  5263. ContentReceiver receiver) {
  5264. return cli.Post(path, headers, body, content_type, receiver);
  5265. });
  5266. }
  5267. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5268. #ifdef CPPHTTPLIB_SSL_ENABLED
  5269. using ClientT = SSLClient;
  5270. #else
  5271. using ClientT = Client;
  5272. #endif
  5273. TestWithHeadersAndContentReceiverError<ClientT>(
  5274. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5275. const std::string &body, const std::string &content_type,
  5276. ContentReceiver receiver) {
  5277. return cli.Put(path, headers, body, content_type, receiver);
  5278. });
  5279. }
  5280. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5281. #ifdef CPPHTTPLIB_SSL_ENABLED
  5282. using ClientT = SSLClient;
  5283. #else
  5284. using ClientT = Client;
  5285. #endif
  5286. TestWithHeadersAndContentReceiverError<ClientT>(
  5287. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5288. const std::string &body, const std::string &content_type,
  5289. ContentReceiver receiver) {
  5290. return cli.Patch(path, headers, body, content_type, receiver);
  5291. });
  5292. }
  5293. TEST_F(ServerTest, PostQueryStringAndBody) {
  5294. auto res =
  5295. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5296. ASSERT_TRUE(res);
  5297. ASSERT_EQ(StatusCode::OK_200, res->status);
  5298. }
  5299. TEST_F(ServerTest, HTTP2Magic) {
  5300. Request req;
  5301. req.method = "PRI";
  5302. req.path = "*";
  5303. req.body = "SM";
  5304. auto res = std::make_shared<Response>();
  5305. auto error = Error::Success;
  5306. auto ret = cli_.send(req, *res, error);
  5307. ASSERT_TRUE(ret);
  5308. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5309. }
  5310. TEST_F(ServerTest, KeepAlive) {
  5311. auto res = cli_.Get("/hi");
  5312. ASSERT_TRUE(res);
  5313. EXPECT_EQ(StatusCode::OK_200, res->status);
  5314. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5315. EXPECT_EQ("Hello World!", res->body);
  5316. res = cli_.Get("/hi");
  5317. ASSERT_TRUE(res);
  5318. EXPECT_EQ(StatusCode::OK_200, res->status);
  5319. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5320. EXPECT_EQ("Hello World!", res->body);
  5321. res = cli_.Get("/hi");
  5322. ASSERT_TRUE(res);
  5323. EXPECT_EQ(StatusCode::OK_200, res->status);
  5324. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5325. EXPECT_EQ("Hello World!", res->body);
  5326. res = cli_.Get("/not-exist");
  5327. ASSERT_TRUE(res);
  5328. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5329. res = cli_.Post("/empty", "", "text/plain");
  5330. ASSERT_TRUE(res);
  5331. EXPECT_EQ(StatusCode::OK_200, res->status);
  5332. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5333. EXPECT_EQ("empty", res->body);
  5334. EXPECT_EQ("close", res->get_header_value("Connection"));
  5335. res = cli_.Post(
  5336. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5337. "text/plain");
  5338. ASSERT_TRUE(res);
  5339. EXPECT_EQ(StatusCode::OK_200, res->status);
  5340. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5341. EXPECT_EQ("empty", res->body);
  5342. cli_.set_keep_alive(false);
  5343. res = cli_.Get("/last-request");
  5344. ASSERT_TRUE(res);
  5345. EXPECT_EQ(StatusCode::OK_200, res->status);
  5346. EXPECT_EQ("close", res->get_header_value("Connection"));
  5347. }
  5348. TEST_F(ServerTest, TooManyRedirect) {
  5349. cli_.set_follow_location(true);
  5350. auto res = cli_.Get("/redirect/0");
  5351. ASSERT_TRUE(!res);
  5352. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5353. }
  5354. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5355. Request req;
  5356. req.method = "FOOBAR";
  5357. req.path = "/hi";
  5358. cli_.set_keep_alive(true);
  5359. auto res = cli_.send(req);
  5360. ASSERT_TRUE(res);
  5361. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5362. EXPECT_EQ("close", res->get_header_value("Connection"));
  5363. EXPECT_FALSE(cli_.is_socket_open());
  5364. }
  5365. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5366. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5367. TEST_F(ServerTest, Gzip) {
  5368. Headers headers;
  5369. headers.emplace("Accept-Encoding", "gzip, deflate");
  5370. auto res = cli_.Get("/compress", headers);
  5371. ASSERT_TRUE(res);
  5372. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5373. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5374. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5375. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5376. "7890123456789012345678901234567890",
  5377. res->body);
  5378. EXPECT_EQ(StatusCode::OK_200, res->status);
  5379. }
  5380. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5381. Headers headers;
  5382. headers.emplace("Accept-Encoding", "gzip, deflate");
  5383. auto res = cli_.Get("/compress-with-charset", headers);
  5384. ASSERT_TRUE(res);
  5385. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5386. EXPECT_EQ("application/json; charset=utf-8",
  5387. res->get_header_value("Content-Type"));
  5388. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5389. "7890123456789012345678901234567890",
  5390. res->body);
  5391. EXPECT_EQ(StatusCode::OK_200, res->status);
  5392. }
  5393. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5394. Headers headers;
  5395. headers.emplace("Accept-Encoding", "");
  5396. auto res = cli_.Get("/compress", headers);
  5397. ASSERT_TRUE(res);
  5398. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5399. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5400. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5401. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5402. "7890123456789012345678901234567890",
  5403. res->body);
  5404. EXPECT_EQ(StatusCode::OK_200, res->status);
  5405. }
  5406. TEST_F(ServerTest, GzipWithContentReceiver) {
  5407. Headers headers;
  5408. headers.emplace("Accept-Encoding", "gzip, deflate");
  5409. std::string body;
  5410. auto res = cli_.Get("/compress", headers,
  5411. [&](const char *data, uint64_t data_length) {
  5412. EXPECT_EQ(100U, data_length);
  5413. body.append(data, data_length);
  5414. return true;
  5415. });
  5416. ASSERT_TRUE(res);
  5417. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5418. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5419. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5420. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5421. "7890123456789012345678901234567890",
  5422. body);
  5423. EXPECT_EQ(StatusCode::OK_200, res->status);
  5424. }
  5425. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5426. Headers headers;
  5427. headers.emplace("Accept-Encoding", "gzip, deflate");
  5428. cli_.set_decompress(false);
  5429. auto res = cli_.Get("/compress", headers);
  5430. ASSERT_TRUE(res);
  5431. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5432. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5433. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5434. EXPECT_EQ(33U, res->body.size());
  5435. EXPECT_EQ(StatusCode::OK_200, res->status);
  5436. }
  5437. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5438. Headers headers;
  5439. headers.emplace("Accept-Encoding", "");
  5440. std::string body;
  5441. auto res = cli_.Get("/compress", headers,
  5442. [&](const char *data, uint64_t data_length) {
  5443. EXPECT_EQ(100U, data_length);
  5444. body.append(data, data_length);
  5445. return true;
  5446. });
  5447. ASSERT_TRUE(res);
  5448. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5449. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5450. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5451. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5452. "7890123456789012345678901234567890",
  5453. body);
  5454. EXPECT_EQ(StatusCode::OK_200, res->status);
  5455. }
  5456. TEST_F(ServerTest, NoGzip) {
  5457. Headers headers;
  5458. headers.emplace("Accept-Encoding", "gzip, deflate");
  5459. auto res = cli_.Get("/nocompress", headers);
  5460. ASSERT_TRUE(res);
  5461. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5462. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5463. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5464. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5465. "7890123456789012345678901234567890",
  5466. res->body);
  5467. EXPECT_EQ(StatusCode::OK_200, res->status);
  5468. }
  5469. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5470. Headers headers;
  5471. headers.emplace("Accept-Encoding", "gzip, deflate");
  5472. std::string body;
  5473. auto res = cli_.Get("/nocompress", headers,
  5474. [&](const char *data, uint64_t data_length) {
  5475. EXPECT_EQ(100U, data_length);
  5476. body.append(data, data_length);
  5477. return true;
  5478. });
  5479. ASSERT_TRUE(res);
  5480. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5481. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5482. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5483. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5484. "7890123456789012345678901234567890",
  5485. body);
  5486. EXPECT_EQ(StatusCode::OK_200, res->status);
  5487. }
  5488. TEST_F(ServerTest, MultipartFormDataGzip) {
  5489. UploadFormDataItems items = {
  5490. {"key1", "test", "", ""},
  5491. {"key2", "--abcdefg123", "", ""},
  5492. };
  5493. cli_.set_compress(true);
  5494. auto res = cli_.Post("/compress-multipart", items);
  5495. ASSERT_TRUE(res);
  5496. EXPECT_EQ(StatusCode::OK_200, res->status);
  5497. }
  5498. #endif
  5499. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5500. TEST_F(ServerTest, Brotli) {
  5501. Headers headers;
  5502. headers.emplace("Accept-Encoding", "br");
  5503. auto res = cli_.Get("/compress", headers);
  5504. ASSERT_TRUE(res);
  5505. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5506. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5507. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5508. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5509. "7890123456789012345678901234567890",
  5510. res->body);
  5511. EXPECT_EQ(StatusCode::OK_200, res->status);
  5512. }
  5513. #endif
  5514. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5515. TEST_F(ServerTest, Zstd) {
  5516. Headers headers;
  5517. headers.emplace("Accept-Encoding", "zstd");
  5518. auto res = cli_.Get("/compress", headers);
  5519. ASSERT_TRUE(res);
  5520. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5521. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5522. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5523. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5524. "7890123456789012345678901234567890",
  5525. res->body);
  5526. EXPECT_EQ(StatusCode::OK_200, res->status);
  5527. }
  5528. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5529. Headers headers;
  5530. headers.emplace("Accept-Encoding", "");
  5531. auto res = cli_.Get("/compress", headers);
  5532. ASSERT_TRUE(res);
  5533. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5534. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5535. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5536. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5537. "7890123456789012345678901234567890",
  5538. res->body);
  5539. EXPECT_EQ(StatusCode::OK_200, res->status);
  5540. }
  5541. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5542. Headers headers;
  5543. headers.emplace("Accept-Encoding", "zstd");
  5544. std::string body;
  5545. auto res = cli_.Get("/compress", headers,
  5546. [&](const char *data, uint64_t data_length) {
  5547. EXPECT_EQ(100U, data_length);
  5548. body.append(data, data_length);
  5549. return true;
  5550. });
  5551. ASSERT_TRUE(res);
  5552. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5553. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5554. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5555. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5556. "7890123456789012345678901234567890",
  5557. body);
  5558. EXPECT_EQ(StatusCode::OK_200, res->status);
  5559. }
  5560. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5561. Headers headers;
  5562. headers.emplace("Accept-Encoding", "zstd");
  5563. cli_.set_decompress(false);
  5564. auto res = cli_.Get("/compress", headers);
  5565. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5566. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5567. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5568. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5569. ASSERT_TRUE(res);
  5570. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5571. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5572. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5573. EXPECT_EQ(StatusCode::OK_200, res->status);
  5574. ASSERT_EQ(26U, res->body.size());
  5575. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5576. 0);
  5577. }
  5578. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5579. Headers headers;
  5580. headers.emplace("Accept-Encoding", "");
  5581. std::string body;
  5582. auto res = cli_.Get("/compress", headers,
  5583. [&](const char *data, uint64_t data_length) {
  5584. EXPECT_EQ(100U, data_length);
  5585. body.append(data, data_length);
  5586. return true;
  5587. });
  5588. ASSERT_TRUE(res);
  5589. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5590. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5591. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5592. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5593. "7890123456789012345678901234567890",
  5594. body);
  5595. EXPECT_EQ(StatusCode::OK_200, res->status);
  5596. }
  5597. TEST_F(ServerTest, NoZstd) {
  5598. Headers headers;
  5599. headers.emplace("Accept-Encoding", "zstd");
  5600. auto res = cli_.Get("/nocompress", headers);
  5601. ASSERT_TRUE(res);
  5602. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5603. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5604. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5605. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5606. "7890123456789012345678901234567890",
  5607. res->body);
  5608. EXPECT_EQ(StatusCode::OK_200, res->status);
  5609. }
  5610. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5611. Headers headers;
  5612. headers.emplace("Accept-Encoding", "zstd");
  5613. std::string body;
  5614. auto res = cli_.Get("/nocompress", headers,
  5615. [&](const char *data, uint64_t data_length) {
  5616. EXPECT_EQ(100U, data_length);
  5617. body.append(data, data_length);
  5618. return true;
  5619. });
  5620. ASSERT_TRUE(res);
  5621. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5622. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5623. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5624. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5625. "7890123456789012345678901234567890",
  5626. body);
  5627. EXPECT_EQ(StatusCode::OK_200, res->status);
  5628. }
  5629. // TODO: How to enable zstd ??
  5630. TEST_F(ServerTest, MultipartFormDataZstd) {
  5631. UploadFormDataItems items = {
  5632. {"key1", "test", "", ""},
  5633. {"key2", "--abcdefg123", "", ""},
  5634. };
  5635. Headers headers;
  5636. headers.emplace("Accept-Encoding", "zstd");
  5637. cli_.set_compress(true);
  5638. auto res = cli_.Post("/compress-multipart", headers, items);
  5639. ASSERT_TRUE(res);
  5640. EXPECT_EQ(StatusCode::OK_200, res->status);
  5641. }
  5642. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5643. Headers headers;
  5644. headers.emplace("Accept-Encoding", "zstd");
  5645. cli_.set_compress(true);
  5646. auto res = cli_.Put(
  5647. "/put", headers, 3,
  5648. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5649. sink.os << "PUT";
  5650. return true;
  5651. },
  5652. "text/plain");
  5653. ASSERT_TRUE(res);
  5654. EXPECT_EQ(StatusCode::OK_200, res->status);
  5655. EXPECT_EQ("PUT", res->body);
  5656. }
  5657. // Pre-compression logging tests
  5658. TEST_F(ServerTest, PreCompressionLogging) {
  5659. // Test data for compression (matches the actual /compress endpoint content)
  5660. const std::string test_content =
  5661. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5662. "3456789012345678901234567890";
  5663. // Variables to capture logging data
  5664. std::string pre_compression_body;
  5665. std::string pre_compression_content_type;
  5666. std::string pre_compression_content_encoding;
  5667. std::string post_compression_body;
  5668. std::string post_compression_content_type;
  5669. std::string post_compression_content_encoding;
  5670. // Set up pre-compression logger
  5671. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5672. const Response &res) {
  5673. pre_compression_body = res.body;
  5674. pre_compression_content_type = res.get_header_value("Content-Type");
  5675. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5676. });
  5677. // Set up post-compression logger
  5678. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5679. post_compression_body = res.body;
  5680. post_compression_content_type = res.get_header_value("Content-Type");
  5681. post_compression_content_encoding =
  5682. res.get_header_value("Content-Encoding");
  5683. });
  5684. // Test with gzip compression
  5685. Headers headers;
  5686. headers.emplace("Accept-Encoding", "gzip");
  5687. auto res = cli_.Get("/compress", headers);
  5688. // Verify response was compressed
  5689. ASSERT_TRUE(res);
  5690. EXPECT_EQ(StatusCode::OK_200, res->status);
  5691. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5692. // Verify pre-compression logger captured uncompressed content
  5693. EXPECT_EQ(test_content, pre_compression_body);
  5694. EXPECT_EQ("text/plain", pre_compression_content_type);
  5695. EXPECT_TRUE(pre_compression_content_encoding
  5696. .empty()); // No encoding header before compression
  5697. // Verify post-compression logger captured compressed content
  5698. EXPECT_NE(test_content,
  5699. post_compression_body); // Should be different after compression
  5700. EXPECT_EQ("text/plain", post_compression_content_type);
  5701. EXPECT_EQ("gzip", post_compression_content_encoding);
  5702. // Verify compressed content is smaller
  5703. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5704. }
  5705. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5706. const std::string test_content =
  5707. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5708. "3456789012345678901234567890";
  5709. std::string pre_compression_body;
  5710. std::string post_compression_body;
  5711. svr_.set_pre_compression_logger(
  5712. [&](const Request & /*req*/, const Response &res) {
  5713. pre_compression_body = res.body;
  5714. });
  5715. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5716. post_compression_body = res.body;
  5717. });
  5718. Headers headers;
  5719. headers.emplace("Accept-Encoding", "br");
  5720. auto res = cli_.Get("/compress", headers);
  5721. ASSERT_TRUE(res);
  5722. EXPECT_EQ(StatusCode::OK_200, res->status);
  5723. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5724. // Verify pre-compression content is uncompressed
  5725. EXPECT_EQ(test_content, pre_compression_body);
  5726. // Verify post-compression content is compressed
  5727. EXPECT_NE(test_content, post_compression_body);
  5728. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5729. }
  5730. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5731. const std::string test_content =
  5732. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5733. "3456789012345678901234567890";
  5734. std::string pre_compression_body;
  5735. std::string post_compression_body;
  5736. svr_.set_pre_compression_logger(
  5737. [&](const Request & /*req*/, const Response &res) {
  5738. pre_compression_body = res.body;
  5739. });
  5740. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5741. post_compression_body = res.body;
  5742. });
  5743. // Request without compression (use /nocompress endpoint)
  5744. Headers headers;
  5745. auto res = cli_.Get("/nocompress", headers);
  5746. ASSERT_TRUE(res);
  5747. EXPECT_EQ(StatusCode::OK_200, res->status);
  5748. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5749. // Pre-compression logger should not be called when no compression is applied
  5750. EXPECT_TRUE(
  5751. pre_compression_body.empty()); // Pre-compression logger not called
  5752. EXPECT_EQ(
  5753. test_content,
  5754. post_compression_body); // Post-compression logger captures final content
  5755. }
  5756. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5757. const std::string test_content =
  5758. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5759. "3456789012345678901234567890";
  5760. std::string pre_compression_body;
  5761. bool pre_logger_called = false;
  5762. // Set only pre-compression logger
  5763. svr_.set_pre_compression_logger(
  5764. [&](const Request & /*req*/, const Response &res) {
  5765. pre_compression_body = res.body;
  5766. pre_logger_called = true;
  5767. });
  5768. Headers headers;
  5769. headers.emplace("Accept-Encoding", "gzip");
  5770. auto res = cli_.Get("/compress", headers);
  5771. ASSERT_TRUE(res);
  5772. EXPECT_EQ(StatusCode::OK_200, res->status);
  5773. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5774. // Verify pre-compression logger was called
  5775. EXPECT_TRUE(pre_logger_called);
  5776. EXPECT_EQ(test_content, pre_compression_body);
  5777. }
  5778. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5779. {
  5780. // Test with Expect: 100-continue header - success case
  5781. // Server returns 100 Continue, client sends body, server returns 200 OK
  5782. Request req;
  5783. req.method = "POST";
  5784. req.path = "/post-large";
  5785. req.set_header("Expect", "100-continue");
  5786. req.body = LARGE_DATA;
  5787. Response res;
  5788. auto error = Error::Success;
  5789. cli_.set_keep_alive(true);
  5790. auto ret = cli_.send(req, res, error);
  5791. EXPECT_TRUE(ret);
  5792. EXPECT_EQ(StatusCode::OK_200, res.status);
  5793. EXPECT_EQ(LARGE_DATA, res.body);
  5794. }
  5795. {
  5796. // Test with Expect: 100-continue header - error case
  5797. // Client should not send the body when server returns an error
  5798. Request req;
  5799. req.method = "POST";
  5800. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5801. req.set_header("Expect", "100-continue");
  5802. req.body = LARGE_DATA;
  5803. Response res;
  5804. auto error = Error::Success;
  5805. auto start = std::chrono::high_resolution_clock::now();
  5806. cli_.set_keep_alive(true);
  5807. auto ret = cli_.send(req, res, error);
  5808. auto end = std::chrono::high_resolution_clock::now();
  5809. auto elapsed =
  5810. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5811. .count();
  5812. // With Expect: 100-continue, request completes successfully but with error
  5813. EXPECT_TRUE(ret);
  5814. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5815. EXPECT_EQ("close", res.get_header_value("Connection"));
  5816. EXPECT_FALSE(cli_.is_socket_open());
  5817. EXPECT_LE(elapsed, 200);
  5818. }
  5819. {
  5820. // Send an extra GET request to ensure error recovery without hanging
  5821. Request req;
  5822. req.method = "GET";
  5823. req.path = "/hi";
  5824. auto start = std::chrono::high_resolution_clock::now();
  5825. auto res = cli_.send(req);
  5826. auto end = std::chrono::high_resolution_clock::now();
  5827. auto elapsed =
  5828. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5829. .count();
  5830. ASSERT_TRUE(res);
  5831. EXPECT_EQ(StatusCode::OK_200, res->status);
  5832. EXPECT_EQ("Hello World!", res->body);
  5833. EXPECT_LE(elapsed, 500);
  5834. }
  5835. }
  5836. TEST(ZstdDecompressor, ChunkedDecompression) {
  5837. std::string data;
  5838. for (size_t i = 0; i < 32 * 1024; ++i) {
  5839. data.push_back(static_cast<char>('a' + i % 26));
  5840. }
  5841. std::string compressed_data;
  5842. {
  5843. httplib::detail::zstd_compressor compressor;
  5844. bool result = compressor.compress(
  5845. data.data(), data.size(),
  5846. /*last=*/true,
  5847. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5848. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5849. compressed_data_size);
  5850. return true;
  5851. });
  5852. ASSERT_TRUE(result);
  5853. }
  5854. std::string decompressed_data;
  5855. {
  5856. httplib::detail::zstd_decompressor decompressor;
  5857. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5858. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5859. size_t chunk_size = 130;
  5860. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5861. chunk_begin += chunk_size) {
  5862. size_t current_chunk_size =
  5863. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5864. bool result = decompressor.decompress(
  5865. compressed_data.data() + chunk_begin, current_chunk_size,
  5866. [&](const char *decompressed_data_chunk,
  5867. size_t decompressed_data_chunk_size) {
  5868. decompressed_data.insert(decompressed_data.size(),
  5869. decompressed_data_chunk,
  5870. decompressed_data_chunk_size);
  5871. return true;
  5872. });
  5873. ASSERT_TRUE(result);
  5874. }
  5875. }
  5876. ASSERT_EQ(data, decompressed_data);
  5877. }
  5878. TEST(ZstdDecompressor, Decompress) {
  5879. std::string original_text = "Compressed with ZSTD";
  5880. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5881. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5882. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5883. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5884. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5885. std::string decompressed_data;
  5886. {
  5887. httplib::detail::zstd_decompressor decompressor;
  5888. bool result = decompressor.decompress(
  5889. compressed_data.data(), compressed_data.size(),
  5890. [&](const char *decompressed_data_chunk,
  5891. size_t decompressed_data_chunk_size) {
  5892. decompressed_data.insert(decompressed_data.size(),
  5893. decompressed_data_chunk,
  5894. decompressed_data_chunk_size);
  5895. return true;
  5896. });
  5897. ASSERT_TRUE(result);
  5898. }
  5899. ASSERT_EQ(original_text, decompressed_data);
  5900. }
  5901. #endif
  5902. // Sends a raw request to a server listening at HOST:PORT.
  5903. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5904. std::string *resp = nullptr) {
  5905. auto error = Error::Success;
  5906. auto client_sock = detail::create_client_socket(
  5907. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5908. /*connection_timeout_sec=*/5, 0,
  5909. /*read_timeout_sec=*/5, 0,
  5910. /*write_timeout_sec=*/5, 0, std::string(), error);
  5911. if (client_sock == INVALID_SOCKET) { return false; }
  5912. auto ret = detail::process_client_socket(
  5913. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5914. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5915. if (req.size() !=
  5916. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5917. return false;
  5918. }
  5919. char buf[512];
  5920. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5921. while (line_reader.getline()) {
  5922. if (resp) { *resp += line_reader.ptr(); }
  5923. }
  5924. return true;
  5925. });
  5926. detail::close_socket(client_sock);
  5927. return ret;
  5928. }
  5929. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5930. Server svr;
  5931. std::string header_value;
  5932. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5933. header_value = req.get_header_value("foo");
  5934. res.set_content("ok", "text/plain");
  5935. });
  5936. thread t = thread([&] { svr.listen(HOST, PORT); });
  5937. auto se = detail::scope_exit([&] {
  5938. svr.stop();
  5939. t.join();
  5940. ASSERT_FALSE(svr.is_running());
  5941. });
  5942. svr.wait_until_ready();
  5943. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5944. // like characters are not treated the same - use vertical tab and escape.
  5945. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5946. "foo: \t \v bar \x1B\t \r\n"
  5947. "Connection: close\r\n"
  5948. "\r\n";
  5949. std::string res;
  5950. ASSERT_TRUE(send_request(5, req, &res));
  5951. EXPECT_EQ(header_value, "");
  5952. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5953. }
  5954. // Sends a raw request and verifies that there isn't a crash or exception.
  5955. static void test_raw_request(const std::string &req,
  5956. std::string *out = nullptr) {
  5957. Server svr;
  5958. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5959. res.set_content("ok", "text/plain");
  5960. });
  5961. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5962. res.set_content("ok", "text/plain");
  5963. });
  5964. svr.Get("/header_field_value_check",
  5965. [&](const Request & /*req*/, Response &res) {
  5966. res.set_content("ok", "text/plain");
  5967. });
  5968. // Server read timeout must be longer than the client read timeout for the
  5969. // bug to reproduce, probably to force the server to process a request
  5970. // without a trailing blank line.
  5971. const time_t client_read_timeout_sec = 1;
  5972. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5973. bool listen_thread_ok = false;
  5974. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5975. auto se = detail::scope_exit([&] {
  5976. svr.stop();
  5977. t.join();
  5978. ASSERT_FALSE(svr.is_running());
  5979. EXPECT_TRUE(listen_thread_ok);
  5980. });
  5981. svr.wait_until_ready();
  5982. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5983. }
  5984. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5985. // A certain header line causes an exception if the header property is parsed
  5986. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5987. test_raw_request(
  5988. "GET /hi HTTP/1.1\r\n"
  5989. " : "
  5990. " "
  5991. " ");
  5992. }
  5993. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5994. // A certain header line causes an exception if the header property *name* is
  5995. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5996. // greedy matcher and requires backtracking when there are a lot of ":"
  5997. // characters.
  5998. // This occurs with libc++ but not libstdc++.
  5999. test_raw_request(
  6000. "GET /hi HTTP/1.1\r\n"
  6001. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6002. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6003. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6004. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6005. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6006. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6007. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6008. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6009. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6010. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6011. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6012. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6013. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6014. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6015. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6016. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6017. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6018. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6019. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6020. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6021. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6022. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6023. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6024. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6025. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6026. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6027. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6028. "&&&%%%");
  6029. }
  6030. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6031. // Make sure this doesn't crash the server.
  6032. // In a previous version of the header line regex, the "\r" rendered the line
  6033. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6034. // a new position where the leading white space ended and the field value
  6035. // began.
  6036. // The crash occurs with libc++ but not libstdc++.
  6037. test_raw_request("GET /hi HTTP/1.1\r\n"
  6038. "a:" +
  6039. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6040. "\r\n"
  6041. "\r\n");
  6042. }
  6043. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6044. std::string out;
  6045. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6046. "Content-Type: text/plain\r\n"
  6047. "Transfer-Encoding: chunked\r\n"
  6048. "\r\n"
  6049. "nothex\r\n",
  6050. &out);
  6051. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6052. }
  6053. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6054. std::string out;
  6055. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6056. "Content-Type: text/plain\r\n"
  6057. "Transfer-Encoding: chunked\r\n"
  6058. "\r\n"
  6059. "3\r\n"
  6060. "xyz\r\n"
  6061. "NaN\r\n",
  6062. &out);
  6063. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6064. }
  6065. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6066. std::string out;
  6067. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6068. "Content-Type: text/plain\r\n"
  6069. "Transfer-Encoding: chunked\r\n"
  6070. "\r\n"
  6071. // Length is too large for 64 bits.
  6072. "1ffffffffffffffff\r\n"
  6073. "xyz\r\n",
  6074. &out);
  6075. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6076. }
  6077. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6078. test_raw_request("GET /hi HTTP/1.1\r\n"
  6079. "Content-Type: text/plain\r\n\r");
  6080. }
  6081. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6082. std::string out;
  6083. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6084. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6085. }
  6086. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6087. Server svr;
  6088. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6089. EXPECT_TRUE(!req.remote_addr.empty());
  6090. });
  6091. thread t = thread([&] { svr.listen(HOST, PORT); });
  6092. auto se = detail::scope_exit([&] {
  6093. svr.stop();
  6094. t.join();
  6095. ASSERT_FALSE(svr.is_running());
  6096. });
  6097. svr.wait_until_ready();
  6098. // Send an invalid request line to trigger Bad Request
  6099. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6100. std::string out;
  6101. ASSERT_TRUE(send_request(5, bad_req, &out));
  6102. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6103. }
  6104. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6105. std::string out;
  6106. std::string request(
  6107. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6108. test_raw_request(request, &out);
  6109. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6110. }
  6111. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6112. std::string out;
  6113. std::string request(
  6114. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6115. test_raw_request(request, &out);
  6116. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6117. }
  6118. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6119. std::string out;
  6120. std::string request(
  6121. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6122. test_raw_request(request, &out);
  6123. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6124. }
  6125. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6126. std::string out;
  6127. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6128. "Test: \r\n\r\n",
  6129. &out);
  6130. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6131. }
  6132. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6133. Server svr;
  6134. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6135. res.set_header("Cache-Control", "no-cache");
  6136. res.set_chunked_content_provider(
  6137. "text/event-stream", [](size_t offset, DataSink &sink) {
  6138. std::string s = "data:";
  6139. s += std::to_string(offset);
  6140. s += "\n\n";
  6141. auto ret = sink.write(s.data(), s.size());
  6142. EXPECT_TRUE(ret);
  6143. std::this_thread::sleep_for(std::chrono::seconds(1));
  6144. return true;
  6145. });
  6146. });
  6147. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6148. svr.wait_until_ready();
  6149. Client client(HOST, PORT);
  6150. const Headers headers = {{"Accept", "text/event-stream"}};
  6151. auto get_thread = std::thread([&client, &headers]() {
  6152. auto res = client.Get(
  6153. "/events", headers,
  6154. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6155. });
  6156. auto se = detail::scope_exit([&] {
  6157. svr.stop();
  6158. get_thread.join();
  6159. listen_thread.join();
  6160. ASSERT_FALSE(svr.is_running());
  6161. });
  6162. // Give GET time to get a few messages.
  6163. std::this_thread::sleep_for(std::chrono::seconds(2));
  6164. }
  6165. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6166. httplib::Server svr;
  6167. svr.Post("/hi",
  6168. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6169. res.status = StatusCode::OK_200;
  6170. });
  6171. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6172. svr.wait_until_ready();
  6173. Client cli(HOST, PORT);
  6174. auto res = cli.Post("/hi", "data", "text/plain");
  6175. ASSERT_TRUE(res);
  6176. EXPECT_EQ(StatusCode::OK_200, res->status);
  6177. svr.stop();
  6178. thread.join();
  6179. ASSERT_FALSE(svr.is_running());
  6180. res = cli.Post("/hi", "data", "text/plain");
  6181. ASSERT_FALSE(res);
  6182. }
  6183. TEST(ServerStopTest, ListenFailure) {
  6184. Server svr;
  6185. auto t = thread([&]() {
  6186. auto ret = svr.listen("????", PORT);
  6187. EXPECT_FALSE(ret);
  6188. });
  6189. svr.wait_until_ready();
  6190. svr.stop();
  6191. t.join();
  6192. }
  6193. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6194. TEST(ServerStopTest, Decommision) {
  6195. Server svr;
  6196. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6197. for (int i = 0; i < 4; i++) {
  6198. auto is_even = !(i % 2);
  6199. std::thread t{[&] {
  6200. try {
  6201. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6202. if (is_even) {
  6203. throw std::runtime_error("Some thing that happens to go wrong.");
  6204. }
  6205. svr.listen(HOST, PORT);
  6206. } catch (...) { svr.decommission(); }
  6207. }};
  6208. svr.wait_until_ready();
  6209. // Server is up
  6210. {
  6211. Client cli(HOST, PORT);
  6212. auto res = cli.Get("/hi");
  6213. if (is_even) {
  6214. EXPECT_FALSE(res);
  6215. } else {
  6216. EXPECT_TRUE(res);
  6217. EXPECT_EQ("hi...", res->body);
  6218. }
  6219. }
  6220. svr.stop();
  6221. t.join();
  6222. // Server is down...
  6223. {
  6224. Client cli(HOST, PORT);
  6225. auto res = cli.Get("/hi");
  6226. EXPECT_FALSE(res);
  6227. }
  6228. }
  6229. }
  6230. #endif
  6231. // Helper function for string body upload progress tests
  6232. template <typename SetupHandler, typename ClientCall>
  6233. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6234. ClientCall &&client_call,
  6235. const string &body) {
  6236. Server svr;
  6237. setup_handler(svr);
  6238. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6239. auto se = detail::scope_exit([&] {
  6240. svr.stop();
  6241. t.join();
  6242. });
  6243. svr.wait_until_ready();
  6244. Client cli(HOST, PORT);
  6245. vector<uint64_t> progress_values;
  6246. bool progress_called = false;
  6247. auto res =
  6248. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6249. progress_values.push_back(current);
  6250. progress_called = true;
  6251. return true;
  6252. });
  6253. ASSERT_TRUE(res);
  6254. EXPECT_EQ(200, res->status);
  6255. EXPECT_TRUE(progress_called);
  6256. }
  6257. TEST(UploadProgressTest, PostStringBodyBasic) {
  6258. TestStringBodyUploadProgress(
  6259. [](Server &svr) {
  6260. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6261. res.set_content("received", "text/plain");
  6262. });
  6263. },
  6264. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6265. return cli.Post("/test", body, "text/plain", progress_callback);
  6266. },
  6267. "test data for upload progress");
  6268. }
  6269. TEST(UploadProgressTest, PutStringBodyBasic) {
  6270. TestStringBodyUploadProgress(
  6271. [](Server &svr) {
  6272. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6273. res.set_content("put received", "text/plain");
  6274. });
  6275. },
  6276. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6277. return cli.Put("/test", body, "text/plain", progress_callback);
  6278. },
  6279. "put test data for upload progress");
  6280. }
  6281. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6282. TestStringBodyUploadProgress(
  6283. [](Server &svr) {
  6284. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6285. res.set_content("patch received", "text/plain");
  6286. });
  6287. },
  6288. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6289. return cli.Patch("/test", body, "text/plain", progress_callback);
  6290. },
  6291. "patch test data for upload progress");
  6292. }
  6293. // Helper function for content provider upload progress tests
  6294. template <typename SetupHandler, typename ClientCall>
  6295. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6296. ClientCall &&client_call) {
  6297. Server svr;
  6298. setup_handler(svr);
  6299. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6300. auto se = detail::scope_exit([&] {
  6301. svr.stop();
  6302. t.join();
  6303. });
  6304. svr.wait_until_ready();
  6305. Client cli(HOST, PORT);
  6306. vector<uint64_t> progress_values;
  6307. auto res =
  6308. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6309. progress_values.push_back(current);
  6310. return true;
  6311. });
  6312. ASSERT_TRUE(res);
  6313. EXPECT_EQ(200, res->status);
  6314. EXPECT_FALSE(progress_values.empty());
  6315. }
  6316. TEST(UploadProgressTest, PostContentProviderProgress) {
  6317. TestContentProviderUploadProgress(
  6318. [](Server &svr) {
  6319. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6320. res.set_content("provider received", "text/plain");
  6321. });
  6322. },
  6323. [](Client &cli, UploadProgress progress_callback) {
  6324. return cli.Post(
  6325. "/test", 10,
  6326. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6327. sink.os << "test data";
  6328. return true;
  6329. },
  6330. "text/plain", progress_callback);
  6331. });
  6332. }
  6333. // Helper function for multipart upload progress tests
  6334. template <typename SetupHandler, typename ClientCall>
  6335. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6336. ClientCall &&client_call,
  6337. const string &endpoint) {
  6338. Server svr;
  6339. setup_handler(svr);
  6340. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6341. auto se = detail::scope_exit([&] {
  6342. svr.stop();
  6343. t.join();
  6344. });
  6345. svr.wait_until_ready();
  6346. Client cli(HOST, PORT);
  6347. vector<uint64_t> progress_values;
  6348. UploadFormDataItems items = {
  6349. {"field1", "value1", "", ""},
  6350. {"field2", "longer value for progress tracking test", "", ""},
  6351. {"file1", "file content data for upload progress", "test.txt",
  6352. "text/plain"}};
  6353. auto res = client_call(cli, endpoint, items,
  6354. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6355. progress_values.push_back(current);
  6356. return true;
  6357. });
  6358. ASSERT_TRUE(res);
  6359. EXPECT_EQ(200, res->status);
  6360. EXPECT_FALSE(progress_values.empty());
  6361. }
  6362. TEST(UploadProgressTest, PostMultipartProgress) {
  6363. TestMultipartUploadProgress(
  6364. [](Server &svr) {
  6365. svr.Post("/multipart", [](const Request &req, Response &res) {
  6366. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6367. res.set_content("multipart received", "text/plain");
  6368. });
  6369. },
  6370. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6371. UploadProgress progress_callback) {
  6372. return cli.Post(endpoint, items, progress_callback);
  6373. },
  6374. "/multipart");
  6375. }
  6376. // Helper function for basic download progress tests
  6377. template <typename SetupHandler, typename ClientCall>
  6378. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6379. ClientCall &&client_call, const string &endpoint,
  6380. size_t expected_content_size) {
  6381. Server svr;
  6382. setup_handler(svr);
  6383. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6384. auto se = detail::scope_exit([&] {
  6385. svr.stop();
  6386. t.join();
  6387. });
  6388. svr.wait_until_ready();
  6389. Client cli(HOST, PORT);
  6390. vector<uint64_t> progress_values;
  6391. auto res = client_call(cli, endpoint,
  6392. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6393. progress_values.push_back(current);
  6394. return true;
  6395. });
  6396. ASSERT_TRUE(res);
  6397. EXPECT_EQ(200, res->status);
  6398. EXPECT_FALSE(progress_values.empty());
  6399. EXPECT_EQ(expected_content_size, res->body.size());
  6400. }
  6401. TEST(DownloadProgressTest, GetBasic) {
  6402. TestBasicDownloadProgress(
  6403. [](Server &svr) {
  6404. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6405. string content(1000, 'D');
  6406. res.set_content(content, "text/plain");
  6407. });
  6408. },
  6409. [](Client &cli, const string &endpoint,
  6410. DownloadProgress progress_callback) {
  6411. return cli.Get(endpoint, progress_callback);
  6412. },
  6413. "/download", 1000u);
  6414. }
  6415. // Helper function for content receiver download progress tests
  6416. template <typename SetupHandler, typename ClientCall>
  6417. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6418. ClientCall &&client_call,
  6419. const string &endpoint,
  6420. size_t expected_content_size) {
  6421. Server svr;
  6422. setup_handler(svr);
  6423. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6424. auto se = detail::scope_exit([&] {
  6425. svr.stop();
  6426. t.join();
  6427. });
  6428. svr.wait_until_ready();
  6429. Client cli(HOST, PORT);
  6430. vector<uint64_t> progress_values;
  6431. string received_body;
  6432. auto res = client_call(
  6433. cli, endpoint,
  6434. [&](const char *data, size_t data_length) -> bool {
  6435. received_body.append(data, data_length);
  6436. return true;
  6437. },
  6438. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6439. progress_values.push_back(current);
  6440. return true;
  6441. });
  6442. ASSERT_TRUE(res);
  6443. EXPECT_EQ(200, res->status);
  6444. EXPECT_FALSE(progress_values.empty());
  6445. EXPECT_EQ(expected_content_size, received_body.size());
  6446. EXPECT_TRUE(res->body.empty());
  6447. }
  6448. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6449. TestContentReceiverDownloadProgress(
  6450. [](Server &svr) {
  6451. svr.Get("/download-receiver",
  6452. [](const Request & /*req*/, Response &res) {
  6453. string content(2000, 'R');
  6454. res.set_content(content, "text/plain");
  6455. });
  6456. },
  6457. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6458. DownloadProgress progress_callback) {
  6459. return cli.Get(endpoint, content_receiver, progress_callback);
  6460. },
  6461. "/download-receiver", 2000u);
  6462. }
  6463. TEST(StreamingTest, NoContentLengthStreaming) {
  6464. Server svr;
  6465. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6466. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6467. if (offset < 6) {
  6468. sink.os << (offset < 3 ? "a" : "b");
  6469. } else {
  6470. sink.done();
  6471. }
  6472. return true;
  6473. });
  6474. });
  6475. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6476. auto listen_se = detail::scope_exit([&] {
  6477. svr.stop();
  6478. listen_thread.join();
  6479. ASSERT_FALSE(svr.is_running());
  6480. });
  6481. svr.wait_until_ready();
  6482. Client client(HOST, PORT);
  6483. auto get_thread = std::thread([&client]() {
  6484. std::string s;
  6485. auto res =
  6486. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6487. s += std::string(data, len);
  6488. return true;
  6489. });
  6490. ASSERT_TRUE(res);
  6491. EXPECT_EQ(StatusCode::OK_200, res->status);
  6492. EXPECT_EQ("aaabbb", s);
  6493. });
  6494. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6495. // Give GET time to get a few messages.
  6496. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6497. }
  6498. TEST(MountTest, Unmount) {
  6499. Server svr;
  6500. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6501. auto se = detail::scope_exit([&] {
  6502. svr.stop();
  6503. listen_thread.join();
  6504. ASSERT_FALSE(svr.is_running());
  6505. });
  6506. svr.wait_until_ready();
  6507. Client cli("localhost", PORT);
  6508. svr.set_mount_point("/mount2", "./www2");
  6509. auto res = cli.Get("/");
  6510. ASSERT_TRUE(res);
  6511. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6512. res = cli.Get("/mount2/dir/test.html");
  6513. ASSERT_TRUE(res);
  6514. EXPECT_EQ(StatusCode::OK_200, res->status);
  6515. svr.set_mount_point("/", "./www");
  6516. res = cli.Get("/dir/");
  6517. ASSERT_TRUE(res);
  6518. EXPECT_EQ(StatusCode::OK_200, res->status);
  6519. svr.remove_mount_point("/");
  6520. res = cli.Get("/dir/");
  6521. ASSERT_TRUE(res);
  6522. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6523. svr.remove_mount_point("/mount2");
  6524. res = cli.Get("/mount2/dir/test.html");
  6525. ASSERT_TRUE(res);
  6526. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6527. }
  6528. TEST(MountTest, Redicect) {
  6529. Server svr;
  6530. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6531. auto se = detail::scope_exit([&] {
  6532. svr.stop();
  6533. listen_thread.join();
  6534. ASSERT_FALSE(svr.is_running());
  6535. });
  6536. svr.set_mount_point("/", "./www");
  6537. svr.wait_until_ready();
  6538. Client cli("localhost", PORT);
  6539. auto res = cli.Get("/dir/");
  6540. ASSERT_TRUE(res);
  6541. EXPECT_EQ(StatusCode::OK_200, res->status);
  6542. res = cli.Get("/dir");
  6543. ASSERT_TRUE(res);
  6544. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6545. res = cli.Get("/file");
  6546. ASSERT_TRUE(res);
  6547. EXPECT_EQ(StatusCode::OK_200, res->status);
  6548. res = cli.Get("/file/");
  6549. ASSERT_TRUE(res);
  6550. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6551. cli.set_follow_location(true);
  6552. res = cli.Get("/dir");
  6553. ASSERT_TRUE(res);
  6554. EXPECT_EQ(StatusCode::OK_200, res->status);
  6555. }
  6556. TEST(MountTest, MultibytesPathName) {
  6557. Server svr;
  6558. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6559. auto se = detail::scope_exit([&] {
  6560. svr.stop();
  6561. listen_thread.join();
  6562. ASSERT_FALSE(svr.is_running());
  6563. });
  6564. svr.set_mount_point("/", "./www");
  6565. svr.wait_until_ready();
  6566. Client cli("localhost", PORT);
  6567. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6568. ASSERT_TRUE(res);
  6569. EXPECT_EQ(StatusCode::OK_200, res->status);
  6570. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6571. }
  6572. TEST(KeepAliveTest, ReadTimeout) {
  6573. Server svr;
  6574. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6575. std::this_thread::sleep_for(std::chrono::seconds(2));
  6576. res.set_content("a", "text/plain");
  6577. });
  6578. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6579. res.set_content("b", "text/plain");
  6580. });
  6581. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6582. auto se = detail::scope_exit([&] {
  6583. svr.stop();
  6584. listen_thread.join();
  6585. ASSERT_FALSE(svr.is_running());
  6586. });
  6587. svr.wait_until_ready();
  6588. Client cli("localhost", PORT);
  6589. cli.set_keep_alive(true);
  6590. cli.set_read_timeout(std::chrono::seconds(1));
  6591. auto resa = cli.Get("/a");
  6592. ASSERT_FALSE(resa);
  6593. EXPECT_EQ(Error::Read, resa.error());
  6594. auto resb = cli.Get("/b");
  6595. ASSERT_TRUE(resb);
  6596. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6597. EXPECT_EQ("b", resb->body);
  6598. }
  6599. TEST(KeepAliveTest, MaxCount) {
  6600. size_t keep_alive_max_count = 3;
  6601. Server svr;
  6602. svr.set_keep_alive_max_count(keep_alive_max_count);
  6603. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6604. res.set_content("Hello World!", "text/plain");
  6605. });
  6606. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6607. auto se = detail::scope_exit([&] {
  6608. svr.stop();
  6609. listen_thread.join();
  6610. ASSERT_FALSE(svr.is_running());
  6611. });
  6612. svr.wait_until_ready();
  6613. Client cli(HOST, PORT);
  6614. cli.set_keep_alive(true);
  6615. for (size_t i = 0; i < 5; i++) {
  6616. auto result = cli.Get("/hi");
  6617. ASSERT_TRUE(result);
  6618. EXPECT_EQ(StatusCode::OK_200, result->status);
  6619. if (i == keep_alive_max_count - 1) {
  6620. EXPECT_EQ("close", result->get_header_value("Connection"));
  6621. } else {
  6622. EXPECT_FALSE(result->has_header("Connection"));
  6623. }
  6624. }
  6625. }
  6626. TEST(KeepAliveTest, Issue1041) {
  6627. Server svr;
  6628. svr.set_keep_alive_timeout(3);
  6629. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6630. res.set_content("Hello World!", "text/plain");
  6631. });
  6632. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6633. auto se = detail::scope_exit([&] {
  6634. svr.stop();
  6635. listen_thread.join();
  6636. ASSERT_FALSE(svr.is_running());
  6637. });
  6638. svr.wait_until_ready();
  6639. Client cli(HOST, PORT);
  6640. cli.set_keep_alive(true);
  6641. auto result = cli.Get("/hi");
  6642. ASSERT_TRUE(result);
  6643. EXPECT_EQ(StatusCode::OK_200, result->status);
  6644. std::this_thread::sleep_for(std::chrono::seconds(5));
  6645. result = cli.Get("/hi");
  6646. ASSERT_TRUE(result);
  6647. EXPECT_EQ(StatusCode::OK_200, result->status);
  6648. }
  6649. TEST(KeepAliveTest, Issue1959) {
  6650. Server svr;
  6651. svr.set_keep_alive_timeout(5);
  6652. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6653. res.set_content("a", "text/plain");
  6654. });
  6655. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6656. auto se = detail::scope_exit([&] {
  6657. if (!svr.is_running()) return;
  6658. svr.stop();
  6659. listen_thread.join();
  6660. ASSERT_FALSE(svr.is_running());
  6661. });
  6662. svr.wait_until_ready();
  6663. Client cli("localhost", PORT);
  6664. cli.set_keep_alive(true);
  6665. using namespace std::chrono;
  6666. auto start = steady_clock::now();
  6667. cli.Get("/a");
  6668. svr.stop();
  6669. listen_thread.join();
  6670. auto end = steady_clock::now();
  6671. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6672. EXPECT_LT(elapsed, 5000);
  6673. }
  6674. #ifdef CPPHTTPLIB_SSL_ENABLED
  6675. TEST(KeepAliveTest, SSLClientReconnection) {
  6676. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6677. ASSERT_TRUE(svr.is_valid());
  6678. svr.set_keep_alive_timeout(1);
  6679. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6680. res.set_content("Hello World!", "text/plain");
  6681. });
  6682. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6683. auto se = detail::scope_exit([&] {
  6684. svr.stop();
  6685. listen_thread.join();
  6686. ASSERT_FALSE(svr.is_running());
  6687. });
  6688. svr.wait_until_ready();
  6689. SSLClient cli(HOST, PORT);
  6690. cli.enable_server_certificate_verification(false);
  6691. cli.set_keep_alive(true);
  6692. auto result = cli.Get("/hi");
  6693. ASSERT_TRUE(result);
  6694. EXPECT_EQ(StatusCode::OK_200, result->status);
  6695. result = cli.Get("/hi");
  6696. ASSERT_TRUE(result);
  6697. EXPECT_EQ(StatusCode::OK_200, result->status);
  6698. std::this_thread::sleep_for(std::chrono::seconds(2));
  6699. // Recoonect
  6700. result = cli.Get("/hi");
  6701. ASSERT_TRUE(result);
  6702. EXPECT_EQ(StatusCode::OK_200, result->status);
  6703. result = cli.Get("/hi");
  6704. ASSERT_TRUE(result);
  6705. EXPECT_EQ(StatusCode::OK_200, result->status);
  6706. }
  6707. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6708. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6709. ASSERT_TRUE(svr.is_valid());
  6710. svr.set_keep_alive_timeout(1);
  6711. std::string content = "reconnect";
  6712. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6713. res.set_content("Hello World!", "text/plain");
  6714. });
  6715. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6716. auto se = detail::scope_exit([&] {
  6717. svr.stop();
  6718. listen_thread.join();
  6719. ASSERT_FALSE(svr.is_running());
  6720. });
  6721. svr.wait_until_ready();
  6722. SSLClient cli(HOST, PORT);
  6723. cli.enable_server_certificate_verification(false);
  6724. cli.set_keep_alive(true);
  6725. auto result = cli.Post(
  6726. "/hi", content.size(),
  6727. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6728. sink.write(content.c_str(), content.size());
  6729. return true;
  6730. },
  6731. "text/plain");
  6732. ASSERT_TRUE(result);
  6733. EXPECT_EQ(200, result->status);
  6734. std::this_thread::sleep_for(std::chrono::seconds(2));
  6735. // Recoonect
  6736. result = cli.Post(
  6737. "/hi", content.size(),
  6738. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6739. sink.write(content.c_str(), content.size());
  6740. return true;
  6741. },
  6742. "text/plain");
  6743. ASSERT_TRUE(result);
  6744. EXPECT_EQ(200, result->status);
  6745. result = cli.Post(
  6746. "/hi", content.size(),
  6747. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6748. sink.write(content.c_str(), content.size());
  6749. return true;
  6750. },
  6751. "text/plain");
  6752. ASSERT_TRUE(result);
  6753. EXPECT_EQ(200, result->status);
  6754. }
  6755. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6756. using namespace httplib::tls;
  6757. {
  6758. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6759. ASSERT_TRUE(svr.is_valid());
  6760. svr.Get("/sni", [&](const Request &req, Response &res) {
  6761. std::string expected = req.sni();
  6762. EXPECT_EQ(expected, req.get_param_value("expected"));
  6763. res.set_content("ok", "text/plain");
  6764. });
  6765. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6766. auto se = detail::scope_exit([&] {
  6767. svr.stop();
  6768. listen_thread.join();
  6769. ASSERT_FALSE(svr.is_running());
  6770. });
  6771. svr.wait_until_ready();
  6772. {
  6773. SSLClient cli("localhost", PORT);
  6774. cli.enable_server_certificate_verification(false);
  6775. auto res = cli.Get("/sni?expected=localhost");
  6776. ASSERT_TRUE(res);
  6777. }
  6778. {
  6779. SSLClient cli("::1", PORT);
  6780. cli.enable_server_certificate_verification(false);
  6781. auto res = cli.Get("/sni?expected=");
  6782. // NOTE: This may fail if the server is listening on IPv4 only
  6783. // (e.g., when localhost resolves to 127.0.0.1 only)
  6784. if (res) {
  6785. EXPECT_EQ(StatusCode::OK_200, res->status);
  6786. } else {
  6787. EXPECT_EQ(Error::Connection, res.error());
  6788. }
  6789. }
  6790. }
  6791. }
  6792. #endif
  6793. TEST(ClientProblemDetectionTest, ContentProvider) {
  6794. Server svr;
  6795. size_t content_length = 1024 * 1024;
  6796. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6797. res.set_content_provider(
  6798. content_length, "text/plain",
  6799. [&](size_t offset, size_t length, DataSink &sink) {
  6800. auto out_len = std::min(length, static_cast<size_t>(1024));
  6801. std::string out(out_len, '@');
  6802. sink.write(out.data(), out_len);
  6803. return offset < 4096;
  6804. },
  6805. [](bool success) { ASSERT_FALSE(success); });
  6806. });
  6807. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6808. res.set_content_provider(
  6809. 0, "text/plain",
  6810. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6811. EXPECT_TRUE(false);
  6812. return true;
  6813. },
  6814. [](bool success) { ASSERT_FALSE(success); });
  6815. });
  6816. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6817. auto se = detail::scope_exit([&] {
  6818. svr.stop();
  6819. listen_thread.join();
  6820. ASSERT_FALSE(svr.is_running());
  6821. });
  6822. svr.wait_until_ready();
  6823. Client cli("localhost", PORT);
  6824. {
  6825. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6826. size_t /*data_length*/) { return false; });
  6827. ASSERT_FALSE(res);
  6828. }
  6829. {
  6830. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6831. size_t /*data_length*/) { return false; });
  6832. ASSERT_TRUE(res);
  6833. }
  6834. }
  6835. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6836. Server svr;
  6837. svr.set_error_handler([](Request const &, Response &res) -> void {
  6838. res.set_chunked_content_provider(
  6839. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6840. sink.os << "hello";
  6841. sink.os << "world";
  6842. sink.done();
  6843. return true;
  6844. });
  6845. });
  6846. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", 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. Client cli("localhost", PORT);
  6854. auto res = cli.Get("/");
  6855. ASSERT_TRUE(res);
  6856. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6857. EXPECT_EQ("helloworld", res->body);
  6858. }
  6859. TEST(LongPollingTest, ClientCloseDetection) {
  6860. Server svr;
  6861. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6862. res.set_chunked_content_provider(
  6863. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6864. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6865. sink.os << "hello";
  6866. auto count = 10;
  6867. while (count > 0 && sink.is_writable()) {
  6868. this_thread::sleep_for(chrono::milliseconds(10));
  6869. count--;
  6870. }
  6871. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6872. return true;
  6873. });
  6874. });
  6875. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6876. auto se = detail::scope_exit([&] {
  6877. svr.stop();
  6878. listen_thread.join();
  6879. ASSERT_FALSE(svr.is_running());
  6880. });
  6881. svr.wait_until_ready();
  6882. Client cli("localhost", PORT);
  6883. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6884. EXPECT_EQ("hello", string(data, data_length));
  6885. return false; // close the socket immediately.
  6886. });
  6887. ASSERT_FALSE(res);
  6888. }
  6889. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  6890. Server svr;
  6891. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6892. res.set_chunked_content_provider(
  6893. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6894. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6895. sink.os << "hello";
  6896. EXPECT_TRUE(sink.os.good());
  6897. // Wait for the client to close the connection
  6898. auto count = 10;
  6899. while (count > 0 && sink.is_writable()) {
  6900. this_thread::sleep_for(chrono::milliseconds(10));
  6901. count--;
  6902. }
  6903. // After client disconnect, write repeatedly until the socket
  6904. // write actually fails (small writes may be absorbed by the
  6905. // kernel buffer)
  6906. std::string chunk(1024, 'x');
  6907. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  6908. sink.os << chunk;
  6909. }
  6910. EXPECT_TRUE(sink.os.fail());
  6911. return true;
  6912. });
  6913. });
  6914. auto port = svr.bind_to_any_port("localhost");
  6915. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  6916. auto se = detail::scope_exit([&] {
  6917. svr.stop();
  6918. listen_thread.join();
  6919. ASSERT_FALSE(svr.is_running());
  6920. });
  6921. svr.wait_until_ready();
  6922. Client cli("localhost", port);
  6923. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6924. EXPECT_EQ("hello", string(data, data_length));
  6925. return false; // close the socket immediately.
  6926. });
  6927. ASSERT_FALSE(res);
  6928. }
  6929. TEST(GetWithParametersTest, GetWithParameters) {
  6930. Server svr;
  6931. svr.Get("/", [&](const Request &req, Response &) {
  6932. EXPECT_EQ("world", req.get_param_value("hello"));
  6933. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6934. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6935. });
  6936. svr.Get("/params", [&](const Request &req, Response &) {
  6937. EXPECT_EQ("world", req.get_param_value("hello"));
  6938. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6939. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6940. });
  6941. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6942. EXPECT_EQ("resource-id", req.matches[1]);
  6943. EXPECT_EQ("foo", req.get_param_value("param1"));
  6944. EXPECT_EQ("bar", req.get_param_value("param2"));
  6945. });
  6946. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6947. EXPECT_EQ("user-id", req.path_params.at("id"));
  6948. EXPECT_EQ("foo", req.get_param_value("param1"));
  6949. EXPECT_EQ("bar", req.get_param_value("param2"));
  6950. });
  6951. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6952. auto se = detail::scope_exit([&] {
  6953. svr.stop();
  6954. listen_thread.join();
  6955. ASSERT_FALSE(svr.is_running());
  6956. });
  6957. svr.wait_until_ready();
  6958. {
  6959. Client cli(HOST, PORT);
  6960. Params params;
  6961. params.emplace("hello", "world");
  6962. params.emplace("hello2", "world2");
  6963. params.emplace("hello3", "world3");
  6964. auto res = cli.Get("/", params, Headers{});
  6965. ASSERT_TRUE(res);
  6966. EXPECT_EQ(StatusCode::OK_200, res->status);
  6967. }
  6968. {
  6969. Client cli(HOST, PORT);
  6970. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6971. ASSERT_TRUE(res);
  6972. EXPECT_EQ(StatusCode::OK_200, res->status);
  6973. }
  6974. {
  6975. Client cli(HOST, PORT);
  6976. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6977. ASSERT_TRUE(res);
  6978. EXPECT_EQ(StatusCode::OK_200, res->status);
  6979. }
  6980. {
  6981. Client cli(HOST, PORT);
  6982. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6983. ASSERT_TRUE(res);
  6984. EXPECT_EQ(StatusCode::OK_200, res->status);
  6985. }
  6986. }
  6987. TEST(GetWithParametersTest, GetWithParameters2) {
  6988. Server svr;
  6989. svr.Get("/", [&](const Request &req, Response &res) {
  6990. auto text = req.get_param_value("hello");
  6991. res.set_content(text, "text/plain");
  6992. });
  6993. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6994. auto se = detail::scope_exit([&] {
  6995. svr.stop();
  6996. listen_thread.join();
  6997. ASSERT_FALSE(svr.is_running());
  6998. });
  6999. svr.wait_until_ready();
  7000. Client cli("localhost", PORT);
  7001. Params params;
  7002. params.emplace("hello", "world");
  7003. std::string body;
  7004. auto res = cli.Get("/", params, Headers{},
  7005. [&](const char *data, size_t data_length) {
  7006. body.append(data, data_length);
  7007. return true;
  7008. });
  7009. ASSERT_TRUE(res);
  7010. EXPECT_EQ(StatusCode::OK_200, res->status);
  7011. EXPECT_EQ("world", body);
  7012. }
  7013. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  7014. auto host = "httpbingo.org";
  7015. auto path = std::string{"/range/32"};
  7016. #ifdef CPPHTTPLIB_SSL_ENABLED
  7017. SSLClient cli(host);
  7018. #else
  7019. Client cli(host);
  7020. #endif
  7021. cli.set_default_headers({make_range_header({{1, 10}})});
  7022. cli.set_connection_timeout(5);
  7023. {
  7024. auto res = cli.Get(path);
  7025. ASSERT_TRUE(res);
  7026. EXPECT_EQ("bcdefghijk", res->body);
  7027. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7028. }
  7029. {
  7030. auto res = cli.Get(path);
  7031. ASSERT_TRUE(res);
  7032. EXPECT_EQ("bcdefghijk", res->body);
  7033. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7034. }
  7035. }
  7036. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7037. Server svr;
  7038. svr.set_default_headers({{"Hello", "World"}});
  7039. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7040. res.set_content("ok", "text/plain");
  7041. });
  7042. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7043. auto se = detail::scope_exit([&] {
  7044. svr.stop();
  7045. listen_thread.join();
  7046. ASSERT_FALSE(svr.is_running());
  7047. });
  7048. svr.wait_until_ready();
  7049. Client cli("localhost", PORT);
  7050. auto res = cli.Get("/");
  7051. ASSERT_TRUE(res);
  7052. EXPECT_EQ(StatusCode::OK_200, res->status);
  7053. EXPECT_EQ("ok", res->body);
  7054. EXPECT_EQ("World", res->get_header_value("Hello"));
  7055. }
  7056. #ifdef CPPHTTPLIB_SSL_ENABLED
  7057. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7058. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7059. ASSERT_TRUE(svr.is_valid());
  7060. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7061. std::this_thread::sleep_for(std::chrono::seconds(2));
  7062. res.set_content("a", "text/plain");
  7063. });
  7064. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7065. res.set_content("b", "text/plain");
  7066. });
  7067. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7068. auto se = detail::scope_exit([&] {
  7069. svr.stop();
  7070. listen_thread.join();
  7071. ASSERT_FALSE(svr.is_running());
  7072. });
  7073. svr.wait_until_ready();
  7074. SSLClient cli("localhost", PORT);
  7075. cli.enable_server_certificate_verification(false);
  7076. cli.set_keep_alive(true);
  7077. cli.set_read_timeout(std::chrono::seconds(1));
  7078. auto resa = cli.Get("/a");
  7079. ASSERT_TRUE(!resa);
  7080. EXPECT_EQ(Error::Read, resa.error());
  7081. auto resb = cli.Get("/b");
  7082. ASSERT_TRUE(resb);
  7083. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7084. EXPECT_EQ("b", resb->body);
  7085. }
  7086. #endif
  7087. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7088. protected:
  7089. ServerTestWithAI_PASSIVE()
  7090. : cli_(HOST, PORT)
  7091. #ifdef CPPHTTPLIB_SSL_ENABLED
  7092. ,
  7093. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7094. #endif
  7095. {
  7096. #ifdef CPPHTTPLIB_SSL_ENABLED
  7097. cli_.enable_server_certificate_verification(false);
  7098. #endif
  7099. }
  7100. virtual void SetUp() {
  7101. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7102. res.set_content("Hello World!", "text/plain");
  7103. });
  7104. t_ = thread(
  7105. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7106. svr_.wait_until_ready();
  7107. }
  7108. virtual void TearDown() {
  7109. svr_.stop();
  7110. t_.join();
  7111. }
  7112. #ifdef CPPHTTPLIB_SSL_ENABLED
  7113. SSLClient cli_;
  7114. SSLServer svr_;
  7115. #else
  7116. Client cli_;
  7117. Server svr_;
  7118. #endif
  7119. thread t_;
  7120. };
  7121. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7122. auto res = cli_.Get("/hi");
  7123. ASSERT_TRUE(res);
  7124. EXPECT_EQ(StatusCode::OK_200, res->status);
  7125. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7126. EXPECT_EQ("Hello World!", res->body);
  7127. }
  7128. class ServerUpDownTest : public ::testing::Test {
  7129. protected:
  7130. ServerUpDownTest() : cli_(HOST, PORT) {}
  7131. virtual void SetUp() {
  7132. t_ = thread([&]() {
  7133. svr_.bind_to_any_port(HOST);
  7134. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7135. ASSERT_TRUE(svr_.listen_after_bind());
  7136. });
  7137. svr_.wait_until_ready();
  7138. }
  7139. virtual void TearDown() {
  7140. svr_.stop();
  7141. t_.join();
  7142. }
  7143. Client cli_;
  7144. Server svr_;
  7145. thread t_;
  7146. };
  7147. TEST_F(ServerUpDownTest, QuickStartStop) {
  7148. // Should not crash, especially when run with
  7149. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7150. }
  7151. class PayloadMaxLengthTest : public ::testing::Test {
  7152. protected:
  7153. PayloadMaxLengthTest()
  7154. : cli_(HOST, PORT)
  7155. #ifdef CPPHTTPLIB_SSL_ENABLED
  7156. ,
  7157. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7158. #endif
  7159. {
  7160. #ifdef CPPHTTPLIB_SSL_ENABLED
  7161. cli_.enable_server_certificate_verification(false);
  7162. #endif
  7163. }
  7164. virtual void SetUp() {
  7165. svr_.set_payload_max_length(8);
  7166. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7167. res.set_content("test", "text/plain");
  7168. });
  7169. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7170. svr_.wait_until_ready();
  7171. }
  7172. virtual void TearDown() {
  7173. svr_.stop();
  7174. t_.join();
  7175. }
  7176. #ifdef CPPHTTPLIB_SSL_ENABLED
  7177. SSLClient cli_;
  7178. SSLServer svr_;
  7179. #else
  7180. Client cli_;
  7181. Server svr_;
  7182. #endif
  7183. thread t_;
  7184. };
  7185. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7186. auto res = cli_.Post("/test", "123456789", "text/plain");
  7187. ASSERT_TRUE(res);
  7188. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7189. res = cli_.Post("/test", "12345678", "text/plain");
  7190. ASSERT_TRUE(res);
  7191. EXPECT_EQ(StatusCode::OK_200, res->status);
  7192. }
  7193. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7194. // Test chunked encoding with payload exceeding the 8-byte limit
  7195. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7196. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7197. ASSERT_TRUE(res);
  7198. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7199. }
  7200. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7201. // Test chunked encoding with payload within the 8-byte limit
  7202. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7203. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7204. ASSERT_TRUE(res);
  7205. EXPECT_EQ(StatusCode::OK_200, res->status);
  7206. }
  7207. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7208. // Test using send_request to send chunked data exceeding payload limit
  7209. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7210. "Host: " +
  7211. std::string(HOST) + ":" + std::to_string(PORT) +
  7212. "\r\n"
  7213. "Transfer-Encoding: chunked\r\n"
  7214. "Connection: close\r\n"
  7215. "\r\n"
  7216. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7217. "0123456789\r\n"
  7218. "0\r\n" // End chunk
  7219. "\r\n";
  7220. std::string response;
  7221. bool result = send_request(1, chunked_request, &response);
  7222. if (!result) {
  7223. // If send_request fails, it might be because the server closed the
  7224. // connection due to payload limit enforcement, which is acceptable
  7225. SUCCEED()
  7226. << "Server rejected oversized chunked request (connection closed)";
  7227. } else {
  7228. // If we got a response, check if it's an error response or connection was
  7229. // closed early Short response length indicates connection was closed due to
  7230. // payload limit
  7231. if (response.length() <= 10) {
  7232. SUCCEED() << "Server closed connection for oversized chunked request";
  7233. } else {
  7234. // Check for error status codes
  7235. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7236. response.find("Payload Too Large") != std::string::npos ||
  7237. response.find("400") != std::string::npos);
  7238. }
  7239. }
  7240. }
  7241. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7242. // Test request without Content-Length header exceeding payload limit
  7243. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7244. "Host: " +
  7245. std::string(HOST) + ":" +
  7246. std::to_string(PORT) +
  7247. "\r\n"
  7248. "Connection: close\r\n"
  7249. "\r\n";
  7250. // Add payload exceeding the 8-byte limit
  7251. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7252. request_without_content_length += large_payload;
  7253. std::string response;
  7254. bool result = send_request(1, request_without_content_length, &response);
  7255. if (!result) {
  7256. // If send_request fails, server likely closed connection due to payload
  7257. // limit
  7258. SUCCEED() << "Server rejected oversized request without Content-Length "
  7259. "(connection closed)";
  7260. } else {
  7261. // Check if server responded with error or closed connection early
  7262. if (response.length() <= 10) {
  7263. SUCCEED() << "Server closed connection for oversized request without "
  7264. "Content-Length";
  7265. } else {
  7266. // Check for error status codes
  7267. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7268. response.find("Payload Too Large") != std::string::npos ||
  7269. response.find("400") != std::string::npos);
  7270. }
  7271. }
  7272. }
  7273. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7274. // Test request without Content-Length header within payload limit
  7275. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7276. "Host: " +
  7277. std::string(HOST) + ":" +
  7278. std::to_string(PORT) +
  7279. "\r\n"
  7280. "Connection: close\r\n"
  7281. "\r\n";
  7282. // Add payload within the 8-byte limit
  7283. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7284. request_without_content_length += small_payload;
  7285. std::string response;
  7286. bool result = send_request(1, request_without_content_length, &response);
  7287. // For requests without Content-Length, the server may have different behavior
  7288. // The key is that it should not reject due to payload limit for small
  7289. // payloads
  7290. if (result) {
  7291. // Check for any HTTP response (success or error, but not connection closed)
  7292. if (response.length() > 10) {
  7293. SUCCEED()
  7294. << "Server processed request without Content-Length within limit";
  7295. } else {
  7296. // Short response might indicate connection closed, which is acceptable
  7297. SUCCEED() << "Server closed connection for request without "
  7298. "Content-Length (acceptable behavior)";
  7299. }
  7300. } else {
  7301. // Connection failure might be due to protocol requirements
  7302. SUCCEED() << "Connection issue with request without Content-Length "
  7303. "(environment-specific)";
  7304. }
  7305. }
  7306. class LargePayloadMaxLengthTest : public ::testing::Test {
  7307. protected:
  7308. LargePayloadMaxLengthTest()
  7309. : cli_(HOST, PORT)
  7310. #ifdef CPPHTTPLIB_SSL_ENABLED
  7311. ,
  7312. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7313. #endif
  7314. {
  7315. #ifdef CPPHTTPLIB_SSL_ENABLED
  7316. cli_.enable_server_certificate_verification(false);
  7317. #endif
  7318. }
  7319. virtual void SetUp() {
  7320. // Set 10MB payload limit
  7321. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7322. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7323. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7324. res.set_content("Large payload test", "text/plain");
  7325. });
  7326. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7327. svr_.wait_until_ready();
  7328. }
  7329. virtual void TearDown() {
  7330. svr_.stop();
  7331. t_.join();
  7332. }
  7333. #ifdef CPPHTTPLIB_SSL_ENABLED
  7334. SSLClient cli_;
  7335. SSLServer svr_;
  7336. #else
  7337. Client cli_;
  7338. Server svr_;
  7339. #endif
  7340. thread t_;
  7341. };
  7342. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7343. // Test chunked encoding with payload within 10MB limit
  7344. std::string medium_payload(5 * 1024 * 1024,
  7345. 'A'); // 5MB payload, within 10MB limit
  7346. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7347. ASSERT_TRUE(res);
  7348. EXPECT_EQ(StatusCode::OK_200, res->status);
  7349. }
  7350. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7351. // Test chunked encoding with payload exceeding 10MB limit
  7352. std::string large_payload(12 * 1024 * 1024,
  7353. 'B'); // 12MB payload, exceeds 10MB limit
  7354. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7355. // Server may either return 413 or close the connection
  7356. if (res) {
  7357. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7358. } else {
  7359. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7360. }
  7361. }
  7362. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7363. // Test request without Content-Length header within 10MB limit
  7364. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7365. "Host: " +
  7366. std::string(HOST) + ":" +
  7367. std::to_string(PORT) +
  7368. "\r\n"
  7369. "Connection: close\r\n"
  7370. "\r\n";
  7371. // Add 1MB payload (within 10MB limit)
  7372. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7373. request_without_content_length += medium_payload;
  7374. std::string response;
  7375. bool result = send_request(5, request_without_content_length, &response);
  7376. if (result) {
  7377. // Should get a proper HTTP response for payloads within limit
  7378. if (response.length() > 10) {
  7379. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7380. "10MB limit";
  7381. } else {
  7382. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7383. "Content-Length)";
  7384. }
  7385. } else {
  7386. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7387. }
  7388. }
  7389. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7390. // Test request without Content-Length header exceeding 10MB limit
  7391. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7392. "Host: " +
  7393. std::string(HOST) + ":" +
  7394. std::to_string(PORT) +
  7395. "\r\n"
  7396. "Connection: close\r\n"
  7397. "\r\n";
  7398. // Add 12MB payload (exceeds 10MB limit)
  7399. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7400. request_without_content_length += large_payload;
  7401. std::string response;
  7402. bool result = send_request(10, request_without_content_length, &response);
  7403. if (!result) {
  7404. // Server should close connection due to payload limit
  7405. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7406. "(connection closed)";
  7407. } else {
  7408. // Check for error response
  7409. if (response.length() <= 10) {
  7410. SUCCEED()
  7411. << "Server closed connection for 12MB request exceeding 10MB limit";
  7412. } else {
  7413. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7414. response.find("Payload Too Large") != std::string::npos ||
  7415. response.find("400") != std::string::npos);
  7416. }
  7417. }
  7418. }
  7419. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7420. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7421. // path.
  7422. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7423. Server svr;
  7424. const size_t LIMIT = 64 * 1024; // 64KB
  7425. svr.set_payload_max_length(LIMIT);
  7426. size_t total = 0;
  7427. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7428. const ContentReader &content_reader) {
  7429. content_reader([&](const char * /*data*/, size_t len) {
  7430. total += len;
  7431. return true;
  7432. });
  7433. res.status = 200;
  7434. res.set_content("stream_ok", "text/plain");
  7435. });
  7436. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7437. auto se = detail::scope_exit([&] {
  7438. svr.stop();
  7439. thread.join();
  7440. ASSERT_FALSE(svr.is_running());
  7441. });
  7442. svr.wait_until_ready();
  7443. // Prepare 256KB raw data and gzip-compress it
  7444. std::string raw(256 * 1024, 'A');
  7445. std::string gz;
  7446. {
  7447. z_stream zs{};
  7448. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7449. Z_DEFAULT_STRATEGY);
  7450. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7451. zs.avail_in = static_cast<uInt>(raw.size());
  7452. char outbuf[4096];
  7453. int ret;
  7454. do {
  7455. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7456. zs.avail_out = sizeof(outbuf);
  7457. ret = deflate(&zs, Z_FINISH);
  7458. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7459. } while (ret != Z_STREAM_END);
  7460. deflateEnd(&zs);
  7461. }
  7462. Client cli(HOST, PORT);
  7463. cli.set_connection_timeout(std::chrono::seconds(5));
  7464. Headers headers = {{"Content-Encoding", "gzip"}};
  7465. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7466. "application/octet-stream");
  7467. ASSERT_TRUE(res);
  7468. // Server must reject oversized decompressed payloads with 413.
  7469. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7470. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7471. EXPECT_LE(total, LIMIT);
  7472. }
  7473. #endif
  7474. // Regression test for DoS vulnerability: a malicious server sending a response
  7475. // without Content-Length header must not cause unbounded memory consumption on
  7476. // the client side. The client should stop reading after a reasonable limit,
  7477. // similar to the server-side set_payload_max_length protection.
  7478. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7479. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7480. #ifndef _WIN32
  7481. signal(SIGPIPE, SIG_IGN);
  7482. #endif
  7483. auto server_thread = std::thread([] {
  7484. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7485. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7486. default_socket_options(srv);
  7487. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7488. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7489. sockaddr_in addr{};
  7490. addr.sin_family = AF_INET;
  7491. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7492. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7493. int opt = 1;
  7494. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7495. #ifdef _WIN32
  7496. reinterpret_cast<const char *>(&opt),
  7497. #else
  7498. &opt,
  7499. #endif
  7500. sizeof(opt));
  7501. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7502. ::listen(srv, 1);
  7503. sockaddr_in cli_addr{};
  7504. socklen_t cli_len = sizeof(cli_addr);
  7505. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7506. if (cli != INVALID_SOCKET) {
  7507. char buf[4096];
  7508. ::recv(cli, buf, sizeof(buf), 0);
  7509. // Malicious response: no Content-Length, no chunked encoding
  7510. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7511. "Connection: close\r\n"
  7512. "\r\n";
  7513. ::send(cli,
  7514. #ifdef _WIN32
  7515. static_cast<const char *>(response_header.c_str()),
  7516. static_cast<int>(response_header.size()),
  7517. #else
  7518. response_header.c_str(), response_header.size(),
  7519. #endif
  7520. 0);
  7521. // Send 10MB of data
  7522. std::string chunk(64 * 1024, 'A');
  7523. size_t total_sent = 0;
  7524. while (total_sent < MALICIOUS_DATA_SIZE) {
  7525. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7526. auto sent = ::send(cli,
  7527. #ifdef _WIN32
  7528. static_cast<const char *>(chunk.c_str()),
  7529. static_cast<int>(to_send),
  7530. #else
  7531. chunk.c_str(), to_send,
  7532. #endif
  7533. 0);
  7534. if (sent <= 0) break;
  7535. total_sent += static_cast<size_t>(sent);
  7536. }
  7537. detail::close_socket(cli);
  7538. }
  7539. detail::close_socket(srv);
  7540. });
  7541. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7542. size_t total_read = 0;
  7543. {
  7544. Client cli("127.0.0.1", PORT + 2);
  7545. cli.set_read_timeout(5, 0);
  7546. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7547. auto stream = cli.open_stream("GET", "/malicious");
  7548. ASSERT_TRUE(stream.is_valid());
  7549. char buffer[64 * 1024];
  7550. ssize_t n;
  7551. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7552. total_read += static_cast<size_t>(n);
  7553. }
  7554. } // StreamHandle and Client destroyed here, closing the socket
  7555. server_thread.join();
  7556. // With set_payload_max_length, the client must stop reading before consuming
  7557. // all 10MB. The read loop should be cut off at or near the configured limit.
  7558. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7559. << "Client read " << total_read << " bytes, exceeding the configured "
  7560. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7561. }
  7562. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7563. // the entire response body without truncation.
  7564. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7565. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7566. #ifndef _WIN32
  7567. signal(SIGPIPE, SIG_IGN);
  7568. #endif
  7569. auto server_thread = std::thread([] {
  7570. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7571. default_socket_options(srv);
  7572. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7573. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7574. sockaddr_in addr{};
  7575. addr.sin_family = AF_INET;
  7576. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7577. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7578. int opt = 1;
  7579. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7580. #ifdef _WIN32
  7581. reinterpret_cast<const char *>(&opt),
  7582. #else
  7583. &opt,
  7584. #endif
  7585. sizeof(opt));
  7586. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7587. ::listen(srv, 1);
  7588. sockaddr_in cli_addr{};
  7589. socklen_t cli_len = sizeof(cli_addr);
  7590. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7591. if (cli != INVALID_SOCKET) {
  7592. char buf[4096];
  7593. ::recv(cli, buf, sizeof(buf), 0);
  7594. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7595. "Connection: close\r\n"
  7596. "\r\n";
  7597. ::send(cli,
  7598. #ifdef _WIN32
  7599. static_cast<const char *>(response_header.c_str()),
  7600. static_cast<int>(response_header.size()),
  7601. #else
  7602. response_header.c_str(), response_header.size(),
  7603. #endif
  7604. 0);
  7605. std::string chunk(64 * 1024, 'A');
  7606. size_t total_sent = 0;
  7607. while (total_sent < DATA_SIZE) {
  7608. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7609. auto sent = ::send(cli,
  7610. #ifdef _WIN32
  7611. static_cast<const char *>(chunk.c_str()),
  7612. static_cast<int>(to_send),
  7613. #else
  7614. chunk.c_str(), to_send,
  7615. #endif
  7616. 0);
  7617. if (sent <= 0) break;
  7618. total_sent += static_cast<size_t>(sent);
  7619. }
  7620. #ifdef _WIN32
  7621. ::shutdown(cli, SD_SEND);
  7622. #else
  7623. ::shutdown(cli, SHUT_WR);
  7624. #endif
  7625. // Drain until the client closes its end, ensuring all data is delivered
  7626. char drain[1024];
  7627. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7628. detail::close_socket(cli);
  7629. }
  7630. detail::close_socket(srv);
  7631. });
  7632. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7633. size_t total_read = 0;
  7634. {
  7635. Client cli("127.0.0.1", PORT + 2);
  7636. cli.set_read_timeout(5, 0);
  7637. cli.set_payload_max_length(0); // 0 means no limit
  7638. auto stream = cli.open_stream("GET", "/data");
  7639. ASSERT_TRUE(stream.is_valid());
  7640. char buffer[64 * 1024];
  7641. ssize_t n;
  7642. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7643. total_read += static_cast<size_t>(n);
  7644. }
  7645. }
  7646. server_thread.join();
  7647. EXPECT_EQ(total_read, DATA_SIZE)
  7648. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7649. << " bytes without truncation, but only read " << total_read << " bytes.";
  7650. }
  7651. // Verify that content_receiver bypasses the default payload_max_length,
  7652. // allowing streaming downloads larger than 100MB without requiring an explicit
  7653. // set_payload_max_length call.
  7654. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  7655. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7656. #ifndef _WIN32
  7657. signal(SIGPIPE, SIG_IGN);
  7658. #endif
  7659. auto server_thread = std::thread([] {
  7660. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7661. default_socket_options(srv);
  7662. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7663. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7664. sockaddr_in addr{};
  7665. addr.sin_family = AF_INET;
  7666. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7667. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7668. int opt = 1;
  7669. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7670. #ifdef _WIN32
  7671. reinterpret_cast<const char *>(&opt),
  7672. #else
  7673. &opt,
  7674. #endif
  7675. sizeof(opt));
  7676. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7677. ::listen(srv, 1);
  7678. sockaddr_in cli_addr{};
  7679. socklen_t cli_len = sizeof(cli_addr);
  7680. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7681. if (cli != INVALID_SOCKET) {
  7682. char buf[4096];
  7683. ::recv(cli, buf, sizeof(buf), 0);
  7684. // Response with Content-Length larger than default 100MB limit
  7685. auto content_length = std::to_string(DATA_SIZE);
  7686. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7687. "Content-Length: " +
  7688. content_length +
  7689. "\r\n"
  7690. "Connection: close\r\n"
  7691. "\r\n";
  7692. ::send(cli,
  7693. #ifdef _WIN32
  7694. static_cast<const char *>(response_header.c_str()),
  7695. static_cast<int>(response_header.size()),
  7696. #else
  7697. response_header.c_str(), response_header.size(),
  7698. #endif
  7699. 0);
  7700. std::string chunk(64 * 1024, 'A');
  7701. size_t total_sent = 0;
  7702. while (total_sent < DATA_SIZE) {
  7703. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7704. auto sent = ::send(cli,
  7705. #ifdef _WIN32
  7706. static_cast<const char *>(chunk.c_str()),
  7707. static_cast<int>(to_send),
  7708. #else
  7709. chunk.c_str(), to_send,
  7710. #endif
  7711. 0);
  7712. if (sent <= 0) break;
  7713. total_sent += static_cast<size_t>(sent);
  7714. }
  7715. detail::close_socket(cli);
  7716. }
  7717. detail::close_socket(srv);
  7718. });
  7719. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7720. size_t total_received = 0;
  7721. {
  7722. Client cli("127.0.0.1", PORT + 2);
  7723. cli.set_read_timeout(10, 0);
  7724. // Do NOT call set_payload_max_length — use the default 100MB limit
  7725. auto res =
  7726. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7727. total_received += data_length;
  7728. return true;
  7729. });
  7730. ASSERT_TRUE(res);
  7731. EXPECT_EQ(StatusCode::OK_200, res->status);
  7732. }
  7733. server_thread.join();
  7734. EXPECT_EQ(total_received, DATA_SIZE)
  7735. << "With content_receiver, the client should read all " << DATA_SIZE
  7736. << " bytes despite the default 100MB payload_max_length, but only read "
  7737. << total_received << " bytes.";
  7738. }
  7739. // Verify that an explicit set_payload_max_length smaller than the response is
  7740. // enforced even when a content_receiver is used.
  7741. TEST(ClientVulnerabilityTest,
  7742. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  7743. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7744. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  7745. #ifndef _WIN32
  7746. signal(SIGPIPE, SIG_IGN);
  7747. #endif
  7748. auto server_thread = std::thread([] {
  7749. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7750. default_socket_options(srv);
  7751. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7752. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7753. sockaddr_in addr{};
  7754. addr.sin_family = AF_INET;
  7755. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7756. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7757. int opt = 1;
  7758. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7759. #ifdef _WIN32
  7760. reinterpret_cast<const char *>(&opt),
  7761. #else
  7762. &opt,
  7763. #endif
  7764. sizeof(opt));
  7765. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7766. ::listen(srv, 1);
  7767. sockaddr_in cli_addr{};
  7768. socklen_t cli_len = sizeof(cli_addr);
  7769. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7770. if (cli != INVALID_SOCKET) {
  7771. char buf[4096];
  7772. ::recv(cli, buf, sizeof(buf), 0);
  7773. auto content_length = std::to_string(DATA_SIZE);
  7774. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7775. "Content-Length: " +
  7776. content_length +
  7777. "\r\n"
  7778. "Connection: close\r\n"
  7779. "\r\n";
  7780. ::send(cli,
  7781. #ifdef _WIN32
  7782. static_cast<const char *>(response_header.c_str()),
  7783. static_cast<int>(response_header.size()),
  7784. #else
  7785. response_header.c_str(), response_header.size(),
  7786. #endif
  7787. 0);
  7788. std::string chunk(64 * 1024, 'A');
  7789. size_t total_sent = 0;
  7790. while (total_sent < DATA_SIZE) {
  7791. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7792. auto sent = ::send(cli,
  7793. #ifdef _WIN32
  7794. static_cast<const char *>(chunk.c_str()),
  7795. static_cast<int>(to_send),
  7796. #else
  7797. chunk.c_str(), to_send,
  7798. #endif
  7799. 0);
  7800. if (sent <= 0) break;
  7801. total_sent += static_cast<size_t>(sent);
  7802. }
  7803. detail::close_socket(cli);
  7804. }
  7805. detail::close_socket(srv);
  7806. });
  7807. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7808. size_t total_received = 0;
  7809. {
  7810. Client cli("127.0.0.1", PORT + 2);
  7811. cli.set_read_timeout(10, 0);
  7812. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  7813. auto res =
  7814. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7815. total_received += data_length;
  7816. return true;
  7817. });
  7818. // Should fail because 200MB exceeds the explicit 150MB limit
  7819. EXPECT_FALSE(res);
  7820. }
  7821. server_thread.join();
  7822. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  7823. << "Client with content_receiver should respect the explicit "
  7824. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  7825. << total_received << " bytes.";
  7826. }
  7827. // Verify that an explicit set_payload_max_length larger than the response
  7828. // allows the content_receiver to read all data successfully.
  7829. TEST(ClientVulnerabilityTest,
  7830. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  7831. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7832. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  7833. #ifndef _WIN32
  7834. signal(SIGPIPE, SIG_IGN);
  7835. #endif
  7836. auto server_thread = std::thread([] {
  7837. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7838. default_socket_options(srv);
  7839. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7840. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7841. sockaddr_in addr{};
  7842. addr.sin_family = AF_INET;
  7843. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7844. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7845. int opt = 1;
  7846. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7847. #ifdef _WIN32
  7848. reinterpret_cast<const char *>(&opt),
  7849. #else
  7850. &opt,
  7851. #endif
  7852. sizeof(opt));
  7853. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7854. ::listen(srv, 1);
  7855. sockaddr_in cli_addr{};
  7856. socklen_t cli_len = sizeof(cli_addr);
  7857. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7858. if (cli != INVALID_SOCKET) {
  7859. char buf[4096];
  7860. ::recv(cli, buf, sizeof(buf), 0);
  7861. auto content_length = std::to_string(DATA_SIZE);
  7862. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7863. "Content-Length: " +
  7864. content_length +
  7865. "\r\n"
  7866. "Connection: close\r\n"
  7867. "\r\n";
  7868. ::send(cli,
  7869. #ifdef _WIN32
  7870. static_cast<const char *>(response_header.c_str()),
  7871. static_cast<int>(response_header.size()),
  7872. #else
  7873. response_header.c_str(), response_header.size(),
  7874. #endif
  7875. 0);
  7876. std::string chunk(64 * 1024, 'A');
  7877. size_t total_sent = 0;
  7878. while (total_sent < DATA_SIZE) {
  7879. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7880. auto sent = ::send(cli,
  7881. #ifdef _WIN32
  7882. static_cast<const char *>(chunk.c_str()),
  7883. static_cast<int>(to_send),
  7884. #else
  7885. chunk.c_str(), to_send,
  7886. #endif
  7887. 0);
  7888. if (sent <= 0) break;
  7889. total_sent += static_cast<size_t>(sent);
  7890. }
  7891. #ifdef _WIN32
  7892. ::shutdown(cli, SD_SEND);
  7893. #else
  7894. ::shutdown(cli, SHUT_WR);
  7895. #endif
  7896. char drain[1024];
  7897. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7898. detail::close_socket(cli);
  7899. }
  7900. detail::close_socket(srv);
  7901. });
  7902. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7903. size_t total_received = 0;
  7904. {
  7905. Client cli("127.0.0.1", PORT + 2);
  7906. cli.set_read_timeout(10, 0);
  7907. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  7908. auto res =
  7909. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7910. total_received += data_length;
  7911. return true;
  7912. });
  7913. ASSERT_TRUE(res);
  7914. EXPECT_EQ(StatusCode::OK_200, res->status);
  7915. }
  7916. server_thread.join();
  7917. EXPECT_EQ(total_received, DATA_SIZE)
  7918. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  7919. << " bytes (larger than " << DATA_SIZE
  7920. << " bytes response), content_receiver should read all data, but only "
  7921. "read "
  7922. << total_received << " bytes.";
  7923. }
  7924. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  7925. // Regression test for "zip bomb" attack on the client side: a malicious server
  7926. // sends a small gzip-compressed response that decompresses to a huge payload.
  7927. // The client must enforce payload_max_length on the decompressed size.
  7928. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  7929. constexpr size_t DECOMPRESSED_SIZE =
  7930. 10 * 1024 * 1024; // 10MB after decompression
  7931. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7932. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  7933. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  7934. std::string compressed;
  7935. {
  7936. httplib::detail::gzip_compressor compressor;
  7937. bool ok =
  7938. compressor.compress(uncompressed.data(), uncompressed.size(),
  7939. /*last=*/true, [&](const char *buf, size_t len) {
  7940. compressed.append(buf, len);
  7941. return true;
  7942. });
  7943. ASSERT_TRUE(ok);
  7944. }
  7945. // Sanity: compressed data should be much smaller than the decompressed size
  7946. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  7947. #ifndef _WIN32
  7948. signal(SIGPIPE, SIG_IGN);
  7949. #endif
  7950. // Set up the listening socket in the main thread so the server is guaranteed
  7951. // to be ready before the client connects (eliminates race condition).
  7952. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7953. default_socket_options(srv);
  7954. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7955. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7956. sockaddr_in addr{};
  7957. addr.sin_family = AF_INET;
  7958. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  7959. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7960. int opt = 1;
  7961. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7962. #ifdef _WIN32
  7963. reinterpret_cast<const char *>(&opt),
  7964. #else
  7965. &opt,
  7966. #endif
  7967. sizeof(opt));
  7968. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  7969. ASSERT_EQ(0, ::listen(srv, 1));
  7970. auto server_thread = std::thread([&compressed, srv] {
  7971. sockaddr_in cli_addr{};
  7972. socklen_t cli_len = sizeof(cli_addr);
  7973. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7974. if (cli != INVALID_SOCKET) {
  7975. // Read the full HTTP request (until \r\n\r\n)
  7976. char buf[4096];
  7977. size_t total = 0;
  7978. while (total < sizeof(buf)) {
  7979. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  7980. if (n <= 0) break;
  7981. total += static_cast<size_t>(n);
  7982. // Check for end of headers
  7983. if (total >= 4) {
  7984. std::string req(buf, total);
  7985. if (req.find("\r\n\r\n") != std::string::npos) break;
  7986. }
  7987. }
  7988. // Malicious response: gzip-compressed body, no Content-Length
  7989. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7990. "Content-Encoding: gzip\r\n"
  7991. "Connection: close\r\n"
  7992. "\r\n";
  7993. ::send(cli,
  7994. #ifdef _WIN32
  7995. static_cast<const char *>(response_header.c_str()),
  7996. static_cast<int>(response_header.size()),
  7997. #else
  7998. response_header.c_str(), response_header.size(),
  7999. #endif
  8000. 0);
  8001. // Send the compressed payload (small on the wire, huge when decompressed)
  8002. size_t total_sent = 0;
  8003. while (total_sent < compressed.size()) {
  8004. auto to_send = std::min(compressed.size() - total_sent,
  8005. static_cast<size_t>(64 * 1024));
  8006. auto sent =
  8007. ::send(cli,
  8008. #ifdef _WIN32
  8009. static_cast<const char *>(compressed.c_str() + total_sent),
  8010. static_cast<int>(to_send),
  8011. #else
  8012. compressed.c_str() + total_sent, to_send,
  8013. #endif
  8014. 0);
  8015. if (sent <= 0) break;
  8016. total_sent += static_cast<size_t>(sent);
  8017. }
  8018. detail::close_socket(cli);
  8019. }
  8020. });
  8021. auto se = detail::scope_exit([&] {
  8022. detail::close_socket(srv);
  8023. server_thread.join();
  8024. });
  8025. size_t total_decompressed = 0;
  8026. {
  8027. Client cli("127.0.0.1", PORT + 3);
  8028. cli.set_read_timeout(5, 0);
  8029. cli.set_decompress(true);
  8030. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8031. auto stream = cli.open_stream("GET", "/zipbomb");
  8032. ASSERT_TRUE(stream.is_valid());
  8033. char buffer[64 * 1024];
  8034. ssize_t n;
  8035. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8036. total_decompressed += static_cast<size_t>(n);
  8037. }
  8038. }
  8039. // The decompressed size must be capped by payload_max_length. Without
  8040. // protection, the client would decompress the full 10MB from a tiny
  8041. // compressed payload, enabling a zip bomb DoS attack.
  8042. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8043. << "Client decompressed " << total_decompressed
  8044. << " bytes from a gzip response. The decompressed size should be "
  8045. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8046. }
  8047. #endif
  8048. TEST(HostAndPortPropertiesTest, NoSSL) {
  8049. httplib::Client cli("www.google.com", 1234);
  8050. ASSERT_EQ("www.google.com", cli.host());
  8051. ASSERT_EQ(1234, cli.port());
  8052. }
  8053. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8054. httplib::Client cli("www.google.com:1234");
  8055. ASSERT_EQ("www.google.com", cli.host());
  8056. ASSERT_EQ(1234, cli.port());
  8057. }
  8058. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8059. // Port number that overflows int — should not crash, client becomes invalid
  8060. httplib::Client cli("http://www.google.com:99999999999999999999");
  8061. ASSERT_FALSE(cli.is_valid());
  8062. }
  8063. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8064. // Port 99999 exceeds valid range (1-65535) — should not crash
  8065. httplib::Client cli("http://www.google.com:99999");
  8066. ASSERT_FALSE(cli.is_valid());
  8067. }
  8068. #ifdef CPPHTTPLIB_SSL_ENABLED
  8069. TEST(HostAndPortPropertiesTest, SSL) {
  8070. httplib::SSLClient cli("www.google.com");
  8071. ASSERT_EQ("www.google.com", cli.host());
  8072. ASSERT_EQ(443, cli.port());
  8073. }
  8074. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8075. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8076. std::string cert;
  8077. read_file(CA_CERT_FILE, cert);
  8078. httplib::SSLClient httplib_client("www.google.com");
  8079. // Load CA store first time
  8080. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8081. // Load CA store second time (update)
  8082. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8083. // Verify client is still valid and can make connections
  8084. httplib_client.enable_server_certificate_verification(true);
  8085. auto res = httplib_client.Get("/");
  8086. ASSERT_TRUE(res);
  8087. // Google may return 200 or 301 depending on various factors
  8088. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8089. res->status == StatusCode::MovedPermanently_301);
  8090. }
  8091. TEST(SSLClientTest, ServerNameIndication_Online) {
  8092. auto host = "httpbingo.org";
  8093. auto path = std::string{"/get"};
  8094. SSLClient cli(host, 443);
  8095. auto res = cli.Get(path);
  8096. ASSERT_TRUE(res);
  8097. ASSERT_EQ(StatusCode::OK_200, res->status);
  8098. }
  8099. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8100. // Use a site that will cause SSL verification failure due to self-signed cert
  8101. SSLClient cli("self-signed.badssl.com", 443);
  8102. cli.enable_server_certificate_verification(true);
  8103. auto res = cli.Get("/");
  8104. ASSERT_TRUE(!res);
  8105. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8106. // Verify backend error is captured for SSLServerVerification
  8107. // This occurs when certificate verification fails
  8108. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8109. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8110. EXPECT_NE(0UL, res.ssl_backend_error());
  8111. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8112. // For OpenSSL, ssl_error is 0 for verification errors
  8113. EXPECT_EQ(0, res.ssl_error());
  8114. #if !defined(_WIN32) || \
  8115. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8116. // On non-Windows or when Windows Schannel is disabled, the error comes
  8117. // from OpenSSL's verification
  8118. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8119. res.ssl_backend_error());
  8120. #endif
  8121. #endif
  8122. }
  8123. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8124. // Use a site where hostname doesn't match the certificate
  8125. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8126. SSLClient cli("wrong.host.badssl.com", 443);
  8127. cli.enable_server_certificate_verification(true);
  8128. cli.enable_server_hostname_verification(true);
  8129. auto res = cli.Get("/");
  8130. ASSERT_TRUE(!res);
  8131. // The error type depends on when hostname verification occurs:
  8132. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8133. // - Mbed TLS: SSLServerVerification (during handshake)
  8134. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8135. res.error() == Error::SSLServerVerification);
  8136. // Verify backend error is captured for hostname verification failure
  8137. EXPECT_NE(0UL, res.ssl_backend_error());
  8138. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8139. // For OpenSSL, ssl_error is 0 for verification errors
  8140. EXPECT_EQ(0, res.ssl_error());
  8141. #if !defined(_WIN32) || \
  8142. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8143. // On non-Windows or when Windows Schannel is disabled, the error comes
  8144. // from OpenSSL's hostname verification
  8145. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8146. res.ssl_backend_error());
  8147. #endif
  8148. #endif
  8149. }
  8150. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8151. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8152. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8153. SSLClient cli("www.google.com", 443);
  8154. cli.enable_server_certificate_verification(true);
  8155. auto res = cli.Get("/");
  8156. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8157. }
  8158. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8159. SSLClient cli("www.google.com", 443);
  8160. cli.enable_server_certificate_verification(true);
  8161. cli.enable_windows_certificate_verification(false);
  8162. auto res = cli.Get("/");
  8163. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8164. }
  8165. #endif
  8166. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8167. Client cli("https://google.com");
  8168. auto res = cli.Get("/");
  8169. ASSERT_TRUE(res);
  8170. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8171. }
  8172. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8173. SSLClient cli("google.com");
  8174. cli.set_ca_cert_path(CA_CERT_FILE);
  8175. auto res = cli.Get("/");
  8176. ASSERT_TRUE(res);
  8177. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8178. }
  8179. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8180. SSLClient cli("google.com");
  8181. cli.enable_server_certificate_verification(true);
  8182. cli.set_ca_cert_path("hello");
  8183. auto res = cli.Get("/");
  8184. ASSERT_TRUE(!res);
  8185. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8186. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8187. // should be set
  8188. EXPECT_EQ(0, res.ssl_error());
  8189. // Verify backend error is captured for SSLLoadingCerts
  8190. // This error occurs when loading CA certificates fails
  8191. EXPECT_NE(0UL, res.ssl_backend_error());
  8192. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8193. // OpenSSL specific error codes:
  8194. // > openssl errstr 0x80000002
  8195. // error:80000002:system library::No such file or directory
  8196. // > openssl errstr 0xA000126
  8197. // error:0A000126:SSL routines::unexpected eof while reading
  8198. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8199. res.ssl_backend_error() == 0xA000126);
  8200. #endif
  8201. }
  8202. TEST(SSLClientTest, ServerCertificateVerification4) {
  8203. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8204. ASSERT_TRUE(svr.is_valid());
  8205. svr.Get("/test", [&](const Request &, Response &res) {
  8206. res.set_content("test", "text/plain");
  8207. svr.stop();
  8208. ASSERT_TRUE(true);
  8209. });
  8210. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8211. auto se = detail::scope_exit([&] {
  8212. t.join();
  8213. ASSERT_FALSE(svr.is_running());
  8214. });
  8215. svr.wait_until_ready();
  8216. SSLClient cli("127.0.0.1", PORT);
  8217. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8218. cli.enable_server_certificate_verification(true);
  8219. cli.set_connection_timeout(30);
  8220. auto res = cli.Get("/test");
  8221. ASSERT_TRUE(res);
  8222. ASSERT_EQ(StatusCode::OK_200, res->status);
  8223. }
  8224. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8225. std::string cert;
  8226. read_file(CA_CERT_FILE, cert);
  8227. SSLClient cli("google.com");
  8228. cli.load_ca_cert_store(cert.data(), cert.size());
  8229. const auto res = cli.Get("/");
  8230. ASSERT_TRUE(res);
  8231. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8232. }
  8233. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8234. // clang-format off
  8235. static constexpr char cert[] =
  8236. "GlobalSign Root CA\n"
  8237. "==================\n"
  8238. "-----BEGIN CERTIFICATE-----\n"
  8239. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8240. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8241. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8242. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8243. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8244. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8245. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8246. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8247. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8248. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8249. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8250. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8251. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8252. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8253. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8254. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8255. "-----END CERTIFICATE-----\n";
  8256. // clang-format on
  8257. SSLClient cli("google.com");
  8258. cli.load_ca_cert_store(cert, sizeof(cert));
  8259. const auto res = cli.Get("/");
  8260. ASSERT_TRUE(res);
  8261. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8262. }
  8263. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8264. SSLClient cli("www.youtube.com");
  8265. cli.set_ca_cert_path(CA_CERT_FILE);
  8266. cli.enable_server_certificate_verification(true);
  8267. cli.set_follow_location(true);
  8268. auto res = cli.Get("/");
  8269. ASSERT_TRUE(res);
  8270. ASSERT_EQ(StatusCode::OK_200, res->status);
  8271. }
  8272. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8273. SSLClient cli("wWw.YouTube.Com");
  8274. cli.set_ca_cert_path(CA_CERT_FILE);
  8275. cli.enable_server_certificate_verification(true);
  8276. cli.enable_server_hostname_verification(true);
  8277. cli.set_follow_location(true);
  8278. auto res = cli.Get("/");
  8279. ASSERT_TRUE(res);
  8280. ASSERT_EQ(StatusCode::OK_200, res->status);
  8281. }
  8282. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8283. SSLClient cli("gOoGlE.COm");
  8284. cli.enable_server_certificate_verification(true);
  8285. cli.enable_server_hostname_verification(true);
  8286. cli.set_follow_location(true);
  8287. auto res = cli.Get("/");
  8288. ASSERT_TRUE(res);
  8289. ASSERT_EQ(StatusCode::OK_200, res->status);
  8290. }
  8291. TEST(SSLClientTest, Issue2004_Online) {
  8292. Client client("https://google.com");
  8293. client.set_follow_location(true);
  8294. auto res = client.Get("/");
  8295. ASSERT_TRUE(res);
  8296. ASSERT_EQ(StatusCode::OK_200, res->status);
  8297. auto body = res->body;
  8298. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8299. }
  8300. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8301. // Create SSLClient with invalid cert/key to make is_valid() return false
  8302. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8303. "nonexistent_key.pem");
  8304. // is_valid() should be false due to cert loading failure
  8305. ASSERT_FALSE(cli.is_valid());
  8306. auto res = cli.Get("/");
  8307. ASSERT_FALSE(res);
  8308. EXPECT_EQ(Error::SSLConnection, res.error());
  8309. }
  8310. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8311. // Test for Issue #2251: SSL error not properly reported when client cert
  8312. // and key paths are swapped or mismatched
  8313. // This simulates the scenario where user accidentally swaps the cert and key
  8314. // files
  8315. // Using client cert file as private key and vice versa (completely wrong)
  8316. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8317. // Should fail validation due to cert/key mismatch
  8318. ASSERT_FALSE(cli.is_valid());
  8319. // Attempt to make a request should fail with proper error
  8320. auto res = cli.Get("/");
  8321. ASSERT_FALSE(res);
  8322. EXPECT_EQ(Error::SSLConnection, res.error());
  8323. // SSL error should be recorded in the Result object (this is the key fix for
  8324. // Issue #2251)
  8325. auto backend_error = res.ssl_backend_error();
  8326. EXPECT_NE(0u, backend_error);
  8327. }
  8328. // Tests cert/key mismatch detection at the TLS context level
  8329. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8330. // Test that using mismatched cert/key causes connection failure.
  8331. // We verify this at the SSLClient level rather than through internal
  8332. // TLS API functions.
  8333. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8334. cli.enable_server_certificate_verification(false);
  8335. cli.set_connection_timeout(2);
  8336. // The mismatch should cause a connection or handshake error
  8337. auto res = cli.Get("/test");
  8338. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8339. // Either way, the request should fail
  8340. EXPECT_FALSE(res);
  8341. }
  8342. #endif
  8343. #if 0
  8344. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8345. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8346. ASSERT_TRUE(cli != nullptr);
  8347. cli->set_address_family(AF_INET6);
  8348. cli->set_interface("en0");
  8349. auto res = cli->Get("/get");
  8350. ASSERT_TRUE(res);
  8351. ASSERT_EQ(StatusCode::OK_200, res->status);
  8352. }
  8353. #endif
  8354. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8355. #ifdef CPPHTTPLIB_SSL_ENABLED
  8356. void ClientCertPresent(
  8357. const std::string &client_cert_file,
  8358. const std::string &client_private_key_file,
  8359. const std::string &client_encrypted_private_key_pass = std::string()) {
  8360. using namespace httplib::tls;
  8361. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8362. CLIENT_CA_CERT_DIR);
  8363. ASSERT_TRUE(svr.is_valid());
  8364. svr.Get("/test", [&](const Request &req, Response &res) {
  8365. res.set_content("test", "text/plain");
  8366. auto cert = req.peer_cert();
  8367. ASSERT_TRUE(static_cast<bool>(cert));
  8368. std::string common_name = cert.subject_cn();
  8369. EXPECT_EQ("Common Name", common_name);
  8370. });
  8371. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8372. auto se = detail::scope_exit([&] {
  8373. svr.stop();
  8374. t.join();
  8375. ASSERT_FALSE(svr.is_running());
  8376. });
  8377. svr.wait_until_ready();
  8378. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8379. client_encrypted_private_key_pass);
  8380. cli.enable_server_certificate_verification(false);
  8381. cli.set_connection_timeout(30);
  8382. auto res = cli.Get("/test");
  8383. ASSERT_TRUE(res);
  8384. ASSERT_EQ(StatusCode::OK_200, res->status);
  8385. }
  8386. TEST(SSLClientServerTest, ClientCertPresent) {
  8387. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8388. }
  8389. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8390. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8391. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8392. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8393. }
  8394. // PEM memory-based constructor tests (works with all TLS backends)
  8395. void PemMemoryClientCertPresent(
  8396. const std::string &client_cert_file,
  8397. const std::string &client_private_key_file,
  8398. const std::string &client_encrypted_private_key_pass = std::string()) {
  8399. // Read PEM files into memory
  8400. std::string server_cert_pem, server_key_pem;
  8401. std::string client_ca_pem;
  8402. std::string client_cert_pem, client_key_pem;
  8403. read_file(SERVER_CERT_FILE, server_cert_pem);
  8404. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8405. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8406. read_file(client_cert_file, client_cert_pem);
  8407. read_file(client_private_key_file, client_key_pem);
  8408. // Create server with PEM memory
  8409. SSLServer::PemMemory server_pem = {
  8410. server_cert_pem.c_str(),
  8411. server_cert_pem.size(),
  8412. server_key_pem.c_str(),
  8413. server_key_pem.size(),
  8414. client_ca_pem.c_str(),
  8415. client_ca_pem.size(),
  8416. nullptr // no password for server key
  8417. };
  8418. SSLServer svr(server_pem);
  8419. ASSERT_TRUE(svr.is_valid());
  8420. svr.Get("/test", [&](const Request &, Response &res) {
  8421. res.set_content("test", "text/plain");
  8422. });
  8423. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8424. auto se = detail::scope_exit([&] {
  8425. svr.stop();
  8426. t.join();
  8427. ASSERT_FALSE(svr.is_running());
  8428. });
  8429. svr.wait_until_ready();
  8430. // Create client with PEM memory
  8431. const char *password = client_encrypted_private_key_pass.empty()
  8432. ? nullptr
  8433. : client_encrypted_private_key_pass.c_str();
  8434. SSLClient::PemMemory client_pem = {
  8435. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8436. client_key_pem.size(), password};
  8437. SSLClient cli(HOST, PORT, client_pem);
  8438. cli.enable_server_certificate_verification(false);
  8439. cli.set_connection_timeout(30);
  8440. auto res = cli.Get("/test");
  8441. ASSERT_TRUE(res);
  8442. ASSERT_EQ(StatusCode::OK_200, res->status);
  8443. }
  8444. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8445. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8446. }
  8447. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8448. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8449. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8450. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8451. }
  8452. TEST(SSLClientServerTest, ClientCertMissing) {
  8453. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8454. CLIENT_CA_CERT_DIR);
  8455. ASSERT_TRUE(svr.is_valid());
  8456. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  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);
  8465. cli.set_connection_timeout(30);
  8466. auto res = cli.Get("/test");
  8467. ASSERT_TRUE(!res);
  8468. // When client cert is missing and server requires it, connection fails
  8469. // Error type depends on backend implementation
  8470. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8471. res.error() == Error::SSLConnection);
  8472. // Verify backend error is captured
  8473. // Note: This test may have different error codes depending on the exact
  8474. // verification failure
  8475. EXPECT_NE(0UL, res.ssl_backend_error());
  8476. }
  8477. TEST(SSLClientServerTest, TrustDirOptional) {
  8478. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8479. ASSERT_TRUE(svr.is_valid());
  8480. svr.Get("/test", [&](const Request &, Response &res) {
  8481. res.set_content("test", "text/plain");
  8482. });
  8483. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8484. auto se = detail::scope_exit([&] {
  8485. svr.stop();
  8486. t.join();
  8487. ASSERT_FALSE(svr.is_running());
  8488. });
  8489. svr.wait_until_ready();
  8490. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8491. cli.enable_server_certificate_verification(false);
  8492. cli.set_connection_timeout(30);
  8493. auto res = cli.Get("/test");
  8494. ASSERT_TRUE(res);
  8495. ASSERT_EQ(StatusCode::OK_200, res->status);
  8496. }
  8497. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8498. class NoListenSSLServer : public SSLServer {
  8499. public:
  8500. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8501. const char *client_ca_cert_file_path,
  8502. const char *client_ca_cert_dir_path = nullptr)
  8503. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8504. client_ca_cert_dir_path),
  8505. stop_(false) {}
  8506. std::atomic_bool stop_;
  8507. private:
  8508. bool process_and_close_socket(socket_t /*sock*/) override {
  8509. // Don't create SSL context
  8510. while (!stop_.load()) {
  8511. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8512. }
  8513. return true;
  8514. }
  8515. };
  8516. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8517. CLIENT_CA_CERT_FILE);
  8518. ASSERT_TRUE(svr.is_valid());
  8519. svr.Get("/test", [&](const Request &, Response &res) {
  8520. res.set_content("test", "text/plain");
  8521. });
  8522. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8523. auto se = detail::scope_exit([&] {
  8524. svr.stop_ = true;
  8525. svr.stop();
  8526. t.join();
  8527. ASSERT_FALSE(svr.is_running());
  8528. });
  8529. svr.wait_until_ready();
  8530. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8531. cli.enable_server_certificate_verification(false);
  8532. cli.set_connection_timeout(1);
  8533. auto res = cli.Get("/test");
  8534. ASSERT_TRUE(!res);
  8535. EXPECT_EQ(Error::SSLConnection, res.error());
  8536. // Timeout results in WantRead error code (maps to backend-specific value)
  8537. EXPECT_NE(0, res.ssl_error());
  8538. }
  8539. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8540. // Test SSLServer with client certificate verification using the standard
  8541. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8542. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8543. CLIENT_CA_CERT_DIR);
  8544. ASSERT_TRUE(svr.is_valid());
  8545. svr.Get("/test", [&](const Request &req, Response &res) {
  8546. res.set_content("test", "text/plain");
  8547. auto cert = req.peer_cert();
  8548. ASSERT_TRUE(static_cast<bool>(cert));
  8549. auto common_name = cert.subject_cn();
  8550. EXPECT_EQ("Common Name", common_name);
  8551. });
  8552. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8553. auto se = detail::scope_exit([&] {
  8554. svr.stop();
  8555. t.join();
  8556. ASSERT_FALSE(svr.is_running());
  8557. });
  8558. svr.wait_until_ready();
  8559. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8560. cli.enable_server_certificate_verification(false);
  8561. cli.set_connection_timeout(30);
  8562. auto res = cli.Get("/test");
  8563. ASSERT_TRUE(res);
  8564. ASSERT_EQ(StatusCode::OK_200, res->status);
  8565. }
  8566. // Test verify_hostname for both OpenSSL and MbedTLS backends
  8567. // Verifies that wildcard matching and exact matching work consistently
  8568. TEST(SSLClientServerTest, TlsVerifyHostname) {
  8569. using namespace httplib::tls;
  8570. // We need a running server to test against
  8571. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8572. ASSERT_TRUE(svr.is_valid());
  8573. svr.Get("/test", [](const Request &, Response &res) {
  8574. res.set_content("ok", "text/plain");
  8575. });
  8576. thread t([&]() { svr.listen(HOST, PORT); });
  8577. auto se = detail::scope_exit([&] {
  8578. svr.stop();
  8579. t.join();
  8580. });
  8581. svr.wait_until_ready();
  8582. bool verify_callback_called = false;
  8583. bool verify_result_wrong = false;
  8584. SSLClient cli(HOST, PORT);
  8585. cli.enable_server_certificate_verification(true);
  8586. cli.set_ca_cert_path(CA_CERT_FILE);
  8587. cli.set_connection_timeout(5);
  8588. // Note: Test certificate has CN="Common Name", not "localhost"
  8589. bool verify_result_cn = false;
  8590. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8591. verify_callback_called = true;
  8592. if (!ctx.cert) return false;
  8593. // Test 1: "Common Name" should match (our test server cert CN)
  8594. verify_result_cn = ctx.check_hostname("Common Name");
  8595. // Test 2: wrong hostname should not match
  8596. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  8597. return true; // Accept for the purpose of this test
  8598. });
  8599. auto res = cli.Get("/test");
  8600. // The request may succeed or fail depending on cert configuration
  8601. // but the callback should have been called
  8602. ASSERT_TRUE(verify_callback_called)
  8603. << "Verify callback should have been called";
  8604. // CN="Common Name" should match our test certificate
  8605. EXPECT_TRUE(verify_result_cn)
  8606. << "verify_hostname should match 'Common Name' (certificate CN)";
  8607. // Wrong hostname should not match
  8608. EXPECT_FALSE(verify_result_wrong)
  8609. << "verify_hostname should not match 'wronghost.example.com'";
  8610. }
  8611. #endif
  8612. // mbedTLS-specific callback constructor test
  8613. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8614. #ifdef CPPHTTPLIB_SSL_ENABLED
  8615. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8616. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8617. ASSERT_TRUE(svr.is_valid());
  8618. // Set up a handler to verify client certificate is present
  8619. bool client_cert_verified = false;
  8620. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8621. // Verify that client certificate was provided
  8622. client_cert_verified = true;
  8623. res.set_content("success", "text/plain");
  8624. });
  8625. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8626. auto se = detail::scope_exit([&] {
  8627. svr.stop();
  8628. t.join();
  8629. ASSERT_FALSE(svr.is_running());
  8630. });
  8631. svr.wait_until_ready();
  8632. // Client with certificate
  8633. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8634. cli.enable_server_certificate_verification(false);
  8635. cli.set_connection_timeout(30);
  8636. auto res = cli.Get("/test");
  8637. ASSERT_TRUE(res);
  8638. ASSERT_EQ(StatusCode::OK_200, res->status);
  8639. ASSERT_TRUE(client_cert_verified);
  8640. EXPECT_EQ("success", res->body);
  8641. }
  8642. #endif
  8643. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  8644. // backends
  8645. #ifdef CPPHTTPLIB_SSL_ENABLED
  8646. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  8647. using namespace httplib::tls;
  8648. // Test that when client CA cert file is provided,
  8649. // the server properly requests and validates client certificates
  8650. // Create a server with client authentication
  8651. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8652. ASSERT_TRUE(svr.is_valid());
  8653. bool handler_called = false;
  8654. svr.Get("/test", [&](const Request &req, Response &res) {
  8655. handler_called = true;
  8656. // Verify that a client certificate was provided
  8657. auto cert = req.peer_cert();
  8658. ASSERT_TRUE(static_cast<bool>(cert));
  8659. // Get the issuer name
  8660. std::string issuer_str = cert.issuer_name();
  8661. ASSERT_FALSE(issuer_str.empty());
  8662. // The client certificate should be issued by our test CA
  8663. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  8664. res.set_content("authenticated", "text/plain");
  8665. });
  8666. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8667. auto se = detail::scope_exit([&] {
  8668. svr.stop();
  8669. t.join();
  8670. ASSERT_FALSE(svr.is_running());
  8671. });
  8672. svr.wait_until_ready();
  8673. // Connect with a client certificate issued by the CA
  8674. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8675. cli.enable_server_certificate_verification(false);
  8676. cli.set_connection_timeout(30);
  8677. auto res = cli.Get("/test");
  8678. ASSERT_TRUE(res);
  8679. ASSERT_EQ(StatusCode::OK_200, res->status);
  8680. ASSERT_TRUE(handler_called);
  8681. EXPECT_EQ("authenticated", res->body);
  8682. }
  8683. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  8684. using namespace httplib::tls;
  8685. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8686. ASSERT_TRUE(svr.is_valid());
  8687. svr.Get("/test", [](const Request &, Response &res) {
  8688. res.set_content("ok", "text/plain");
  8689. });
  8690. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8691. auto se = detail::scope_exit([&] {
  8692. svr.stop();
  8693. t.join();
  8694. });
  8695. svr.wait_until_ready();
  8696. SSLClient cli(HOST, PORT);
  8697. cli.enable_server_certificate_verification(false);
  8698. cli.set_connection_timeout(30);
  8699. bool cert_checked = false;
  8700. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8701. if (ctx.cert) {
  8702. auto sans = ctx.sans();
  8703. // Test certificate may or may not have SANs - just verify the API
  8704. // works If SANs exist, verify the types are valid
  8705. for (const auto &san : sans) {
  8706. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  8707. san.type == SanType::EMAIL || san.type == SanType::URI ||
  8708. san.type == SanType::OTHER);
  8709. EXPECT_FALSE(san.value.empty());
  8710. }
  8711. cert_checked = true;
  8712. }
  8713. return true;
  8714. });
  8715. auto res = cli.Get("/test");
  8716. ASSERT_TRUE(res);
  8717. EXPECT_TRUE(cert_checked);
  8718. }
  8719. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  8720. using namespace httplib::tls;
  8721. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8722. ASSERT_TRUE(svr.is_valid());
  8723. svr.Get("/test", [](const Request &, Response &res) {
  8724. res.set_content("ok", "text/plain");
  8725. });
  8726. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8727. auto se = detail::scope_exit([&] {
  8728. svr.stop();
  8729. t.join();
  8730. });
  8731. svr.wait_until_ready();
  8732. SSLClient cli(HOST, PORT);
  8733. cli.enable_server_certificate_verification(false);
  8734. cli.set_connection_timeout(30);
  8735. bool validity_checked = false;
  8736. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8737. if (ctx.cert) {
  8738. time_t not_before = 0, not_after = 0;
  8739. bool result = ctx.validity(not_before, not_after);
  8740. EXPECT_TRUE(result);
  8741. // Verify that not_before < now < not_after for a valid cert
  8742. time_t now = time(nullptr);
  8743. EXPECT_LT(not_before, now);
  8744. EXPECT_GT(not_after, now);
  8745. validity_checked = true;
  8746. }
  8747. return true;
  8748. });
  8749. auto res = cli.Get("/test");
  8750. ASSERT_TRUE(res);
  8751. EXPECT_TRUE(validity_checked);
  8752. }
  8753. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  8754. using namespace httplib::tls;
  8755. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8756. ASSERT_TRUE(svr.is_valid());
  8757. svr.Get("/test", [](const Request &, Response &res) {
  8758. res.set_content("ok", "text/plain");
  8759. });
  8760. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8761. auto se = detail::scope_exit([&] {
  8762. svr.stop();
  8763. t.join();
  8764. });
  8765. svr.wait_until_ready();
  8766. SSLClient cli(HOST, PORT);
  8767. cli.enable_server_certificate_verification(false);
  8768. cli.set_connection_timeout(30);
  8769. bool serial_checked = false;
  8770. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8771. if (ctx.cert) {
  8772. std::string serial = ctx.serial();
  8773. EXPECT_FALSE(serial.empty());
  8774. // Serial should be a hex string
  8775. for (char c : serial) {
  8776. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  8777. (c >= 'a' && c <= 'f'));
  8778. }
  8779. serial_checked = true;
  8780. }
  8781. return true;
  8782. });
  8783. auto res = cli.Get("/test");
  8784. ASSERT_TRUE(res);
  8785. EXPECT_TRUE(serial_checked);
  8786. }
  8787. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  8788. // Test 1: Valid CA file - no error should be recorded
  8789. {
  8790. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8791. CLIENT_CA_CERT_FILE);
  8792. ASSERT_TRUE(svr.is_valid());
  8793. // With valid setup, last_ssl_error should be 0
  8794. EXPECT_EQ(0, svr.ssl_last_error());
  8795. }
  8796. // Test 2: Invalid CA file content
  8797. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  8798. {
  8799. // Create a temporary file with completely invalid content
  8800. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  8801. {
  8802. std::ofstream ofs(temp_invalid_ca);
  8803. ofs << "This is not a certificate file at all\n";
  8804. ofs << "Just plain text content\n";
  8805. }
  8806. // Create server with invalid CA file
  8807. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  8808. // Clean up temporary file
  8809. std::remove(temp_invalid_ca);
  8810. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  8811. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  8812. // Note: SSL_CTX_load_verify_locations typically fails first,
  8813. // but our error handling code path is still exercised
  8814. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  8815. }
  8816. }
  8817. TEST(VerifyCallbackTest, VerifyContextFields) {
  8818. using namespace httplib::tls;
  8819. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8820. ASSERT_TRUE(svr.is_valid());
  8821. svr.Get("/test", [](const Request &, Response &res) {
  8822. res.set_content("ok", "text/plain");
  8823. });
  8824. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8825. auto se = detail::scope_exit([&] {
  8826. svr.stop();
  8827. t.join();
  8828. });
  8829. svr.wait_until_ready();
  8830. SSLClient cli(HOST, PORT);
  8831. cli.enable_server_certificate_verification(false);
  8832. cli.set_connection_timeout(30);
  8833. int callback_count = 0;
  8834. bool saw_leaf_cert = false;
  8835. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8836. if (ctx.cert) {
  8837. callback_count++;
  8838. // We should see at least one certificate (the leaf)
  8839. std::string cn = ctx.subject_cn();
  8840. if (!cn.empty()) { saw_leaf_cert = true; }
  8841. // Verify context fields are populated
  8842. EXPECT_NE(ctx.session, nullptr);
  8843. EXPECT_GE(ctx.depth, 0);
  8844. }
  8845. return true;
  8846. });
  8847. auto res = cli.Get("/test");
  8848. ASSERT_TRUE(res);
  8849. EXPECT_GT(callback_count, 0);
  8850. EXPECT_TRUE(saw_leaf_cert);
  8851. }
  8852. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  8853. using httplib::tls::TlsError;
  8854. // Test that verify_error_to_string returns empty for success
  8855. std::string success_str = TlsError::verify_error_to_string(0);
  8856. EXPECT_TRUE(success_str.empty());
  8857. // Test that verify_error_to_string returns non-empty for error codes
  8858. // Using a common error code (certificate expired)
  8859. std::string error_str =
  8860. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  8861. EXPECT_FALSE(error_str.empty());
  8862. }
  8863. TEST(SessionVerifierTest, CertificateAccepted) {
  8864. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8865. ASSERT_TRUE(svr.is_valid());
  8866. svr.Get("/test", [](const Request &, Response &res) {
  8867. res.set_content("ok", "text/plain");
  8868. });
  8869. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8870. auto se = detail::scope_exit([&] {
  8871. svr.stop();
  8872. t.join();
  8873. });
  8874. svr.wait_until_ready();
  8875. SSLClient cli(HOST, PORT);
  8876. cli.enable_server_certificate_verification(false);
  8877. cli.set_connection_timeout(30);
  8878. bool callback_called = false;
  8879. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8880. EXPECT_NE(session, nullptr);
  8881. callback_called = true;
  8882. return SSLVerifierResponse::CertificateAccepted;
  8883. });
  8884. auto res = cli.Get("/test");
  8885. ASSERT_TRUE(res);
  8886. EXPECT_EQ(200, res->status);
  8887. EXPECT_TRUE(callback_called);
  8888. }
  8889. TEST(SessionVerifierTest, CertificateRejected) {
  8890. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8891. ASSERT_TRUE(svr.is_valid());
  8892. svr.Get("/test", [](const Request &, Response &res) {
  8893. res.set_content("ok", "text/plain");
  8894. });
  8895. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8896. auto se = detail::scope_exit([&] {
  8897. svr.stop();
  8898. t.join();
  8899. });
  8900. svr.wait_until_ready();
  8901. SSLClient cli(HOST, PORT);
  8902. cli.enable_server_certificate_verification(false);
  8903. cli.set_connection_timeout(30);
  8904. bool callback_called = false;
  8905. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8906. EXPECT_NE(session, nullptr);
  8907. callback_called = true;
  8908. return SSLVerifierResponse::CertificateRejected;
  8909. });
  8910. auto res = cli.Get("/test");
  8911. EXPECT_FALSE(res);
  8912. EXPECT_TRUE(callback_called);
  8913. }
  8914. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  8915. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8916. ASSERT_TRUE(svr.is_valid());
  8917. svr.Get("/test", [](const Request &, Response &res) {
  8918. res.set_content("ok", "text/plain");
  8919. });
  8920. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8921. auto se = detail::scope_exit([&] {
  8922. svr.stop();
  8923. t.join();
  8924. });
  8925. svr.wait_until_ready();
  8926. // NoDecisionMade with verification disabled should succeed (no default check)
  8927. SSLClient cli(HOST, PORT);
  8928. cli.enable_server_certificate_verification(false);
  8929. cli.set_connection_timeout(30);
  8930. bool callback_called = false;
  8931. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8932. EXPECT_NE(session, nullptr);
  8933. callback_called = true;
  8934. return SSLVerifierResponse::NoDecisionMade;
  8935. });
  8936. auto res = cli.Get("/test");
  8937. ASSERT_TRUE(res);
  8938. EXPECT_EQ(200, res->status);
  8939. EXPECT_TRUE(callback_called);
  8940. }
  8941. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  8942. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8943. ASSERT_TRUE(svr.is_valid());
  8944. svr.Get("/test", [](const Request &, Response &res) {
  8945. res.set_content("ok", "text/plain");
  8946. });
  8947. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8948. auto se = detail::scope_exit([&] {
  8949. svr.stop();
  8950. t.join();
  8951. });
  8952. svr.wait_until_ready();
  8953. // NoDecisionMade with verification enabled should fail (self-signed cert).
  8954. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  8955. // so we only check that the request fails, not whether the callback was
  8956. // called.
  8957. SSLClient cli(HOST, PORT);
  8958. cli.enable_server_certificate_verification(true);
  8959. cli.set_connection_timeout(30);
  8960. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8961. EXPECT_NE(session, nullptr);
  8962. return SSLVerifierResponse::NoDecisionMade;
  8963. });
  8964. auto res = cli.Get("/test");
  8965. EXPECT_FALSE(res);
  8966. }
  8967. TEST(SSLClientServerTest, ClientCAListFromPem) {
  8968. // Test SSL server using PemMemory constructor with client CA certificates
  8969. // Read PEM files
  8970. std::string server_cert_pem, server_key_pem, client_ca_pem;
  8971. read_file(SERVER_CERT_FILE, server_cert_pem);
  8972. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8973. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8974. // Create SSLServer with PemMemory constructor including client CA
  8975. SSLServer::PemMemory server_pem = {
  8976. server_cert_pem.c_str(),
  8977. server_cert_pem.size(),
  8978. server_key_pem.c_str(),
  8979. server_key_pem.size(),
  8980. client_ca_pem.c_str(),
  8981. client_ca_pem.size(),
  8982. nullptr // no password for server key
  8983. };
  8984. SSLServer svr(server_pem);
  8985. ASSERT_TRUE(svr.is_valid());
  8986. // No SSL error should be recorded for valid setup
  8987. EXPECT_EQ(0, svr.ssl_last_error());
  8988. // Set up server endpoints
  8989. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  8990. res.set_content("ok", "text/plain");
  8991. });
  8992. // Start server in a thread
  8993. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  8994. svr.wait_until_ready();
  8995. // Connect with client certificate (using constructor with paths)
  8996. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8997. cli.enable_server_certificate_verification(false);
  8998. auto res = cli.Get("/test-pem-ca");
  8999. ASSERT_TRUE(res);
  9000. EXPECT_EQ(200, res->status);
  9001. EXPECT_EQ("ok", res->body);
  9002. svr.stop();
  9003. server_thread.join();
  9004. }
  9005. #endif
  9006. #ifdef _WIN32
  9007. TEST(CleanupTest, WSACleanup) {
  9008. int ret = WSACleanup();
  9009. ASSERT_EQ(0, ret);
  9010. }
  9011. #endif
  9012. #ifndef CPPHTTPLIB_SSL_ENABLED
  9013. TEST(NoSSLSupport, SimpleInterface) {
  9014. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  9015. }
  9016. #endif
  9017. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9018. TEST(InvalidScheme, SimpleInterface) {
  9019. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  9020. }
  9021. #endif
  9022. TEST(NoScheme, SimpleInterface) {
  9023. Client cli("yahoo.com:80");
  9024. ASSERT_TRUE(cli.is_valid());
  9025. }
  9026. TEST(SendAPI, SimpleInterface_Online) {
  9027. Client cli("http://yahoo.com");
  9028. Request req;
  9029. req.method = "GET";
  9030. req.path = "/";
  9031. auto res = cli.send(req);
  9032. ASSERT_TRUE(res);
  9033. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9034. }
  9035. TEST(SendAPI, WithParamsInRequest) {
  9036. Server svr;
  9037. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  9038. EXPECT_TRUE(req.has_param("test"));
  9039. EXPECT_EQ("test_value", req.get_param_value("test"));
  9040. });
  9041. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  9042. auto se = detail::scope_exit([&] {
  9043. svr.stop();
  9044. t.join();
  9045. ASSERT_FALSE(svr.is_running());
  9046. });
  9047. svr.wait_until_ready();
  9048. Client cli(HOST, PORT);
  9049. {
  9050. Request req;
  9051. req.method = "GET";
  9052. req.path = "/";
  9053. req.params.emplace("test", "test_value");
  9054. auto res = cli.send(req);
  9055. ASSERT_TRUE(res);
  9056. }
  9057. {
  9058. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  9059. ASSERT_TRUE(res);
  9060. }
  9061. }
  9062. TEST(ClientImplMethods, GetSocketTest) {
  9063. httplib::Server svr;
  9064. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9065. res.status = StatusCode::OK_200;
  9066. });
  9067. auto port = svr.bind_to_any_port("127.0.0.1");
  9068. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9069. auto se = detail::scope_exit([&] {
  9070. svr.stop();
  9071. thread.join();
  9072. ASSERT_FALSE(svr.is_running());
  9073. });
  9074. svr.wait_until_ready();
  9075. {
  9076. httplib::Client cli("127.0.0.1", port);
  9077. cli.set_keep_alive(true);
  9078. // Use the behavior of cpp-httplib of opening the connection
  9079. // only when the first request happens. If that changes,
  9080. // this test would be obsolete.
  9081. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9082. // This also implicitly tests the server. But other tests would fail much
  9083. // earlier than this one to be considered.
  9084. auto res = cli.Get("/");
  9085. ASSERT_TRUE(res);
  9086. EXPECT_EQ(StatusCode::OK_200, res->status);
  9087. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9088. }
  9089. }
  9090. #ifdef CPPHTTPLIB_SSL_ENABLED
  9091. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9092. Client cli("http://yahoo.com");
  9093. auto res = cli.Get("/");
  9094. ASSERT_TRUE(res);
  9095. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9096. cli.set_follow_location(true);
  9097. res = cli.Get("/");
  9098. ASSERT_TRUE(res);
  9099. EXPECT_EQ(StatusCode::OK_200, res->status);
  9100. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9101. }
  9102. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9103. Client cli("https://yahoo.com");
  9104. auto res = cli.Get("/");
  9105. ASSERT_TRUE(res);
  9106. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9107. cli.set_follow_location(true);
  9108. res = cli.Get("/");
  9109. ASSERT_TRUE(res);
  9110. EXPECT_EQ(StatusCode::OK_200, res->status);
  9111. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9112. }
  9113. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9114. Client cli("https://yahoo.com");
  9115. auto res = cli.Get("/");
  9116. ASSERT_TRUE(res);
  9117. ASSERT_FALSE(!res);
  9118. ASSERT_TRUE(res);
  9119. ASSERT_FALSE(res == nullptr);
  9120. ASSERT_TRUE(res != nullptr);
  9121. EXPECT_EQ(Error::Success, res.error());
  9122. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9123. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9124. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9125. cli.set_follow_location(true);
  9126. res = cli.Get("/");
  9127. ASSERT_TRUE(res);
  9128. EXPECT_EQ(Error::Success, res.error());
  9129. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9130. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9131. EXPECT_EQ(StatusCode::OK_200, res->status);
  9132. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9133. }
  9134. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9135. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9136. Client cli("https://cdnjs.cloudflare.com");
  9137. auto res =
  9138. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9139. ASSERT_TRUE(res);
  9140. EXPECT_EQ(StatusCode::OK_200, res->status);
  9141. EXPECT_EQ(287630U, res->body.size());
  9142. EXPECT_EQ("application/javascript; charset=utf-8",
  9143. res->get_header_value("Content-Type"));
  9144. }
  9145. #endif
  9146. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9147. #undef REDIR_HOST // Silence compiler warning
  9148. #define REDIR_HOST "https://httpbingo.org"
  9149. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9150. Client cli(REDIR_HOST);
  9151. cli.set_follow_location(true);
  9152. auto res =
  9153. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9154. ASSERT_TRUE(res);
  9155. EXPECT_EQ(StatusCode::OK_200, res->status);
  9156. }
  9157. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9158. Client cli(REDIR_HOST);
  9159. cli.set_follow_location(true);
  9160. Params params;
  9161. params.emplace("url", "http://example.com");
  9162. params.emplace("status_code", "302");
  9163. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9164. ASSERT_TRUE(res);
  9165. EXPECT_EQ(StatusCode::OK_200, res->status);
  9166. }
  9167. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9168. Client cli(REDIR_HOST);
  9169. cli.set_follow_location(true);
  9170. Params params;
  9171. params.emplace("url", "http://example.com");
  9172. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9173. ASSERT_TRUE(res);
  9174. EXPECT_EQ(StatusCode::OK_200, res->status);
  9175. }
  9176. TEST(HttpToHttpsRedirectTest, CertFile) {
  9177. auto ssl_port = PORT + 1;
  9178. Server svr;
  9179. ASSERT_TRUE(svr.is_valid());
  9180. svr.Get("/index", [&](const Request &, Response &res) {
  9181. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9182. "/index");
  9183. svr.stop();
  9184. });
  9185. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9186. ASSERT_TRUE(ssl_svr.is_valid());
  9187. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9188. res.set_content("test", "text/plain");
  9189. ssl_svr.stop();
  9190. });
  9191. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9192. thread t2 =
  9193. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9194. auto se = detail::scope_exit([&] {
  9195. t2.join();
  9196. t.join();
  9197. ASSERT_FALSE(svr.is_running());
  9198. });
  9199. svr.wait_until_ready();
  9200. ssl_svr.wait_until_ready();
  9201. Client cli("127.0.0.1", PORT);
  9202. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9203. cli.enable_server_certificate_verification(true);
  9204. cli.set_follow_location(true);
  9205. cli.set_connection_timeout(30);
  9206. auto res = cli.Get("/index");
  9207. ASSERT_TRUE(res);
  9208. ASSERT_EQ(StatusCode::OK_200, res->status);
  9209. }
  9210. TEST(SSLClientRedirectTest, CertFile) {
  9211. auto ssl_port = PORT + 1;
  9212. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9213. ASSERT_TRUE(ssl_svr1.is_valid());
  9214. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9215. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9216. "/index");
  9217. ssl_svr1.stop();
  9218. });
  9219. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9220. ASSERT_TRUE(ssl_svr2.is_valid());
  9221. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9222. res.set_content("test", "text/plain");
  9223. ssl_svr2.stop();
  9224. });
  9225. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9226. thread t2 =
  9227. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9228. auto se = detail::scope_exit([&] {
  9229. t2.join();
  9230. t.join();
  9231. ASSERT_FALSE(ssl_svr1.is_running());
  9232. });
  9233. ssl_svr1.wait_until_ready();
  9234. ssl_svr2.wait_until_ready();
  9235. SSLClient cli("127.0.0.1", PORT);
  9236. std::string cert;
  9237. read_file(SERVER_CERT2_FILE, cert);
  9238. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9239. cli.enable_server_certificate_verification(true);
  9240. cli.set_follow_location(true);
  9241. cli.set_connection_timeout(30);
  9242. auto res = cli.Get("/index");
  9243. ASSERT_TRUE(res);
  9244. ASSERT_EQ(StatusCode::OK_200, res->status);
  9245. }
  9246. #endif
  9247. #ifdef CPPHTTPLIB_SSL_ENABLED
  9248. // Test that set_ca_cert_store() skips system certs (consistent with
  9249. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9250. // should be trusted - system certs should NOT be loaded.
  9251. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9252. // Load a specific cert that is NOT a system CA cert
  9253. std::string cert;
  9254. read_file(SERVER_CERT2_FILE, cert);
  9255. SSLClient cli("google.com");
  9256. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9257. cli.enable_server_certificate_verification(true);
  9258. // This should FAIL because:
  9259. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9260. // 2. System certs should NOT be loaded when custom store is set
  9261. // If system certs WERE loaded, this would succeed
  9262. auto res = cli.Get("/");
  9263. ASSERT_FALSE(res);
  9264. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9265. }
  9266. TEST(MultipartFormDataTest, LargeData) {
  9267. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9268. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9269. const ContentReader &content_reader) {
  9270. if (req.is_multipart_form_data()) {
  9271. std::vector<FormData> items;
  9272. content_reader(
  9273. [&](const FormData &file) {
  9274. items.push_back(file);
  9275. return true;
  9276. },
  9277. [&](const char *data, size_t data_length) {
  9278. items.back().content.append(data, data_length);
  9279. return true;
  9280. });
  9281. EXPECT_TRUE(std::string(items[0].name) == "document");
  9282. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9283. EXPECT_TRUE(items[0].filename == "2MB_data");
  9284. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9285. EXPECT_TRUE(items[1].name == "hello");
  9286. EXPECT_TRUE(items[1].content == "world");
  9287. EXPECT_TRUE(items[1].filename == "");
  9288. EXPECT_TRUE(items[1].content_type == "");
  9289. } else {
  9290. std::string body;
  9291. content_reader([&](const char *data, size_t data_length) {
  9292. body.append(data, data_length);
  9293. return true;
  9294. });
  9295. }
  9296. });
  9297. auto port = svr.bind_to_any_port(HOST);
  9298. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9299. auto se = detail::scope_exit([&] {
  9300. svr.stop();
  9301. t.join();
  9302. ASSERT_FALSE(svr.is_running());
  9303. });
  9304. svr.wait_until_ready();
  9305. {
  9306. std::string data(1024 * 1024 * 2, '.');
  9307. std::stringstream buffer;
  9308. buffer << data;
  9309. SSLClient cli(HOST, port);
  9310. cli.enable_server_certificate_verification(false);
  9311. UploadFormDataItems items{
  9312. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9313. {"hello", "world", "", ""},
  9314. };
  9315. auto res = cli.Post("/post", items);
  9316. ASSERT_TRUE(res);
  9317. ASSERT_EQ(StatusCode::OK_200, res->status);
  9318. }
  9319. }
  9320. TEST(MultipartFormDataTest, DataProviderItems) {
  9321. std::random_device seed_gen;
  9322. std::mt19937 random(seed_gen());
  9323. std::string rand1;
  9324. rand1.resize(1000);
  9325. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9326. std::string rand2;
  9327. rand2.resize(3000);
  9328. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9329. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9330. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9331. const ContentReader &content_reader) {
  9332. ASSERT_FALSE(req.is_multipart_form_data());
  9333. std::string body;
  9334. content_reader([&](const char *data, size_t data_length) {
  9335. body.append(data, data_length);
  9336. return true;
  9337. });
  9338. EXPECT_EQ(body, "");
  9339. });
  9340. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9341. const ContentReader &content_reader) {
  9342. ASSERT_TRUE(req.is_multipart_form_data());
  9343. std::vector<FormData> items;
  9344. content_reader(
  9345. [&](const FormData &file) {
  9346. items.push_back(file);
  9347. return true;
  9348. },
  9349. [&](const char *data, size_t data_length) {
  9350. items.back().content.append(data, data_length);
  9351. return true;
  9352. });
  9353. ASSERT_TRUE(items.size() == 2);
  9354. EXPECT_EQ(std::string(items[0].name), "name1");
  9355. EXPECT_EQ(items[0].content, "Testing123");
  9356. EXPECT_EQ(items[0].filename, "filename1");
  9357. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9358. EXPECT_EQ(items[1].name, "name2");
  9359. EXPECT_EQ(items[1].content, "Testing456");
  9360. EXPECT_EQ(items[1].filename, "");
  9361. EXPECT_EQ(items[1].content_type, "");
  9362. });
  9363. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9364. const ContentReader &content_reader) {
  9365. ASSERT_TRUE(req.is_multipart_form_data());
  9366. std::vector<FormData> items;
  9367. content_reader(
  9368. [&](const FormData &file) {
  9369. items.push_back(file);
  9370. return true;
  9371. },
  9372. [&](const char *data, size_t data_length) {
  9373. items.back().content.append(data, data_length);
  9374. return true;
  9375. });
  9376. ASSERT_TRUE(items.size() == 2);
  9377. EXPECT_EQ(items[0].name, "name3");
  9378. EXPECT_EQ(items[0].content, rand1);
  9379. EXPECT_EQ(items[0].filename, "filename3");
  9380. EXPECT_EQ(items[0].content_type, "");
  9381. EXPECT_EQ(items[1].name, "name4");
  9382. EXPECT_EQ(items[1].content, rand2);
  9383. EXPECT_EQ(items[1].filename, "filename4");
  9384. EXPECT_EQ(items[1].content_type, "");
  9385. });
  9386. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9387. const ContentReader &content_reader) {
  9388. ASSERT_TRUE(req.is_multipart_form_data());
  9389. std::vector<FormData> items;
  9390. content_reader(
  9391. [&](const FormData &file) {
  9392. items.push_back(file);
  9393. return true;
  9394. },
  9395. [&](const char *data, size_t data_length) {
  9396. items.back().content.append(data, data_length);
  9397. return true;
  9398. });
  9399. ASSERT_TRUE(items.size() == 4);
  9400. EXPECT_EQ(std::string(items[0].name), "name1");
  9401. EXPECT_EQ(items[0].content, "Testing123");
  9402. EXPECT_EQ(items[0].filename, "filename1");
  9403. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9404. EXPECT_EQ(items[1].name, "name2");
  9405. EXPECT_EQ(items[1].content, "Testing456");
  9406. EXPECT_EQ(items[1].filename, "");
  9407. EXPECT_EQ(items[1].content_type, "");
  9408. EXPECT_EQ(items[2].name, "name3");
  9409. EXPECT_EQ(items[2].content, rand1);
  9410. EXPECT_EQ(items[2].filename, "filename3");
  9411. EXPECT_EQ(items[2].content_type, "");
  9412. EXPECT_EQ(items[3].name, "name4");
  9413. EXPECT_EQ(items[3].content, rand2);
  9414. EXPECT_EQ(items[3].filename, "filename4");
  9415. EXPECT_EQ(items[3].content_type, "");
  9416. });
  9417. auto port = svr.bind_to_any_port("localhost");
  9418. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9419. auto se = detail::scope_exit([&] {
  9420. svr.stop();
  9421. t.join();
  9422. ASSERT_FALSE(svr.is_running());
  9423. });
  9424. svr.wait_until_ready();
  9425. {
  9426. SSLClient cli("localhost", port);
  9427. cli.enable_server_certificate_verification(false);
  9428. UploadFormDataItems items{
  9429. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9430. {"name2", "Testing456", "", ""}, // not a file
  9431. };
  9432. {
  9433. auto res = cli.Post("/post-none", {}, {}, {});
  9434. ASSERT_TRUE(res);
  9435. ASSERT_EQ(StatusCode::OK_200, res->status);
  9436. }
  9437. FormDataProviderItems providers;
  9438. {
  9439. auto res =
  9440. cli.Post("/post-items", {}, items, providers); // empty providers
  9441. ASSERT_TRUE(res);
  9442. ASSERT_EQ(StatusCode::OK_200, res->status);
  9443. }
  9444. providers.push_back({"name3",
  9445. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9446. // test the offset is given correctly at each step
  9447. if (!offset)
  9448. sink.os.write(rand1.data(), 30);
  9449. else if (offset == 30)
  9450. sink.os.write(rand1.data() + 30, 300);
  9451. else if (offset == 330)
  9452. sink.os.write(rand1.data() + 330, 670);
  9453. else if (offset == rand1.size())
  9454. sink.done();
  9455. return true;
  9456. },
  9457. "filename3",
  9458. {}});
  9459. providers.push_back({"name4",
  9460. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9461. // test the offset is given correctly at each step
  9462. if (!offset)
  9463. sink.os.write(rand2.data(), 2000);
  9464. else if (offset == 2000)
  9465. sink.os.write(rand2.data() + 2000, 1);
  9466. else if (offset == 2001)
  9467. sink.os.write(rand2.data() + 2001, 999);
  9468. else if (offset == rand2.size())
  9469. sink.done();
  9470. return true;
  9471. },
  9472. "filename4",
  9473. {}});
  9474. {
  9475. auto res = cli.Post("/post-providers", {}, {}, providers);
  9476. ASSERT_TRUE(res);
  9477. ASSERT_EQ(StatusCode::OK_200, res->status);
  9478. }
  9479. {
  9480. auto res = cli.Post("/post-both", {}, items, providers);
  9481. ASSERT_TRUE(res);
  9482. ASSERT_EQ(StatusCode::OK_200, res->status);
  9483. }
  9484. }
  9485. }
  9486. TEST(MultipartFormDataTest, BadHeader) {
  9487. Server svr;
  9488. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9489. res.set_content("ok", "text/plain");
  9490. });
  9491. thread t = thread([&] { svr.listen(HOST, PORT); });
  9492. auto se = detail::scope_exit([&] {
  9493. svr.stop();
  9494. t.join();
  9495. ASSERT_FALSE(svr.is_running());
  9496. });
  9497. svr.wait_until_ready();
  9498. const std::string body =
  9499. "This is the preamble. It is to be ignored, though it\r\n"
  9500. "is a handy place for composition agents to include an\r\n"
  9501. "explanatory note to non-MIME conformant readers.\r\n"
  9502. "\r\n"
  9503. "\r\n"
  9504. "--simple boundary\r\n"
  9505. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9506. ": BAD...\r\n"
  9507. "\r\n"
  9508. "value1\r\n"
  9509. "--simple boundary\r\n"
  9510. "Content-Disposition: form-data; name=\"field2\"; "
  9511. "filename=\"example.txt\"\r\n"
  9512. "\r\n"
  9513. "value2\r\n"
  9514. "--simple boundary--\r\n"
  9515. "This is the epilogue. It is also to be ignored.\r\n";
  9516. std::string content_type =
  9517. R"(multipart/form-data; boundary="simple boundary")";
  9518. Client cli(HOST, PORT);
  9519. auto res = cli.Post("/post", body, content_type.c_str());
  9520. ASSERT_TRUE(res);
  9521. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9522. }
  9523. TEST(MultipartFormDataTest, WithPreamble) {
  9524. Server svr;
  9525. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9526. res.set_content("ok", "text/plain");
  9527. });
  9528. thread t = thread([&] { svr.listen(HOST, PORT); });
  9529. auto se = detail::scope_exit([&] {
  9530. svr.stop();
  9531. t.join();
  9532. ASSERT_FALSE(svr.is_running());
  9533. });
  9534. svr.wait_until_ready();
  9535. const std::string body =
  9536. "This is the preamble. It is to be ignored, though it\r\n"
  9537. "is a handy place for composition agents to include an\r\n"
  9538. "explanatory note to non-MIME conformant readers.\r\n"
  9539. "\r\n"
  9540. "\r\n"
  9541. "--simple boundary\r\n"
  9542. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9543. "\r\n"
  9544. "value1\r\n"
  9545. "--simple boundary\r\n"
  9546. "Content-Disposition: form-data; name=\"field2\"; "
  9547. "filename=\"example.txt\"\r\n"
  9548. "\r\n"
  9549. "value2\r\n"
  9550. "--simple boundary--\r\n"
  9551. "This is the epilogue. It is also to be ignored.\r\n";
  9552. std::string content_type =
  9553. R"(multipart/form-data; boundary="simple boundary")";
  9554. Client cli(HOST, PORT);
  9555. auto res = cli.Post("/post", body, content_type.c_str());
  9556. ASSERT_TRUE(res);
  9557. EXPECT_EQ(StatusCode::OK_200, res->status);
  9558. }
  9559. TEST(MultipartFormDataTest, PostCustomBoundary) {
  9560. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9561. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  9562. const ContentReader &content_reader) {
  9563. if (req.is_multipart_form_data()) {
  9564. std::vector<FormData> items;
  9565. content_reader(
  9566. [&](const FormData &file) {
  9567. items.push_back(file);
  9568. return true;
  9569. },
  9570. [&](const char *data, size_t data_length) {
  9571. items.back().content.append(data, data_length);
  9572. return true;
  9573. });
  9574. EXPECT_TRUE(std::string(items[0].name) == "document");
  9575. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9576. EXPECT_TRUE(items[0].filename == "2MB_data");
  9577. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9578. EXPECT_TRUE(items[1].name == "hello");
  9579. EXPECT_TRUE(items[1].content == "world");
  9580. EXPECT_TRUE(items[1].filename == "");
  9581. EXPECT_TRUE(items[1].content_type == "");
  9582. } else {
  9583. std::string body;
  9584. content_reader([&](const char *data, size_t data_length) {
  9585. body.append(data, data_length);
  9586. return true;
  9587. });
  9588. }
  9589. });
  9590. auto port = svr.bind_to_any_port("localhost");
  9591. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9592. auto se = detail::scope_exit([&] {
  9593. svr.stop();
  9594. t.join();
  9595. ASSERT_FALSE(svr.is_running());
  9596. });
  9597. svr.wait_until_ready();
  9598. {
  9599. std::string data(1024 * 1024 * 2, '.');
  9600. std::stringstream buffer;
  9601. buffer << data;
  9602. SSLClient cli("localhost", port);
  9603. cli.enable_server_certificate_verification(false);
  9604. UploadFormDataItems items{
  9605. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9606. {"hello", "world", "", ""},
  9607. };
  9608. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9609. ASSERT_TRUE(res);
  9610. ASSERT_EQ(StatusCode::OK_200, res->status);
  9611. }
  9612. }
  9613. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9614. std::string data(1024 * 1024 * 2, '&');
  9615. std::stringstream buffer;
  9616. buffer << data;
  9617. Client cli("https://localhost:8080");
  9618. UploadFormDataItems items{
  9619. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9620. {"hello", "world", "", ""},
  9621. };
  9622. for (const char &c : " \t\r\n") {
  9623. auto res =
  9624. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9625. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9626. ASSERT_FALSE(res);
  9627. }
  9628. }
  9629. TEST(MultipartFormDataTest, PutFormData) {
  9630. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9631. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9632. const ContentReader &content_reader) {
  9633. if (req.is_multipart_form_data()) {
  9634. std::vector<FormData> items;
  9635. content_reader(
  9636. [&](const FormData &file) {
  9637. items.push_back(file);
  9638. return true;
  9639. },
  9640. [&](const char *data, size_t data_length) {
  9641. items.back().content.append(data, data_length);
  9642. return true;
  9643. });
  9644. EXPECT_TRUE(std::string(items[0].name) == "document");
  9645. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9646. EXPECT_TRUE(items[0].filename == "2MB_data");
  9647. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9648. EXPECT_TRUE(items[1].name == "hello");
  9649. EXPECT_TRUE(items[1].content == "world");
  9650. EXPECT_TRUE(items[1].filename == "");
  9651. EXPECT_TRUE(items[1].content_type == "");
  9652. } else {
  9653. std::string body;
  9654. content_reader([&](const char *data, size_t data_length) {
  9655. body.append(data, data_length);
  9656. return true;
  9657. });
  9658. }
  9659. });
  9660. auto port = svr.bind_to_any_port("localhost");
  9661. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9662. auto se = detail::scope_exit([&] {
  9663. svr.stop();
  9664. t.join();
  9665. ASSERT_FALSE(svr.is_running());
  9666. });
  9667. svr.wait_until_ready();
  9668. {
  9669. std::string data(1024 * 1024 * 2, '&');
  9670. std::stringstream buffer;
  9671. buffer << data;
  9672. SSLClient cli("localhost", port);
  9673. cli.enable_server_certificate_verification(false);
  9674. UploadFormDataItems items{
  9675. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9676. {"hello", "world", "", ""},
  9677. };
  9678. auto res = cli.Put("/put", items);
  9679. ASSERT_TRUE(res);
  9680. ASSERT_EQ(StatusCode::OK_200, res->status);
  9681. }
  9682. }
  9683. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  9684. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9685. svr.Put("/put_customboundary",
  9686. [&](const Request &req, const Response & /*res*/,
  9687. const ContentReader &content_reader) {
  9688. if (req.is_multipart_form_data()) {
  9689. std::vector<FormData> items;
  9690. content_reader(
  9691. [&](const FormData &file) {
  9692. items.push_back(file);
  9693. return true;
  9694. },
  9695. [&](const char *data, size_t data_length) {
  9696. items.back().content.append(data, data_length);
  9697. return true;
  9698. });
  9699. EXPECT_TRUE(std::string(items[0].name) == "document");
  9700. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9701. EXPECT_TRUE(items[0].filename == "2MB_data");
  9702. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9703. EXPECT_TRUE(items[1].name == "hello");
  9704. EXPECT_TRUE(items[1].content == "world");
  9705. EXPECT_TRUE(items[1].filename == "");
  9706. EXPECT_TRUE(items[1].content_type == "");
  9707. } else {
  9708. std::string body;
  9709. content_reader([&](const char *data, size_t data_length) {
  9710. body.append(data, data_length);
  9711. return true;
  9712. });
  9713. }
  9714. });
  9715. auto port = svr.bind_to_any_port("localhost");
  9716. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9717. auto se = detail::scope_exit([&] {
  9718. svr.stop();
  9719. t.join();
  9720. ASSERT_FALSE(svr.is_running());
  9721. });
  9722. svr.wait_until_ready();
  9723. {
  9724. std::string data(1024 * 1024 * 2, '&');
  9725. std::stringstream buffer;
  9726. buffer << data;
  9727. SSLClient cli("localhost", port);
  9728. cli.enable_server_certificate_verification(false);
  9729. UploadFormDataItems items{
  9730. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9731. {"hello", "world", "", ""},
  9732. };
  9733. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  9734. ASSERT_TRUE(res);
  9735. ASSERT_EQ(StatusCode::OK_200, res->status);
  9736. }
  9737. }
  9738. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  9739. std::string data(1024 * 1024 * 2, '&');
  9740. std::stringstream buffer;
  9741. buffer << data;
  9742. Client cli("https://localhost:8080");
  9743. cli.enable_server_certificate_verification(false);
  9744. UploadFormDataItems items{
  9745. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9746. {"hello", "world", "", ""},
  9747. };
  9748. for (const char &c : " \t\r\n") {
  9749. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  9750. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9751. ASSERT_FALSE(res);
  9752. }
  9753. }
  9754. TEST(MultipartFormDataTest, AlternateFilename) {
  9755. auto handled = false;
  9756. Server svr;
  9757. svr.Post("/test", [&](const Request &req, Response &res) {
  9758. ASSERT_EQ(2u, req.form.files.size());
  9759. ASSERT_EQ(1u, req.form.fields.size());
  9760. // Test files
  9761. const auto &file1 = req.form.get_file("file1");
  9762. ASSERT_EQ("file1", file1.name);
  9763. ASSERT_EQ("A.txt", file1.filename);
  9764. ASSERT_EQ("text/plain", file1.content_type);
  9765. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  9766. const auto &file2 = req.form.get_file("file2");
  9767. ASSERT_EQ("file2", file2.name);
  9768. ASSERT_EQ("a.html", file2.filename);
  9769. ASSERT_EQ("text/html", file2.content_type);
  9770. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  9771. file2.content);
  9772. // Test text field
  9773. const auto &text = req.form.get_field("text");
  9774. ASSERT_EQ("text default", text);
  9775. res.set_content("ok", "text/plain");
  9776. handled = true;
  9777. });
  9778. thread t = thread([&] { svr.listen(HOST, PORT); });
  9779. auto se = detail::scope_exit([&] {
  9780. svr.stop();
  9781. t.join();
  9782. ASSERT_FALSE(svr.is_running());
  9783. ASSERT_TRUE(handled);
  9784. });
  9785. svr.wait_until_ready();
  9786. auto req = "POST /test HTTP/1.1\r\n"
  9787. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9788. "Content-Length: 399\r\n"
  9789. "\r\n"
  9790. "----------\r\n"
  9791. "Content-Disposition: form-data; name=\"text\"\r\n"
  9792. "\r\n"
  9793. "text default\r\n"
  9794. "----------\r\n"
  9795. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  9796. "filename=\"a.txt\"; name=\"file1\"\r\n"
  9797. "Content-Type: text/plain\r\n"
  9798. "\r\n"
  9799. "Content of a.txt.\r\n"
  9800. "\r\n"
  9801. "----------\r\n"
  9802. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  9803. "\"a.html\"\r\n"
  9804. "Content-Type: text/html\r\n"
  9805. "\r\n"
  9806. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  9807. "\r\n"
  9808. "------------\r\n";
  9809. ASSERT_TRUE(send_request(1, req));
  9810. }
  9811. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  9812. auto handled = false;
  9813. Server svr;
  9814. svr.Post("/test", [&](const Request &req, Response &res) {
  9815. // Case-insensitive "utf-8''" prefix with a long value
  9816. const auto &file = req.form.get_file("file1");
  9817. ASSERT_EQ("file1", file.name);
  9818. // 8000 chars exercises both the Content-Disposition parser and the
  9819. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  9820. // Prior to the fix, std::regex_match on this header would cause O(N)
  9821. // stack recursion in libstdc++, leading to SIGSEGV.
  9822. std::string expected_filename(8000, 'A');
  9823. ASSERT_EQ(expected_filename, file.filename);
  9824. res.set_content("ok", "text/plain");
  9825. handled = true;
  9826. });
  9827. thread t = thread([&] { svr.listen(HOST, PORT); });
  9828. auto se = detail::scope_exit([&] {
  9829. svr.stop();
  9830. t.join();
  9831. ASSERT_FALSE(svr.is_running());
  9832. ASSERT_TRUE(handled);
  9833. });
  9834. svr.wait_until_ready();
  9835. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  9836. // Regression test for GHSA-qq6v-r583-3h69
  9837. std::string long_filename(8000, 'A');
  9838. std::string body = "----------\r\n"
  9839. "Content-Disposition: form-data; name=\"file1\"; "
  9840. "filename*=\"Utf-8''" +
  9841. long_filename +
  9842. "\"\r\n"
  9843. "\r\n"
  9844. "hello\r\n"
  9845. "------------\r\n";
  9846. auto req = "POST /test HTTP/1.1\r\n"
  9847. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9848. "Content-Length: " +
  9849. std::to_string(body.size()) + "\r\n\r\n" + body;
  9850. ASSERT_TRUE(send_request(1, req));
  9851. }
  9852. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  9853. auto handled = false;
  9854. Server svr;
  9855. svr.Post("/test", [&](const Request &req, Response &) {
  9856. ASSERT_EQ(2u, req.form.fields.size());
  9857. const auto &text1 = req.form.get_field("text1");
  9858. ASSERT_EQ("text1", text1);
  9859. const auto &text2 = req.form.get_field("text2");
  9860. ASSERT_EQ("text2", text2);
  9861. handled = true;
  9862. });
  9863. thread t = thread([&] { svr.listen(HOST, PORT); });
  9864. auto se = detail::scope_exit([&] {
  9865. svr.stop();
  9866. t.join();
  9867. ASSERT_FALSE(svr.is_running());
  9868. ASSERT_TRUE(handled);
  9869. });
  9870. svr.wait_until_ready();
  9871. auto req = "POST /test HTTP/1.1\r\n"
  9872. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9873. "Content-Length: 146\r\n"
  9874. "\r\n----------\r\n"
  9875. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9876. "\r\n"
  9877. "text1"
  9878. "\r\n----------\r\n"
  9879. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9880. "\r\n"
  9881. "text2"
  9882. "\r\n------------";
  9883. std::string response;
  9884. ASSERT_TRUE(send_request(1, req, &response));
  9885. ASSERT_EQ("200", response.substr(9, 3));
  9886. }
  9887. TEST(MultipartFormDataTest, ContentLength) {
  9888. auto handled = false;
  9889. Server svr;
  9890. svr.Post("/test", [&](const Request &req, Response &) {
  9891. ASSERT_EQ(2u, req.form.fields.size());
  9892. const auto &text1 = req.form.get_field("text1");
  9893. ASSERT_EQ("text1", text1);
  9894. const auto &text2 = req.form.get_field("text2");
  9895. ASSERT_EQ("text2", text2);
  9896. handled = true;
  9897. });
  9898. thread t = thread([&] { svr.listen(HOST, PORT); });
  9899. auto se = detail::scope_exit([&] {
  9900. svr.stop();
  9901. t.join();
  9902. ASSERT_FALSE(svr.is_running());
  9903. ASSERT_TRUE(handled);
  9904. });
  9905. svr.wait_until_ready();
  9906. auto req = "POST /test HTTP/1.1\r\n"
  9907. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9908. "Content-Length: 167\r\n"
  9909. "\r\n----------\r\n"
  9910. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9911. "Content-Length: 5\r\n"
  9912. "\r\n"
  9913. "text1"
  9914. "\r\n----------\r\n"
  9915. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9916. "\r\n"
  9917. "text2"
  9918. "\r\n------------\r\n";
  9919. std::string response;
  9920. ASSERT_TRUE(send_request(1, req, &response));
  9921. ASSERT_EQ("200", response.substr(9, 3));
  9922. }
  9923. TEST(MultipartFormDataTest, AccessPartHeaders) {
  9924. auto handled = false;
  9925. Server svr;
  9926. svr.Post("/test", [&](const Request &req, Response &) {
  9927. ASSERT_EQ(2u, req.form.fields.size());
  9928. const auto &text1 = req.form.get_field("text1");
  9929. ASSERT_EQ("text1", text1);
  9930. // TODO: Add header access for text fields if needed
  9931. const auto &text2 = req.form.get_field("text2");
  9932. ASSERT_EQ("text2", text2);
  9933. // TODO: Header access for text fields needs to be implemented
  9934. // auto &headers = it->second.headers;
  9935. // ASSERT_EQ(3U, headers.size());
  9936. // auto custom_header = headers.find("x-whatever");
  9937. // ASSERT_TRUE(custom_header != headers.end());
  9938. // ASSERT_NE("customvalue", custom_header->second);
  9939. // ASSERT_EQ("CustomValue", custom_header->second);
  9940. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  9941. handled = true;
  9942. });
  9943. thread t = thread([&] { svr.listen(HOST, PORT); });
  9944. auto se = detail::scope_exit([&] {
  9945. svr.stop();
  9946. t.join();
  9947. ASSERT_FALSE(svr.is_running());
  9948. ASSERT_TRUE(handled);
  9949. });
  9950. svr.wait_until_ready();
  9951. auto req = "POST /test HTTP/1.1\r\n"
  9952. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9953. "Content-Length: 232\r\n"
  9954. "\r\n----------\r\n"
  9955. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9956. "Content-Length: 5\r\n"
  9957. "X-Test: 1\r\n"
  9958. "\r\n"
  9959. "text1"
  9960. "\r\n----------\r\n"
  9961. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9962. "Content-Type: text/plain\r\n"
  9963. "X-Whatever: CustomValue\r\n"
  9964. "\r\n"
  9965. "text2"
  9966. "\r\n------------\r\n"
  9967. "That should be disregarded. Not even read";
  9968. std::string response;
  9969. ASSERT_TRUE(send_request(1, req, &response));
  9970. ASSERT_EQ("200", response.substr(9, 3));
  9971. }
  9972. TEST(MultipartFormDataTest, LargeHeader) {
  9973. auto handled = false;
  9974. Server svr;
  9975. svr.Post("/test", [&](const Request &req, Response &) {
  9976. ASSERT_EQ(1u, req.form.fields.size());
  9977. const auto &text = req.form.get_field("name1");
  9978. ASSERT_EQ("text1", text);
  9979. handled = true;
  9980. });
  9981. thread t = thread([&] { svr.listen(HOST, PORT); });
  9982. auto se = detail::scope_exit([&] {
  9983. svr.stop();
  9984. t.join();
  9985. ASSERT_FALSE(svr.is_running());
  9986. ASSERT_TRUE(handled);
  9987. });
  9988. svr.wait_until_ready();
  9989. auto boundary = std::string("cpp-httplib-multipart-data");
  9990. std::string content = "--" + boundary +
  9991. "\r\n"
  9992. "Content-Disposition: form-data; name=\"name1\"\r\n"
  9993. "\r\n"
  9994. "text1\r\n"
  9995. "--" +
  9996. boundary + "--\r\n";
  9997. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  9998. "Content-Type: multipart/form-data;boundary=" +
  9999. boundary +
  10000. "\r\n"
  10001. "Content-Length: " +
  10002. std::to_string(content.size()) +
  10003. "\r\n"
  10004. "Dummy-Header: ";
  10005. std::string header_suffix = "\r\n"
  10006. "\r\n";
  10007. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  10008. size_t header_dummy_size =
  10009. read_buff_size -
  10010. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  10011. auto header_dummy = std::string(header_dummy_size, '@');
  10012. auto req = header_prefix + header_dummy + header_suffix + content;
  10013. std::string response;
  10014. ASSERT_TRUE(send_request(1, req, &response));
  10015. ASSERT_EQ("200", response.substr(9, 3));
  10016. }
  10017. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  10018. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  10019. // (not chunked Transfer-Encoding) after the streaming refactor.
  10020. auto handled = false;
  10021. Server svr;
  10022. svr.Post("/upload", [&](const Request &req, Response &res) {
  10023. auto cl_it = req.headers.find("Content-Length");
  10024. EXPECT_TRUE(cl_it != req.headers.end());
  10025. auto te_it = req.headers.find("Transfer-Encoding");
  10026. EXPECT_TRUE(te_it == req.headers.end());
  10027. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  10028. res.set_content("ok", "text/plain");
  10029. handled = true;
  10030. });
  10031. auto port = svr.bind_to_any_port(HOST);
  10032. auto t = thread([&] { svr.listen_after_bind(); });
  10033. auto se = detail::scope_exit([&] {
  10034. svr.stop();
  10035. t.join();
  10036. ASSERT_FALSE(svr.is_running());
  10037. ASSERT_TRUE(handled);
  10038. });
  10039. svr.wait_until_ready();
  10040. UploadFormDataItems items = {
  10041. {"field1", "hello", "", "text/plain"},
  10042. {"file1", "world", "test.txt", "application/octet-stream"},
  10043. };
  10044. Client cli(HOST, port);
  10045. auto res = cli.Post("/upload", {}, items);
  10046. ASSERT_TRUE(res);
  10047. EXPECT_EQ(StatusCode::OK_200, res->status);
  10048. }
  10049. TEST(MultipartFormDataTest, MakeFileProvider) {
  10050. // Verify make_file_provider sends a file's contents correctly.
  10051. const std::string file_content(4096, 'Z');
  10052. const std::string tmp_path = "/tmp/httplib_test_make_file_provider.bin";
  10053. {
  10054. std::ofstream ofs(tmp_path, std::ios::binary);
  10055. ofs.write(file_content.data(),
  10056. static_cast<std::streamsize>(file_content.size()));
  10057. }
  10058. auto handled = false;
  10059. Server svr;
  10060. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  10061. const ContentReader &content_reader) {
  10062. ASSERT_TRUE(req.is_multipart_form_data());
  10063. std::vector<FormData> items;
  10064. content_reader(
  10065. [&](const FormData &file) {
  10066. items.push_back(file);
  10067. return true;
  10068. },
  10069. [&](const char *data, size_t data_length) {
  10070. items.back().content.append(data, data_length);
  10071. return true;
  10072. });
  10073. ASSERT_EQ(1u, items.size());
  10074. EXPECT_EQ("myfile", items[0].name);
  10075. EXPECT_EQ("data.bin", items[0].filename);
  10076. EXPECT_EQ("application/octet-stream", items[0].content_type);
  10077. EXPECT_EQ(file_content, items[0].content);
  10078. handled = true;
  10079. });
  10080. auto port = svr.bind_to_any_port(HOST);
  10081. auto t = thread([&] { svr.listen_after_bind(); });
  10082. auto se = detail::scope_exit([&] {
  10083. svr.stop();
  10084. t.join();
  10085. ASSERT_FALSE(svr.is_running());
  10086. ASSERT_TRUE(handled);
  10087. std::remove(tmp_path.c_str());
  10088. });
  10089. svr.wait_until_ready();
  10090. FormDataProviderItems providers;
  10091. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  10092. "application/octet-stream"));
  10093. Client cli(HOST, port);
  10094. auto res = cli.Post("/upload", {}, {}, providers);
  10095. ASSERT_TRUE(res);
  10096. EXPECT_EQ(StatusCode::OK_200, res->status);
  10097. }
  10098. TEST(MakeFileBodyTest, Basic) {
  10099. const std::string file_content(4096, 'Z');
  10100. const std::string tmp_path = "/tmp/httplib_test_make_file_body.bin";
  10101. {
  10102. std::ofstream ofs(tmp_path, std::ios::binary);
  10103. ofs.write(file_content.data(),
  10104. static_cast<std::streamsize>(file_content.size()));
  10105. }
  10106. auto handled = false;
  10107. Server svr;
  10108. svr.Post("/upload", [&](const Request &req, Response &res) {
  10109. EXPECT_EQ(file_content, req.body);
  10110. handled = true;
  10111. res.status = StatusCode::OK_200;
  10112. });
  10113. auto port = svr.bind_to_any_port(HOST);
  10114. auto t = thread([&] { svr.listen_after_bind(); });
  10115. auto se = detail::scope_exit([&] {
  10116. svr.stop();
  10117. t.join();
  10118. ASSERT_FALSE(svr.is_running());
  10119. ASSERT_TRUE(handled);
  10120. std::remove(tmp_path.c_str());
  10121. });
  10122. svr.wait_until_ready();
  10123. auto fb = make_file_body(tmp_path);
  10124. ASSERT_GT(fb.first, 0u);
  10125. Client cli(HOST, port);
  10126. auto res =
  10127. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  10128. ASSERT_TRUE(res);
  10129. EXPECT_EQ(StatusCode::OK_200, res->status);
  10130. }
  10131. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  10132. static constexpr unsigned int number_of_tasks{1000000};
  10133. std::atomic_uint count{0};
  10134. std::unique_ptr<TaskQueue> task_queue{
  10135. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  10136. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10137. auto queued = task_queue->enqueue(
  10138. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  10139. EXPECT_TRUE(queued);
  10140. }
  10141. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10142. task_queue->shutdown();
  10143. #else
  10144. EXPECT_NO_THROW(task_queue->shutdown());
  10145. #endif
  10146. EXPECT_EQ(number_of_tasks, count.load());
  10147. }
  10148. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  10149. static constexpr unsigned int number_of_tasks{1000000};
  10150. static constexpr unsigned int qlimit{2};
  10151. unsigned int queued_count{0};
  10152. std::atomic_uint count{0};
  10153. std::unique_ptr<TaskQueue> task_queue{
  10154. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  10155. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10156. if (task_queue->enqueue(
  10157. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  10158. queued_count++;
  10159. }
  10160. }
  10161. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10162. task_queue->shutdown();
  10163. #else
  10164. EXPECT_NO_THROW(task_queue->shutdown());
  10165. #endif
  10166. EXPECT_EQ(queued_count, count.load());
  10167. EXPECT_TRUE(queued_count <= number_of_tasks);
  10168. EXPECT_TRUE(queued_count >= qlimit);
  10169. }
  10170. TEST(TaskQueueTest, MaxQueuedRequests) {
  10171. static constexpr unsigned int qlimit{3};
  10172. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  10173. std::condition_variable sem_cv;
  10174. std::mutex sem_mtx;
  10175. int credits = 0;
  10176. bool queued;
  10177. /* Fill up the queue with tasks that will block until we give them credits to
  10178. * complete. */
  10179. for (unsigned int n = 0; n <= qlimit;) {
  10180. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  10181. std::unique_lock<std::mutex> lock(sem_mtx);
  10182. while (credits <= 0) {
  10183. sem_cv.wait(lock);
  10184. }
  10185. /* Consume the credit and signal the test code if they are all gone. */
  10186. if (--credits == 0) { sem_cv.notify_one(); }
  10187. });
  10188. if (n < qlimit) {
  10189. /* The first qlimit enqueues must succeed. */
  10190. EXPECT_TRUE(queued);
  10191. } else {
  10192. /* The last one will succeed only when the worker thread
  10193. * starts and dequeues the first blocking task. Although
  10194. * not necessary for the correctness of this test, we sleep for
  10195. * a short while to avoid busy waiting. */
  10196. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10197. }
  10198. if (queued) { n++; }
  10199. }
  10200. /* Further enqueues must fail since the queue is full. */
  10201. for (auto i = 0; i < 4; i++) {
  10202. queued = task_queue->enqueue([] {});
  10203. EXPECT_FALSE(queued);
  10204. }
  10205. /* Give the credits to allow the previous tasks to complete. */
  10206. {
  10207. std::unique_lock<std::mutex> lock(sem_mtx);
  10208. credits += qlimit + 1;
  10209. }
  10210. sem_cv.notify_all();
  10211. /* Wait for all the credits to be consumed. */
  10212. {
  10213. std::unique_lock<std::mutex> lock(sem_mtx);
  10214. while (credits > 0) {
  10215. sem_cv.wait(lock);
  10216. }
  10217. }
  10218. /* Check that we are able again to enqueue at least qlimit tasks. */
  10219. for (unsigned int i = 0; i < qlimit; i++) {
  10220. queued = task_queue->enqueue([] {});
  10221. EXPECT_TRUE(queued);
  10222. }
  10223. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10224. task_queue->shutdown();
  10225. #else
  10226. EXPECT_NO_THROW(task_queue->shutdown());
  10227. #endif
  10228. }
  10229. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  10230. Server svr;
  10231. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10232. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  10233. });
  10234. svr.Get("/hello", [](const Request &req, Response &res) {
  10235. res.set_content(req.get_param_value("key"), "text/plain");
  10236. });
  10237. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10238. auto se = detail::scope_exit([&] {
  10239. svr.stop();
  10240. thread.join();
  10241. ASSERT_FALSE(svr.is_running());
  10242. });
  10243. svr.wait_until_ready();
  10244. {
  10245. Client cli(HOST, PORT);
  10246. cli.set_follow_location(true);
  10247. auto res = cli.Get("/");
  10248. ASSERT_TRUE(res);
  10249. EXPECT_EQ(StatusCode::OK_200, res->status);
  10250. EXPECT_EQ("val&key2=val2", res->body);
  10251. }
  10252. }
  10253. #endif
  10254. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  10255. Server svr;
  10256. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10257. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  10258. });
  10259. svr.Get("/hello", [](const Request &req, Response &res) {
  10260. res.set_content(req.get_param_value("key"), "text/plain");
  10261. });
  10262. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10263. auto se = detail::scope_exit([&] {
  10264. svr.stop();
  10265. thread.join();
  10266. ASSERT_FALSE(svr.is_running());
  10267. });
  10268. svr.wait_until_ready();
  10269. {
  10270. Client cli(HOST, PORT);
  10271. cli.set_follow_location(true);
  10272. auto res = cli.Get("/");
  10273. ASSERT_TRUE(res);
  10274. EXPECT_EQ(StatusCode::OK_200, res->status);
  10275. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  10276. }
  10277. }
  10278. #ifdef CPPHTTPLIB_SSL_ENABLED
  10279. TEST(RedirectTest, Issue2185_Online) {
  10280. SSLClient client("github.com");
  10281. client.set_follow_location(true);
  10282. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  10283. "Coollab-Windows.zip");
  10284. ASSERT_TRUE(res);
  10285. EXPECT_EQ(StatusCode::OK_200, res->status);
  10286. EXPECT_EQ(9920427U, res->body.size());
  10287. }
  10288. #endif
  10289. TEST(VulnerabilityTest, CRLFInjection) {
  10290. Server svr;
  10291. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  10292. res.set_content("Hello 1", "text/plain");
  10293. });
  10294. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  10295. res.set_content("Hello 2", "text/plain");
  10296. });
  10297. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  10298. res.set_content("Hello 3", "text/plain");
  10299. });
  10300. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  10301. res.set_content("Hello 4", "text/plain");
  10302. });
  10303. svr.set_logger([](const Request &req, const Response & /*res*/) {
  10304. for (const auto &x : req.headers) {
  10305. auto key = x.first;
  10306. EXPECT_STRNE("evil", key.c_str());
  10307. }
  10308. });
  10309. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10310. auto se = detail::scope_exit([&] {
  10311. svr.stop();
  10312. thread.join();
  10313. ASSERT_FALSE(svr.is_running());
  10314. });
  10315. svr.wait_until_ready();
  10316. {
  10317. Client cli(HOST, PORT);
  10318. cli.Post("/test1", "A=B",
  10319. "application/x-www-form-urlencoded\r\nevil: hello1");
  10320. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  10321. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  10322. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  10323. }
  10324. }
  10325. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  10326. auto server_thread = std::thread([] {
  10327. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10328. default_socket_options(srv);
  10329. sockaddr_in addr{};
  10330. addr.sin_family = AF_INET;
  10331. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  10332. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10333. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10334. ::listen(srv, 1);
  10335. sockaddr_in cli_addr{};
  10336. socklen_t cli_len = sizeof(cli_addr);
  10337. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10338. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  10339. std::string buf_all;
  10340. char buf[2048];
  10341. ssize_t n;
  10342. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  10343. buf_all.append(buf, static_cast<size_t>(n));
  10344. size_t pos;
  10345. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  10346. auto request_block = buf_all.substr(0, pos + 4); // include separator
  10347. auto e = request_block.find("\r\n");
  10348. if (e != std::string::npos) {
  10349. auto request_line = request_block.substr(0, e);
  10350. std::string msg =
  10351. "CRLF injection detected in request line: '" + request_line + "'";
  10352. EXPECT_FALSE(true) << msg;
  10353. }
  10354. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  10355. ::send(cli,
  10356. #ifdef _WIN32
  10357. static_cast<const char *>(resp.c_str()),
  10358. static_cast<int>(resp.size()),
  10359. #else
  10360. resp.c_str(), resp.size(),
  10361. #endif
  10362. 0);
  10363. buf_all.erase(0, pos + 4);
  10364. }
  10365. }
  10366. detail::close_socket(cli);
  10367. detail::close_socket(srv);
  10368. });
  10369. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10370. auto cli = Client("127.0.0.1", PORT + 1);
  10371. auto headers = Headers{
  10372. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  10373. {"Connection", "keep-alive"}};
  10374. auto res = cli.Get("/hi", headers);
  10375. EXPECT_FALSE(res);
  10376. EXPECT_EQ(Error::InvalidHeaders, res.error());
  10377. server_thread.join();
  10378. }
  10379. TEST(PathParamsTest, StaticMatch) {
  10380. const auto pattern = "/users/all";
  10381. detail::PathParamsMatcher matcher(pattern);
  10382. Request request;
  10383. request.path = "/users/all";
  10384. ASSERT_TRUE(matcher.match(request));
  10385. std::unordered_map<std::string, std::string> expected_params = {};
  10386. EXPECT_EQ(request.path_params, expected_params);
  10387. }
  10388. TEST(PathParamsTest, StaticMismatch) {
  10389. const auto pattern = "/users/all";
  10390. detail::PathParamsMatcher matcher(pattern);
  10391. Request request;
  10392. request.path = "/users/1";
  10393. ASSERT_FALSE(matcher.match(request));
  10394. }
  10395. TEST(PathParamsTest, SingleParamInTheMiddle) {
  10396. const auto pattern = "/users/:id/subscriptions";
  10397. detail::PathParamsMatcher matcher(pattern);
  10398. Request request;
  10399. request.path = "/users/42/subscriptions";
  10400. ASSERT_TRUE(matcher.match(request));
  10401. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10402. EXPECT_EQ(request.path_params, expected_params);
  10403. }
  10404. TEST(PathParamsTest, SingleParamInTheEnd) {
  10405. const auto pattern = "/users/:id";
  10406. detail::PathParamsMatcher matcher(pattern);
  10407. Request request;
  10408. request.path = "/users/24";
  10409. ASSERT_TRUE(matcher.match(request));
  10410. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  10411. EXPECT_EQ(request.path_params, expected_params);
  10412. }
  10413. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  10414. const auto pattern = "/users/:id/";
  10415. detail::PathParamsMatcher matcher(pattern);
  10416. Request request;
  10417. request.path = "/users/42/";
  10418. ASSERT_TRUE(matcher.match(request));
  10419. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10420. EXPECT_EQ(request.path_params, expected_params);
  10421. }
  10422. TEST(PathParamsTest, EmptyParam) {
  10423. const auto pattern = "/users/:id/";
  10424. detail::PathParamsMatcher matcher(pattern);
  10425. Request request;
  10426. request.path = "/users//";
  10427. ASSERT_TRUE(matcher.match(request));
  10428. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10429. EXPECT_EQ(request.path_params, expected_params);
  10430. }
  10431. TEST(PathParamsTest, FragmentMismatch) {
  10432. const auto pattern = "/users/:id/";
  10433. detail::PathParamsMatcher matcher(pattern);
  10434. Request request;
  10435. request.path = "/admins/24/";
  10436. ASSERT_FALSE(matcher.match(request));
  10437. }
  10438. TEST(PathParamsTest, ExtraFragments) {
  10439. const auto pattern = "/users/:id";
  10440. detail::PathParamsMatcher matcher(pattern);
  10441. Request request;
  10442. request.path = "/users/42/subscriptions";
  10443. ASSERT_FALSE(matcher.match(request));
  10444. }
  10445. TEST(PathParamsTest, MissingTrailingParam) {
  10446. const auto pattern = "/users/:id";
  10447. detail::PathParamsMatcher matcher(pattern);
  10448. Request request;
  10449. request.path = "/users";
  10450. ASSERT_FALSE(matcher.match(request));
  10451. }
  10452. TEST(PathParamsTest, MissingParamInTheMiddle) {
  10453. const auto pattern = "/users/:id/subscriptions";
  10454. detail::PathParamsMatcher matcher(pattern);
  10455. Request request;
  10456. request.path = "/users/subscriptions";
  10457. ASSERT_FALSE(matcher.match(request));
  10458. }
  10459. TEST(PathParamsTest, MultipleParams) {
  10460. const auto pattern = "/users/:userid/subscriptions/:subid";
  10461. detail::PathParamsMatcher matcher(pattern);
  10462. Request request;
  10463. request.path = "/users/42/subscriptions/2";
  10464. ASSERT_TRUE(matcher.match(request));
  10465. std::unordered_map<std::string, std::string> expected_params = {
  10466. {"userid", "42"}, {"subid", "2"}};
  10467. EXPECT_EQ(request.path_params, expected_params);
  10468. }
  10469. TEST(PathParamsTest, SequenceOfParams) {
  10470. const auto pattern = "/values/:x/:y/:z";
  10471. detail::PathParamsMatcher matcher(pattern);
  10472. Request request;
  10473. request.path = "/values/1/2/3";
  10474. ASSERT_TRUE(matcher.match(request));
  10475. std::unordered_map<std::string, std::string> expected_params = {
  10476. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  10477. EXPECT_EQ(request.path_params, expected_params);
  10478. }
  10479. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  10480. const auto pattern = "/prefix:suffix";
  10481. detail::PathParamsMatcher matcher(pattern);
  10482. Request request;
  10483. request.path = "/prefix:suffix";
  10484. ASSERT_TRUE(matcher.match(request));
  10485. const std::unordered_map<std::string, std::string> expected_params = {};
  10486. EXPECT_EQ(request.path_params, expected_params);
  10487. }
  10488. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  10489. // If ipv6 regex working, regex match codepath is taken.
  10490. // else port will default to 80 in Client impl
  10491. int clientImplMagicPort = 80;
  10492. int port = 4321;
  10493. // above ports must be different to avoid false negative
  10494. EXPECT_NE(clientImplMagicPort, port);
  10495. std::string ipV6TestURL = "http://[ff06::c3]";
  10496. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  10497. CLIENT_PRIVATE_KEY_FILE);
  10498. EXPECT_EQ(cli.port(), port);
  10499. }
  10500. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  10501. auto file_path = "./www/dir/index.html";
  10502. auto dir_path = "./www/dir";
  10503. detail::FileStat stat_file(file_path);
  10504. EXPECT_TRUE(stat_file.is_file());
  10505. EXPECT_FALSE(stat_file.is_dir());
  10506. detail::FileStat stat_dir(dir_path);
  10507. EXPECT_FALSE(stat_dir.is_file());
  10508. EXPECT_TRUE(stat_dir.is_dir());
  10509. }
  10510. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  10511. // IPv4 with default HTTP port (80)
  10512. EXPECT_EQ("example.com",
  10513. detail::make_host_and_port_string("example.com", 80, false));
  10514. // IPv4 with default HTTPS port (443)
  10515. EXPECT_EQ("example.com",
  10516. detail::make_host_and_port_string("example.com", 443, true));
  10517. // IPv4 with non-default HTTP port
  10518. EXPECT_EQ("example.com:8080",
  10519. detail::make_host_and_port_string("example.com", 8080, false));
  10520. // IPv4 with non-default HTTPS port
  10521. EXPECT_EQ("example.com:8443",
  10522. detail::make_host_and_port_string("example.com", 8443, true));
  10523. // IPv6 with default HTTP port (80)
  10524. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  10525. // IPv6 with default HTTPS port (443)
  10526. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  10527. // IPv6 with non-default HTTP port
  10528. EXPECT_EQ("[::1]:8080",
  10529. detail::make_host_and_port_string("::1", 8080, false));
  10530. // IPv6 with non-default HTTPS port
  10531. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  10532. // IPv6 full address with default port
  10533. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  10534. detail::make_host_and_port_string(
  10535. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  10536. // IPv6 full address with non-default port
  10537. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  10538. detail::make_host_and_port_string(
  10539. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  10540. // IPv6 localhost with non-default port
  10541. EXPECT_EQ("[::1]:3000",
  10542. detail::make_host_and_port_string("::1", 3000, false));
  10543. // IPv6 with zone ID (link-local address) with default port
  10544. EXPECT_EQ("[fe80::1%eth0]",
  10545. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  10546. // IPv6 with zone ID (link-local address) with non-default port
  10547. EXPECT_EQ("[fe80::1%eth0]:8080",
  10548. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  10549. // Edge case: Port 443 with is_ssl=false (should add port)
  10550. EXPECT_EQ("example.com:443",
  10551. detail::make_host_and_port_string("example.com", 443, false));
  10552. // Edge case: Port 80 with is_ssl=true (should add port)
  10553. EXPECT_EQ("example.com:80",
  10554. detail::make_host_and_port_string("example.com", 80, true));
  10555. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  10556. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  10557. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  10558. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  10559. // Security fix: Already bracketed IPv6 should not get double brackets
  10560. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  10561. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  10562. EXPECT_EQ("[::1]:8080",
  10563. detail::make_host_and_port_string("[::1]", 8080, false));
  10564. EXPECT_EQ("[2001:db8::1]:8080",
  10565. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  10566. EXPECT_EQ("[fe80::1%eth0]",
  10567. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  10568. EXPECT_EQ("[fe80::1%eth0]:8080",
  10569. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  10570. // Edge case: Empty host (should return as-is)
  10571. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  10572. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  10573. // This is a known limitation but shouldn't crash
  10574. EXPECT_EQ("[host:name]",
  10575. detail::make_host_and_port_string("host:name", 80, false));
  10576. // Port number edge cases (no validation, but should not crash)
  10577. EXPECT_EQ("example.com:0",
  10578. detail::make_host_and_port_string("example.com", 0, false));
  10579. EXPECT_EQ("example.com:-1",
  10580. detail::make_host_and_port_string("example.com", -1, false));
  10581. EXPECT_EQ("example.com:65535",
  10582. detail::make_host_and_port_string("example.com", 65535, false));
  10583. EXPECT_EQ("example.com:65536",
  10584. detail::make_host_and_port_string("example.com", 65536, false));
  10585. }
  10586. #ifdef CPPHTTPLIB_SSL_ENABLED
  10587. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  10588. httplib::SSLClient cli("roblox.com", 443);
  10589. cli.set_follow_location(true);
  10590. auto res = cli.Get("/");
  10591. ASSERT_TRUE(res);
  10592. EXPECT_EQ(StatusCode::OK_200, res->status);
  10593. }
  10594. #endif
  10595. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  10596. Server svr;
  10597. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10598. EXPECT_EQ(res.status, 400);
  10599. });
  10600. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10601. auto se = detail::scope_exit([&] {
  10602. svr.stop();
  10603. thread.join();
  10604. ASSERT_FALSE(svr.is_running());
  10605. });
  10606. svr.wait_until_ready();
  10607. Client cli(HOST, PORT);
  10608. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  10609. }
  10610. TEST(InvalidHeaderCharsTest, is_field_name) {
  10611. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  10612. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  10613. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  10614. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  10615. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  10616. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  10617. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  10618. EXPECT_FALSE(detail::fields::is_field_name(""));
  10619. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  10620. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  10621. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  10622. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  10623. }
  10624. TEST(InvalidHeaderCharsTest, is_field_value) {
  10625. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  10626. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  10627. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  10628. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  10629. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  10630. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  10631. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  10632. EXPECT_TRUE(detail::fields::is_field_value(""));
  10633. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  10634. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  10635. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  10636. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  10637. EXPECT_TRUE(detail::fields::is_field_value("0"));
  10638. }
  10639. TEST(InvalidHeaderCharsTest, OnServer) {
  10640. Server svr;
  10641. svr.Get("/test_name", [&](const Request &req, Response &res) {
  10642. std::string header = "Not Set";
  10643. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10644. res.set_header(header, "value");
  10645. res.set_content("Page Content Page Content", "text/plain");
  10646. });
  10647. svr.Get("/test_value", [&](const Request &req, Response &res) {
  10648. std::string header = "Not Set";
  10649. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10650. res.set_header("X-Test", header);
  10651. res.set_content("Page Content Page Content", "text/plain");
  10652. });
  10653. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10654. auto se = detail::scope_exit([&] {
  10655. svr.stop();
  10656. thread.join();
  10657. ASSERT_FALSE(svr.is_running());
  10658. });
  10659. svr.wait_until_ready();
  10660. Client cli(HOST, PORT);
  10661. {
  10662. auto res = cli.Get(
  10663. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10664. ASSERT_TRUE(res);
  10665. EXPECT_EQ("Page Content Page Content", res->body);
  10666. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10667. }
  10668. {
  10669. auto res = cli.Get(
  10670. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10671. ASSERT_TRUE(res);
  10672. EXPECT_EQ("Page Content Page Content", res->body);
  10673. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10674. }
  10675. }
  10676. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  10677. auto handled = false;
  10678. Server svr;
  10679. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10680. thread t = thread([&] { svr.listen(HOST, PORT); });
  10681. auto se = detail::scope_exit([&] {
  10682. svr.stop();
  10683. t.join();
  10684. ASSERT_FALSE(svr.is_running());
  10685. ASSERT_FALSE(handled);
  10686. });
  10687. svr.wait_until_ready();
  10688. auto req = "POST /test HTTP/1.1\r\n"
  10689. "Content-Length: x\r\n"
  10690. "\r\n";
  10691. std::string response;
  10692. ASSERT_TRUE(send_request(1, req, &response));
  10693. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10694. response.substr(0, response.find("\r\n")));
  10695. }
  10696. #ifndef _WIN32
  10697. TEST(Expect100ContinueTest, ServerClosesConnection) {
  10698. static constexpr char reject[] = "Unauthorized";
  10699. static constexpr char accept[] = "Upload accepted";
  10700. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  10701. Server svr;
  10702. svr.set_expect_100_continue_handler(
  10703. [](const Request & /*req*/, Response &res) {
  10704. res.status = StatusCode::Unauthorized_401;
  10705. res.set_content(reject, "text/plain");
  10706. return res.status;
  10707. });
  10708. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  10709. res.set_content(accept, "text/plain");
  10710. });
  10711. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10712. auto se = detail::scope_exit([&] {
  10713. svr.stop();
  10714. thread.join();
  10715. ASSERT_FALSE(svr.is_running());
  10716. });
  10717. svr.wait_until_ready();
  10718. {
  10719. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  10720. curl_easy_init(), &curl_easy_cleanup};
  10721. ASSERT_NE(curl, nullptr);
  10722. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  10723. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  10724. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  10725. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  10726. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  10727. &curl_slist_free_all};
  10728. ASSERT_NE(list, nullptr);
  10729. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  10730. struct read_data {
  10731. size_t read_size;
  10732. size_t total_size;
  10733. } data = {0, total_size};
  10734. using read_callback_t =
  10735. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10736. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  10737. void *userdata) -> size_t {
  10738. read_data *data = (read_data *)userdata;
  10739. if (!userdata || data->read_size >= data->total_size) { return 0; }
  10740. std::fill_n(ptr, size * nmemb, 'A');
  10741. data->read_size += size * nmemb;
  10742. return size * nmemb;
  10743. };
  10744. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  10745. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  10746. std::vector<char> buffer;
  10747. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  10748. using write_callback_t =
  10749. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10750. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  10751. void *userdata) -> size_t {
  10752. std::vector<char> *buffer = (std::vector<char> *)userdata;
  10753. buffer->reserve(buffer->size() + size * nmemb + 1);
  10754. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  10755. return size * nmemb;
  10756. };
  10757. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  10758. {
  10759. const auto res = curl_easy_perform(curl.get());
  10760. ASSERT_EQ(res, CURLE_OK);
  10761. }
  10762. {
  10763. auto response_code = long{};
  10764. const auto res =
  10765. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  10766. ASSERT_EQ(res, CURLE_OK);
  10767. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  10768. }
  10769. {
  10770. auto dl = curl_off_t{};
  10771. const auto res =
  10772. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  10773. ASSERT_EQ(res, CURLE_OK);
  10774. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  10775. }
  10776. {
  10777. buffer.push_back('\0');
  10778. ASSERT_STRCASEEQ(buffer.data(), reject);
  10779. }
  10780. }
  10781. }
  10782. #endif
  10783. template <typename S, typename C>
  10784. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  10785. svr.Get("/stream", [&](const Request &, Response &res) {
  10786. auto data = new std::string("01234567890123456789");
  10787. res.set_content_provider(
  10788. data->size(), "text/plain",
  10789. [&, data](size_t offset, size_t length, DataSink &sink) {
  10790. const size_t DATA_CHUNK_SIZE = 4;
  10791. const auto &d = *data;
  10792. std::this_thread::sleep_for(std::chrono::seconds(1));
  10793. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  10794. return true;
  10795. },
  10796. [data](bool success) {
  10797. EXPECT_FALSE(success);
  10798. delete data;
  10799. });
  10800. });
  10801. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  10802. auto i = new size_t(0);
  10803. res.set_content_provider(
  10804. "text/plain",
  10805. [i](size_t, DataSink &sink) {
  10806. if (*i < 5) {
  10807. std::this_thread::sleep_for(std::chrono::seconds(1));
  10808. sink.write("abcd", 4);
  10809. (*i)++;
  10810. } else {
  10811. sink.done();
  10812. }
  10813. return true;
  10814. },
  10815. [i](bool success) {
  10816. EXPECT_FALSE(success);
  10817. delete i;
  10818. });
  10819. });
  10820. svr.Get("/chunked", [&](const Request &, Response &res) {
  10821. auto i = new size_t(0);
  10822. res.set_chunked_content_provider(
  10823. "text/plain",
  10824. [i](size_t, DataSink &sink) {
  10825. if (*i < 5) {
  10826. std::this_thread::sleep_for(std::chrono::seconds(1));
  10827. sink.os << "abcd";
  10828. (*i)++;
  10829. } else {
  10830. sink.done();
  10831. }
  10832. return true;
  10833. },
  10834. [i](bool success) {
  10835. EXPECT_FALSE(success);
  10836. delete i;
  10837. });
  10838. });
  10839. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10840. auto se = detail::scope_exit([&] {
  10841. svr.stop();
  10842. listen_thread.join();
  10843. ASSERT_FALSE(svr.is_running());
  10844. });
  10845. svr.wait_until_ready();
  10846. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  10847. {
  10848. auto start = std::chrono::steady_clock::now();
  10849. auto res = cli.Get("/stream");
  10850. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10851. std::chrono::steady_clock::now() - start)
  10852. .count();
  10853. ASSERT_FALSE(res);
  10854. EXPECT_EQ(Error::Read, res.error());
  10855. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10856. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10857. }
  10858. {
  10859. auto start = std::chrono::steady_clock::now();
  10860. auto res = cli.Get("/stream_without_length");
  10861. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10862. std::chrono::steady_clock::now() - start)
  10863. .count();
  10864. ASSERT_FALSE(res);
  10865. EXPECT_EQ(Error::Read, res.error());
  10866. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10867. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10868. }
  10869. {
  10870. auto start = std::chrono::steady_clock::now();
  10871. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  10872. EXPECT_EQ("abcd", string(data, data_length));
  10873. return true;
  10874. });
  10875. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10876. std::chrono::steady_clock::now() - start)
  10877. .count();
  10878. ASSERT_FALSE(res);
  10879. EXPECT_EQ(Error::Read, res.error());
  10880. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10881. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10882. }
  10883. }
  10884. TEST(MaxTimeoutTest, ContentStream) {
  10885. time_t timeout = 2000;
  10886. time_t threshold = 200;
  10887. Server svr;
  10888. Client cli("localhost", PORT);
  10889. max_timeout_test(svr, cli, timeout, threshold);
  10890. }
  10891. #ifdef CPPHTTPLIB_SSL_ENABLED
  10892. TEST(MaxTimeoutTest, ContentStreamSSL) {
  10893. time_t timeout = 2000;
  10894. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  10895. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10896. SSLClient cli("localhost", PORT);
  10897. cli.enable_server_certificate_verification(false);
  10898. max_timeout_test(svr, cli, timeout, threshold);
  10899. }
  10900. #endif
  10901. class EventDispatcher {
  10902. public:
  10903. EventDispatcher() {}
  10904. bool wait_event(DataSink *sink) {
  10905. unique_lock<mutex> lk(m_);
  10906. int id = id_;
  10907. // Wait with timeout to prevent hanging if client disconnects
  10908. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  10909. [&] { return cid_ == id; })) {
  10910. return false; // Timeout occurred
  10911. }
  10912. sink->write(message_.data(), message_.size());
  10913. return true;
  10914. }
  10915. void send_event(const string &message) {
  10916. lock_guard<mutex> lk(m_);
  10917. cid_ = id_++;
  10918. message_ = message;
  10919. cv_.notify_all();
  10920. }
  10921. private:
  10922. mutex m_;
  10923. condition_variable cv_;
  10924. atomic_int id_{0};
  10925. atomic_int cid_{-1};
  10926. string message_;
  10927. };
  10928. TEST(ClientInThreadTest, Issue2068) {
  10929. EventDispatcher ed;
  10930. Server svr;
  10931. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  10932. res.set_chunked_content_provider("text/event-stream",
  10933. [&](size_t /*offset*/, DataSink &sink) {
  10934. return ed.wait_event(&sink);
  10935. });
  10936. });
  10937. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10938. svr.wait_until_ready();
  10939. thread event_thread([&] {
  10940. int id = 0;
  10941. while (svr.is_running()) {
  10942. this_thread::sleep_for(chrono::milliseconds(500));
  10943. std::stringstream ss;
  10944. ss << "data: " << id << "\n\n";
  10945. ed.send_event(ss.str());
  10946. id++;
  10947. }
  10948. });
  10949. auto se = detail::scope_exit([&] {
  10950. svr.stop();
  10951. listen_thread.join();
  10952. event_thread.join();
  10953. ASSERT_FALSE(svr.is_running());
  10954. });
  10955. {
  10956. auto client = detail::make_unique<Client>(HOST, PORT);
  10957. client->set_read_timeout(std::chrono::minutes(10));
  10958. std::atomic<bool> stop{false};
  10959. std::thread t([&] {
  10960. client->Get("/event1",
  10961. [&](const char *, size_t) -> bool { return !stop; });
  10962. });
  10963. std::this_thread::sleep_for(std::chrono::seconds(2));
  10964. stop = true;
  10965. client->stop();
  10966. t.join();
  10967. // Reset client after thread has finished
  10968. client.reset();
  10969. }
  10970. }
  10971. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  10972. auto handled = false;
  10973. Server svr;
  10974. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10975. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10976. auto se = detail::scope_exit([&] {
  10977. svr.stop();
  10978. t.join();
  10979. ASSERT_FALSE(svr.is_running());
  10980. ASSERT_FALSE(handled);
  10981. });
  10982. svr.wait_until_ready();
  10983. // Two Content-Length headers with different values — must be rejected
  10984. auto req = "POST /test HTTP/1.1\r\n"
  10985. "Content-Length: 5\r\n"
  10986. "Content-Length: 10\r\n"
  10987. "\r\n"
  10988. "hello";
  10989. std::string response;
  10990. ASSERT_TRUE(send_request(1, req, &response));
  10991. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10992. response.substr(0, response.find("\r\n")));
  10993. }
  10994. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  10995. auto handled = false;
  10996. Server svr;
  10997. svr.Post("/test", [&](const Request &, Response &res) {
  10998. handled = true;
  10999. res.set_content("ok", "text/plain");
  11000. });
  11001. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11002. auto se = detail::scope_exit([&] {
  11003. svr.stop();
  11004. t.join();
  11005. ASSERT_FALSE(svr.is_running());
  11006. ASSERT_TRUE(handled);
  11007. });
  11008. svr.wait_until_ready();
  11009. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  11010. auto req = "POST /test HTTP/1.1\r\n"
  11011. "Content-Length: 5\r\n"
  11012. "Content-Length: 5\r\n"
  11013. "\r\n"
  11014. "hello";
  11015. std::string response;
  11016. ASSERT_TRUE(send_request(1, req, &response));
  11017. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  11018. }
  11019. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  11020. Server svr;
  11021. svr.Get("/", [](const Request &req, Response &res) {
  11022. EXPECT_EQ(2U, req.trailers.size());
  11023. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  11024. // Denied
  11025. EXPECT_FALSE(req.has_trailer("Content-Length"));
  11026. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  11027. // Accepted
  11028. EXPECT_TRUE(req.has_trailer("X-Hello"));
  11029. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  11030. EXPECT_TRUE(req.has_trailer("X-World"));
  11031. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  11032. res.set_content("ok", "text/plain");
  11033. });
  11034. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11035. auto se = detail::scope_exit([&] {
  11036. svr.stop();
  11037. t.join();
  11038. ASSERT_FALSE(svr.is_running());
  11039. });
  11040. svr.wait_until_ready();
  11041. const std::string req = "GET / HTTP/1.1\r\n"
  11042. "Transfer-Encoding: chunked\r\n"
  11043. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  11044. "\r\n"
  11045. "0\r\n"
  11046. "Content-Length: 10\r\n"
  11047. "Host: internal.local\r\n"
  11048. "Content-Type: malicious/content\r\n"
  11049. "Cookie: any\r\n"
  11050. "Set-Cookie: any\r\n"
  11051. "X-Forwarded-For: attacker.com\r\n"
  11052. "X-Real-Ip: 1.1.1.1\r\n"
  11053. "X-Hello: hello\r\n"
  11054. "X-World: world\r\n"
  11055. "\r\n";
  11056. std::string res;
  11057. ASSERT_TRUE(send_request(1, req, &res));
  11058. }
  11059. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  11060. Server svr;
  11061. std::string observed_remote_addr;
  11062. std::string observed_xff;
  11063. svr.Get("/ip", [&](const Request &req, Response &res) {
  11064. observed_remote_addr = req.remote_addr;
  11065. observed_xff = req.get_header_value("X-Forwarded-For");
  11066. res.set_content("ok", "text/plain");
  11067. });
  11068. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11069. auto se = detail::scope_exit([&] {
  11070. svr.stop();
  11071. t.join();
  11072. ASSERT_FALSE(svr.is_running());
  11073. });
  11074. svr.wait_until_ready();
  11075. Client cli(HOST, PORT);
  11076. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  11077. ASSERT_TRUE(res);
  11078. EXPECT_EQ(StatusCode::OK_200, res->status);
  11079. EXPECT_EQ(observed_xff, "203.0.113.66");
  11080. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11081. observed_remote_addr == "127.0.0.1");
  11082. }
  11083. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  11084. Server svr;
  11085. svr.set_trusted_proxies({"203.0.113.66"});
  11086. std::string observed_remote_addr;
  11087. std::string observed_xff;
  11088. svr.Get("/ip", [&](const Request &req, Response &res) {
  11089. observed_remote_addr = req.remote_addr;
  11090. observed_xff = req.get_header_value("X-Forwarded-For");
  11091. res.set_content("ok", "text/plain");
  11092. });
  11093. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11094. auto se = detail::scope_exit([&] {
  11095. svr.stop();
  11096. t.join();
  11097. ASSERT_FALSE(svr.is_running());
  11098. });
  11099. svr.wait_until_ready();
  11100. Client cli(HOST, PORT);
  11101. auto res = cli.Get("/ip");
  11102. ASSERT_TRUE(res);
  11103. EXPECT_EQ(StatusCode::OK_200, res->status);
  11104. EXPECT_EQ(observed_xff, "");
  11105. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11106. observed_remote_addr == "127.0.0.1");
  11107. }
  11108. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  11109. Server svr;
  11110. svr.set_trusted_proxies({"203.0.113.66"});
  11111. std::string observed_remote_addr;
  11112. std::string observed_xff;
  11113. svr.Get("/ip", [&](const Request &req, Response &res) {
  11114. observed_remote_addr = req.remote_addr;
  11115. observed_xff = req.get_header_value("X-Forwarded-For");
  11116. res.set_content("ok", "text/plain");
  11117. });
  11118. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11119. auto se = detail::scope_exit([&] {
  11120. svr.stop();
  11121. t.join();
  11122. ASSERT_FALSE(svr.is_running());
  11123. });
  11124. svr.wait_until_ready();
  11125. Client cli(HOST, PORT);
  11126. auto res =
  11127. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  11128. ASSERT_TRUE(res);
  11129. EXPECT_EQ(StatusCode::OK_200, res->status);
  11130. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  11131. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11132. }
  11133. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  11134. Server svr;
  11135. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  11136. std::string observed_remote_addr;
  11137. std::string observed_xff;
  11138. svr.Get("/ip", [&](const Request &req, Response &res) {
  11139. observed_remote_addr = req.remote_addr;
  11140. observed_xff = req.get_header_value("X-Forwarded-For");
  11141. res.set_content("ok", "text/plain");
  11142. });
  11143. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11144. auto se = detail::scope_exit([&] {
  11145. svr.stop();
  11146. t.join();
  11147. ASSERT_FALSE(svr.is_running());
  11148. });
  11149. svr.wait_until_ready();
  11150. Client cli(HOST, PORT);
  11151. auto res = cli.Get(
  11152. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11153. ASSERT_TRUE(res);
  11154. EXPECT_EQ(StatusCode::OK_200, res->status);
  11155. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11156. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11157. }
  11158. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  11159. Server svr;
  11160. svr.set_trusted_proxies({"192.0.2.45"});
  11161. std::string observed_remote_addr;
  11162. std::string observed_xff;
  11163. svr.Get("/ip", [&](const Request &req, Response &res) {
  11164. observed_remote_addr = req.remote_addr;
  11165. observed_xff = req.get_header_value("X-Forwarded-For");
  11166. res.set_content("ok", "text/plain");
  11167. });
  11168. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11169. auto se = detail::scope_exit([&] {
  11170. svr.stop();
  11171. t.join();
  11172. ASSERT_FALSE(svr.is_running());
  11173. });
  11174. svr.wait_until_ready();
  11175. Client cli(HOST, PORT);
  11176. auto res =
  11177. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  11178. ASSERT_TRUE(res);
  11179. EXPECT_EQ(StatusCode::OK_200, res->status);
  11180. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  11181. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11182. }
  11183. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  11184. Server svr;
  11185. svr.set_trusted_proxies({"192.0.2.45"});
  11186. std::string observed_remote_addr;
  11187. std::string observed_xff;
  11188. svr.Get("/ip", [&](const Request &req, Response &res) {
  11189. observed_remote_addr = req.remote_addr;
  11190. observed_xff = req.get_header_value("X-Forwarded-For");
  11191. res.set_content("ok", "text/plain");
  11192. });
  11193. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11194. auto se = detail::scope_exit([&] {
  11195. svr.stop();
  11196. t.join();
  11197. ASSERT_FALSE(svr.is_running());
  11198. });
  11199. svr.wait_until_ready();
  11200. Client cli(HOST, PORT);
  11201. auto res = cli.Get(
  11202. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11203. ASSERT_TRUE(res);
  11204. EXPECT_EQ(StatusCode::OK_200, res->status);
  11205. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11206. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11207. }
  11208. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  11209. Server svr;
  11210. svr.set_trusted_proxies({"192.0.2.45"});
  11211. std::string observed_remote_addr;
  11212. std::string observed_xff;
  11213. svr.Get("/ip", [&](const Request &req, Response &res) {
  11214. observed_remote_addr = req.remote_addr;
  11215. observed_xff = req.get_header_value("X-Forwarded-For");
  11216. res.set_content("ok", "text/plain");
  11217. });
  11218. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11219. auto se = detail::scope_exit([&] {
  11220. svr.stop();
  11221. t.join();
  11222. ASSERT_FALSE(svr.is_running());
  11223. });
  11224. svr.wait_until_ready();
  11225. std::string raw_req =
  11226. "GET /ip HTTP/1.1\r\n"
  11227. "Host: localhost\r\n"
  11228. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  11229. "Connection: close\r\n"
  11230. "\r\n";
  11231. std::string out;
  11232. ASSERT_TRUE(send_request(5, raw_req, &out));
  11233. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11234. // Header parser trims surrounding whitespace of the header value
  11235. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  11236. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11237. }
  11238. #ifndef _WIN32
  11239. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  11240. Server svr;
  11241. svr.Post("/post", [&](const Request &req, Response &res) {
  11242. res.set_content(req.body, "text/plain");
  11243. });
  11244. svr.Put("/put", [&](const Request &req, Response &res) {
  11245. res.set_content(req.body, "text/plain");
  11246. });
  11247. svr.Patch("/patch", [&](const Request &req, Response &res) {
  11248. res.set_content(req.body, "text/plain");
  11249. });
  11250. svr.Delete("/delete", [&](const Request &req, Response &res) {
  11251. res.set_content(req.body, "text/plain");
  11252. });
  11253. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11254. auto se = detail::scope_exit([&] {
  11255. svr.stop();
  11256. t.join();
  11257. ASSERT_FALSE(svr.is_running());
  11258. });
  11259. svr.wait_until_ready();
  11260. std::string resp;
  11261. // POST without Content-Length
  11262. ASSERT_TRUE(send_request(5,
  11263. "POST /post HTTP/1.1\r\n"
  11264. "Host: localhost\r\n"
  11265. "Connection: close\r\n"
  11266. "\r\n",
  11267. &resp));
  11268. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11269. // PUT without Content-Length
  11270. resp.clear();
  11271. ASSERT_TRUE(send_request(5,
  11272. "PUT /put HTTP/1.1\r\n"
  11273. "Host: localhost\r\n"
  11274. "Connection: close\r\n"
  11275. "\r\n",
  11276. &resp));
  11277. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11278. // PATCH without Content-Length
  11279. resp.clear();
  11280. ASSERT_TRUE(send_request(5,
  11281. "PATCH /patch HTTP/1.1\r\n"
  11282. "Host: localhost\r\n"
  11283. "Connection: close\r\n"
  11284. "\r\n",
  11285. &resp));
  11286. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11287. // DELETE without Content-Length
  11288. resp.clear();
  11289. ASSERT_TRUE(send_request(5,
  11290. "DELETE /delete HTTP/1.1\r\n"
  11291. "Host: localhost\r\n"
  11292. "Connection: close\r\n"
  11293. "\r\n",
  11294. &resp));
  11295. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11296. }
  11297. #endif
  11298. //==============================================================================
  11299. // open_stream() Tests
  11300. //==============================================================================
  11301. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  11302. std::string result;
  11303. char buf[8192];
  11304. ssize_t n;
  11305. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11306. result.append(buf, static_cast<size_t>(n));
  11307. }
  11308. return result;
  11309. }
  11310. // Mock stream for unit tests
  11311. class MockStream : public Stream {
  11312. public:
  11313. std::string data;
  11314. size_t pos = 0;
  11315. ssize_t error_after = -1; // -1 = no error
  11316. explicit MockStream(const std::string &d, ssize_t err = -1)
  11317. : data(d), error_after(err) {}
  11318. bool is_readable() const override { return true; }
  11319. bool wait_readable() const override { return true; }
  11320. bool wait_writable() const override { return true; }
  11321. ssize_t read(char *ptr, size_t size) override {
  11322. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  11323. if (pos >= data.size()) return 0;
  11324. size_t limit =
  11325. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  11326. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  11327. std::memcpy(ptr, data.data() + pos, to_read);
  11328. pos += to_read;
  11329. return static_cast<ssize_t>(to_read);
  11330. }
  11331. ssize_t write(const char *, size_t) override { return -1; }
  11332. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  11333. ip = "127.0.0.1";
  11334. port = 0;
  11335. }
  11336. void get_local_ip_and_port(std::string &ip, int &port) const override {
  11337. ip = "127.0.0.1";
  11338. port = 0;
  11339. }
  11340. socket_t socket() const override { return INVALID_SOCKET; }
  11341. time_t duration() const override { return 0; }
  11342. };
  11343. TEST(StreamHandleTest, Basic) {
  11344. ClientImpl::StreamHandle handle;
  11345. EXPECT_FALSE(handle.is_valid());
  11346. handle.response = detail::make_unique<Response>();
  11347. handle.error = Error::Connection;
  11348. EXPECT_FALSE(handle.is_valid());
  11349. handle.error = Error::Success;
  11350. EXPECT_TRUE(handle.is_valid());
  11351. }
  11352. TEST(BodyReaderTest, Basic) {
  11353. MockStream stream("Hello, World!");
  11354. detail::BodyReader reader;
  11355. reader.stream = &stream;
  11356. reader.content_length = 13;
  11357. char buf[32];
  11358. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  11359. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  11360. EXPECT_TRUE(reader.eof);
  11361. }
  11362. TEST(BodyReaderTest, NoStream) {
  11363. detail::BodyReader reader;
  11364. char buf[32];
  11365. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11366. EXPECT_EQ(Error::Connection, reader.last_error);
  11367. }
  11368. TEST(BodyReaderTest, Error) {
  11369. MockStream stream("Hello, World!", 5);
  11370. detail::BodyReader reader;
  11371. reader.stream = &stream;
  11372. reader.content_length = 13;
  11373. char buf[32];
  11374. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  11375. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11376. EXPECT_EQ(Error::Read, reader.last_error);
  11377. }
  11378. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  11379. // Mock-based StreamHandle tests relying on private internals are removed.
  11380. class OpenStreamTest : public ::testing::Test {
  11381. protected:
  11382. void SetUp() override {
  11383. svr_.Get("/hello", [](const Request &, Response &res) {
  11384. res.set_content("Hello World!", "text/plain");
  11385. });
  11386. svr_.Get("/large", [](const Request &, Response &res) {
  11387. res.set_content(std::string(10000, 'X'), "text/plain");
  11388. });
  11389. svr_.Get("/chunked", [](const Request &, Response &res) {
  11390. res.set_chunked_content_provider("text/plain",
  11391. [](size_t offset, DataSink &sink) {
  11392. if (offset < 15) {
  11393. sink.write("chunk", 5);
  11394. return true;
  11395. }
  11396. sink.done();
  11397. return true;
  11398. });
  11399. });
  11400. svr_.Get("/compressible", [](const Request &, Response &res) {
  11401. res.set_chunked_content_provider("text/plain", [](size_t offset,
  11402. DataSink &sink) {
  11403. if (offset < 100 * 1024) {
  11404. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  11405. sink.write(chunk.data(), chunk.size());
  11406. return true;
  11407. }
  11408. sink.done();
  11409. return true;
  11410. });
  11411. });
  11412. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  11413. [](const Request & /*req*/, Response &res) {
  11414. auto i = new int(0);
  11415. res.set_header("Trailer", "Content-Length, X-Allowed");
  11416. res.set_chunked_content_provider(
  11417. "text/plain",
  11418. [i](size_t /*offset*/, DataSink &sink) {
  11419. switch (*i) {
  11420. case 0: sink.os << "123"; break;
  11421. case 1: sink.os << "456"; break;
  11422. case 2: sink.os << "789"; break;
  11423. case 3: {
  11424. sink.done_with_trailer(
  11425. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  11426. } break;
  11427. }
  11428. (*i)++;
  11429. return true;
  11430. },
  11431. [i](bool success) {
  11432. EXPECT_TRUE(success);
  11433. delete i;
  11434. });
  11435. });
  11436. // Echo headers endpoint for header-related tests
  11437. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  11438. std::string body;
  11439. for (const auto &h : req.headers) {
  11440. body.append(h.first);
  11441. body.push_back(':');
  11442. body.append(h.second);
  11443. body.push_back('\n');
  11444. }
  11445. res.set_content(body, "text/plain");
  11446. });
  11447. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  11448. std::string body;
  11449. for (const auto &h : req.headers) {
  11450. body.append(h.first);
  11451. body.push_back(':');
  11452. body.append(h.second);
  11453. body.push_back('\n');
  11454. }
  11455. res.set_content(body, "text/plain");
  11456. });
  11457. port_ = svr_.bind_to_any_port("127.0.0.1");
  11458. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11459. svr_.wait_until_ready();
  11460. }
  11461. void TearDown() override {
  11462. svr_.stop();
  11463. if (thread_.joinable()) thread_.join();
  11464. }
  11465. Server svr_;
  11466. std::thread thread_;
  11467. int port_ = 0;
  11468. };
  11469. TEST_F(OpenStreamTest, Basic) {
  11470. Client cli("127.0.0.1", port_);
  11471. auto handle = cli.open_stream("GET", "/hello");
  11472. EXPECT_TRUE(handle.is_valid());
  11473. EXPECT_EQ("Hello World!", read_all(handle));
  11474. }
  11475. TEST_F(OpenStreamTest, SmallBuffer) {
  11476. Client cli("127.0.0.1", port_);
  11477. auto handle = cli.open_stream("GET", "/hello");
  11478. std::string result;
  11479. char buf[4];
  11480. ssize_t n;
  11481. while ((n = handle.read(buf, sizeof(buf))) > 0)
  11482. result.append(buf, static_cast<size_t>(n));
  11483. EXPECT_EQ("Hello World!", result);
  11484. }
  11485. TEST_F(OpenStreamTest, DefaultHeaders) {
  11486. Client cli("127.0.0.1", port_);
  11487. // open_stream GET should include Host, User-Agent and Accept-Encoding
  11488. {
  11489. auto handle = cli.open_stream("GET", "/echo-headers");
  11490. ASSERT_TRUE(handle.is_valid());
  11491. auto body = read_all(handle);
  11492. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  11493. std::string::npos);
  11494. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  11495. std::string::npos);
  11496. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  11497. }
  11498. // open_stream POST with body and no explicit content_type should NOT add
  11499. // text/plain Content-Type (behavior differs from non-streaming path), but
  11500. // should include Content-Length
  11501. {
  11502. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  11503. ASSERT_TRUE(handle.is_valid());
  11504. auto body = read_all(handle);
  11505. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  11506. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  11507. }
  11508. // open_stream POST with explicit Content-Type should preserve it
  11509. {
  11510. auto handle = cli.open_stream("POST", "/echo-headers", {},
  11511. {{"Content-Type", "application/custom"}},
  11512. "{}", "application/custom");
  11513. ASSERT_TRUE(handle.is_valid());
  11514. auto body = read_all(handle);
  11515. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  11516. }
  11517. // User-specified User-Agent must not be overwritten for stream API
  11518. {
  11519. auto handle = cli.open_stream("GET", "/echo-headers", {},
  11520. {{"User-Agent", "MyAgent/1.2"}});
  11521. ASSERT_TRUE(handle.is_valid());
  11522. auto body = read_all(handle);
  11523. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  11524. }
  11525. }
  11526. TEST_F(OpenStreamTest, Large) {
  11527. Client cli("127.0.0.1", port_);
  11528. auto handle = cli.open_stream("GET", "/large");
  11529. EXPECT_EQ(10000u, read_all(handle).size());
  11530. }
  11531. TEST_F(OpenStreamTest, ConnectionError) {
  11532. Client cli("127.0.0.1", 9999);
  11533. auto handle = cli.open_stream("GET", "/hello");
  11534. EXPECT_FALSE(handle.is_valid());
  11535. }
  11536. TEST_F(OpenStreamTest, Chunked) {
  11537. Client cli("127.0.0.1", port_);
  11538. auto handle = cli.open_stream("GET", "/chunked");
  11539. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11540. "Transfer-Encoding") == "chunked");
  11541. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  11542. }
  11543. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  11544. Client cli("127.0.0.1", port_);
  11545. auto handle =
  11546. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  11547. ASSERT_TRUE(handle.is_valid());
  11548. // Consume body to allow trailers to be received/parsed
  11549. auto body = read_all(handle);
  11550. // Explicitly parse trailers (ensure trailers are available for assertion)
  11551. handle.parse_trailers_if_needed();
  11552. EXPECT_EQ(std::string("123456789"), body);
  11553. // The response should include a Trailer header declaring both names
  11554. ASSERT_TRUE(handle.response);
  11555. EXPECT_TRUE(handle.response->has_header("Trailer"));
  11556. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  11557. handle.response->get_header_value("Trailer"));
  11558. // Prohibited trailer must not be present
  11559. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  11560. // Allowed trailer should be present
  11561. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  11562. EXPECT_EQ(std::string("yes"),
  11563. handle.response->get_trailer_value("X-Allowed"));
  11564. // Verify trailers are NOT present as regular headers
  11565. EXPECT_EQ(std::string(""),
  11566. handle.response->get_header_value("Content-Length"));
  11567. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  11568. }
  11569. static std::thread serve_single_response(std::promise<int> &port_promise,
  11570. const std::string &response) {
  11571. return std::thread([&port_promise, response] {
  11572. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11573. default_socket_options(srv);
  11574. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11575. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11576. sockaddr_in addr{};
  11577. addr.sin_family = AF_INET;
  11578. addr.sin_port = htons(0); // Let OS assign a free port
  11579. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11580. int opt = 1;
  11581. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11582. #ifdef _WIN32
  11583. reinterpret_cast<const char *>(&opt),
  11584. #else
  11585. &opt,
  11586. #endif
  11587. sizeof(opt));
  11588. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  11589. ::listen(srv, 1) != 0) {
  11590. port_promise.set_value(-1);
  11591. detail::close_socket(srv);
  11592. return;
  11593. }
  11594. socklen_t addr_len = sizeof(addr);
  11595. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  11596. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  11597. sockaddr_in cli_addr{};
  11598. socklen_t cli_len = sizeof(cli_addr);
  11599. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11600. if (cli != INVALID_SOCKET) {
  11601. char buf[4096];
  11602. ::recv(cli, buf, sizeof(buf), 0);
  11603. ::send(cli,
  11604. #ifdef _WIN32
  11605. static_cast<const char *>(response.c_str()),
  11606. static_cast<int>(response.size()),
  11607. #else
  11608. response.c_str(), response.size(),
  11609. #endif
  11610. 0);
  11611. detail::close_socket(cli);
  11612. }
  11613. detail::close_socket(srv);
  11614. });
  11615. }
  11616. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  11617. #ifndef _WIN32
  11618. signal(SIGPIPE, SIG_IGN);
  11619. #endif
  11620. std::promise<int> port_promise;
  11621. auto port_future = port_promise.get_future();
  11622. auto server_thread =
  11623. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  11624. "Content-Type: text/plain\r\n"
  11625. "Content-Length: not-a-number\r\n"
  11626. "Connection: close\r\n"
  11627. "\r\n"
  11628. "hello");
  11629. auto port = port_future.get();
  11630. ASSERT_GT(port, 0);
  11631. Client cli("127.0.0.1", port);
  11632. auto handle = cli.open_stream("GET", "/");
  11633. EXPECT_FALSE(handle.is_valid());
  11634. server_thread.join();
  11635. }
  11636. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  11637. #ifndef _WIN32
  11638. signal(SIGPIPE, SIG_IGN);
  11639. #endif
  11640. std::promise<int> port_promise;
  11641. auto port_future = port_promise.get_future();
  11642. auto server_thread = serve_single_response(
  11643. port_promise, "HTTP/1.1 200 OK\r\n"
  11644. "Content-Type: text/plain\r\n"
  11645. "Content-Length: 99999999999999999999999999\r\n"
  11646. "Connection: close\r\n"
  11647. "\r\n"
  11648. "hello");
  11649. auto port = port_future.get();
  11650. ASSERT_GT(port, 0);
  11651. // Before the fix, std::stoull would throw std::out_of_range here and
  11652. // crash the process. After the fix, strtoull silently clamps to
  11653. // ULLONG_MAX so the stream opens without crashing. The important thing
  11654. // is that the process does NOT terminate.
  11655. Client cli("127.0.0.1", port);
  11656. auto handle = cli.open_stream("GET", "/");
  11657. EXPECT_TRUE(handle.is_valid());
  11658. server_thread.join();
  11659. }
  11660. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11661. TEST_F(OpenStreamTest, Gzip) {
  11662. Client cli("127.0.0.1", port_);
  11663. auto handle = cli.open_stream("GET", "/compressible", {},
  11664. {{"Accept-Encoding", "gzip"}});
  11665. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  11666. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11667. }
  11668. #endif
  11669. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11670. TEST_F(OpenStreamTest, Brotli) {
  11671. Client cli("127.0.0.1", port_);
  11672. auto handle =
  11673. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  11674. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  11675. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11676. }
  11677. #endif
  11678. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11679. TEST_F(OpenStreamTest, Zstd) {
  11680. Client cli("127.0.0.1", port_);
  11681. auto handle = cli.open_stream("GET", "/compressible", {},
  11682. {{"Accept-Encoding", "zstd"}});
  11683. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  11684. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11685. }
  11686. #endif
  11687. #ifdef CPPHTTPLIB_SSL_ENABLED
  11688. class SSLOpenStreamTest : public ::testing::Test {
  11689. protected:
  11690. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  11691. void SetUp() override {
  11692. svr_.Get("/hello", [](const Request &, Response &res) {
  11693. res.set_content("Hello SSL World!", "text/plain");
  11694. });
  11695. svr_.Get("/chunked", [](const Request &, Response &res) {
  11696. res.set_chunked_content_provider("text/plain",
  11697. [](size_t offset, DataSink &sink) {
  11698. if (offset < 15) {
  11699. sink.write("chunk", 5);
  11700. return true;
  11701. }
  11702. sink.done();
  11703. return true;
  11704. });
  11705. });
  11706. svr_.Post("/echo", [](const Request &req, Response &res) {
  11707. res.set_content(req.body, req.get_header_value("Content-Type"));
  11708. });
  11709. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  11710. std::string body = req.body;
  11711. res.set_chunked_content_provider(
  11712. "text/plain", [body](size_t offset, DataSink &sink) {
  11713. if (offset < body.size()) {
  11714. sink.write(body.data() + offset, body.size() - offset);
  11715. }
  11716. sink.done();
  11717. return true;
  11718. });
  11719. });
  11720. port_ = svr_.bind_to_any_port("127.0.0.1");
  11721. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11722. svr_.wait_until_ready();
  11723. }
  11724. void TearDown() override {
  11725. svr_.stop();
  11726. if (thread_.joinable()) thread_.join();
  11727. }
  11728. SSLServer svr_;
  11729. std::thread thread_;
  11730. int port_ = 0;
  11731. };
  11732. TEST_F(SSLOpenStreamTest, Basic) {
  11733. SSLClient cli("127.0.0.1", port_);
  11734. cli.enable_server_certificate_verification(false);
  11735. auto handle = cli.open_stream("GET", "/hello");
  11736. ASSERT_TRUE(handle.is_valid());
  11737. EXPECT_EQ("Hello SSL World!", read_all(handle));
  11738. }
  11739. TEST_F(SSLOpenStreamTest, Chunked) {
  11740. SSLClient cli("127.0.0.1", port_);
  11741. cli.enable_server_certificate_verification(false);
  11742. auto handle = cli.open_stream("GET", "/chunked");
  11743. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11744. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11745. "Transfer-Encoding") == "chunked");
  11746. auto body = read_all(handle);
  11747. EXPECT_EQ("chunkchunkchunk", body);
  11748. }
  11749. TEST_F(SSLOpenStreamTest, Post) {
  11750. SSLClient cli("127.0.0.1", port_);
  11751. cli.enable_server_certificate_verification(false);
  11752. auto handle =
  11753. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  11754. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11755. EXPECT_EQ(200, handle.response->status);
  11756. auto body = read_all(handle);
  11757. EXPECT_EQ("Hello SSL POST", body);
  11758. }
  11759. TEST_F(SSLOpenStreamTest, PostChunked) {
  11760. SSLClient cli("127.0.0.1", port_);
  11761. cli.enable_server_certificate_verification(false);
  11762. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  11763. "Chunked SSL Data", "text/plain");
  11764. ASSERT_TRUE(handle.is_valid());
  11765. EXPECT_EQ(200, handle.response->status);
  11766. auto body = read_all(handle);
  11767. EXPECT_EQ("Chunked SSL Data", body);
  11768. }
  11769. #endif // CPPHTTPLIB_SSL_ENABLED
  11770. //==============================================================================
  11771. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  11772. // results for various scenarios.
  11773. //==============================================================================
  11774. TEST(ParityTest, GetVsOpenStream) {
  11775. Server svr;
  11776. const std::string path = "/parity";
  11777. const std::string content = "Parity test content: hello world";
  11778. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11779. res.set_content(content, "text/plain");
  11780. });
  11781. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11782. auto se = detail::scope_exit([&] {
  11783. svr.stop();
  11784. t.join();
  11785. ASSERT_FALSE(svr.is_running());
  11786. });
  11787. svr.wait_until_ready();
  11788. Client cli(HOST, PORT);
  11789. // Non-stream path
  11790. auto r1 = cli.Get(path);
  11791. ASSERT_TRUE(r1);
  11792. EXPECT_EQ(StatusCode::OK_200, r1->status);
  11793. // Stream path
  11794. auto h = cli.open_stream("GET", path);
  11795. ASSERT_TRUE(h.is_valid());
  11796. EXPECT_EQ(r1->body, read_all(h));
  11797. }
  11798. // Helper to compress data with provided compressor type T
  11799. template <typename Compressor>
  11800. static std::string compress_payload_for_parity(const std::string &in) {
  11801. std::string out;
  11802. Compressor compressor;
  11803. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  11804. [&](const char *data, size_t n) {
  11805. out.append(data, n);
  11806. return true;
  11807. });
  11808. EXPECT_TRUE(ok);
  11809. return out;
  11810. }
  11811. // Helper function for compression parity tests
  11812. template <typename Compressor>
  11813. static void test_compression_parity(const std::string &original,
  11814. const std::string &path,
  11815. const std::string &encoding) {
  11816. const std::string compressed =
  11817. compress_payload_for_parity<Compressor>(original);
  11818. Server svr;
  11819. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11820. res.set_content(compressed, "application/octet-stream");
  11821. res.set_header("Content-Encoding", encoding);
  11822. });
  11823. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  11824. auto se = detail::scope_exit([&] {
  11825. svr.stop();
  11826. t.join();
  11827. ASSERT_FALSE(svr.is_running());
  11828. });
  11829. svr.wait_until_ready();
  11830. Client cli(HOST, PORT);
  11831. // Non-streaming
  11832. {
  11833. auto res = cli.Get(path);
  11834. ASSERT_TRUE(res);
  11835. EXPECT_EQ(StatusCode::OK_200, res->status);
  11836. EXPECT_EQ(original, res->body);
  11837. }
  11838. // Streaming
  11839. {
  11840. auto h = cli.open_stream("GET", path);
  11841. ASSERT_TRUE(h.is_valid());
  11842. EXPECT_EQ(original, read_all(h));
  11843. }
  11844. }
  11845. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11846. TEST(ParityTest, Gzip) {
  11847. test_compression_parity<detail::gzip_compressor>(
  11848. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  11849. }
  11850. #endif
  11851. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11852. TEST(ParityTest, Brotli) {
  11853. test_compression_parity<detail::brotli_compressor>(
  11854. "Hello, brotli parity test payload", "/parity-br", "br");
  11855. }
  11856. #endif
  11857. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11858. TEST(ParityTest, Zstd) {
  11859. test_compression_parity<detail::zstd_compressor>(
  11860. "Zstandard parity test payload", "/parity-zstd", "zstd");
  11861. }
  11862. #endif
  11863. //==============================================================================
  11864. // New Stream API Tests
  11865. //==============================================================================
  11866. inline std::string read_body(httplib::stream::Result &result) {
  11867. std::string body;
  11868. while (result.next()) {
  11869. body.append(result.data(), result.size());
  11870. }
  11871. return body;
  11872. }
  11873. TEST(ClientConnectionTest, Basic) {
  11874. httplib::ClientConnection conn;
  11875. EXPECT_FALSE(conn.is_open());
  11876. conn.sock = 1;
  11877. EXPECT_TRUE(conn.is_open());
  11878. httplib::ClientConnection conn2(std::move(conn));
  11879. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  11880. conn2.sock = INVALID_SOCKET;
  11881. }
  11882. // Unified test server for all stream::* tests
  11883. class StreamApiTest : public ::testing::Test {
  11884. protected:
  11885. void SetUp() override {
  11886. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11887. res.set_content("Hello World!", "text/plain");
  11888. });
  11889. svr_.Get("/echo-params",
  11890. [](const httplib::Request &req, httplib::Response &res) {
  11891. std::string r;
  11892. for (const auto &p : req.params) {
  11893. if (!r.empty()) r += "&";
  11894. r += p.first + "=" + p.second;
  11895. }
  11896. res.set_content(r, "text/plain");
  11897. });
  11898. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11899. res.set_content(req.body, req.get_header_value("Content-Type"));
  11900. });
  11901. svr_.Post("/echo-headers",
  11902. [](const httplib::Request &req, httplib::Response &res) {
  11903. std::string r;
  11904. for (const auto &h : req.headers)
  11905. r += h.first + ": " + h.second + "\n";
  11906. res.set_content(r, "text/plain");
  11907. });
  11908. svr_.Post("/echo-params",
  11909. [](const httplib::Request &req, httplib::Response &res) {
  11910. std::string r = "params:";
  11911. for (const auto &p : req.params)
  11912. r += p.first + "=" + p.second + ";";
  11913. res.set_content(r + " body:" + req.body, "text/plain");
  11914. });
  11915. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  11916. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  11917. });
  11918. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11919. res.set_content("PUT:" + req.body, "text/plain");
  11920. });
  11921. svr_.Patch("/echo",
  11922. [](const httplib::Request &req, httplib::Response &res) {
  11923. res.set_content("PATCH:" + req.body, "text/plain");
  11924. });
  11925. svr_.Delete(
  11926. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  11927. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  11928. "text/plain");
  11929. });
  11930. svr_.Get("/head-test",
  11931. [](const httplib::Request &, httplib::Response &res) {
  11932. res.set_content("body for HEAD", "text/plain");
  11933. });
  11934. svr_.Options("/options",
  11935. [](const httplib::Request &, httplib::Response &res) {
  11936. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  11937. });
  11938. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  11939. svr_.wait_until_ready();
  11940. }
  11941. void TearDown() override {
  11942. svr_.stop();
  11943. if (thread_.joinable()) thread_.join();
  11944. }
  11945. httplib::Server svr_;
  11946. std::thread thread_;
  11947. };
  11948. // stream::Get tests
  11949. TEST_F(StreamApiTest, GetBasic) {
  11950. httplib::Client cli(HOST, PORT);
  11951. auto result = httplib::stream::Get(cli, "/hello");
  11952. ASSERT_TRUE(result.is_valid());
  11953. EXPECT_EQ(200, result.status());
  11954. EXPECT_EQ("Hello World!", read_body(result));
  11955. }
  11956. TEST_F(StreamApiTest, GetWithParams) {
  11957. httplib::Client cli(HOST, PORT);
  11958. httplib::Params params{{"foo", "bar"}};
  11959. auto result = httplib::stream::Get(cli, "/echo-params", params);
  11960. ASSERT_TRUE(result.is_valid());
  11961. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  11962. }
  11963. TEST_F(StreamApiTest, GetConnectionError) {
  11964. httplib::Client cli(HOST, 9999);
  11965. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  11966. }
  11967. TEST_F(StreamApiTest, Get404) {
  11968. httplib::Client cli(HOST, PORT);
  11969. auto result = httplib::stream::Get(cli, "/nonexistent");
  11970. EXPECT_TRUE(result.is_valid());
  11971. EXPECT_EQ(404, result.status());
  11972. }
  11973. // stream::Post tests
  11974. TEST_F(StreamApiTest, PostBasic) {
  11975. httplib::Client cli(HOST, PORT);
  11976. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  11977. "application/json");
  11978. ASSERT_TRUE(result.is_valid());
  11979. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  11980. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  11981. }
  11982. TEST_F(StreamApiTest, PostWithHeaders) {
  11983. httplib::Client cli(HOST, PORT);
  11984. httplib::Headers headers{{"X-Custom", "value"}};
  11985. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  11986. "text/plain");
  11987. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  11988. }
  11989. TEST_F(StreamApiTest, PostWithParams) {
  11990. httplib::Client cli(HOST, PORT);
  11991. httplib::Params params{{"k", "v"}};
  11992. auto result =
  11993. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  11994. auto body = read_body(result);
  11995. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  11996. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  11997. }
  11998. TEST_F(StreamApiTest, PostLarge) {
  11999. httplib::Client cli(HOST, PORT);
  12000. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  12001. size_t total = 0;
  12002. while (result.next()) {
  12003. total += result.size();
  12004. }
  12005. EXPECT_EQ(100u * 1024u, total);
  12006. }
  12007. // stream::Put/Patch tests
  12008. TEST_F(StreamApiTest, PutAndPatch) {
  12009. httplib::Client cli(HOST, PORT);
  12010. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  12011. EXPECT_EQ("PUT:test", read_body(put));
  12012. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  12013. EXPECT_EQ("PATCH:test", read_body(patch));
  12014. }
  12015. // stream::Delete tests
  12016. TEST_F(StreamApiTest, Delete) {
  12017. httplib::Client cli(HOST, PORT);
  12018. auto del1 = httplib::stream::Delete(cli, "/resource");
  12019. EXPECT_EQ("Deleted", read_body(del1));
  12020. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  12021. EXPECT_EQ("Deleted:data", read_body(del2));
  12022. }
  12023. // stream::Head/Options tests
  12024. TEST_F(StreamApiTest, HeadAndOptions) {
  12025. httplib::Client cli(HOST, PORT);
  12026. auto head = httplib::stream::Head(cli, "/head-test");
  12027. EXPECT_TRUE(head.is_valid());
  12028. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  12029. auto opts = httplib::stream::Options(cli, "/options");
  12030. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  12031. }
  12032. // SSL stream::* tests
  12033. #ifdef CPPHTTPLIB_SSL_ENABLED
  12034. class SSLStreamApiTest : public ::testing::Test {
  12035. protected:
  12036. void SetUp() override {
  12037. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12038. res.set_content("Hello SSL!", "text/plain");
  12039. });
  12040. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12041. res.set_content(req.body, "text/plain");
  12042. });
  12043. port_ = svr_.bind_to_any_port("127.0.0.1");
  12044. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12045. svr_.wait_until_ready();
  12046. }
  12047. void TearDown() override {
  12048. svr_.stop();
  12049. if (thread_.joinable()) thread_.join();
  12050. }
  12051. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  12052. std::thread thread_;
  12053. int port_ = 0;
  12054. };
  12055. TEST_F(SSLStreamApiTest, GetAndPost) {
  12056. httplib::SSLClient cli("127.0.0.1", port_);
  12057. cli.enable_server_certificate_verification(false);
  12058. auto get = httplib::stream::Get(cli, "/hello");
  12059. EXPECT_EQ("Hello SSL!", read_body(get));
  12060. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  12061. EXPECT_EQ("test", read_body(post));
  12062. }
  12063. #endif
  12064. // Tests for Error::Timeout and Error::ConnectionClosed error types
  12065. // These errors are set in SocketStream/SSLSocketStream and propagated through
  12066. // BodyReader
  12067. TEST(ErrorHandlingTest, StreamReadTimeout) {
  12068. // Test that read timeout during streaming is detected
  12069. // Use a large content-length response where server delays mid-stream
  12070. Server svr;
  12071. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12072. // Send a large response with delay in the middle
  12073. res.set_content_provider(
  12074. 1000, // content_length
  12075. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  12076. if (offset < 100) {
  12077. // Send first 100 bytes immediately
  12078. std::string data(100, 'A');
  12079. sink.write(data.c_str(), data.size());
  12080. return true;
  12081. }
  12082. // Then delay longer than client timeout
  12083. std::this_thread::sleep_for(std::chrono::seconds(3));
  12084. std::string data(900, 'B');
  12085. sink.write(data.c_str(), data.size());
  12086. return true;
  12087. });
  12088. });
  12089. auto port = 8091;
  12090. std::thread t([&]() { svr.listen("localhost", port); });
  12091. svr.wait_until_ready();
  12092. Client cli("localhost", port);
  12093. cli.set_read_timeout(1, 0); // 1 second timeout
  12094. auto handle = cli.open_stream("GET", "/slow-stream");
  12095. ASSERT_TRUE(handle.is_valid());
  12096. char buf[256];
  12097. ssize_t total = 0;
  12098. ssize_t n;
  12099. bool got_error = false;
  12100. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12101. total += n;
  12102. }
  12103. if (n < 0) {
  12104. got_error = true;
  12105. // Should be timeout or read error
  12106. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12107. handle.get_read_error() == Error::Read)
  12108. << "Actual error: " << to_string(handle.get_read_error());
  12109. }
  12110. // Either we got an error, or we got less data than expected
  12111. EXPECT_TRUE(got_error || total < 1000)
  12112. << "Expected timeout but got all " << total << " bytes";
  12113. svr.stop();
  12114. t.join();
  12115. }
  12116. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  12117. // Test connection closed detection via BodyReader
  12118. Server svr;
  12119. std::atomic<bool> close_now{false};
  12120. svr.Get("/will-close", [&](const Request &, Response &res) {
  12121. res.set_content_provider(
  12122. 10000, // Large content_length that we won't fully send
  12123. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12124. if (offset < 100) {
  12125. std::string data(100, 'X');
  12126. sink.write(data.c_str(), data.size());
  12127. return true;
  12128. }
  12129. // Wait for signal then abort
  12130. while (!close_now) {
  12131. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12132. }
  12133. return false; // Abort - server will close connection
  12134. });
  12135. });
  12136. auto port = 8092;
  12137. std::thread t([&]() { svr.listen("localhost", port); });
  12138. svr.wait_until_ready();
  12139. Client cli("localhost", port);
  12140. auto handle = cli.open_stream("GET", "/will-close");
  12141. ASSERT_TRUE(handle.is_valid());
  12142. char buf[256];
  12143. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12144. EXPECT_GT(n, 0) << "First read should succeed";
  12145. // Signal server to close
  12146. close_now = true;
  12147. // Keep reading until error or EOF
  12148. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12149. // Keep reading
  12150. }
  12151. // Should get an error since content_length wasn't satisfied
  12152. if (n < 0) {
  12153. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12154. handle.get_read_error() == Error::Read)
  12155. << "Actual error: " << to_string(handle.get_read_error());
  12156. }
  12157. svr.stop();
  12158. t.join();
  12159. }
  12160. #ifdef CPPHTTPLIB_SSL_ENABLED
  12161. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  12162. // Test that read timeout during SSL streaming is detected
  12163. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12164. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12165. res.set_content_provider(
  12166. 1000, "text/plain",
  12167. [](size_t offset, size_t /*length*/, DataSink &sink) {
  12168. if (offset < 100) {
  12169. std::string data(100, 'A');
  12170. sink.write(data.c_str(), data.size());
  12171. return true;
  12172. }
  12173. std::this_thread::sleep_for(std::chrono::seconds(3));
  12174. std::string data(900, 'B');
  12175. sink.write(data.c_str(), data.size());
  12176. return true;
  12177. });
  12178. });
  12179. auto port = 8093;
  12180. std::thread t([&]() { svr.listen("localhost", port); });
  12181. svr.wait_until_ready();
  12182. SSLClient cli("localhost", port);
  12183. cli.enable_server_certificate_verification(false);
  12184. cli.set_read_timeout(1, 0); // 1 second timeout
  12185. auto handle = cli.open_stream("GET", "/slow-stream");
  12186. ASSERT_TRUE(handle.is_valid());
  12187. char buf[256];
  12188. ssize_t total = 0;
  12189. ssize_t n;
  12190. bool got_error = false;
  12191. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12192. total += n;
  12193. }
  12194. if (n < 0) {
  12195. got_error = true;
  12196. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12197. handle.get_read_error() == Error::Read)
  12198. << "Actual error: " << to_string(handle.get_read_error());
  12199. }
  12200. EXPECT_TRUE(got_error || total < 1000)
  12201. << "Expected timeout but got all " << total << " bytes";
  12202. svr.stop();
  12203. t.join();
  12204. }
  12205. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  12206. // Test SSL connection closed detection
  12207. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12208. std::atomic<bool> close_now{false};
  12209. svr.Get("/will-close", [&](const Request &, Response &res) {
  12210. res.set_content_provider(
  12211. 10000, "text/plain",
  12212. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12213. if (offset < 100) {
  12214. std::string data(100, 'X');
  12215. sink.write(data.c_str(), data.size());
  12216. return true;
  12217. }
  12218. while (!close_now) {
  12219. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12220. }
  12221. return false;
  12222. });
  12223. });
  12224. auto port = 8094;
  12225. std::thread t([&]() { svr.listen("localhost", port); });
  12226. svr.wait_until_ready();
  12227. SSLClient cli("localhost", port);
  12228. cli.enable_server_certificate_verification(false);
  12229. auto handle = cli.open_stream("GET", "/will-close");
  12230. ASSERT_TRUE(handle.is_valid());
  12231. char buf[256];
  12232. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12233. EXPECT_GT(n, 0);
  12234. // Signal server to close
  12235. close_now = true;
  12236. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12237. // Keep reading
  12238. }
  12239. if (n < 0) {
  12240. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12241. handle.get_read_error() == Error::Read)
  12242. << "Actual error: " << to_string(handle.get_read_error());
  12243. }
  12244. svr.stop();
  12245. t.join();
  12246. }
  12247. #endif
  12248. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  12249. using namespace httplib;
  12250. // Create a test file
  12251. const char *fname = "etag_testfile.txt";
  12252. const char *content = "etag-content";
  12253. {
  12254. std::ofstream ofs(fname);
  12255. ofs << content;
  12256. ASSERT_TRUE(ofs.good());
  12257. }
  12258. Server svr;
  12259. svr.set_mount_point("/static", ".");
  12260. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12261. svr.wait_until_ready();
  12262. Client cli(HOST, PORT);
  12263. // First request: should get 200 with ETag header
  12264. auto res1 = cli.Get("/static/etag_testfile.txt");
  12265. ASSERT_TRUE(res1);
  12266. ASSERT_EQ(200, res1->status);
  12267. ASSERT_TRUE(res1->has_header("ETag"));
  12268. std::string etag = res1->get_header_value("ETag");
  12269. EXPECT_FALSE(etag.empty());
  12270. // Verify ETag format: W/"hex-hex"
  12271. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  12272. EXPECT_EQ('W', etag[0]);
  12273. EXPECT_EQ('/', etag[1]);
  12274. EXPECT_EQ('"', etag[2]);
  12275. EXPECT_EQ('"', etag.back());
  12276. // Exact match: expect 304 Not Modified
  12277. Headers h2 = {{"If-None-Match", etag}};
  12278. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  12279. ASSERT_TRUE(res2);
  12280. EXPECT_EQ(304, res2->status);
  12281. // Wildcard match: expect 304 Not Modified
  12282. Headers h3 = {{"If-None-Match", "*"}};
  12283. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  12284. ASSERT_TRUE(res3);
  12285. EXPECT_EQ(304, res3->status);
  12286. // Non-matching ETag: expect 200
  12287. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  12288. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  12289. ASSERT_TRUE(res4);
  12290. EXPECT_EQ(200, res4->status);
  12291. // Multiple ETags with one matching: expect 304
  12292. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  12293. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  12294. ASSERT_TRUE(res5);
  12295. EXPECT_EQ(304, res5->status);
  12296. svr.stop();
  12297. t.join();
  12298. std::remove(fname);
  12299. }
  12300. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  12301. using namespace httplib;
  12302. Server svr;
  12303. svr.set_mount_point("/static", ".");
  12304. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12305. svr.wait_until_ready();
  12306. Client cli(HOST, PORT);
  12307. // Send If-None-Match: * to a non-existent file
  12308. Headers h = {{"If-None-Match", "*"}};
  12309. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  12310. ASSERT_TRUE(res);
  12311. EXPECT_EQ(404, res->status);
  12312. svr.stop();
  12313. t.join();
  12314. }
  12315. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  12316. using namespace httplib;
  12317. // Create a test file
  12318. const char *fname = "etag_boundary_testfile.txt";
  12319. const char *content = "boundary-test";
  12320. {
  12321. std::ofstream ofs(fname);
  12322. ofs << content;
  12323. ASSERT_TRUE(ofs.good());
  12324. }
  12325. Server svr;
  12326. svr.set_mount_point("/static", ".");
  12327. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12328. svr.wait_until_ready();
  12329. Client cli(HOST, PORT);
  12330. // Get the actual ETag
  12331. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  12332. ASSERT_TRUE(res1);
  12333. ASSERT_EQ(200, res1->status);
  12334. ASSERT_TRUE(res1->has_header("ETag"));
  12335. std::string etag = res1->get_header_value("ETag");
  12336. // Test 1: Very long ETag value (longer than actual ETag)
  12337. // Should NOT match and return 200 (not trigger out-of-bounds read)
  12338. Headers h1 = {{"If-None-Match", "W/"
  12339. "\"very-long-etag-value-that-is-much-longer-"
  12340. "than-the-actual-etag-value\""}};
  12341. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  12342. ASSERT_TRUE(res2);
  12343. EXPECT_EQ(200, res2->status); // Should not match
  12344. // Test 2: Long string followed by wildcard
  12345. // Should match on "*" and return 304 (without out-of-bounds read on the long
  12346. // string)
  12347. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  12348. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  12349. ASSERT_TRUE(res3);
  12350. EXPECT_EQ(304, res3->status); // Should match on "*"
  12351. // Test 3: Wildcard followed by long string
  12352. // Should match on "*" immediately and return 304
  12353. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  12354. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  12355. ASSERT_TRUE(res4);
  12356. EXPECT_EQ(304, res4->status); // Should match on "*"
  12357. // Test 4: Multiple long non-matching values
  12358. // Should NOT match and return 200 (test that all comparisons are safe)
  12359. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  12360. "W/\"second-long-non-matching-value\", "
  12361. "W/\"third-long-non-matching-value\""}};
  12362. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  12363. ASSERT_TRUE(res5);
  12364. EXPECT_EQ(200, res5->status); // Should not match
  12365. // Test 5: Single character that is not "*" (edge case)
  12366. Headers h5 = {{"If-None-Match", "X"}};
  12367. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  12368. ASSERT_TRUE(res6);
  12369. EXPECT_EQ(200, res6->status); // Should not match
  12370. svr.stop();
  12371. t.join();
  12372. std::remove(fname);
  12373. }
  12374. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  12375. using namespace httplib;
  12376. // Create a test file
  12377. const char *fname = "ims_testfile.txt";
  12378. const char *content = "if-modified-since-test";
  12379. {
  12380. std::ofstream ofs(fname);
  12381. ofs << content;
  12382. ASSERT_TRUE(ofs.good());
  12383. }
  12384. Server svr;
  12385. svr.set_mount_point("/static", ".");
  12386. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12387. svr.wait_until_ready();
  12388. Client cli(HOST, PORT);
  12389. // First request: should get 200 with Last-Modified header
  12390. auto res1 = cli.Get("/static/ims_testfile.txt");
  12391. ASSERT_TRUE(res1);
  12392. ASSERT_EQ(200, res1->status);
  12393. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12394. std::string last_modified = res1->get_header_value("Last-Modified");
  12395. EXPECT_FALSE(last_modified.empty());
  12396. // If-Modified-Since with same time: expect 304
  12397. Headers h2 = {{"If-Modified-Since", last_modified}};
  12398. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  12399. ASSERT_TRUE(res2);
  12400. EXPECT_EQ(304, res2->status);
  12401. // If-Modified-Since with future time: expect 304
  12402. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12403. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  12404. ASSERT_TRUE(res3);
  12405. EXPECT_EQ(304, res3->status);
  12406. // If-Modified-Since with past time: expect 200
  12407. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12408. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  12409. ASSERT_TRUE(res4);
  12410. EXPECT_EQ(200, res4->status);
  12411. // If-None-Match takes precedence over If-Modified-Since
  12412. // (send matching ETag with old If-Modified-Since -> should still be 304)
  12413. ASSERT_TRUE(res1->has_header("ETag"));
  12414. std::string etag = res1->get_header_value("ETag");
  12415. Headers h5 = {{"If-None-Match", etag},
  12416. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12417. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  12418. ASSERT_TRUE(res5);
  12419. EXPECT_EQ(304, res5->status);
  12420. svr.stop();
  12421. t.join();
  12422. std::remove(fname);
  12423. }
  12424. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  12425. using namespace httplib;
  12426. Server svr;
  12427. // Endpoint that returns compressible content
  12428. svr.Get("/compressible", [](const Request &, Response &res) {
  12429. // Return a large enough body to trigger compression
  12430. std::string body(1000, 'a');
  12431. res.set_content(body, "text/plain");
  12432. });
  12433. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12434. svr.wait_until_ready();
  12435. Client cli(HOST, PORT);
  12436. // Request with gzip support: should get Vary header when compressed
  12437. cli.set_compress(true);
  12438. auto res1 = cli.Get("/compressible");
  12439. ASSERT_TRUE(res1);
  12440. EXPECT_EQ(200, res1->status);
  12441. // If Content-Encoding is set, Vary should also be set
  12442. if (res1->has_header("Content-Encoding")) {
  12443. EXPECT_TRUE(res1->has_header("Vary"));
  12444. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  12445. }
  12446. // Request without Accept-Encoding header: should not have compression
  12447. Headers h_no_compress;
  12448. auto res2 = cli.Get("/compressible", h_no_compress);
  12449. ASSERT_TRUE(res2);
  12450. EXPECT_EQ(200, res2->status);
  12451. // Verify Vary header is present when compression is applied
  12452. // (the exact behavior depends on server configuration)
  12453. svr.stop();
  12454. t.join();
  12455. }
  12456. TEST(ETagTest, IfRangeWithETag) {
  12457. using namespace httplib;
  12458. // Create a test file with known content
  12459. const char *fname = "if_range_testfile.txt";
  12460. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  12461. {
  12462. std::ofstream ofs(fname);
  12463. ofs << content;
  12464. ASSERT_TRUE(ofs.good());
  12465. }
  12466. Server svr;
  12467. svr.set_mount_point("/static", ".");
  12468. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12469. svr.wait_until_ready();
  12470. Client cli(HOST, PORT);
  12471. // First request: get ETag
  12472. auto res1 = cli.Get("/static/if_range_testfile.txt");
  12473. ASSERT_TRUE(res1);
  12474. ASSERT_EQ(200, res1->status);
  12475. ASSERT_TRUE(res1->has_header("ETag"));
  12476. std::string etag = res1->get_header_value("ETag");
  12477. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  12478. // Since our server generates weak ETags (W/"..."), If-Range with our
  12479. // ETag should NOT result in partial content - it should return full content.
  12480. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  12481. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  12482. ASSERT_TRUE(res2);
  12483. // Weak ETag in If-Range -> full content (200), not partial (206)
  12484. EXPECT_EQ(200, res2->status);
  12485. EXPECT_EQ(content, res2->body);
  12486. EXPECT_FALSE(res2->has_header("Content-Range"));
  12487. // Range request with non-matching If-Range (ETag): should get 200 (full
  12488. // content)
  12489. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  12490. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  12491. ASSERT_TRUE(res3);
  12492. EXPECT_EQ(200, res3->status);
  12493. EXPECT_EQ(content, res3->body);
  12494. EXPECT_FALSE(res3->has_header("Content-Range"));
  12495. // Range request with strong ETag (hypothetical - our server doesn't generate
  12496. // strong ETags, but if client sends a strong ETag that doesn't match, it
  12497. // should return full content)
  12498. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  12499. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  12500. ASSERT_TRUE(res4);
  12501. EXPECT_EQ(200, res4->status);
  12502. EXPECT_EQ(content, res4->body);
  12503. EXPECT_FALSE(res4->has_header("Content-Range"));
  12504. svr.stop();
  12505. t.join();
  12506. std::remove(fname);
  12507. }
  12508. TEST(ETagTest, IfRangeWithDate) {
  12509. using namespace httplib;
  12510. // Create a test file
  12511. const char *fname = "if_range_date_testfile.txt";
  12512. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  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. // First request: get Last-Modified
  12524. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  12525. ASSERT_TRUE(res1);
  12526. ASSERT_EQ(200, res1->status);
  12527. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12528. std::string last_modified = res1->get_header_value("Last-Modified");
  12529. // Range request with matching If-Range (date): should get 206
  12530. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  12531. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  12532. ASSERT_TRUE(res2);
  12533. EXPECT_EQ(206, res2->status);
  12534. EXPECT_EQ("FGHIJ", res2->body);
  12535. // Range request with old If-Range date: should get 200 (full content)
  12536. Headers h3 = {{"Range", "bytes=5-9"},
  12537. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12538. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  12539. ASSERT_TRUE(res3);
  12540. EXPECT_EQ(200, res3->status);
  12541. EXPECT_EQ(content, res3->body);
  12542. // Range request with future If-Range date: should get 206
  12543. Headers h4 = {{"Range", "bytes=0-4"},
  12544. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12545. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  12546. ASSERT_TRUE(res4);
  12547. EXPECT_EQ(206, res4->status);
  12548. EXPECT_EQ("ABCDE", res4->body);
  12549. svr.stop();
  12550. t.join();
  12551. std::remove(fname);
  12552. }
  12553. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  12554. using namespace httplib;
  12555. const char *fname = "etag_malformed.txt";
  12556. const char *content = "malformed-etag";
  12557. {
  12558. std::ofstream ofs(fname);
  12559. ofs << content;
  12560. ASSERT_TRUE(ofs.good());
  12561. }
  12562. Server svr;
  12563. svr.set_mount_point("/static", ".");
  12564. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12565. svr.wait_until_ready();
  12566. Client cli(HOST, PORT);
  12567. // baseline: should get 200 and an ETag
  12568. auto res1 = cli.Get("/static/etag_malformed.txt");
  12569. ASSERT_TRUE(res1);
  12570. ASSERT_EQ(200, res1->status);
  12571. ASSERT_TRUE(res1->has_header("ETag"));
  12572. // Malformed ETag value (missing quotes) should be treated as non-matching
  12573. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  12574. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  12575. ASSERT_TRUE(res_bad);
  12576. EXPECT_EQ(200, res_bad->status);
  12577. // Whitespace-only header value should be considered invalid / non-matching
  12578. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  12579. "Host: localhost\r\n"
  12580. "If-None-Match: \r\n"
  12581. "Connection: close\r\n"
  12582. "\r\n";
  12583. std::string out;
  12584. ASSERT_TRUE(send_request(5, raw_req, &out));
  12585. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12586. svr.stop();
  12587. t.join();
  12588. std::remove(fname);
  12589. }
  12590. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  12591. using namespace httplib;
  12592. const char *fname = "ims_invalid_format.txt";
  12593. const char *content = "ims-bad-format";
  12594. {
  12595. std::ofstream ofs(fname);
  12596. ofs << content;
  12597. ASSERT_TRUE(ofs.good());
  12598. }
  12599. Server svr;
  12600. svr.set_mount_point("/static", ".");
  12601. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12602. svr.wait_until_ready();
  12603. Client cli(HOST, PORT);
  12604. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  12605. ASSERT_TRUE(res1);
  12606. ASSERT_EQ(200, res1->status);
  12607. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12608. // If-Modified-Since with invalid format should not result in 304
  12609. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  12610. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  12611. ASSERT_TRUE(res_bad);
  12612. EXPECT_EQ(200, res_bad->status);
  12613. // If-Range with invalid date format should be treated as mismatch -> full
  12614. // content (200)
  12615. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  12616. {"If-Range", "invalid-date"}};
  12617. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  12618. ASSERT_TRUE(res_ifrange);
  12619. EXPECT_EQ(200, res_ifrange->status);
  12620. svr.stop();
  12621. t.join();
  12622. std::remove(fname);
  12623. }
  12624. TEST(ETagTest, IfRangeWithMalformedETag) {
  12625. using namespace httplib;
  12626. const char *fname = "ifrange_malformed.txt";
  12627. const std::string content = "0123456789";
  12628. {
  12629. std::ofstream ofs(fname);
  12630. ofs << content;
  12631. ASSERT_TRUE(ofs.good());
  12632. }
  12633. Server svr;
  12634. svr.set_mount_point("/static", ".");
  12635. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12636. svr.wait_until_ready();
  12637. Client cli(HOST, PORT);
  12638. // First request: get ETag
  12639. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  12640. ASSERT_TRUE(res1);
  12641. ASSERT_EQ(200, res1->status);
  12642. ASSERT_TRUE(res1->has_header("ETag"));
  12643. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  12644. // full content (200)
  12645. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  12646. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  12647. ASSERT_TRUE(res2);
  12648. EXPECT_EQ(200, res2->status);
  12649. EXPECT_EQ(content, res2->body);
  12650. svr.stop();
  12651. t.join();
  12652. std::remove(fname);
  12653. }
  12654. TEST(ETagTest, ExtremeLargeDateValues) {
  12655. using namespace httplib;
  12656. const char *fname = "ims_extreme_date.txt";
  12657. const char *content = "ims-extreme-date";
  12658. {
  12659. std::ofstream ofs(fname);
  12660. ofs << content;
  12661. ASSERT_TRUE(ofs.good());
  12662. }
  12663. Server svr;
  12664. svr.set_mount_point("/static", ".");
  12665. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12666. svr.wait_until_ready();
  12667. Client cli(HOST, PORT);
  12668. auto res1 = cli.Get(std::string("/static/") + fname);
  12669. ASSERT_TRUE(res1);
  12670. ASSERT_EQ(200, res1->status);
  12671. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12672. // Extremely large year that may overflow date parsing routines.
  12673. Headers h_large_date = {
  12674. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12675. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  12676. ASSERT_TRUE(res_bad);
  12677. // Expect server to treat this as invalid/mismatch and return full content
  12678. EXPECT_EQ(200, res_bad->status);
  12679. // If-Range with extremely large date should be treated as mismatch -> full
  12680. // content (200)
  12681. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  12682. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12683. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  12684. ASSERT_TRUE(res_ifrange);
  12685. EXPECT_EQ(200, res_ifrange->status);
  12686. svr.stop();
  12687. t.join();
  12688. std::remove(fname);
  12689. }
  12690. TEST(ETagTest, NegativeFileModificationTime) {
  12691. using namespace httplib;
  12692. const char *fname = "ims_negative_mtime.txt";
  12693. const std::string content = "negative-mtime";
  12694. {
  12695. std::ofstream ofs(fname);
  12696. ofs << content;
  12697. ASSERT_TRUE(ofs.good());
  12698. }
  12699. // Try to set file mtime to a negative value. This may fail on some
  12700. // platforms/filesystems; if it fails, the test will still verify server
  12701. // behaves safely by performing a regular conditional request.
  12702. #if defined(__APPLE__) || defined(__linux__)
  12703. bool set_negative = false;
  12704. do {
  12705. struct timeval times[2];
  12706. // access time: now
  12707. times[0].tv_sec = time(nullptr);
  12708. times[0].tv_usec = 0;
  12709. // modification time: negative (e.g., -1)
  12710. times[1].tv_sec = -1;
  12711. times[1].tv_usec = 0;
  12712. if (utimes(fname, times) == 0) { set_negative = true; }
  12713. } while (0);
  12714. #else
  12715. bool set_negative = false;
  12716. #endif
  12717. Server svr;
  12718. svr.set_mount_point("/static", ".");
  12719. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12720. svr.wait_until_ready();
  12721. Client cli(HOST, PORT);
  12722. auto res1 = cli.Get(std::string("/static/") + fname);
  12723. ASSERT_TRUE(res1);
  12724. ASSERT_EQ(200, res1->status);
  12725. bool has_last_modified = res1->has_header("Last-Modified");
  12726. std::string last_modified;
  12727. if (has_last_modified) {
  12728. last_modified = res1->get_header_value("Last-Modified");
  12729. }
  12730. if (set_negative) {
  12731. // If we successfully set a negative mtime, ensure server returns a
  12732. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  12733. // with an old date and ensure server handles it without crash.
  12734. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  12735. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  12736. ASSERT_TRUE(res2);
  12737. // Behavior may vary; at minimum ensure server responds (200 or 304).
  12738. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  12739. } else {
  12740. // Could not set negative mtime on this platform; fall back to verifying
  12741. // that normal invalid/malformed dates are treated safely (non-304).
  12742. Headers h_bad_date = {
  12743. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12744. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  12745. ASSERT_TRUE(res_bad);
  12746. EXPECT_EQ(200, res_bad->status);
  12747. }
  12748. svr.stop();
  12749. t.join();
  12750. std::remove(fname);
  12751. }
  12752. //==============================================================================
  12753. // SSE Parsing Tests
  12754. //==============================================================================
  12755. class SSEParsingTest : public ::testing::Test {
  12756. protected:
  12757. // Test helper that mimics SSE parsing behavior
  12758. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  12759. int &retry_ms) {
  12760. // Blank line signals end of event
  12761. if (line.empty() || line == "\r") { return true; }
  12762. // Lines starting with ':' are comments (ignored)
  12763. if (!line.empty() && line[0] == ':') { return false; }
  12764. // Find the colon separator
  12765. auto colon_pos = line.find(':');
  12766. if (colon_pos == std::string::npos) {
  12767. // Line with no colon is treated as field name with empty value
  12768. return false;
  12769. }
  12770. std::string field = line.substr(0, colon_pos);
  12771. std::string value;
  12772. // Value starts after colon, skip optional single space
  12773. if (colon_pos + 1 < line.size()) {
  12774. size_t value_start = colon_pos + 1;
  12775. if (line[value_start] == ' ') { value_start++; }
  12776. value = line.substr(value_start);
  12777. // Remove trailing \r if present
  12778. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  12779. }
  12780. // Handle known fields
  12781. if (field == "event") {
  12782. msg.event = value;
  12783. } else if (field == "data") {
  12784. // Multiple data lines are concatenated with newlines
  12785. if (!msg.data.empty()) { msg.data += "\n"; }
  12786. msg.data += value;
  12787. } else if (field == "id") {
  12788. // Empty id is valid (clears the last event ID)
  12789. msg.id = value;
  12790. } else if (field == "retry") {
  12791. // Parse retry interval in milliseconds
  12792. {
  12793. int v = 0;
  12794. auto res =
  12795. detail::from_chars(value.data(), value.data() + value.size(), v);
  12796. if (res.ec == std::errc{}) { retry_ms = v; }
  12797. }
  12798. }
  12799. // Unknown fields are ignored per SSE spec
  12800. return false;
  12801. }
  12802. };
  12803. // Test: Single-line data
  12804. TEST_F(SSEParsingTest, SingleLineData) {
  12805. sse::SSEMessage msg;
  12806. int retry_ms = 3000;
  12807. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  12808. EXPECT_EQ(msg.data, "hello");
  12809. EXPECT_EQ(msg.event, "message");
  12810. // Blank line ends event
  12811. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12812. }
  12813. // Test: Multi-line data
  12814. TEST_F(SSEParsingTest, MultiLineData) {
  12815. sse::SSEMessage msg;
  12816. int retry_ms = 3000;
  12817. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  12818. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  12819. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  12820. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  12821. }
  12822. // Test: Custom event types
  12823. TEST_F(SSEParsingTest, CustomEventType) {
  12824. sse::SSEMessage msg;
  12825. int retry_ms = 3000;
  12826. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  12827. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  12828. EXPECT_EQ(msg.event, "update");
  12829. EXPECT_EQ(msg.data, "payload");
  12830. }
  12831. // Test: Event ID handling
  12832. TEST_F(SSEParsingTest, EventIdHandling) {
  12833. sse::SSEMessage msg;
  12834. int retry_ms = 3000;
  12835. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  12836. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  12837. EXPECT_EQ(msg.id, "12345");
  12838. }
  12839. // Test: Empty event ID (clears last event ID)
  12840. TEST_F(SSEParsingTest, EmptyEventId) {
  12841. sse::SSEMessage msg;
  12842. msg.id = "previous";
  12843. int retry_ms = 3000;
  12844. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  12845. EXPECT_EQ(msg.id, "");
  12846. }
  12847. // Test: Retry field parsing
  12848. TEST_F(SSEParsingTest, RetryFieldParsing) {
  12849. sse::SSEMessage msg;
  12850. int retry_ms = 3000;
  12851. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  12852. EXPECT_EQ(retry_ms, 5000);
  12853. }
  12854. // Test: Invalid retry value
  12855. TEST_F(SSEParsingTest, InvalidRetryValue) {
  12856. sse::SSEMessage msg;
  12857. int retry_ms = 3000;
  12858. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  12859. EXPECT_EQ(retry_ms, 3000); // Unchanged
  12860. }
  12861. // Test: Comments (lines starting with :)
  12862. TEST_F(SSEParsingTest, CommentsIgnored) {
  12863. sse::SSEMessage msg;
  12864. int retry_ms = 3000;
  12865. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  12866. EXPECT_EQ(msg.data, "");
  12867. EXPECT_EQ(msg.event, "message");
  12868. }
  12869. // Test: Colon in value
  12870. TEST_F(SSEParsingTest, ColonInValue) {
  12871. sse::SSEMessage msg;
  12872. int retry_ms = 3000;
  12873. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  12874. EXPECT_EQ(msg.data, "hello:world:test");
  12875. }
  12876. // Test: Line with no colon (field name only)
  12877. TEST_F(SSEParsingTest, FieldNameOnly) {
  12878. sse::SSEMessage msg;
  12879. int retry_ms = 3000;
  12880. // According to SSE spec, this is treated as field name with empty value
  12881. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  12882. // Since we don't recognize "data" without colon, data should be empty
  12883. EXPECT_EQ(msg.data, "");
  12884. }
  12885. // Test: Trailing \r handling
  12886. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  12887. sse::SSEMessage msg;
  12888. int retry_ms = 3000;
  12889. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  12890. EXPECT_EQ(msg.data, "hello");
  12891. }
  12892. // Test: Unknown fields ignored
  12893. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  12894. sse::SSEMessage msg;
  12895. int retry_ms = 3000;
  12896. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  12897. EXPECT_EQ(msg.data, "");
  12898. EXPECT_EQ(msg.event, "message");
  12899. }
  12900. // Test: Space after colon is optional
  12901. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  12902. sse::SSEMessage msg1, msg2;
  12903. int retry_ms = 3000;
  12904. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  12905. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  12906. EXPECT_EQ(msg1.data, "hello");
  12907. EXPECT_EQ(msg2.data, "hello");
  12908. }
  12909. // Test: SSEMessage clear
  12910. TEST_F(SSEParsingTest, MessageClear) {
  12911. sse::SSEMessage msg;
  12912. msg.event = "custom";
  12913. msg.data = "some data";
  12914. msg.id = "123";
  12915. msg.clear();
  12916. EXPECT_EQ(msg.event, "message");
  12917. EXPECT_EQ(msg.data, "");
  12918. EXPECT_EQ(msg.id, "");
  12919. }
  12920. // Test: Complete event parsing
  12921. TEST_F(SSEParsingTest, CompleteEventParsing) {
  12922. sse::SSEMessage msg;
  12923. int retry_ms = 3000;
  12924. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  12925. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  12926. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  12927. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  12928. // Blank line ends event
  12929. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12930. EXPECT_EQ(msg.event, "notification");
  12931. EXPECT_EQ(msg.id, "evt-42");
  12932. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  12933. EXPECT_EQ(retry_ms, 1000);
  12934. }
  12935. //==============================================================================
  12936. // Integration Tests with Server
  12937. //==============================================================================
  12938. class SSEIntegrationTest : public ::testing::Test {
  12939. protected:
  12940. void SetUp() override {
  12941. stop_server_.store(false);
  12942. events_.clear();
  12943. server_ = httplib::detail::make_unique<Server>();
  12944. setup_server();
  12945. start_server();
  12946. }
  12947. void TearDown() override {
  12948. stop_server_.store(true);
  12949. event_cv_.notify_all();
  12950. server_->stop();
  12951. if (server_thread_.joinable()) { server_thread_.join(); }
  12952. }
  12953. void setup_server() {
  12954. // Simple SSE endpoint
  12955. server_->Get("/events", [this](const Request &req, Response &res) {
  12956. auto last_id = req.get_header_value("Last-Event-ID");
  12957. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  12958. res.set_chunked_content_provider(
  12959. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  12960. std::unique_lock<std::mutex> lock(event_mutex_);
  12961. if (event_cv_.wait_for(
  12962. lock, std::chrono::milliseconds(200), [this] {
  12963. return !events_.empty() || stop_server_.load();
  12964. })) {
  12965. if (stop_server_.load()) { return false; }
  12966. if (!events_.empty()) {
  12967. std::string event = events_.front();
  12968. events_.erase(events_.begin());
  12969. sink.write(event.data(), event.size());
  12970. return true;
  12971. }
  12972. }
  12973. return !stop_server_.load();
  12974. });
  12975. });
  12976. // Endpoint that returns error
  12977. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  12978. res.status = 500;
  12979. res.set_content("Internal Server Error", "text/plain");
  12980. });
  12981. // Endpoint for custom event types
  12982. server_->Get("/custom-events", [](const Request &, Response &res) {
  12983. res.set_chunked_content_provider(
  12984. "text/event-stream", [](size_t offset, DataSink &sink) {
  12985. if (offset == 0) {
  12986. std::string event = "event: update\ndata: updated\n\n"
  12987. "event: delete\ndata: deleted\n\n";
  12988. sink.write(event.data(), event.size());
  12989. }
  12990. return false; // End stream after sending
  12991. });
  12992. });
  12993. }
  12994. void start_server() {
  12995. port_ = server_->bind_to_any_port(HOST);
  12996. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  12997. // Wait for server to start
  12998. while (!server_->is_running()) {
  12999. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13000. }
  13001. }
  13002. int get_port() const { return port_; }
  13003. void send_event(const std::string &event) {
  13004. std::lock_guard<std::mutex> lock(event_mutex_);
  13005. events_.push_back(event);
  13006. event_cv_.notify_all();
  13007. }
  13008. std::unique_ptr<Server> server_;
  13009. std::thread server_thread_;
  13010. std::mutex event_mutex_;
  13011. std::condition_variable event_cv_;
  13012. std::vector<std::string> events_;
  13013. std::atomic<bool> stop_server_{false};
  13014. std::string last_received_event_id_;
  13015. int port_ = 0;
  13016. };
  13017. // Test: Successful connection and on_open callback
  13018. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  13019. // Add a simple endpoint that sends one event and closes
  13020. server_->Get("/simple-event", [](const Request &, Response &res) {
  13021. res.set_chunked_content_provider(
  13022. "text/event-stream", [](size_t offset, DataSink &sink) {
  13023. if (offset == 0) {
  13024. std::string event = "data: hello\n\n";
  13025. sink.write(event.data(), event.size());
  13026. }
  13027. return false; // Close stream after sending
  13028. });
  13029. });
  13030. Client client("localhost", get_port());
  13031. sse::SSEClient sse(client, "/simple-event");
  13032. std::atomic<bool> open_called{false};
  13033. std::atomic<bool> message_received{false};
  13034. sse.on_open([&open_called]() { open_called.store(true); });
  13035. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  13036. if (msg.data == "hello") { message_received.store(true); }
  13037. });
  13038. sse.set_reconnect_interval(100);
  13039. sse.set_max_reconnect_attempts(1);
  13040. // Start async
  13041. sse.start_async();
  13042. // Wait for message to be processed
  13043. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13044. sse.stop();
  13045. EXPECT_TRUE(open_called.load());
  13046. EXPECT_TRUE(message_received.load());
  13047. }
  13048. // Test: on_message callback
  13049. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  13050. // Endpoint that sends multiple events then closes
  13051. server_->Get("/multi-event", [](const Request &, Response &res) {
  13052. res.set_chunked_content_provider(
  13053. "text/event-stream", [](size_t offset, DataSink &sink) {
  13054. if (offset == 0) {
  13055. std::string events = "data: message1\n\ndata: message2\n\n";
  13056. sink.write(events.data(), events.size());
  13057. }
  13058. return false;
  13059. });
  13060. });
  13061. Client client("localhost", get_port());
  13062. sse::SSEClient sse(client, "/multi-event");
  13063. std::vector<std::string> received_messages;
  13064. std::mutex messages_mutex;
  13065. sse.on_message([&](const sse::SSEMessage &msg) {
  13066. std::lock_guard<std::mutex> lock(messages_mutex);
  13067. received_messages.push_back(msg.data);
  13068. });
  13069. sse.set_reconnect_interval(100);
  13070. sse.set_max_reconnect_attempts(1);
  13071. sse.start_async();
  13072. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13073. sse.stop();
  13074. std::lock_guard<std::mutex> lock(messages_mutex);
  13075. EXPECT_GE(received_messages.size(), 2u);
  13076. if (received_messages.size() >= 2) {
  13077. EXPECT_EQ(received_messages[0], "message1");
  13078. EXPECT_EQ(received_messages[1], "message2");
  13079. }
  13080. }
  13081. // Test: on_event for specific types
  13082. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  13083. Client client("localhost", get_port());
  13084. sse::SSEClient sse(client, "/custom-events");
  13085. std::atomic<bool> update_received{false};
  13086. std::atomic<bool> delete_received{false};
  13087. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  13088. if (msg.data == "updated") { update_received.store(true); }
  13089. });
  13090. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  13091. if (msg.data == "deleted") { delete_received.store(true); }
  13092. });
  13093. sse.set_max_reconnect_attempts(1);
  13094. sse.start_async();
  13095. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  13096. sse.stop();
  13097. EXPECT_TRUE(update_received.load());
  13098. EXPECT_TRUE(delete_received.load());
  13099. }
  13100. // Test: on_error callback on connection failure
  13101. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  13102. // Connect to a non-existent port
  13103. Client client("localhost", 59999);
  13104. sse::SSEClient sse(client, "/events");
  13105. std::atomic<bool> error_called{false};
  13106. Error received_error = Error::Success;
  13107. sse.on_error([&](Error err) {
  13108. error_called.store(true);
  13109. received_error = err;
  13110. });
  13111. sse.set_reconnect_interval(50);
  13112. sse.set_max_reconnect_attempts(1);
  13113. sse.start_async();
  13114. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13115. sse.stop();
  13116. EXPECT_TRUE(error_called.load());
  13117. EXPECT_NE(received_error, Error::Success);
  13118. }
  13119. // Test: Last-Event-ID header sent on reconnect
  13120. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  13121. // Endpoint that sends event with ID
  13122. server_->Get("/event-with-id", [](const Request &, Response &res) {
  13123. res.set_chunked_content_provider(
  13124. "text/event-stream", [](size_t offset, DataSink &sink) {
  13125. if (offset == 0) {
  13126. std::string event = "id: evt-123\ndata: test\n\n";
  13127. sink.write(event.data(), event.size());
  13128. }
  13129. return false;
  13130. });
  13131. });
  13132. Client client("localhost", get_port());
  13133. sse::SSEClient sse(client, "/event-with-id");
  13134. std::atomic<bool> id_received{false};
  13135. sse.on_message([&](const sse::SSEMessage &msg) {
  13136. if (!msg.id.empty()) { id_received.store(true); }
  13137. });
  13138. sse.set_reconnect_interval(100);
  13139. sse.set_max_reconnect_attempts(1);
  13140. sse.start_async();
  13141. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13142. sse.stop();
  13143. EXPECT_TRUE(id_received.load());
  13144. EXPECT_EQ(sse.last_event_id(), "evt-123");
  13145. }
  13146. // Test: Manual stop
  13147. TEST_F(SSEIntegrationTest, ManualStop) {
  13148. // Endpoint that sends one event and stays open briefly
  13149. std::atomic<bool> handler_running{true};
  13150. server_->Get("/stay-open", [&handler_running](const Request &,
  13151. Response &res) {
  13152. res.set_chunked_content_provider(
  13153. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  13154. if (offset == 0) {
  13155. std::string event = "data: connected\n\n";
  13156. sink.write(event.data(), event.size());
  13157. }
  13158. // Keep connection open while handler_running is true
  13159. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  13160. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13161. }
  13162. return false;
  13163. });
  13164. });
  13165. Client client("localhost", get_port());
  13166. sse::SSEClient sse(client, "/stay-open");
  13167. std::atomic<bool> connected{false};
  13168. sse.on_open([&connected]() { connected.store(true); });
  13169. sse.set_reconnect_interval(100);
  13170. sse.set_max_reconnect_attempts(1);
  13171. sse.start_async();
  13172. // Wait for connection to establish
  13173. for (int i = 0; i < 20 && !connected.load(); ++i) {
  13174. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13175. }
  13176. EXPECT_TRUE(connected.load());
  13177. EXPECT_TRUE(sse.is_connected());
  13178. // Signal handler to stop
  13179. handler_running.store(false);
  13180. // Stop SSE client
  13181. sse.stop();
  13182. EXPECT_FALSE(sse.is_connected());
  13183. }
  13184. // Test: SSEClient with custom headers
  13185. TEST_F(SSEIntegrationTest, CustomHeaders) {
  13186. // Setup a server endpoint that checks for custom header
  13187. std::atomic<bool> header_received{false};
  13188. server_->Get("/header-check", [&](const Request &req, Response &res) {
  13189. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  13190. header_received.store(true);
  13191. }
  13192. res.set_chunked_content_provider("text/event-stream",
  13193. [](size_t, DataSink &) { return false; });
  13194. });
  13195. Client client("localhost", get_port());
  13196. Headers headers = {{"X-Custom-Header", "custom-value"}};
  13197. sse::SSEClient sse(client, "/header-check", headers);
  13198. sse.set_max_reconnect_attempts(1);
  13199. sse.start_async();
  13200. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13201. sse.stop();
  13202. EXPECT_TRUE(header_received.load());
  13203. }
  13204. // Test: Reconnect interval configuration
  13205. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  13206. Client client("localhost", get_port());
  13207. sse::SSEClient sse(client, "/events");
  13208. auto &result = sse.set_reconnect_interval(500);
  13209. // Builder pattern should return reference to self
  13210. EXPECT_EQ(&result, &sse);
  13211. }
  13212. // Test: Max reconnect attempts
  13213. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  13214. // Connect to non-existent port to force reconnects
  13215. Client client("localhost", 59998);
  13216. sse::SSEClient sse(client, "/events");
  13217. std::atomic<int> error_count{0};
  13218. sse.on_error([&](Error) { error_count.fetch_add(1); });
  13219. sse.set_reconnect_interval(50);
  13220. sse.set_max_reconnect_attempts(2);
  13221. auto start = std::chrono::steady_clock::now();
  13222. sse.start(); // Blocking call
  13223. auto end = std::chrono::steady_clock::now();
  13224. // Should have stopped after 2 failed attempts
  13225. EXPECT_GE(error_count.load(), 2);
  13226. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  13227. auto duration =
  13228. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  13229. #ifdef _WIN32
  13230. // Windows is much slower for socket connection failures
  13231. EXPECT_LT(duration.count(), 7000);
  13232. #else
  13233. EXPECT_LT(duration.count(), 1000);
  13234. #endif
  13235. }
  13236. // Test: Multi-line data in integration
  13237. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  13238. // Endpoint with multi-line data
  13239. server_->Get("/multiline-data", [](const Request &, Response &res) {
  13240. res.set_chunked_content_provider(
  13241. "text/event-stream", [](size_t offset, DataSink &sink) {
  13242. if (offset == 0) {
  13243. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  13244. sink.write(event.data(), event.size());
  13245. }
  13246. return false;
  13247. });
  13248. });
  13249. Client client("localhost", get_port());
  13250. sse::SSEClient sse(client, "/multiline-data");
  13251. std::string received_data;
  13252. std::mutex data_mutex;
  13253. sse.on_message([&](const sse::SSEMessage &msg) {
  13254. std::lock_guard<std::mutex> lock(data_mutex);
  13255. received_data = msg.data;
  13256. });
  13257. sse.set_reconnect_interval(100);
  13258. sse.set_max_reconnect_attempts(1);
  13259. sse.start_async();
  13260. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13261. sse.stop();
  13262. std::lock_guard<std::mutex> lock(data_mutex);
  13263. EXPECT_EQ(received_data, "line1\nline2\nline3");
  13264. }
  13265. // Test: Auto-reconnect after server disconnection
  13266. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  13267. std::atomic<int> connection_count{0};
  13268. std::atomic<int> message_count{0};
  13269. // Endpoint that sends one event and closes, forcing reconnect
  13270. server_->Get("/reconnect-test",
  13271. [&connection_count](const Request &, Response &res) {
  13272. connection_count.fetch_add(1);
  13273. res.set_chunked_content_provider(
  13274. "text/event-stream", [](size_t offset, DataSink &sink) {
  13275. if (offset == 0) {
  13276. std::string event = "data: hello\n\n";
  13277. sink.write(event.data(), event.size());
  13278. }
  13279. return false; // Close connection after sending
  13280. });
  13281. });
  13282. Client client("localhost", get_port());
  13283. sse::SSEClient sse(client, "/reconnect-test");
  13284. sse.on_message([&message_count](const sse::SSEMessage &) {
  13285. message_count.fetch_add(1);
  13286. });
  13287. sse.set_reconnect_interval(100);
  13288. sse.set_max_reconnect_attempts(3);
  13289. sse.start_async();
  13290. // Wait long enough for multiple reconnects
  13291. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13292. sse.stop();
  13293. // Should have connected multiple times (initial + reconnects)
  13294. EXPECT_GE(connection_count.load(), 2);
  13295. // Should have received messages from multiple connections
  13296. EXPECT_GE(message_count.load(), 2);
  13297. }
  13298. // Test: Last-Event-ID sent on reconnect
  13299. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  13300. std::atomic<int> connection_count{0};
  13301. std::vector<std::string> received_last_event_ids;
  13302. std::mutex id_mutex;
  13303. // Endpoint that checks Last-Event-ID header and sends event with ID
  13304. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  13305. int conn = connection_count.fetch_add(1);
  13306. // Capture the Last-Event-ID header from each connection
  13307. {
  13308. std::lock_guard<std::mutex> lock(id_mutex);
  13309. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  13310. }
  13311. res.set_chunked_content_provider(
  13312. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  13313. if (offset == 0) {
  13314. std::string event =
  13315. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  13316. sink.write(event.data(), event.size());
  13317. }
  13318. return false;
  13319. });
  13320. });
  13321. Client client("localhost", get_port());
  13322. sse::SSEClient sse(client, "/reconnect-with-id");
  13323. sse.set_reconnect_interval(100);
  13324. sse.set_max_reconnect_attempts(3);
  13325. sse.start_async();
  13326. // Wait for at least 2 connections
  13327. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13328. sse.stop();
  13329. // Verify behavior
  13330. std::lock_guard<std::mutex> lock(id_mutex);
  13331. EXPECT_GE(received_last_event_ids.size(), 2u);
  13332. // First connection should have no Last-Event-ID
  13333. if (!received_last_event_ids.empty()) {
  13334. EXPECT_EQ(received_last_event_ids[0], "");
  13335. }
  13336. // Second connection should have Last-Event-ID from first connection
  13337. if (received_last_event_ids.size() >= 2) {
  13338. EXPECT_EQ(received_last_event_ids[1], "event-0");
  13339. }
  13340. }
  13341. // Test: set_headers updates headers used on reconnect
  13342. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  13343. std::vector<std::string> received_tokens;
  13344. std::mutex token_mutex;
  13345. // Endpoint that captures Authorization header
  13346. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  13347. {
  13348. std::lock_guard<std::mutex> lock(token_mutex);
  13349. received_tokens.push_back(req.get_header_value("Authorization"));
  13350. }
  13351. res.set_chunked_content_provider(
  13352. "text/event-stream", [](size_t offset, DataSink &sink) {
  13353. if (offset == 0) {
  13354. std::string event = "data: hello\n\n";
  13355. sink.write(event.data(), event.size());
  13356. }
  13357. return false; // Close connection to trigger reconnect
  13358. });
  13359. });
  13360. Client client("localhost", get_port());
  13361. Headers headers = {{"Authorization", "Bearer old-token"}};
  13362. sse::SSEClient sse(client, "/auth-check", headers);
  13363. // Update headers on each successful connection
  13364. sse.on_open(
  13365. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  13366. sse.set_reconnect_interval(100);
  13367. sse.set_max_reconnect_attempts(3);
  13368. sse.start_async();
  13369. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13370. sse.stop();
  13371. std::lock_guard<std::mutex> lock(token_mutex);
  13372. ASSERT_GE(received_tokens.size(), 2u);
  13373. // First connection uses original header
  13374. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  13375. // Second connection uses updated header from set_headers
  13376. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  13377. }
  13378. // Test: 401 allows reconnection (so on_error can refresh headers)
  13379. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  13380. std::atomic<int> connection_count{0};
  13381. // Endpoint: returns 401 on first attempt, 200 on second
  13382. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  13383. int conn = connection_count.fetch_add(1);
  13384. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  13385. res.status = StatusCode::Unauthorized_401;
  13386. res.set_content("Unauthorized", "text/plain");
  13387. return;
  13388. }
  13389. res.set_chunked_content_provider(
  13390. "text/event-stream", [](size_t offset, DataSink &sink) {
  13391. if (offset == 0) {
  13392. std::string event = "data: authenticated\n\n";
  13393. sink.write(event.data(), event.size());
  13394. }
  13395. return false;
  13396. });
  13397. });
  13398. Client client("localhost", get_port());
  13399. Headers headers = {{"Authorization", "Bearer expired"}};
  13400. sse::SSEClient sse(client, "/auth-retry", headers);
  13401. std::atomic<bool> message_received{false};
  13402. // Refresh token on error
  13403. sse.on_error(
  13404. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  13405. sse.on_message([&](const sse::SSEMessage &msg) {
  13406. if (msg.data == "authenticated") { message_received.store(true); }
  13407. });
  13408. sse.set_reconnect_interval(100);
  13409. sse.set_max_reconnect_attempts(3);
  13410. sse.start_async();
  13411. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13412. sse.stop();
  13413. // Should have reconnected after 401 and succeeded with new token
  13414. EXPECT_GE(connection_count.load(), 2);
  13415. EXPECT_TRUE(message_received.load());
  13416. }
  13417. TEST(Issue2318Test, EmptyHostString) {
  13418. {
  13419. httplib::Client cli_empty("", PORT);
  13420. auto res = cli_empty.Get("/");
  13421. ASSERT_FALSE(res);
  13422. EXPECT_EQ(httplib::Error::Connection, res.error());
  13423. }
  13424. {
  13425. httplib::Client cli(" ", PORT);
  13426. auto res = cli.Get("/");
  13427. ASSERT_FALSE(res);
  13428. EXPECT_EQ(httplib::Error::Connection, res.error());
  13429. }
  13430. }
  13431. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13432. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  13433. Server svr;
  13434. // Set a small payload limit (1KB)
  13435. svr.set_payload_max_length(1024);
  13436. svr.Post("/test", [&](const Request &req, Response &res) {
  13437. res.set_content("Body size: " + std::to_string(req.body.size()),
  13438. "text/plain");
  13439. });
  13440. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13441. auto se = detail::scope_exit([&] {
  13442. svr.stop();
  13443. listen_thread.join();
  13444. });
  13445. svr.wait_until_ready();
  13446. // Create data that compresses well but exceeds limit when decompressed
  13447. // 8KB of repeated null bytes compresses to a very small size
  13448. std::string original_data(8 * 1024, '\0');
  13449. // Compress the data using gzip
  13450. std::string compressed_data;
  13451. detail::gzip_compressor compressor;
  13452. compressor.compress(original_data.data(), original_data.size(), true,
  13453. [&](const char *data, size_t size) {
  13454. compressed_data.append(data, size);
  13455. return true;
  13456. });
  13457. // Verify compression worked (compressed should be much smaller)
  13458. ASSERT_LT(compressed_data.size(), original_data.size());
  13459. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  13460. // Send compressed data with Content-Encoding: gzip
  13461. Client cli(HOST, PORT);
  13462. Headers headers = {{"Content-Encoding", "gzip"}};
  13463. auto res =
  13464. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  13465. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  13466. ASSERT_TRUE(res);
  13467. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13468. }
  13469. #endif
  13470. // ============================================================================
  13471. // OpenSSL-Specific Tests
  13472. // ============================================================================
  13473. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13474. X509 *readCertificate(const std::string &strFileName) {
  13475. std::ifstream inStream(strFileName);
  13476. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  13477. std::istreambuf_iterator<char>());
  13478. if (strCertPEM.empty()) return (nullptr);
  13479. BIO *pbCert = BIO_new(BIO_s_mem());
  13480. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  13481. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  13482. BIO_free(pbCert);
  13483. return (pCert);
  13484. }
  13485. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  13486. std::ifstream inStream(strFileName);
  13487. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  13488. std::istreambuf_iterator<char>());
  13489. if (strPrivateKeyPEM.empty()) return (nullptr);
  13490. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  13491. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  13492. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  13493. BIO_free(pbPrivKey);
  13494. return (pPrivateKey);
  13495. }
  13496. TEST(BindServerTest, UpdateCerts) {
  13497. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13498. int port = svr.bind_to_any_port("0.0.0.0");
  13499. ASSERT_TRUE(svr.is_valid());
  13500. ASSERT_TRUE(port > 0);
  13501. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13502. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13503. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13504. ASSERT_TRUE(cert != nullptr);
  13505. ASSERT_TRUE(ca_cert != nullptr);
  13506. ASSERT_TRUE(key != nullptr);
  13507. X509_STORE *cert_store = X509_STORE_new();
  13508. X509_STORE_add_cert(cert_store, ca_cert);
  13509. // svr.update_certs(cert, key, cert_store); // deprecated
  13510. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13511. CLIENT_CA_CERT_FILE);
  13512. ASSERT_TRUE(svr.is_valid());
  13513. svr.stop();
  13514. X509_STORE_free(cert_store);
  13515. X509_free(cert);
  13516. X509_free(ca_cert);
  13517. EVP_PKEY_free(key);
  13518. }
  13519. // Test that SSLServer(X509*, EVP_PKEY*, X509_STORE*) constructor sets
  13520. // client CA list correctly for TLS handshake
  13521. TEST(SSLClientServerTest, X509ConstructorSetsClientCAList) {
  13522. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13523. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13524. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13525. ASSERT_TRUE(cert != nullptr);
  13526. ASSERT_TRUE(ca_cert != nullptr);
  13527. ASSERT_TRUE(key != nullptr);
  13528. X509_STORE *cert_store = X509_STORE_new();
  13529. X509_STORE_add_cert(cert_store, ca_cert);
  13530. // Use X509-based constructor (deprecated but should still work correctly)
  13531. #pragma GCC diagnostic push
  13532. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  13533. SSLServer svr(cert, key, cert_store);
  13534. #pragma GCC diagnostic pop
  13535. ASSERT_TRUE(svr.is_valid());
  13536. // Verify that client CA list is set in SSL_CTX
  13537. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13538. ASSERT_TRUE(ssl_ctx != nullptr);
  13539. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13540. ASSERT_TRUE(ca_list != nullptr);
  13541. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13542. X509_free(cert);
  13543. X509_free(ca_cert);
  13544. EVP_PKEY_free(key);
  13545. }
  13546. // Test that update_certs() updates client CA list correctly
  13547. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  13548. // Start with file-based constructor
  13549. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13550. ASSERT_TRUE(svr.is_valid());
  13551. // Initially no client CA list should be set
  13552. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13553. ASSERT_TRUE(ssl_ctx != nullptr);
  13554. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  13555. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  13556. EXPECT_EQ(0, count_before);
  13557. // Now update with client CA (PEM string)
  13558. std::string cert_pem, key_pem, ca_pem;
  13559. read_file(SERVER_CERT_FILE, cert_pem);
  13560. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13561. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13562. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  13563. ASSERT_TRUE(svr.is_valid());
  13564. // Now client CA list should be set
  13565. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  13566. ASSERT_TRUE(ca_list_after != nullptr);
  13567. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  13568. }
  13569. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  13570. // Test that the file-path SSLServer constructor properly sets the client CA
  13571. // list that is sent to clients during the TLS handshake (CertificateRequest)
  13572. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13573. ASSERT_TRUE(svr.is_valid());
  13574. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13575. ASSERT_TRUE(ssl_ctx != nullptr);
  13576. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13577. ASSERT_TRUE(ca_list != nullptr);
  13578. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13579. }
  13580. #endif
  13581. // ============================================================================
  13582. // MbedTLS-Specific Tests
  13583. // ============================================================================
  13584. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  13585. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  13586. using namespace httplib::tls;
  13587. // Track if callback was invoked
  13588. bool callback_invoked = false;
  13589. // The callback receives void* ctx which is actually MbedTlsContext*
  13590. // We can access the mbedtls_ssl_config via the context
  13591. auto setup_callback = [&callback_invoked](void *ctx) {
  13592. callback_invoked = true;
  13593. // Cast to MbedTlsContext* to access the ssl config
  13594. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  13595. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  13596. // Use static variables to hold certificate data (simplified for test)
  13597. static mbedtls_x509_crt own_cert;
  13598. static mbedtls_pk_context own_key;
  13599. static mbedtls_x509_crt ca_chain;
  13600. static bool initialized = false;
  13601. if (!initialized) {
  13602. mbedtls_x509_crt_init(&own_cert);
  13603. mbedtls_pk_init(&own_key);
  13604. mbedtls_x509_crt_init(&ca_chain);
  13605. // Load server certificate
  13606. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  13607. return false;
  13608. }
  13609. // Load server private key
  13610. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  13611. #if MBEDTLS_VERSION_MAJOR >= 3
  13612. ,
  13613. mbedtls_ctr_drbg_random, nullptr
  13614. #endif
  13615. ) != 0) {
  13616. return false;
  13617. }
  13618. // Load CA chain for client verification
  13619. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  13620. return false;
  13621. }
  13622. initialized = true;
  13623. }
  13624. // Configure the SSL config
  13625. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  13626. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  13627. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  13628. // Set minimum TLS version using mbedTLS native API
  13629. #if MBEDTLS_VERSION_MAJOR >= 3
  13630. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  13631. #else
  13632. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  13633. MBEDTLS_SSL_MINOR_VERSION_3);
  13634. #endif
  13635. return true;
  13636. };
  13637. SSLServer svr(setup_callback);
  13638. ASSERT_TRUE(svr.is_valid());
  13639. ASSERT_TRUE(callback_invoked);
  13640. svr.Get("/test", [&](const Request &req, Response &res) {
  13641. res.set_content("test", "text/plain");
  13642. auto cert = req.peer_cert();
  13643. ASSERT_TRUE(static_cast<bool>(cert));
  13644. auto common_name = cert.subject_cn();
  13645. EXPECT_EQ("Common Name", common_name);
  13646. });
  13647. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13648. auto se = detail::scope_exit([&] {
  13649. svr.stop();
  13650. t.join();
  13651. ASSERT_FALSE(svr.is_running());
  13652. });
  13653. svr.wait_until_ready();
  13654. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13655. cli.enable_server_certificate_verification(false);
  13656. cli.set_connection_timeout(30);
  13657. auto res = cli.Get("/test");
  13658. ASSERT_TRUE(res);
  13659. ASSERT_EQ(StatusCode::OK_200, res->status);
  13660. }
  13661. #endif
  13662. // WebSocket Tests
  13663. TEST(WebSocketTest, RSVBitsMustBeZero) {
  13664. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  13665. // defining the meaning of these bits has been negotiated.
  13666. auto make_frame = [](uint8_t first_byte) {
  13667. std::string frame;
  13668. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  13669. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  13670. frame += "Hello";
  13671. return frame;
  13672. };
  13673. // RSV1 set (0x40)
  13674. {
  13675. detail::BufferStream strm;
  13676. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  13677. ws::Opcode opcode;
  13678. std::string payload;
  13679. bool fin;
  13680. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13681. false, 1024));
  13682. }
  13683. // RSV2 set (0x20)
  13684. {
  13685. detail::BufferStream strm;
  13686. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  13687. ws::Opcode opcode;
  13688. std::string payload;
  13689. bool fin;
  13690. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13691. false, 1024));
  13692. }
  13693. // RSV3 set (0x10)
  13694. {
  13695. detail::BufferStream strm;
  13696. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  13697. ws::Opcode opcode;
  13698. std::string payload;
  13699. bool fin;
  13700. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13701. false, 1024));
  13702. }
  13703. // No RSV bits set - should succeed
  13704. {
  13705. detail::BufferStream strm;
  13706. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  13707. ws::Opcode opcode;
  13708. std::string payload;
  13709. bool fin;
  13710. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13711. false, 1024));
  13712. EXPECT_EQ(ws::Opcode::Text, opcode);
  13713. EXPECT_EQ("Hello", payload);
  13714. EXPECT_TRUE(fin);
  13715. }
  13716. }
  13717. TEST(WebSocketTest, ControlFrameValidation) {
  13718. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  13719. // payload length <= 125.
  13720. // Ping with FIN=0 - must be rejected
  13721. {
  13722. detail::BufferStream strm;
  13723. std::string frame;
  13724. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  13725. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13726. strm.write(frame.data(), frame.size());
  13727. ws::Opcode opcode;
  13728. std::string payload;
  13729. bool fin;
  13730. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13731. false, 1024));
  13732. }
  13733. // Close with FIN=0 - must be rejected
  13734. {
  13735. detail::BufferStream strm;
  13736. std::string frame;
  13737. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  13738. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13739. strm.write(frame.data(), frame.size());
  13740. ws::Opcode opcode;
  13741. std::string payload;
  13742. bool fin;
  13743. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13744. false, 1024));
  13745. }
  13746. // Ping with payload_len=126 (extended length) - must be rejected
  13747. {
  13748. detail::BufferStream strm;
  13749. std::string frame;
  13750. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13751. frame += static_cast<char>(126); // payload_len=126 (>125)
  13752. frame += static_cast<char>(0x00); // extended length high byte
  13753. frame += static_cast<char>(126); // extended length low byte
  13754. frame += std::string(126, 'x');
  13755. strm.write(frame.data(), frame.size());
  13756. ws::Opcode opcode;
  13757. std::string payload;
  13758. bool fin;
  13759. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13760. false, 1024));
  13761. }
  13762. // Ping with FIN=1 and payload_len=125 - should succeed
  13763. {
  13764. detail::BufferStream strm;
  13765. std::string frame;
  13766. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13767. frame += static_cast<char>(125); // payload_len=125
  13768. frame += std::string(125, 'x');
  13769. strm.write(frame.data(), frame.size());
  13770. ws::Opcode opcode;
  13771. std::string payload;
  13772. bool fin;
  13773. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13774. false, 1024));
  13775. EXPECT_EQ(ws::Opcode::Ping, opcode);
  13776. EXPECT_EQ(125u, payload.size());
  13777. EXPECT_TRUE(fin);
  13778. }
  13779. }
  13780. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  13781. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  13782. // length MUST be 0.
  13783. // MSB set - must be rejected
  13784. {
  13785. detail::BufferStream strm;
  13786. std::string frame;
  13787. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13788. frame += static_cast<char>(127); // 64-bit extended length
  13789. frame += static_cast<char>(0x80); // MSB set (invalid)
  13790. frame += std::string(7, '\0'); // remaining 7 bytes of length
  13791. strm.write(frame.data(), frame.size());
  13792. ws::Opcode opcode;
  13793. std::string payload;
  13794. bool fin;
  13795. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13796. false, 1024));
  13797. }
  13798. // MSB clear - should pass length parsing (will be rejected by max_len,
  13799. // but that's a different check; use a small length to verify)
  13800. {
  13801. detail::BufferStream strm;
  13802. std::string frame;
  13803. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13804. frame += static_cast<char>(127); // 64-bit extended length
  13805. frame += std::string(7, '\0'); // high bytes = 0
  13806. frame += static_cast<char>(0x03); // length = 3
  13807. frame += "abc";
  13808. strm.write(frame.data(), frame.size());
  13809. ws::Opcode opcode;
  13810. std::string payload;
  13811. bool fin;
  13812. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13813. false, 1024));
  13814. EXPECT_EQ(ws::Opcode::Text, opcode);
  13815. EXPECT_EQ("abc", payload);
  13816. }
  13817. }
  13818. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  13819. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  13820. // Valid UTF-8
  13821. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  13822. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  13823. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  13824. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  13825. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  13826. // Invalid UTF-8
  13827. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  13828. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  13829. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  13830. EXPECT_FALSE(
  13831. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  13832. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  13833. }
  13834. TEST(WebSocketTest, ConnectAndDisconnect) {
  13835. Server svr;
  13836. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  13837. std::string msg;
  13838. while (ws.read(msg)) {}
  13839. });
  13840. auto port = svr.bind_to_any_port(HOST);
  13841. std::thread t([&]() { svr.listen_after_bind(); });
  13842. svr.wait_until_ready();
  13843. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  13844. ASSERT_TRUE(client.connect());
  13845. EXPECT_TRUE(client.is_open());
  13846. client.close();
  13847. EXPECT_FALSE(client.is_open());
  13848. svr.stop();
  13849. t.join();
  13850. }
  13851. TEST(WebSocketTest, ValidURL) {
  13852. ws::WebSocketClient ws1("ws://localhost:8080/path");
  13853. EXPECT_TRUE(ws1.is_valid());
  13854. ws::WebSocketClient ws2("ws://example.com/path");
  13855. EXPECT_TRUE(ws2.is_valid());
  13856. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  13857. EXPECT_TRUE(ws3.is_valid());
  13858. #ifdef CPPHTTPLIB_SSL_ENABLED
  13859. ws::WebSocketClient wss1("wss://example.com/path");
  13860. EXPECT_TRUE(wss1.is_valid());
  13861. ws::WebSocketClient wss2("wss://example.com:443/path");
  13862. EXPECT_TRUE(wss2.is_valid());
  13863. #endif
  13864. }
  13865. TEST(WebSocketTest, InvalidURL) {
  13866. // No scheme
  13867. ws::WebSocketClient ws1("localhost:8080/path");
  13868. EXPECT_FALSE(ws1.is_valid());
  13869. // No path
  13870. ws::WebSocketClient ws2("ws://localhost:8080");
  13871. EXPECT_FALSE(ws2.is_valid());
  13872. // Empty string
  13873. ws::WebSocketClient ws3("");
  13874. EXPECT_FALSE(ws3.is_valid());
  13875. // Missing host
  13876. ws::WebSocketClient ws4("ws://:8080/path");
  13877. EXPECT_FALSE(ws4.is_valid());
  13878. // Port number overflow — should not crash
  13879. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  13880. EXPECT_FALSE(ws5.is_valid());
  13881. // Port out of range
  13882. ws::WebSocketClient ws6("ws://localhost:99999/path");
  13883. EXPECT_FALSE(ws6.is_valid());
  13884. }
  13885. TEST(WebSocketTest, UnsupportedScheme) {
  13886. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13887. ws::WebSocketClient ws1("http://localhost:8080/path");
  13888. EXPECT_FALSE(ws1.is_valid());
  13889. ws::WebSocketClient ws2("https://localhost:8080/path");
  13890. EXPECT_FALSE(ws2.is_valid());
  13891. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  13892. EXPECT_FALSE(ws3.is_valid());
  13893. #else
  13894. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  13895. std::invalid_argument);
  13896. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  13897. std::invalid_argument);
  13898. #endif
  13899. }
  13900. TEST(WebSocketTest, ConnectWhenInvalid) {
  13901. ws::WebSocketClient ws("not a valid url");
  13902. EXPECT_FALSE(ws.is_valid());
  13903. EXPECT_FALSE(ws.connect());
  13904. }
  13905. TEST(WebSocketTest, DefaultPort) {
  13906. ws::WebSocketClient ws1("ws://example.com/path");
  13907. EXPECT_TRUE(ws1.is_valid());
  13908. // ws:// defaults to port 80 (verified by successful parse)
  13909. #ifdef CPPHTTPLIB_SSL_ENABLED
  13910. ws::WebSocketClient ws2("wss://example.com/path");
  13911. EXPECT_TRUE(ws2.is_valid());
  13912. // wss:// defaults to port 443 (verified by successful parse)
  13913. #endif
  13914. }
  13915. TEST(WebSocketTest, IPv6LiteralAddress) {
  13916. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  13917. EXPECT_TRUE(ws1.is_valid());
  13918. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  13919. EXPECT_TRUE(ws2.is_valid());
  13920. }
  13921. TEST(WebSocketTest, ComplexPath) {
  13922. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  13923. EXPECT_TRUE(ws1.is_valid());
  13924. ws::WebSocketClient ws2("ws://localhost:8080/");
  13925. EXPECT_TRUE(ws2.is_valid());
  13926. }
  13927. class WebSocketIntegrationTest : public ::testing::Test {
  13928. protected:
  13929. void SetUp() override {
  13930. server_ = httplib::detail::make_unique<Server>();
  13931. setup_server();
  13932. start_server();
  13933. }
  13934. void TearDown() override {
  13935. server_->stop();
  13936. if (server_thread_.joinable()) { server_thread_.join(); }
  13937. }
  13938. void setup_server() {
  13939. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  13940. std::string msg;
  13941. ws::ReadResult ret;
  13942. while ((ret = ws.read(msg))) {
  13943. if (ret == ws::Binary) {
  13944. ws.send(msg.data(), msg.size());
  13945. } else {
  13946. ws.send(msg);
  13947. }
  13948. }
  13949. });
  13950. server_->WebSocket("/ws-echo-string",
  13951. [](const Request &, ws::WebSocket &ws) {
  13952. std::string msg;
  13953. while (ws.read(msg)) {
  13954. ws.send("echo: " + msg);
  13955. }
  13956. });
  13957. server_->WebSocket(
  13958. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  13959. // Echo back request metadata
  13960. ws.send("path:" + req.path);
  13961. ws.send("header:" + req.get_header_value("X-Test-Header"));
  13962. std::string msg;
  13963. while (ws.read(msg)) {}
  13964. });
  13965. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  13966. std::string msg;
  13967. ws.read(msg); // wait for a message
  13968. ws.close();
  13969. });
  13970. server_->WebSocket("/ws-close-status",
  13971. [](const Request &, ws::WebSocket &ws) {
  13972. std::string msg;
  13973. ws.read(msg); // wait for a message
  13974. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  13975. });
  13976. server_->WebSocket(
  13977. "/ws-subprotocol",
  13978. [](const Request &, ws::WebSocket &ws) {
  13979. std::string msg;
  13980. while (ws.read(msg)) {
  13981. ws.send(msg);
  13982. }
  13983. },
  13984. [](const std::vector<std::string> &protocols) -> std::string {
  13985. for (const auto &p : protocols) {
  13986. if (p == "graphql-ws") { return p; }
  13987. }
  13988. return "";
  13989. });
  13990. }
  13991. void start_server() {
  13992. port_ = server_->bind_to_any_port(HOST);
  13993. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13994. server_->wait_until_ready();
  13995. }
  13996. std::unique_ptr<Server> server_;
  13997. std::thread server_thread_;
  13998. int port_ = 0;
  13999. };
  14000. TEST_F(WebSocketIntegrationTest, TextEcho) {
  14001. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14002. "/ws-echo");
  14003. ASSERT_TRUE(client.connect());
  14004. ASSERT_TRUE(client.is_open());
  14005. ASSERT_TRUE(client.send("Hello WebSocket"));
  14006. std::string msg;
  14007. EXPECT_EQ(ws::Text, client.read(msg));
  14008. EXPECT_EQ("Hello WebSocket", msg);
  14009. client.close();
  14010. }
  14011. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  14012. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14013. "/ws-echo");
  14014. ASSERT_TRUE(client.connect());
  14015. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  14016. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  14017. std::string msg;
  14018. EXPECT_EQ(ws::Binary, client.read(msg));
  14019. EXPECT_EQ(binary_data, msg);
  14020. client.close();
  14021. }
  14022. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  14023. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14024. "/ws-echo");
  14025. ASSERT_TRUE(client.connect());
  14026. for (int i = 0; i < 10; i++) {
  14027. auto text = "message " + std::to_string(i);
  14028. ASSERT_TRUE(client.send(text));
  14029. std::string msg;
  14030. ASSERT_TRUE(client.read(msg));
  14031. EXPECT_EQ(text, msg);
  14032. }
  14033. client.close();
  14034. }
  14035. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  14036. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14037. "/ws-close");
  14038. ASSERT_TRUE(client.connect());
  14039. // Send a message to trigger the server to close
  14040. ASSERT_TRUE(client.send("trigger close"));
  14041. // The server will close, so read should return false
  14042. std::string msg;
  14043. EXPECT_FALSE(client.read(msg));
  14044. EXPECT_FALSE(client.is_open());
  14045. }
  14046. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  14047. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14048. "/ws-echo");
  14049. ASSERT_TRUE(client.connect());
  14050. // 128KB message
  14051. std::string large_data(128 * 1024, 'X');
  14052. ASSERT_TRUE(client.send(large_data));
  14053. std::string msg;
  14054. ASSERT_TRUE(client.read(msg));
  14055. EXPECT_EQ(large_data, msg);
  14056. client.close();
  14057. }
  14058. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  14059. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14060. "/ws-echo");
  14061. ASSERT_TRUE(client.connect());
  14062. const int num_threads = 4;
  14063. std::vector<std::thread> threads;
  14064. std::atomic<int> send_count{0};
  14065. for (int t = 0; t < num_threads; t++) {
  14066. threads.emplace_back([&client, &send_count, t]() {
  14067. for (int i = 0; i < 5; i++) {
  14068. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  14069. if (client.send(text)) { send_count++; }
  14070. }
  14071. });
  14072. }
  14073. for (auto &th : threads) {
  14074. th.join();
  14075. }
  14076. int received = 0;
  14077. std::string msg;
  14078. while (received < send_count.load()) {
  14079. if (!client.read(msg)) { break; }
  14080. received++;
  14081. }
  14082. EXPECT_EQ(send_count.load(), received);
  14083. client.close();
  14084. }
  14085. TEST_F(WebSocketIntegrationTest, ReadString) {
  14086. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14087. "/ws-echo-string");
  14088. ASSERT_TRUE(client.connect());
  14089. ASSERT_TRUE(client.send("hello"));
  14090. std::string msg;
  14091. ASSERT_TRUE(client.read(msg));
  14092. EXPECT_EQ("echo: hello", msg);
  14093. ASSERT_TRUE(client.send("world"));
  14094. ASSERT_TRUE(client.read(msg));
  14095. EXPECT_EQ("echo: world", msg);
  14096. client.close();
  14097. }
  14098. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  14099. Headers headers = {{"X-Test-Header", "test-value"}};
  14100. ws::WebSocketClient client(
  14101. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  14102. ASSERT_TRUE(client.connect());
  14103. std::string msg;
  14104. ASSERT_TRUE(client.read(msg));
  14105. EXPECT_EQ("path:/ws-request-info", msg);
  14106. ASSERT_TRUE(client.read(msg));
  14107. EXPECT_EQ("header:test-value", msg);
  14108. client.close();
  14109. }
  14110. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  14111. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14112. "/ws-echo");
  14113. client.set_read_timeout(1, 0); // 1 second
  14114. ASSERT_TRUE(client.connect());
  14115. // Don't send anything — server echo handler waits for a message,
  14116. // so read() should time out and return false.
  14117. std::string msg;
  14118. EXPECT_FALSE(client.read(msg));
  14119. }
  14120. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  14121. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14122. "/ws-echo");
  14123. client.set_read_timeout(5, 0);
  14124. ASSERT_TRUE(client.connect());
  14125. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14126. // The server should reject it and close the connection.
  14127. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  14128. client.send(oversized);
  14129. // The server's read() should have failed due to payload limit,
  14130. // so our read() should return false (connection closed).
  14131. std::string msg;
  14132. EXPECT_FALSE(client.read(msg));
  14133. }
  14134. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  14135. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14136. "/ws-echo");
  14137. client.set_read_timeout(10, 0);
  14138. ASSERT_TRUE(client.connect());
  14139. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14140. // This should succeed.
  14141. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  14142. ASSERT_TRUE(client.send(at_limit));
  14143. std::string msg;
  14144. ASSERT_TRUE(client.read(msg));
  14145. EXPECT_EQ(at_limit.size(), msg.size());
  14146. client.close();
  14147. }
  14148. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  14149. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14150. "/nonexistent");
  14151. EXPECT_FALSE(client.connect());
  14152. EXPECT_FALSE(client.is_open());
  14153. }
  14154. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  14155. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14156. "/ws-echo");
  14157. ASSERT_TRUE(client.connect());
  14158. ASSERT_TRUE(client.send(""));
  14159. std::string msg;
  14160. EXPECT_EQ(ws::Text, client.read(msg));
  14161. EXPECT_EQ("", msg);
  14162. client.close();
  14163. }
  14164. TEST_F(WebSocketIntegrationTest, Reconnect) {
  14165. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14166. "/ws-echo");
  14167. // First connection
  14168. ASSERT_TRUE(client.connect());
  14169. ASSERT_TRUE(client.send("first"));
  14170. std::string msg;
  14171. ASSERT_TRUE(client.read(msg));
  14172. EXPECT_EQ("first", msg);
  14173. client.close();
  14174. EXPECT_FALSE(client.is_open());
  14175. // Reconnect using the same client object
  14176. ASSERT_TRUE(client.connect());
  14177. ASSERT_TRUE(client.is_open());
  14178. ASSERT_TRUE(client.send("second"));
  14179. ASSERT_TRUE(client.read(msg));
  14180. EXPECT_EQ("second", msg);
  14181. client.close();
  14182. }
  14183. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  14184. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14185. "/ws-close-status");
  14186. ASSERT_TRUE(client.connect());
  14187. // Trigger the server to close with GoingAway status
  14188. ASSERT_TRUE(client.send("trigger"));
  14189. // read() should return false after receiving the close frame
  14190. std::string msg;
  14191. EXPECT_FALSE(client.read(msg));
  14192. EXPECT_FALSE(client.is_open());
  14193. }
  14194. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  14195. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14196. "/ws-echo");
  14197. ASSERT_TRUE(client.connect());
  14198. client.close(ws::CloseStatus::GoingAway, "client leaving");
  14199. EXPECT_FALSE(client.is_open());
  14200. }
  14201. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  14202. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  14203. ws::WebSocketClient client(
  14204. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14205. ASSERT_TRUE(client.connect());
  14206. // Server should have selected graphql-ws
  14207. EXPECT_EQ("graphql-ws", client.subprotocol());
  14208. client.close();
  14209. }
  14210. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  14211. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  14212. ws::WebSocketClient client(
  14213. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14214. ASSERT_TRUE(client.connect());
  14215. // Server should not have selected any subprotocol
  14216. EXPECT_TRUE(client.subprotocol().empty());
  14217. client.close();
  14218. }
  14219. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  14220. // Connect without requesting any subprotocol
  14221. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14222. "/ws-subprotocol");
  14223. ASSERT_TRUE(client.connect());
  14224. EXPECT_TRUE(client.subprotocol().empty());
  14225. client.close();
  14226. }
  14227. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  14228. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14229. "/ws-echo");
  14230. client.set_tcp_nodelay(true);
  14231. client.set_address_family(AF_INET);
  14232. client.set_connection_timeout(3, 0);
  14233. bool socket_options_called = false;
  14234. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  14235. ASSERT_TRUE(client.connect());
  14236. ASSERT_TRUE(client.is_open());
  14237. EXPECT_TRUE(socket_options_called);
  14238. ASSERT_TRUE(client.send("hello"));
  14239. std::string msg;
  14240. auto result = client.read(msg);
  14241. EXPECT_EQ(result, ws::ReadResult::Text);
  14242. EXPECT_EQ(msg, "hello");
  14243. client.close();
  14244. }
  14245. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  14246. Server svr;
  14247. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  14248. if (!req.has_header("Authorization")) {
  14249. res.status = StatusCode::Unauthorized_401;
  14250. res.set_content("Unauthorized", "text/plain");
  14251. return Server::HandlerResponse::Handled;
  14252. }
  14253. return Server::HandlerResponse::Unhandled;
  14254. });
  14255. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14256. std::string msg;
  14257. while (ws.read(msg)) {
  14258. ws.send(msg);
  14259. }
  14260. });
  14261. auto port = svr.bind_to_any_port("localhost");
  14262. std::thread t([&]() { svr.listen_after_bind(); });
  14263. svr.wait_until_ready();
  14264. // Without Authorization header - should be rejected before upgrade
  14265. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  14266. EXPECT_FALSE(client1.connect());
  14267. // With Authorization header - should succeed
  14268. Headers headers = {{"Authorization", "Bearer token123"}};
  14269. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  14270. headers);
  14271. ASSERT_TRUE(client2.connect());
  14272. ASSERT_TRUE(client2.send("hello"));
  14273. std::string msg;
  14274. ASSERT_TRUE(client2.read(msg));
  14275. EXPECT_EQ("hello", msg);
  14276. client2.close();
  14277. svr.stop();
  14278. t.join();
  14279. }
  14280. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14281. class WebSocketSSLIntegrationTest : public ::testing::Test {
  14282. protected:
  14283. void SetUp() override {
  14284. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  14285. SERVER_PRIVATE_KEY_FILE);
  14286. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14287. std::string msg;
  14288. ws::ReadResult ret;
  14289. while ((ret = ws.read(msg))) {
  14290. if (ret == ws::Binary) {
  14291. ws.send(msg.data(), msg.size());
  14292. } else {
  14293. ws.send(msg);
  14294. }
  14295. }
  14296. });
  14297. port_ = server_->bind_to_any_port(HOST);
  14298. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14299. server_->wait_until_ready();
  14300. }
  14301. void TearDown() override {
  14302. server_->stop();
  14303. if (server_thread_.joinable()) { server_thread_.join(); }
  14304. }
  14305. std::unique_ptr<SSLServer> server_;
  14306. std::thread server_thread_;
  14307. int port_ = 0;
  14308. };
  14309. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  14310. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  14311. "/ws-echo");
  14312. client.enable_server_certificate_verification(false);
  14313. ASSERT_TRUE(client.connect());
  14314. ASSERT_TRUE(client.is_open());
  14315. ASSERT_TRUE(client.send("Hello WSS"));
  14316. std::string msg;
  14317. EXPECT_EQ(ws::Text, client.read(msg));
  14318. EXPECT_EQ("Hello WSS", msg);
  14319. client.close();
  14320. }
  14321. #endif
  14322. #if !defined(_WIN32)
  14323. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  14324. auto secret_dir = std::string("./symlink_test_secret");
  14325. auto served_dir = std::string("./symlink_test_served");
  14326. auto secret_file = secret_dir + "/secret.txt";
  14327. auto symlink_path = served_dir + "/escape";
  14328. // Setup: create directories and files
  14329. mkdir(secret_dir.c_str(), 0755);
  14330. mkdir(served_dir.c_str(), 0755);
  14331. {
  14332. std::ofstream ofs(secret_file);
  14333. ofs << "SECRET_DATA";
  14334. }
  14335. // Create symlink using absolute path so it resolves correctly
  14336. char abs_secret[PATH_MAX];
  14337. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  14338. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  14339. auto se = detail::scope_exit([&] {
  14340. unlink(symlink_path.c_str());
  14341. unlink(secret_file.c_str());
  14342. rmdir(served_dir.c_str());
  14343. rmdir(secret_dir.c_str());
  14344. });
  14345. Server svr;
  14346. svr.set_mount_point("/", served_dir);
  14347. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  14348. auto se2 = detail::scope_exit([&] {
  14349. svr.stop();
  14350. listen_thread.join();
  14351. });
  14352. svr.wait_until_ready();
  14353. Client cli("localhost", PORT);
  14354. // Symlink pointing outside base dir should be blocked
  14355. auto res = cli.Get("/escape/secret.txt");
  14356. ASSERT_TRUE(res);
  14357. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  14358. }
  14359. #endif