test.cc 527 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #if __cplusplus >= 202002L
  28. inline std::string u8_to_string(const char8_t *s) {
  29. return std::string(reinterpret_cast<const char *>(s));
  30. }
  31. #define U8(x) u8_to_string(u8##x)
  32. #else
  33. #define U8(x) u8##x
  34. #endif
  35. #define SERVER_CERT_FILE "./cert.pem"
  36. #define SERVER_CERT2_FILE "./cert2.pem"
  37. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  38. #define CA_CERT_FILE "./ca-bundle.crt"
  39. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  40. #define CLIENT_CA_CERT_DIR "."
  41. #define CLIENT_CERT_FILE "./client.cert.pem"
  42. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  43. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  44. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  45. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  46. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  47. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  48. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  49. using namespace std;
  50. using namespace httplib;
  51. const char *HOST = "localhost";
  52. static int get_base_port() {
  53. const char *shard = getenv("GTEST_SHARD_INDEX");
  54. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  55. }
  56. const int PORT = get_base_port();
  57. const string LONG_QUERY_VALUE = string(25000, '@');
  58. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  59. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  60. const string TOO_LONG_QUERY_URL =
  61. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  62. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  63. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  64. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  65. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  66. return file.name == key;
  67. });
  68. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  69. return *it;
  70. #else
  71. if (it != items.end()) { return *it; }
  72. throw std::runtime_error("invalid multipart form data name error");
  73. #endif
  74. }
  75. static void read_file(const std::string &path, std::string &out) {
  76. std::ifstream fs(path, std::ios_base::binary);
  77. if (!fs) {
  78. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  79. return;
  80. #else
  81. throw std::runtime_error("File not found: " + path);
  82. #endif
  83. }
  84. fs.seekg(0, std::ios_base::end);
  85. auto size = fs.tellg();
  86. fs.seekg(0);
  87. out.resize(static_cast<size_t>(size));
  88. fs.read(&out[0], static_cast<std::streamsize>(size));
  89. }
  90. void performance_test(const char *host) {
  91. Server svr;
  92. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  93. res.set_content("Benchmark Response", "text/plain");
  94. });
  95. auto listen_thread = std::thread([&]() { svr.listen(host, PORT); });
  96. auto se = detail::scope_exit([&] {
  97. svr.stop();
  98. listen_thread.join();
  99. ASSERT_FALSE(svr.is_running());
  100. });
  101. svr.wait_until_ready();
  102. Client cli(host, PORT);
  103. // Warm-up request to establish connection and resolve DNS
  104. auto warmup_res = cli.Get("/benchmark");
  105. ASSERT_TRUE(warmup_res); // Ensure server is responding correctly
  106. // Run multiple trials and collect timings
  107. const int num_trials = 20;
  108. std::vector<int64_t> timings;
  109. timings.reserve(num_trials);
  110. for (int i = 0; i < num_trials; i++) {
  111. auto start = std::chrono::high_resolution_clock::now();
  112. auto res = cli.Get("/benchmark");
  113. auto end = std::chrono::high_resolution_clock::now();
  114. auto elapsed =
  115. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  116. .count();
  117. // Assertions after timing measurement to avoid overhead
  118. ASSERT_TRUE(res);
  119. EXPECT_EQ(StatusCode::OK_200, res->status);
  120. timings.push_back(elapsed);
  121. }
  122. // Calculate 25th percentile (lower quartile)
  123. std::sort(timings.begin(), timings.end());
  124. auto p25 = timings[num_trials / 4];
  125. // Format timings for output
  126. std::ostringstream timings_str;
  127. timings_str << "[";
  128. for (size_t i = 0; i < timings.size(); i++) {
  129. if (i > 0) timings_str << ", ";
  130. timings_str << timings[i];
  131. }
  132. timings_str << "]";
  133. // Localhost HTTP GET should be fast even in CI environments
  134. EXPECT_LE(p25, 5) << "25th percentile performance is too slow: " << p25
  135. << "ms (Issue #1777). Timings: " << timings_str.str();
  136. }
  137. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  138. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  139. class UnixSocketTest : public ::testing::Test {
  140. protected:
  141. void TearDown() override { std::remove(pathname_.c_str()); }
  142. void client_GET(const std::string &addr) {
  143. httplib::Client cli{addr};
  144. cli.set_address_family(AF_UNIX);
  145. ASSERT_TRUE(cli.is_valid());
  146. const auto &result = cli.Get(pattern_);
  147. ASSERT_TRUE(result) << "error: " << result.error();
  148. const auto &resp = result.value();
  149. EXPECT_EQ(resp.status, StatusCode::OK_200);
  150. EXPECT_EQ(resp.body, content_);
  151. }
  152. static std::string make_sock_path() {
  153. const char *shard = getenv("GTEST_SHARD_INDEX");
  154. return shard ? std::string("./httplib-server-") + shard + ".sock"
  155. : "./httplib-server.sock";
  156. }
  157. const std::string pathname_{make_sock_path()};
  158. const std::string pattern_{"/hi"};
  159. const std::string content_{"Hello World!"};
  160. };
  161. TEST_F(UnixSocketTest, pathname) {
  162. httplib::Server svr;
  163. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  164. res.set_content(content_, "text/plain");
  165. });
  166. std::thread t{[&] {
  167. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  168. }};
  169. auto se = detail::scope_exit([&] {
  170. svr.stop();
  171. t.join();
  172. ASSERT_FALSE(svr.is_running());
  173. });
  174. svr.wait_until_ready();
  175. ASSERT_TRUE(svr.is_running());
  176. client_GET(pathname_);
  177. }
  178. #if defined(__linux__) || \
  179. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  180. TEST_F(UnixSocketTest, PeerPid) {
  181. httplib::Server svr;
  182. std::string remote_port_val;
  183. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  184. res.set_content(content_, "text/plain");
  185. remote_port_val = std::to_string(req.remote_port);
  186. });
  187. std::thread t{[&] {
  188. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  189. }};
  190. auto se = detail::scope_exit([&] {
  191. svr.stop();
  192. t.join();
  193. ASSERT_FALSE(svr.is_running());
  194. });
  195. svr.wait_until_ready();
  196. ASSERT_TRUE(svr.is_running());
  197. client_GET(pathname_);
  198. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  199. }
  200. #endif
  201. #ifdef __linux__
  202. TEST_F(UnixSocketTest, abstract) {
  203. constexpr char svr_path[]{"\x00httplib-server.sock"};
  204. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  205. httplib::Server svr;
  206. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  207. res.set_content(content_, "text/plain");
  208. });
  209. std::thread t{[&] {
  210. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  211. }};
  212. auto se = detail::scope_exit([&] {
  213. svr.stop();
  214. t.join();
  215. ASSERT_FALSE(svr.is_running());
  216. });
  217. svr.wait_until_ready();
  218. ASSERT_TRUE(svr.is_running());
  219. client_GET(abstract_addr);
  220. }
  221. #endif
  222. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  223. httplib::Server svr;
  224. std::string received_host_header;
  225. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  226. // Capture the Host header sent by the client
  227. auto host_iter = req.headers.find("Host");
  228. if (host_iter != req.headers.end()) {
  229. received_host_header = host_iter->second;
  230. }
  231. res.set_content(content_, "text/plain");
  232. });
  233. std::thread t{[&] {
  234. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  235. }};
  236. auto se = detail::scope_exit([&] {
  237. svr.stop();
  238. t.join();
  239. ASSERT_FALSE(svr.is_running());
  240. });
  241. svr.wait_until_ready();
  242. ASSERT_TRUE(svr.is_running());
  243. // Test that Host header is automatically set to "localhost" for Unix socket
  244. // connections
  245. httplib::Client cli{pathname_};
  246. cli.set_address_family(AF_UNIX);
  247. ASSERT_TRUE(cli.is_valid());
  248. const auto &result = cli.Get(pattern_);
  249. ASSERT_TRUE(result) << "error: " << result.error();
  250. const auto &resp = result.value();
  251. EXPECT_EQ(resp.status, StatusCode::OK_200);
  252. EXPECT_EQ(resp.body, content_);
  253. // Verify that Host header was automatically set to "localhost"
  254. EXPECT_EQ(received_host_header, "localhost");
  255. }
  256. #ifndef _WIN32
  257. TEST(SocketStream, wait_writable_UNIX) {
  258. int fds[2];
  259. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  260. const auto asSocketStream = [&](socket_t fd,
  261. std::function<bool(Stream &)> func) {
  262. return detail::process_client_socket(
  263. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  264. };
  265. asSocketStream(fds[0], [&](Stream &s0) {
  266. EXPECT_EQ(s0.socket(), fds[0]);
  267. EXPECT_TRUE(s0.wait_writable());
  268. EXPECT_TRUE(s0.is_peer_alive());
  269. EXPECT_EQ(0, close(fds[1]));
  270. EXPECT_FALSE(s0.is_peer_alive());
  271. return true;
  272. });
  273. EXPECT_EQ(0, close(fds[0]));
  274. }
  275. TEST(SocketStream, wait_writable_INET) {
  276. sockaddr_in addr;
  277. memset(&addr, 0, sizeof(addr));
  278. addr.sin_family = AF_INET;
  279. addr.sin_port = htons(PORT + 1);
  280. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  281. int disconnected_svr_sock = -1;
  282. std::thread svr{[&] {
  283. const int s = socket(AF_INET, SOCK_STREAM, 0);
  284. ASSERT_LE(0, s);
  285. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  286. ASSERT_EQ(0, listen(s, 1));
  287. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  288. ASSERT_EQ(0, close(s));
  289. }};
  290. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  291. std::thread cli{[&] {
  292. const int s = socket(AF_INET, SOCK_STREAM, 0);
  293. ASSERT_LE(0, s);
  294. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  295. ASSERT_EQ(0, close(s));
  296. }};
  297. cli.join();
  298. svr.join();
  299. ASSERT_NE(disconnected_svr_sock, -1);
  300. const auto asSocketStream = [&](socket_t fd,
  301. std::function<bool(Stream &)> func) {
  302. return detail::process_client_socket(
  303. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  304. };
  305. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  306. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  307. // wait_writable() returns true because select_write() only checks if the
  308. // send buffer has space. Peer disconnection is detected later by send().
  309. EXPECT_TRUE(ss.wait_writable());
  310. return true;
  311. });
  312. ASSERT_EQ(0, close(disconnected_svr_sock));
  313. }
  314. #endif // #ifndef _WIN32
  315. TEST(ClientTest, MoveConstructible) {
  316. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  317. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  318. }
  319. TEST(ClientTest, MoveAssignable) {
  320. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  321. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  322. }
  323. #ifdef _WIN32
  324. TEST(StartupTest, WSAStartup) {
  325. WSADATA wsaData;
  326. int ret = WSAStartup(0x0002, &wsaData);
  327. ASSERT_EQ(0, ret);
  328. }
  329. #endif
  330. TEST(DecodePathTest, PercentCharacter) {
  331. EXPECT_EQ(
  332. decode_path_component(
  333. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  334. U8("descrip=Gastos áéíóúñÑ 6"));
  335. }
  336. TEST(DecodePathTest, PercentCharacterNUL) {
  337. string expected;
  338. expected.push_back('x');
  339. expected.push_back('\0');
  340. expected.push_back('x');
  341. EXPECT_EQ(decode_path_component("x%00x"), expected);
  342. }
  343. TEST(DecodePathTest, UnicodeEncoding) {
  344. // %u0041 = 'A' (1-byte UTF-8)
  345. EXPECT_EQ("A", decode_path_component("%u0041"));
  346. // %u00E9 = 'é' (2-byte UTF-8)
  347. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  348. // %u3042 = 'あ' (3-byte UTF-8)
  349. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  350. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  351. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  352. // %uD800 = surrogate (invalid, silently dropped)
  353. EXPECT_EQ("", decode_path_component("%uD800"));
  354. }
  355. TEST(SanitizeFilenameTest, VariousPatterns) {
  356. // Path traversal
  357. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  358. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  359. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  360. // Normal and edge cases
  361. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  362. EXPECT_EQ("filename.txt",
  363. httplib::sanitize_filename("/path/to/filename.txt"));
  364. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  365. EXPECT_EQ("", httplib::sanitize_filename(".."));
  366. EXPECT_EQ("", httplib::sanitize_filename(""));
  367. // Null bytes stripped
  368. EXPECT_EQ("safe.txt",
  369. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  370. // Whitespace-only rejected
  371. EXPECT_EQ("", httplib::sanitize_filename(" "));
  372. }
  373. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  374. string unescapedCharacters = "-_.!~*'()";
  375. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  376. }
  377. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  378. string reservedCharacters = ";,/?:@&=+$";
  379. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  380. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  381. }
  382. TEST(ClientQueryOrder, PreserveOrder) {
  383. // This test reproduces Issue #2259: client may reorder query parameters
  384. // when sending a GET request. The expected behavior is that the client
  385. // preserves the original query string order when the caller supplied it
  386. // as part of the path.
  387. Server svr;
  388. svr.Get("/", [&](const Request &req, Response &res) {
  389. // Echo back the raw target so the test can assert ordering
  390. res.set_content(req.target, "text/plain");
  391. });
  392. std::thread t{[&] { svr.listen(HOST, PORT); }};
  393. auto se = detail::scope_exit([&] {
  394. svr.stop();
  395. t.join();
  396. ASSERT_FALSE(svr.is_running());
  397. });
  398. svr.wait_until_ready();
  399. Client cli(HOST, PORT);
  400. ASSERT_TRUE(cli.is_valid());
  401. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  402. auto res = cli.Get(original);
  403. ASSERT_TRUE(res);
  404. // Expect the echoed target to exactly match the original path (order
  405. // preserved)
  406. EXPECT_EQ(res->body, original);
  407. }
  408. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  409. string chineseCharacters = U8("中国語");
  410. string russianCharacters = U8("дом");
  411. string brazilianCharacters = U8("óculos");
  412. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  413. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  414. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  415. "%D0%B4%D0%BE%D0%BC");
  416. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  417. }
  418. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  419. string unescapedCharacters = "-_.!~*'()";
  420. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  421. }
  422. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  423. string reservedCharacters = ";,/?:@&=+$";
  424. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  425. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  426. }
  427. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  428. string chineseCharacters = U8("中国語");
  429. string russianCharacters = U8("дом");
  430. string brazilianCharacters = U8("óculos");
  431. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  432. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  433. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  434. "%D0%B4%D0%BE%D0%BC");
  435. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  436. }
  437. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  438. // Issue #2082 use case: encoding path component with ampersand
  439. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  440. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  441. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  442. }
  443. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  444. string unescapedCharacters = "-_.!~*'()";
  445. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  446. }
  447. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  448. string reservedCharacters = ";,/?:@&=+$#";
  449. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  450. }
  451. TEST(EncodeUriTest, TestUTF8Characters) {
  452. string chineseCharacters = U8("中国語");
  453. string russianCharacters = U8("дом");
  454. string brazilianCharacters = U8("óculos");
  455. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  456. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  457. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  458. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  459. }
  460. TEST(EncodeUriTest, TestCompleteUri) {
  461. string uri =
  462. "https://example.com/path/to/resource?query=value&param=test#fragment";
  463. EXPECT_EQ(
  464. httplib::encode_uri(uri),
  465. "https://example.com/path/to/resource?query=value&param=test#fragment");
  466. }
  467. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  468. string uri =
  469. "https://example.com/path with spaces/file name.html?q=hello world";
  470. EXPECT_EQ(httplib::encode_uri(uri),
  471. "https://example.com/path%20with%20spaces/"
  472. "file%20name.html?q=hello%20world");
  473. }
  474. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  475. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  476. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  477. }
  478. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  479. string unescapedCharacters = "-_.!~*'()";
  480. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  481. }
  482. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  483. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  484. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  485. string encodedBrazilian = "%C3%B3culos";
  486. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  487. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  488. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  489. }
  490. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  491. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  492. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  493. "Piri Tommy Villiers - on & on");
  494. }
  495. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  496. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  497. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  498. }
  499. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  500. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  501. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  502. }
  503. TEST(DecodeUriTest, TestUTF8Characters) {
  504. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  505. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  506. string encodedBrazilian = "%C3%B3culos";
  507. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  508. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  509. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  510. }
  511. TEST(DecodeUriTest, TestCompleteUri) {
  512. string encodedUri = "https://example.com/path%20with%20spaces/"
  513. "file%20name.html?q=hello%20world";
  514. EXPECT_EQ(
  515. httplib::decode_uri(encodedUri),
  516. "https://example.com/path with spaces/file name.html?q=hello world");
  517. }
  518. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  519. string original =
  520. "https://example.com/path with spaces/file name.html?q=hello world";
  521. string encoded = httplib::encode_uri(original);
  522. string decoded = httplib::decode_uri(encoded);
  523. EXPECT_EQ(decoded, original);
  524. }
  525. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  526. string original = "Piri Tommy Villiers - on & on";
  527. string encoded = httplib::encode_uri_component(original);
  528. string decoded = httplib::decode_uri_component(encoded);
  529. EXPECT_EQ(decoded, original);
  530. }
  531. TEST(TrimTests, TrimStringTests) {
  532. EXPECT_EQ("abc", detail::trim_copy("abc"));
  533. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  534. EXPECT_TRUE(detail::trim_copy("").empty());
  535. }
  536. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  537. // Simple case without quality values
  538. std::vector<std::string> result1;
  539. EXPECT_TRUE(detail::parse_accept_header(
  540. "text/html,application/json,text/plain", result1));
  541. EXPECT_EQ(result1.size(), 3U);
  542. EXPECT_EQ(result1[0], "text/html");
  543. EXPECT_EQ(result1[1], "application/json");
  544. EXPECT_EQ(result1[2], "text/plain");
  545. // With quality values
  546. std::vector<std::string> result2;
  547. EXPECT_TRUE(detail::parse_accept_header(
  548. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  549. EXPECT_EQ(result2.size(), 3U);
  550. EXPECT_EQ(result2[0], "application/json"); // highest q value
  551. EXPECT_EQ(result2[1], "text/html");
  552. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  553. }
  554. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  555. // Mixed with and without quality values
  556. std::vector<std::string> result;
  557. EXPECT_TRUE(detail::parse_accept_header(
  558. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  559. EXPECT_EQ(result.size(), 3U);
  560. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  561. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  562. EXPECT_EQ(result[2], "application/json"); // q=0.5
  563. }
  564. TEST(ParseAcceptHeaderTest, EdgeCases) {
  565. // Empty header
  566. std::vector<std::string> empty_result;
  567. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  568. EXPECT_TRUE(empty_result.empty());
  569. // Single type
  570. std::vector<std::string> single_result;
  571. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  572. EXPECT_EQ(single_result.size(), 1U);
  573. EXPECT_EQ(single_result[0], "application/json");
  574. // Wildcard types
  575. std::vector<std::string> wildcard_result;
  576. EXPECT_TRUE(detail::parse_accept_header(
  577. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  578. EXPECT_EQ(wildcard_result.size(), 3U);
  579. EXPECT_EQ(wildcard_result[0], "application/json");
  580. EXPECT_EQ(wildcard_result[1], "text/*");
  581. EXPECT_EQ(wildcard_result[2], "*/*");
  582. }
  583. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  584. // Common browser Accept header
  585. std::vector<std::string> browser_result;
  586. EXPECT_TRUE(
  587. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  588. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  589. browser_result));
  590. EXPECT_EQ(browser_result.size(), 6U);
  591. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  592. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  593. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  594. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  595. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  596. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  597. // API client header
  598. std::vector<std::string> api_result;
  599. EXPECT_TRUE(detail::parse_accept_header(
  600. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  601. api_result));
  602. EXPECT_EQ(api_result.size(), 3U);
  603. EXPECT_EQ(api_result[0], "application/json");
  604. EXPECT_EQ(api_result[1], "application/xml");
  605. EXPECT_EQ(api_result[2], "text/plain");
  606. }
  607. TEST(ParseAcceptHeaderTest, SpecialCases) {
  608. // Quality value with 3 decimal places
  609. std::vector<std::string> decimal_result;
  610. EXPECT_TRUE(detail::parse_accept_header(
  611. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  612. EXPECT_EQ(decimal_result.size(), 2U);
  613. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  614. EXPECT_EQ(decimal_result[1], "text/html");
  615. // Zero quality (should still be included but with lowest priority)
  616. std::vector<std::string> zero_q_result;
  617. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  618. zero_q_result));
  619. EXPECT_EQ(zero_q_result.size(), 2U);
  620. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  621. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  622. // No spaces around commas
  623. std::vector<std::string> no_space_result;
  624. EXPECT_TRUE(detail::parse_accept_header(
  625. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  626. no_space_result));
  627. EXPECT_EQ(no_space_result.size(), 3U);
  628. EXPECT_EQ(no_space_result[0], "text/html");
  629. EXPECT_EQ(no_space_result[1], "application/json");
  630. EXPECT_EQ(no_space_result[2], "text/plain");
  631. }
  632. TEST(ParseAcceptHeaderTest, InvalidCases) {
  633. std::vector<std::string> result;
  634. // Invalid quality value (> 1.0)
  635. EXPECT_FALSE(
  636. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  637. // Invalid quality value (< 0.0)
  638. EXPECT_FALSE(
  639. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  640. // Invalid quality value (not a number)
  641. EXPECT_FALSE(detail::parse_accept_header(
  642. "text/html;q=invalid,application/json", result));
  643. // Empty quality value
  644. EXPECT_FALSE(
  645. detail::parse_accept_header("text/html;q=,application/json", result));
  646. // Invalid media type format (no slash and not wildcard)
  647. EXPECT_FALSE(
  648. detail::parse_accept_header("invalidtype,application/json", result));
  649. // Empty media type
  650. result.clear();
  651. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  652. // Only commas
  653. result.clear();
  654. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  655. // Valid cases should still work
  656. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  657. EXPECT_EQ(result.size(), 1U);
  658. EXPECT_EQ(result[0], "*/*");
  659. EXPECT_TRUE(detail::parse_accept_header("*", result));
  660. EXPECT_EQ(result.size(), 1U);
  661. EXPECT_EQ(result[0], "*");
  662. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  663. EXPECT_EQ(result.size(), 1U);
  664. EXPECT_EQ(result[0], "text/*");
  665. }
  666. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  667. Server svr;
  668. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  669. EXPECT_EQ(req.accept_content_types.size(), 3U);
  670. EXPECT_EQ(req.accept_content_types[0], "application/json");
  671. EXPECT_EQ(req.accept_content_types[1], "text/html");
  672. EXPECT_EQ(req.accept_content_types[2], "*/*");
  673. res.set_content("ok", "text/plain");
  674. });
  675. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  676. EXPECT_TRUE(false);
  677. res.set_content("bad request", "text/plain");
  678. });
  679. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  680. auto se = detail::scope_exit([&] {
  681. svr.stop();
  682. listen_thread.join();
  683. ASSERT_FALSE(svr.is_running());
  684. });
  685. svr.wait_until_ready();
  686. Client cli("localhost", PORT);
  687. {
  688. auto res =
  689. cli.Get("/accept_ok",
  690. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  691. ASSERT_TRUE(res);
  692. EXPECT_EQ(StatusCode::OK_200, res->status);
  693. }
  694. {
  695. auto res = cli.Get("/accept_bad_request",
  696. {{"Accept", "text/html;q=abc,application/json"}});
  697. ASSERT_TRUE(res);
  698. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  699. }
  700. }
  701. TEST(DivideTest, DivideStringTests) {
  702. auto divide = [](const std::string &str, char d) {
  703. std::string lhs;
  704. std::string rhs;
  705. detail::divide(str, d,
  706. [&](const char *lhs_data, std::size_t lhs_size,
  707. const char *rhs_data, std::size_t rhs_size) {
  708. lhs.assign(lhs_data, lhs_size);
  709. rhs.assign(rhs_data, rhs_size);
  710. });
  711. return std::make_pair(std::move(lhs), std::move(rhs));
  712. };
  713. {
  714. const auto res = divide("", '=');
  715. EXPECT_EQ(res.first, "");
  716. EXPECT_EQ(res.second, "");
  717. }
  718. {
  719. const auto res = divide("=", '=');
  720. EXPECT_EQ(res.first, "");
  721. EXPECT_EQ(res.second, "");
  722. }
  723. {
  724. const auto res = divide(" ", '=');
  725. EXPECT_EQ(res.first, " ");
  726. EXPECT_EQ(res.second, "");
  727. }
  728. {
  729. const auto res = divide("a", '=');
  730. EXPECT_EQ(res.first, "a");
  731. EXPECT_EQ(res.second, "");
  732. }
  733. {
  734. const auto res = divide("a=", '=');
  735. EXPECT_EQ(res.first, "a");
  736. EXPECT_EQ(res.second, "");
  737. }
  738. {
  739. const auto res = divide("=b", '=');
  740. EXPECT_EQ(res.first, "");
  741. EXPECT_EQ(res.second, "b");
  742. }
  743. {
  744. const auto res = divide("a=b", '=');
  745. EXPECT_EQ(res.first, "a");
  746. EXPECT_EQ(res.second, "b");
  747. }
  748. {
  749. const auto res = divide("a=b=", '=');
  750. EXPECT_EQ(res.first, "a");
  751. EXPECT_EQ(res.second, "b=");
  752. }
  753. {
  754. const auto res = divide("a=b=c", '=');
  755. EXPECT_EQ(res.first, "a");
  756. EXPECT_EQ(res.second, "b=c");
  757. }
  758. }
  759. TEST(SplitTest, ParseQueryString) {
  760. string s = "key1=val1&key2=val2&key3=val3";
  761. Params dic;
  762. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  763. [&](const char *b, const char *e) {
  764. string key, val;
  765. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  766. if (key.empty()) {
  767. key.assign(b2, e2);
  768. } else {
  769. val.assign(b2, e2);
  770. }
  771. });
  772. dic.emplace(key, val);
  773. });
  774. EXPECT_EQ("val1", dic.find("key1")->second);
  775. EXPECT_EQ("val2", dic.find("key2")->second);
  776. EXPECT_EQ("val3", dic.find("key3")->second);
  777. }
  778. TEST(SplitTest, ParseInvalidQueryTests) {
  779. {
  780. string s = " ";
  781. Params dict;
  782. detail::parse_query_text(s, dict);
  783. EXPECT_TRUE(dict.empty());
  784. }
  785. {
  786. string s = " = =";
  787. Params dict;
  788. detail::parse_query_text(s, dict);
  789. EXPECT_TRUE(dict.empty());
  790. }
  791. }
  792. TEST(ParseQueryTest, ParseQueryString) {
  793. {
  794. std::string s = "key1=val1&key2=val2&key3=val3";
  795. Params dic;
  796. detail::parse_query_text(s, dic);
  797. EXPECT_EQ("val1", dic.find("key1")->second);
  798. EXPECT_EQ("val2", dic.find("key2")->second);
  799. EXPECT_EQ("val3", dic.find("key3")->second);
  800. }
  801. {
  802. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  803. Params dic;
  804. detail::parse_query_text(s, dic);
  805. EXPECT_EQ("", dic.find("key1")->second);
  806. EXPECT_EQ("val1", dic.find("key2")->second);
  807. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  808. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  809. }
  810. }
  811. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  812. Params dic;
  813. EXPECT_EQ(detail::params_to_query_str(dic), "");
  814. dic.emplace("key1", "val1");
  815. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  816. dic.emplace("key2", "val2");
  817. dic.emplace("key3", "val3");
  818. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  819. }
  820. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  821. string content_type = "multipart/form-data; boundary=something";
  822. string boundary;
  823. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  824. EXPECT_TRUE(ret);
  825. EXPECT_EQ(boundary, "something");
  826. }
  827. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  828. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  829. string boundary;
  830. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  831. EXPECT_TRUE(ret);
  832. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  833. }
  834. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  835. string content_type =
  836. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  837. string boundary;
  838. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  839. EXPECT_TRUE(ret);
  840. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  841. }
  842. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  843. string content_type =
  844. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  845. string boundary;
  846. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  847. EXPECT_TRUE(ret);
  848. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  849. }
  850. TEST(GetHeaderValueTest, DefaultValue) {
  851. Headers headers = {{"Dummy", "Dummy"}};
  852. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  853. EXPECT_STREQ("text/plain", val);
  854. }
  855. TEST(GetHeaderValueTest, DefaultValueInt) {
  856. Headers headers = {{"Dummy", "Dummy"}};
  857. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  858. EXPECT_EQ(100ull, val);
  859. }
  860. TEST(GetHeaderValueTest, RegularValue) {
  861. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  862. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  863. EXPECT_STREQ("text/html", val);
  864. }
  865. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  866. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  867. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  868. EXPECT_STREQ("text/html", val);
  869. }
  870. TEST(GetHeaderValueTest, SetContent) {
  871. Response res;
  872. res.set_content("html", "text/html");
  873. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  874. res.set_content("text", "text/plain");
  875. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  876. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  877. }
  878. TEST(GetHeaderValueTest, RegularValueInt) {
  879. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  880. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  881. EXPECT_EQ(100ull, val);
  882. }
  883. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  884. Headers headers = {{"Content-Length", "x"}};
  885. auto is_invalid_value = false;
  886. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  887. is_invalid_value);
  888. EXPECT_EQ(0ull, val);
  889. EXPECT_TRUE(is_invalid_value);
  890. }
  891. TEST(GetHeaderValueTest, Range) {
  892. {
  893. Headers headers = {make_range_header({{1, -1}})};
  894. auto val = detail::get_header_value(headers, "Range", 0, 0);
  895. EXPECT_STREQ("bytes=1-", val);
  896. }
  897. {
  898. Headers headers = {make_range_header({{-1, 1}})};
  899. auto val = detail::get_header_value(headers, "Range", 0, 0);
  900. EXPECT_STREQ("bytes=-1", val);
  901. }
  902. {
  903. Headers headers = {make_range_header({{1, 10}})};
  904. auto val = detail::get_header_value(headers, "Range", 0, 0);
  905. EXPECT_STREQ("bytes=1-10", val);
  906. }
  907. {
  908. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  909. auto val = detail::get_header_value(headers, "Range", 0, 0);
  910. EXPECT_STREQ("bytes=1-10, 100-", val);
  911. }
  912. {
  913. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  914. auto val = detail::get_header_value(headers, "Range", 0, 0);
  915. EXPECT_STREQ("bytes=1-10, 100-200", val);
  916. }
  917. {
  918. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  919. auto val = detail::get_header_value(headers, "Range", 0, 0);
  920. EXPECT_STREQ("bytes=0-0, -1", val);
  921. }
  922. }
  923. TEST(ParseHeaderValueTest, Range) {
  924. {
  925. Ranges ranges;
  926. auto ret = detail::parse_range_header("bytes=1-", ranges);
  927. EXPECT_TRUE(ret);
  928. EXPECT_EQ(1u, ranges.size());
  929. EXPECT_EQ(1u, ranges[0].first);
  930. EXPECT_EQ(-1, ranges[0].second);
  931. }
  932. {
  933. Ranges ranges;
  934. auto ret = detail::parse_range_header("bytes=-1", ranges);
  935. EXPECT_TRUE(ret);
  936. EXPECT_EQ(1u, ranges.size());
  937. EXPECT_EQ(-1, ranges[0].first);
  938. EXPECT_EQ(1u, ranges[0].second);
  939. }
  940. {
  941. Ranges ranges;
  942. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  943. EXPECT_TRUE(ret);
  944. EXPECT_EQ(1u, ranges.size());
  945. EXPECT_EQ(1u, ranges[0].first);
  946. EXPECT_EQ(10u, ranges[0].second);
  947. }
  948. {
  949. Ranges ranges;
  950. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  951. EXPECT_FALSE(ret);
  952. }
  953. {
  954. Ranges ranges;
  955. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  956. EXPECT_TRUE(ret);
  957. EXPECT_EQ(2u, ranges.size());
  958. EXPECT_EQ(1u, ranges[0].first);
  959. EXPECT_EQ(10u, ranges[0].second);
  960. EXPECT_EQ(100u, ranges[1].first);
  961. EXPECT_EQ(-1, ranges[1].second);
  962. }
  963. {
  964. Ranges ranges;
  965. auto ret =
  966. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  967. EXPECT_TRUE(ret);
  968. EXPECT_EQ(3u, ranges.size());
  969. EXPECT_EQ(1u, ranges[0].first);
  970. EXPECT_EQ(10u, ranges[0].second);
  971. EXPECT_EQ(100u, ranges[1].first);
  972. EXPECT_EQ(200u, ranges[1].second);
  973. EXPECT_EQ(300u, ranges[2].first);
  974. EXPECT_EQ(400u, ranges[2].second);
  975. }
  976. {
  977. Ranges ranges;
  978. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  979. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  980. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  981. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  982. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  983. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  984. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  985. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  986. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  987. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  988. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  989. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  990. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  991. EXPECT_TRUE(ranges.empty());
  992. }
  993. }
  994. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  995. Request req;
  996. req.set_header("Accept-Encoding", "gzip");
  997. Response res;
  998. res.set_header("Content-Type", "text/plain");
  999. auto ret = detail::encoding_type(req, res);
  1000. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1001. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1002. #else
  1003. EXPECT_TRUE(ret == detail::EncodingType::None);
  1004. #endif
  1005. }
  1006. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1007. Request req;
  1008. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1009. Response res;
  1010. res.set_header("Content-Type", "text/plain");
  1011. auto ret = detail::encoding_type(req, res);
  1012. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1013. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1014. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1015. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1016. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1017. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1018. #else
  1019. EXPECT_TRUE(ret == detail::EncodingType::None);
  1020. #endif
  1021. }
  1022. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1023. Request req;
  1024. req.set_header("Accept-Encoding",
  1025. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1026. Response res;
  1027. res.set_header("Content-Type", "text/plain");
  1028. auto ret = detail::encoding_type(req, res);
  1029. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1030. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1031. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1032. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1033. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1034. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1035. #else
  1036. EXPECT_TRUE(ret == detail::EncodingType::None);
  1037. #endif
  1038. }
  1039. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1040. // All supported encodings rejected with q=0 should return None
  1041. Request req;
  1042. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1043. Response res;
  1044. res.set_header("Content-Type", "text/plain");
  1045. auto ret = detail::encoding_type(req, res);
  1046. EXPECT_TRUE(ret == detail::EncodingType::None);
  1047. }
  1048. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1049. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1050. Request req;
  1051. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1052. Response res;
  1053. res.set_header("Content-Type", "text/plain");
  1054. auto ret = detail::encoding_type(req, res);
  1055. EXPECT_TRUE(ret == detail::EncodingType::None);
  1056. }
  1057. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1058. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1059. Request req;
  1060. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1061. Response res;
  1062. res.set_header("Content-Type", "text/plain");
  1063. auto ret = detail::encoding_type(req, res);
  1064. EXPECT_TRUE(ret == detail::EncodingType::None);
  1065. }
  1066. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1067. // RFC 7231: Accept-Encoding values are case-insensitive
  1068. Request req;
  1069. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1070. Response res;
  1071. res.set_header("Content-Type", "text/plain");
  1072. auto ret = detail::encoding_type(req, res);
  1073. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1074. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1075. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1076. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1077. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1078. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1079. #else
  1080. EXPECT_TRUE(ret == detail::EncodingType::None);
  1081. #endif
  1082. }
  1083. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1084. // q value should determine priority, not hardcoded order
  1085. Request req;
  1086. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1087. Response res;
  1088. res.set_header("Content-Type", "text/plain");
  1089. auto ret = detail::encoding_type(req, res);
  1090. // gzip has highest q=1.0, so it should be selected even though
  1091. // br and zstd are also supported
  1092. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1093. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1094. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1095. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1096. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1097. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1098. #else
  1099. EXPECT_TRUE(ret == detail::EncodingType::None);
  1100. #endif
  1101. }
  1102. TEST(BufferStreamTest, read) {
  1103. detail::BufferStream strm1;
  1104. Stream &strm = strm1;
  1105. EXPECT_EQ(5, strm.write("hello"));
  1106. char buf[512];
  1107. EXPECT_EQ(2, strm.read(buf, 2));
  1108. EXPECT_EQ('h', buf[0]);
  1109. EXPECT_EQ('e', buf[1]);
  1110. EXPECT_EQ(2, strm.read(buf, 2));
  1111. EXPECT_EQ('l', buf[0]);
  1112. EXPECT_EQ('l', buf[1]);
  1113. EXPECT_EQ(1, strm.read(buf, 1));
  1114. EXPECT_EQ('o', buf[0]);
  1115. EXPECT_EQ(0, strm.read(buf, 1));
  1116. }
  1117. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1118. auto host = "www.httpwatch.com";
  1119. auto ip = hosted_at(host);
  1120. EXPECT_EQ("23.96.13.243", ip);
  1121. std::vector<std::string> addrs;
  1122. hosted_at(host, addrs);
  1123. EXPECT_EQ(1u, addrs.size());
  1124. }
  1125. #if 0 // It depends on each test environment...
  1126. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1127. auto host = "www.youtube.com";
  1128. std::vector<std::string> addrs;
  1129. hosted_at(host, addrs);
  1130. EXPECT_EQ(20u, addrs.size());
  1131. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1132. EXPECT_TRUE(it != addrs.end());
  1133. }
  1134. #endif
  1135. class ChunkedEncodingTest : public ::testing::Test {
  1136. protected:
  1137. ChunkedEncodingTest()
  1138. : cli_(HOST, PORT)
  1139. #ifdef CPPHTTPLIB_SSL_ENABLED
  1140. ,
  1141. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1142. #endif
  1143. {
  1144. cli_.set_connection_timeout(2);
  1145. #ifdef CPPHTTPLIB_SSL_ENABLED
  1146. cli_.enable_server_certificate_verification(false);
  1147. #endif
  1148. }
  1149. virtual void SetUp() {
  1150. read_file("./image.jpg", image_data_);
  1151. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1152. res.set_content("Hello World!", "text/plain");
  1153. });
  1154. svr_.Get(
  1155. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1156. res.set_chunked_content_provider(
  1157. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1158. size_t remaining = image_data_.size() - offset;
  1159. if (remaining == 0) {
  1160. sink.done();
  1161. } else {
  1162. constexpr size_t CHUNK_SIZE = 1024;
  1163. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1164. sink.write(&image_data_[offset], send_size);
  1165. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1166. }
  1167. return true;
  1168. });
  1169. });
  1170. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1171. svr_.wait_until_ready();
  1172. }
  1173. virtual void TearDown() {
  1174. svr_.stop();
  1175. if (!request_threads_.empty()) {
  1176. std::this_thread::sleep_for(std::chrono::seconds(1));
  1177. for (auto &t : request_threads_) {
  1178. t.join();
  1179. }
  1180. }
  1181. t_.join();
  1182. }
  1183. #ifdef CPPHTTPLIB_SSL_ENABLED
  1184. SSLClient cli_;
  1185. SSLServer svr_;
  1186. #else
  1187. Client cli_;
  1188. Server svr_;
  1189. #endif
  1190. thread t_;
  1191. std::vector<thread> request_threads_;
  1192. std::string image_data_;
  1193. };
  1194. TEST_F(ChunkedEncodingTest, NormalGet) {
  1195. auto res = cli_.Get("/chunked");
  1196. ASSERT_TRUE(res);
  1197. std::string out;
  1198. read_file("./image.jpg", out);
  1199. EXPECT_EQ(StatusCode::OK_200, res->status);
  1200. EXPECT_EQ(out, res->body);
  1201. }
  1202. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1203. std::string body;
  1204. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1205. body.append(data, data_length);
  1206. return true;
  1207. });
  1208. ASSERT_TRUE(res);
  1209. std::string out;
  1210. read_file("./image.jpg", out);
  1211. EXPECT_EQ(StatusCode::OK_200, res->status);
  1212. EXPECT_EQ(out, body);
  1213. }
  1214. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1215. std::string body;
  1216. auto res = cli_.Get(
  1217. "/chunked",
  1218. [&](const Response &response) {
  1219. EXPECT_EQ(StatusCode::OK_200, response.status);
  1220. return true;
  1221. },
  1222. [&](const char *data, size_t data_length) {
  1223. body.append(data, data_length);
  1224. return true;
  1225. });
  1226. ASSERT_TRUE(res);
  1227. std::string out;
  1228. read_file("./image.jpg", out);
  1229. EXPECT_EQ(StatusCode::OK_200, res->status);
  1230. EXPECT_EQ(out, body);
  1231. }
  1232. TEST(RangeTest, FromHTTPBin_Online) {
  1233. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1234. auto host = "httpcan.org";
  1235. auto path = std::string{"/range/32"};
  1236. #else
  1237. auto host = "nghttp2.org";
  1238. auto path = std::string{"/httpbin/range/32"};
  1239. #endif
  1240. #ifdef CPPHTTPLIB_SSL_ENABLED
  1241. auto port = 443;
  1242. SSLClient cli(host, port);
  1243. #else
  1244. auto port = 80;
  1245. Client cli(host, port);
  1246. #endif
  1247. cli.set_connection_timeout(5);
  1248. {
  1249. auto res = cli.Get(path);
  1250. ASSERT_TRUE(res);
  1251. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1252. EXPECT_EQ(StatusCode::OK_200, res->status);
  1253. }
  1254. {
  1255. Headers headers = {make_range_header({{1, -1}})};
  1256. auto res = cli.Get(path, headers);
  1257. ASSERT_TRUE(res);
  1258. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1259. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1260. }
  1261. {
  1262. Headers headers = {make_range_header({{1, 10}})};
  1263. auto res = cli.Get(path, headers);
  1264. ASSERT_TRUE(res);
  1265. EXPECT_EQ("bcdefghijk", res->body);
  1266. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1267. }
  1268. {
  1269. Headers headers = {make_range_header({{0, 31}})};
  1270. auto res = cli.Get(path, headers);
  1271. ASSERT_TRUE(res);
  1272. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1273. EXPECT_EQ(StatusCode::OK_200, res->status);
  1274. }
  1275. {
  1276. Headers headers = {make_range_header({{0, -1}})};
  1277. auto res = cli.Get(path, headers);
  1278. ASSERT_TRUE(res);
  1279. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1280. EXPECT_EQ(StatusCode::OK_200, res->status);
  1281. }
  1282. {
  1283. Headers headers = {make_range_header({{0, 32}})};
  1284. auto res = cli.Get(path, headers);
  1285. ASSERT_TRUE(res);
  1286. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1287. }
  1288. }
  1289. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1290. auto host = "unresolvableaddress.local";
  1291. auto path = std::string{"/"};
  1292. #ifdef CPPHTTPLIB_SSL_ENABLED
  1293. auto port = 443;
  1294. SSLClient cli(host, port);
  1295. #else
  1296. auto port = 80;
  1297. Client cli(host, port);
  1298. #endif
  1299. cli.set_connection_timeout(1);
  1300. {
  1301. auto res = cli.Get(path);
  1302. ASSERT_FALSE(res);
  1303. }
  1304. std::this_thread::sleep_for(std::chrono::seconds(8));
  1305. }
  1306. TEST(ConnectionErrorTest, InvalidHost) {
  1307. auto host = "-abcde.com";
  1308. #ifdef CPPHTTPLIB_SSL_ENABLED
  1309. auto port = 443;
  1310. SSLClient cli(host, port);
  1311. #else
  1312. auto port = 80;
  1313. Client cli(host, port);
  1314. #endif
  1315. cli.set_connection_timeout(std::chrono::seconds(2));
  1316. auto res = cli.Get("/");
  1317. ASSERT_TRUE(!res);
  1318. EXPECT_EQ(Error::Connection, res.error());
  1319. }
  1320. TEST(ConnectionErrorTest, InvalidHost2) {
  1321. auto host = "httpcan.org/";
  1322. #ifdef CPPHTTPLIB_SSL_ENABLED
  1323. SSLClient cli(host);
  1324. #else
  1325. Client cli(host);
  1326. #endif
  1327. cli.set_connection_timeout(std::chrono::seconds(2));
  1328. auto res = cli.Get("/");
  1329. ASSERT_TRUE(!res);
  1330. EXPECT_EQ(Error::Connection, res.error());
  1331. }
  1332. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1333. auto host = "httpcan.org/";
  1334. #ifdef CPPHTTPLIB_SSL_ENABLED
  1335. SSLClient cli(host);
  1336. #else
  1337. Client cli(host);
  1338. #endif
  1339. cli.set_connection_timeout(std::chrono::seconds(2));
  1340. auto res = cli.Get("/");
  1341. ASSERT_TRUE(!res);
  1342. stringstream s;
  1343. s << "error code: " << res.error();
  1344. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1345. }
  1346. TEST(ConnectionErrorTest, InvalidPort) {
  1347. auto host = "localhost";
  1348. auto port = 44380;
  1349. #ifdef CPPHTTPLIB_SSL_ENABLED
  1350. SSLClient cli(host, port);
  1351. #else
  1352. Client cli(host, port);
  1353. #endif
  1354. cli.set_connection_timeout(std::chrono::seconds(2));
  1355. auto res = cli.Get("/");
  1356. ASSERT_TRUE(!res);
  1357. EXPECT_TRUE(Error::Connection == res.error() ||
  1358. Error::ConnectionTimeout == res.error());
  1359. }
  1360. TEST(ConnectionErrorTest, Timeout_Online) {
  1361. auto host = "google.com";
  1362. #ifdef CPPHTTPLIB_SSL_ENABLED
  1363. auto port = 44380;
  1364. SSLClient cli(host, port);
  1365. #else
  1366. auto port = 8080;
  1367. Client cli(host, port);
  1368. #endif
  1369. cli.set_connection_timeout(std::chrono::seconds(2));
  1370. // only probe one address type so that the error reason
  1371. // correlates to the timed-out IPv4, not the unsupported
  1372. // IPv6 connection attempt
  1373. cli.set_address_family(AF_INET);
  1374. auto res = cli.Get("/");
  1375. ASSERT_TRUE(!res);
  1376. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1377. }
  1378. TEST(CancelTest, NoCancel_Online) {
  1379. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1380. auto host = "httpcan.org";
  1381. auto path = std::string{"/range/32"};
  1382. #else
  1383. auto host = "nghttp2.org";
  1384. auto path = std::string{"/httpbin/range/32"};
  1385. #endif
  1386. #ifdef CPPHTTPLIB_SSL_ENABLED
  1387. auto port = 443;
  1388. SSLClient cli(host, port);
  1389. #else
  1390. auto port = 80;
  1391. Client cli(host, port);
  1392. #endif
  1393. cli.set_connection_timeout(std::chrono::seconds(5));
  1394. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1395. ASSERT_TRUE(res);
  1396. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1397. EXPECT_EQ(StatusCode::OK_200, res->status);
  1398. }
  1399. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1400. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1401. auto host = "httpcan.org";
  1402. auto path = std::string{"/range/32"};
  1403. #else
  1404. auto host = "nghttp2.org";
  1405. auto path = std::string{"/httpbin/range/32"};
  1406. #endif
  1407. #ifdef CPPHTTPLIB_SSL_ENABLED
  1408. auto port = 443;
  1409. SSLClient cli(host, port);
  1410. #else
  1411. auto port = 80;
  1412. Client cli(host, port);
  1413. #endif
  1414. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1415. cli.set_connection_timeout(std::chrono::seconds(5));
  1416. ASSERT_TRUE(!res);
  1417. EXPECT_EQ(Error::Canceled, res.error());
  1418. }
  1419. TEST(CancelTest, WithCancelLargePayload_Online) {
  1420. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1421. auto host = "httpcan.org";
  1422. auto path = std::string{"/range/65536"};
  1423. #else
  1424. auto host = "nghttp2.org";
  1425. auto path = std::string{"/httpbin/range/65536"};
  1426. #endif
  1427. #ifdef CPPHTTPLIB_SSL_ENABLED
  1428. auto port = 443;
  1429. SSLClient cli(host, port);
  1430. #else
  1431. auto port = 80;
  1432. Client cli(host, port);
  1433. #endif
  1434. cli.set_connection_timeout(std::chrono::seconds(5));
  1435. uint32_t count = 0;
  1436. auto res =
  1437. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1438. ASSERT_TRUE(!res);
  1439. EXPECT_EQ(Error::Canceled, res.error());
  1440. }
  1441. TEST(CancelTest, NoCancelPost) {
  1442. Server svr;
  1443. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1444. res.set_content("Hello World!", "text/plain");
  1445. });
  1446. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1447. auto se = detail::scope_exit([&] {
  1448. svr.stop();
  1449. thread.join();
  1450. ASSERT_FALSE(svr.is_running());
  1451. });
  1452. svr.wait_until_ready();
  1453. Client cli(HOST, PORT);
  1454. cli.set_connection_timeout(std::chrono::seconds(5));
  1455. auto res =
  1456. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1457. "application/json", [](uint64_t, uint64_t) { return true; });
  1458. ASSERT_TRUE(res);
  1459. EXPECT_EQ("Hello World!", res->body);
  1460. EXPECT_EQ(StatusCode::OK_200, res->status);
  1461. }
  1462. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1463. Server svr;
  1464. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1465. res.set_content("Hello World!", "text/plain");
  1466. });
  1467. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1468. auto se = detail::scope_exit([&] {
  1469. svr.stop();
  1470. thread.join();
  1471. ASSERT_FALSE(svr.is_running());
  1472. });
  1473. svr.wait_until_ready();
  1474. Client cli(HOST, PORT);
  1475. cli.set_connection_timeout(std::chrono::seconds(5));
  1476. auto res =
  1477. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1478. "application/json", [](uint64_t, uint64_t) { return false; });
  1479. ASSERT_TRUE(!res);
  1480. EXPECT_EQ(Error::Canceled, res.error());
  1481. }
  1482. TEST(CancelTest, WithCancelLargePayloadPost) {
  1483. Server svr;
  1484. svr.set_payload_max_length(200 * 1024 * 1024);
  1485. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1486. res.set_content(LARGE_DATA, "text/plain");
  1487. });
  1488. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1489. auto se = detail::scope_exit([&] {
  1490. svr.stop();
  1491. thread.join();
  1492. ASSERT_FALSE(svr.is_running());
  1493. });
  1494. svr.wait_until_ready();
  1495. Client cli(HOST, PORT);
  1496. cli.set_payload_max_length(200 * 1024 * 1024);
  1497. cli.set_connection_timeout(std::chrono::seconds(5));
  1498. auto res =
  1499. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1500. "application/json", [](uint64_t, uint64_t) { return false; });
  1501. ASSERT_TRUE(!res);
  1502. EXPECT_EQ(Error::Canceled, res.error());
  1503. }
  1504. TEST(CancelTest, NoCancelPut) {
  1505. Server svr;
  1506. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1507. res.set_content("Hello World!", "text/plain");
  1508. });
  1509. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1510. auto se = detail::scope_exit([&] {
  1511. svr.stop();
  1512. thread.join();
  1513. ASSERT_FALSE(svr.is_running());
  1514. });
  1515. svr.wait_until_ready();
  1516. Client cli(HOST, PORT);
  1517. cli.set_connection_timeout(std::chrono::seconds(5));
  1518. auto res =
  1519. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1520. "application/json", [](uint64_t, uint64_t) { return true; });
  1521. ASSERT_TRUE(res);
  1522. EXPECT_EQ("Hello World!", res->body);
  1523. EXPECT_EQ(StatusCode::OK_200, res->status);
  1524. }
  1525. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1526. Server svr;
  1527. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1528. res.set_content("Hello World!", "text/plain");
  1529. });
  1530. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1531. auto se = detail::scope_exit([&] {
  1532. svr.stop();
  1533. thread.join();
  1534. ASSERT_FALSE(svr.is_running());
  1535. });
  1536. svr.wait_until_ready();
  1537. Client cli(HOST, PORT);
  1538. cli.set_connection_timeout(std::chrono::seconds(5));
  1539. auto res =
  1540. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1541. "application/json", [](uint64_t, uint64_t) { return false; });
  1542. ASSERT_TRUE(!res);
  1543. EXPECT_EQ(Error::Canceled, res.error());
  1544. }
  1545. TEST(CancelTest, WithCancelLargePayloadPut) {
  1546. Server svr;
  1547. svr.set_payload_max_length(200 * 1024 * 1024);
  1548. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1549. res.set_content(LARGE_DATA, "text/plain");
  1550. });
  1551. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1552. auto se = detail::scope_exit([&] {
  1553. svr.stop();
  1554. thread.join();
  1555. ASSERT_FALSE(svr.is_running());
  1556. });
  1557. svr.wait_until_ready();
  1558. Client cli(HOST, PORT);
  1559. cli.set_payload_max_length(200 * 1024 * 1024);
  1560. cli.set_connection_timeout(std::chrono::seconds(5));
  1561. auto res =
  1562. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1563. "application/json", [](uint64_t, uint64_t) { return false; });
  1564. ASSERT_TRUE(!res);
  1565. EXPECT_EQ(Error::Canceled, res.error());
  1566. }
  1567. TEST(CancelTest, NoCancelPatch) {
  1568. Server svr;
  1569. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1570. res.set_content("Hello World!", "text/plain");
  1571. });
  1572. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1573. auto se = detail::scope_exit([&] {
  1574. svr.stop();
  1575. thread.join();
  1576. ASSERT_FALSE(svr.is_running());
  1577. });
  1578. svr.wait_until_ready();
  1579. Client cli(HOST, PORT);
  1580. cli.set_connection_timeout(std::chrono::seconds(5));
  1581. auto res =
  1582. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1583. "application/json", [](uint64_t, uint64_t) { return true; });
  1584. ASSERT_TRUE(res);
  1585. EXPECT_EQ("Hello World!", res->body);
  1586. EXPECT_EQ(StatusCode::OK_200, res->status);
  1587. }
  1588. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1589. Server svr;
  1590. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1591. res.set_content("Hello World!", "text/plain");
  1592. });
  1593. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1594. auto se = detail::scope_exit([&] {
  1595. svr.stop();
  1596. thread.join();
  1597. ASSERT_FALSE(svr.is_running());
  1598. });
  1599. svr.wait_until_ready();
  1600. Client cli(HOST, PORT);
  1601. cli.set_connection_timeout(std::chrono::seconds(5));
  1602. auto res =
  1603. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1604. "application/json", [](uint64_t, uint64_t) { return false; });
  1605. ASSERT_TRUE(!res);
  1606. EXPECT_EQ(Error::Canceled, res.error());
  1607. }
  1608. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1609. Server svr;
  1610. svr.set_payload_max_length(200 * 1024 * 1024);
  1611. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1612. res.set_content(LARGE_DATA, "text/plain");
  1613. });
  1614. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1615. auto se = detail::scope_exit([&] {
  1616. svr.stop();
  1617. thread.join();
  1618. ASSERT_FALSE(svr.is_running());
  1619. });
  1620. svr.wait_until_ready();
  1621. Client cli(HOST, PORT);
  1622. cli.set_payload_max_length(200 * 1024 * 1024);
  1623. cli.set_connection_timeout(std::chrono::seconds(5));
  1624. auto res =
  1625. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1626. "application/json", [](uint64_t, uint64_t) { return false; });
  1627. ASSERT_TRUE(!res);
  1628. EXPECT_EQ(Error::Canceled, res.error());
  1629. }
  1630. TEST(CancelTest, NoCancelDelete) {
  1631. Server svr;
  1632. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1633. res.set_content("Hello World!", "text/plain");
  1634. });
  1635. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1636. auto se = detail::scope_exit([&] {
  1637. svr.stop();
  1638. thread.join();
  1639. ASSERT_FALSE(svr.is_running());
  1640. });
  1641. svr.wait_until_ready();
  1642. Client cli(HOST, PORT);
  1643. cli.set_connection_timeout(std::chrono::seconds(5));
  1644. auto res =
  1645. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1646. "application/json", [](uint64_t, uint64_t) { return true; });
  1647. ASSERT_TRUE(res);
  1648. EXPECT_EQ("Hello World!", res->body);
  1649. EXPECT_EQ(StatusCode::OK_200, res->status);
  1650. }
  1651. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1652. Server svr;
  1653. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1654. res.set_content("Hello World!", "text/plain");
  1655. });
  1656. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1657. auto se = detail::scope_exit([&] {
  1658. svr.stop();
  1659. thread.join();
  1660. ASSERT_FALSE(svr.is_running());
  1661. });
  1662. svr.wait_until_ready();
  1663. Client cli(HOST, PORT);
  1664. cli.set_connection_timeout(std::chrono::seconds(5));
  1665. auto res =
  1666. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1667. "application/json", [](uint64_t, uint64_t) { return false; });
  1668. ASSERT_TRUE(!res);
  1669. EXPECT_EQ(Error::Canceled, res.error());
  1670. }
  1671. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1672. Server svr;
  1673. svr.set_payload_max_length(200 * 1024 * 1024);
  1674. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1675. res.set_content(LARGE_DATA, "text/plain");
  1676. });
  1677. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1678. auto se = detail::scope_exit([&] {
  1679. svr.stop();
  1680. thread.join();
  1681. ASSERT_FALSE(svr.is_running());
  1682. });
  1683. svr.wait_until_ready();
  1684. Client cli(HOST, PORT);
  1685. cli.set_payload_max_length(200 * 1024 * 1024);
  1686. cli.set_connection_timeout(std::chrono::seconds(5));
  1687. auto res =
  1688. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1689. "application/json", [](uint64_t, uint64_t) { return false; });
  1690. ASSERT_TRUE(!res);
  1691. EXPECT_EQ(Error::Canceled, res.error());
  1692. }
  1693. static std::string remove_whitespace(const std::string &input) {
  1694. std::string output;
  1695. output.reserve(input.size());
  1696. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1697. [](unsigned char c) { return !std::isspace(c); });
  1698. return output;
  1699. }
  1700. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1701. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1702. auto host = "httpcan.org";
  1703. auto path = std::string{"/basic-auth/hello/world"};
  1704. #else
  1705. auto host = "nghttp2.org";
  1706. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1707. #endif
  1708. #ifdef CPPHTTPLIB_SSL_ENABLED
  1709. auto port = 443;
  1710. SSLClient cli(host, port);
  1711. #else
  1712. auto port = 80;
  1713. Client cli(host, port);
  1714. #endif
  1715. {
  1716. auto res = cli.Get(path);
  1717. ASSERT_TRUE(res);
  1718. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1719. }
  1720. {
  1721. auto res =
  1722. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1723. ASSERT_TRUE(res);
  1724. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1725. remove_whitespace(res->body));
  1726. EXPECT_EQ(StatusCode::OK_200, res->status);
  1727. }
  1728. {
  1729. cli.set_basic_auth("hello", "world");
  1730. auto res = cli.Get(path);
  1731. ASSERT_TRUE(res);
  1732. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1733. remove_whitespace(res->body));
  1734. EXPECT_EQ(StatusCode::OK_200, res->status);
  1735. }
  1736. {
  1737. cli.set_basic_auth("hello", "bad");
  1738. auto res = cli.Get(path);
  1739. ASSERT_TRUE(res);
  1740. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1741. }
  1742. {
  1743. cli.set_basic_auth("bad", "world");
  1744. auto res = cli.Get(path);
  1745. ASSERT_TRUE(res);
  1746. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1747. }
  1748. }
  1749. #ifdef CPPHTTPLIB_SSL_ENABLED
  1750. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1751. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1752. auto host = "httpcan.org";
  1753. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1754. auto paths = std::vector<std::string>{
  1755. "/digest-auth/auth/hello/world/MD5",
  1756. "/digest-auth/auth/hello/world/SHA-256",
  1757. "/digest-auth/auth/hello/world/SHA-512",
  1758. };
  1759. #else
  1760. auto host = "nghttp2.org";
  1761. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1762. auto paths = std::vector<std::string>{
  1763. "/httpbin/digest-auth/auth/hello/world/MD5",
  1764. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1765. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1766. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1767. };
  1768. #endif
  1769. auto port = 443;
  1770. SSLClient cli(host, port);
  1771. {
  1772. auto res = cli.Get(unauth_path);
  1773. ASSERT_TRUE(res);
  1774. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1775. }
  1776. {
  1777. cli.set_digest_auth("hello", "world");
  1778. for (const auto &path : paths) {
  1779. auto res = cli.Get(path.c_str());
  1780. ASSERT_TRUE(res);
  1781. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1782. std::string algo(path.substr(path.rfind('/') + 1));
  1783. EXPECT_EQ(
  1784. remove_whitespace("{\"algorithm\":\"" + algo +
  1785. "\",\"authenticated\":true,\"user\":\"hello\"}\n"),
  1786. remove_whitespace(res->body));
  1787. #else
  1788. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1789. remove_whitespace(res->body));
  1790. #endif
  1791. EXPECT_EQ(StatusCode::OK_200, res->status);
  1792. }
  1793. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1794. cli.set_digest_auth("hello", "bad");
  1795. for (const auto &path : paths) {
  1796. auto res = cli.Get(path.c_str());
  1797. ASSERT_TRUE(res);
  1798. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1799. }
  1800. #endif
  1801. }
  1802. }
  1803. #endif
  1804. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1805. auto host = "google.com";
  1806. auto another_host = "example.com";
  1807. auto wrong_ip = "0.0.0.0";
  1808. #ifdef CPPHTTPLIB_SSL_ENABLED
  1809. SSLClient cli(host);
  1810. #else
  1811. Client cli(host);
  1812. #endif
  1813. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1814. auto res = cli.Get("/");
  1815. ASSERT_TRUE(res);
  1816. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1817. }
  1818. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1819. auto host = "google.com";
  1820. auto wrong_ip = "0.0.0.0";
  1821. #ifdef CPPHTTPLIB_SSL_ENABLED
  1822. SSLClient cli(host);
  1823. #else
  1824. Client cli(host);
  1825. #endif
  1826. cli.set_hostname_addr_map({{host, wrong_ip}});
  1827. auto res = cli.Get("/");
  1828. ASSERT_TRUE(!res);
  1829. EXPECT_EQ(Error::Connection, res.error());
  1830. }
  1831. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1832. auto host = "nghttp2.org";
  1833. #ifdef CPPHTTPLIB_SSL_ENABLED
  1834. SSLClient cli(host);
  1835. #else
  1836. Client cli(host);
  1837. #endif
  1838. cli.set_follow_location(true);
  1839. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1840. ASSERT_TRUE(res);
  1841. EXPECT_EQ(StatusCode::OK_200, res->status);
  1842. }
  1843. TEST(RedirectTest, Redirect_Online) {
  1844. auto host = "nghttp2.org";
  1845. #ifdef CPPHTTPLIB_SSL_ENABLED
  1846. SSLClient cli(host);
  1847. #else
  1848. Client cli(host);
  1849. #endif
  1850. cli.set_follow_location(true);
  1851. auto res = cli.Get("/httpbin/redirect/3");
  1852. ASSERT_TRUE(res);
  1853. EXPECT_EQ(StatusCode::OK_200, res->status);
  1854. }
  1855. TEST(RelativeRedirectTest, Redirect_Online) {
  1856. auto host = "nghttp2.org";
  1857. #ifdef CPPHTTPLIB_SSL_ENABLED
  1858. SSLClient cli(host);
  1859. #else
  1860. Client cli(host);
  1861. #endif
  1862. cli.set_follow_location(true);
  1863. auto res = cli.Get("/httpbin/relative-redirect/3");
  1864. ASSERT_TRUE(res);
  1865. EXPECT_EQ(StatusCode::OK_200, res->status);
  1866. }
  1867. TEST(TooManyRedirectTest, Redirect_Online) {
  1868. auto host = "nghttp2.org";
  1869. #ifdef CPPHTTPLIB_SSL_ENABLED
  1870. SSLClient cli(host);
  1871. #else
  1872. Client cli(host);
  1873. #endif
  1874. cli.set_follow_location(true);
  1875. auto res = cli.Get("/httpbin/redirect/21");
  1876. ASSERT_TRUE(!res);
  1877. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1878. }
  1879. #ifdef CPPHTTPLIB_SSL_ENABLED
  1880. TEST(YahooRedirectTest, Redirect_Online) {
  1881. Client cli("yahoo.com");
  1882. auto res = cli.Get("/");
  1883. ASSERT_TRUE(res);
  1884. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1885. cli.set_follow_location(true);
  1886. res = cli.Get("/");
  1887. ASSERT_TRUE(res);
  1888. EXPECT_EQ(StatusCode::OK_200, res->status);
  1889. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1890. }
  1891. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1892. #define REDIR_HOST "httpbingo.org"
  1893. #define REDIR_PATH "/redirect-to"
  1894. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1895. SSLClient cli(REDIR_HOST);
  1896. cli.set_follow_location(true);
  1897. auto res =
  1898. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1899. ASSERT_TRUE(res);
  1900. EXPECT_EQ(StatusCode::OK_200, res->status);
  1901. }
  1902. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1903. SSLClient cli(REDIR_HOST);
  1904. cli.set_follow_location(true);
  1905. Params params;
  1906. params.emplace("url", "http://example.com");
  1907. params.emplace("status_code", "302");
  1908. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1909. ASSERT_TRUE(res);
  1910. EXPECT_EQ(StatusCode::OK_200, res->status);
  1911. }
  1912. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1913. SSLClient cli(REDIR_HOST);
  1914. cli.set_follow_location(true);
  1915. Params params;
  1916. params.emplace("url", "http://example.com");
  1917. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1918. ASSERT_TRUE(res);
  1919. EXPECT_EQ(StatusCode::OK_200, res->status);
  1920. }
  1921. TEST(UrlWithSpace, Redirect_Online) {
  1922. SSLClient cli("edge.forgecdn.net");
  1923. cli.set_follow_location(true);
  1924. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1925. ASSERT_TRUE(res);
  1926. EXPECT_EQ(StatusCode::OK_200, res->status);
  1927. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1928. }
  1929. #endif
  1930. #if !defined(_WIN32) && !defined(_WIN64)
  1931. TEST(ReceiveSignals, Signal) {
  1932. auto setupSignalHandlers = []() {
  1933. struct sigaction act;
  1934. sigemptyset(&act.sa_mask);
  1935. act.sa_flags = SA_SIGINFO;
  1936. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1937. switch (sig) {
  1938. case SIGINT:
  1939. default: break;
  1940. }
  1941. };
  1942. ::sigaction(SIGINT, &act, nullptr);
  1943. };
  1944. Server svr;
  1945. int port = 0;
  1946. auto thread = std::thread([&]() {
  1947. setupSignalHandlers();
  1948. port = svr.bind_to_any_port(HOST);
  1949. svr.listen_after_bind();
  1950. });
  1951. auto se = detail::scope_exit([&] {
  1952. svr.stop();
  1953. thread.join();
  1954. ASSERT_FALSE(svr.is_running());
  1955. });
  1956. svr.wait_until_ready();
  1957. ASSERT_TRUE(svr.is_running());
  1958. pthread_kill(thread.native_handle(), SIGINT);
  1959. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1960. ASSERT_TRUE(svr.is_running());
  1961. }
  1962. #endif
  1963. TEST(RedirectToDifferentPort, Redirect) {
  1964. Server svr1;
  1965. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1966. res.set_content("Hello World!", "text/plain");
  1967. });
  1968. int svr1_port = 0;
  1969. auto thread1 = std::thread([&]() {
  1970. svr1_port = svr1.bind_to_any_port(HOST);
  1971. svr1.listen_after_bind();
  1972. });
  1973. Server svr2;
  1974. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1975. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1976. });
  1977. int svr2_port = 0;
  1978. auto thread2 = std::thread([&]() {
  1979. svr2_port = svr2.bind_to_any_port(HOST);
  1980. svr2.listen_after_bind();
  1981. });
  1982. auto se = detail::scope_exit([&] {
  1983. svr2.stop();
  1984. thread2.join();
  1985. svr1.stop();
  1986. thread1.join();
  1987. ASSERT_FALSE(svr2.is_running());
  1988. ASSERT_FALSE(svr1.is_running());
  1989. });
  1990. svr1.wait_until_ready();
  1991. svr2.wait_until_ready();
  1992. Client cli("localhost", svr2_port);
  1993. cli.set_follow_location(true);
  1994. auto res = cli.Get("/2");
  1995. ASSERT_TRUE(res);
  1996. EXPECT_EQ(StatusCode::OK_200, res->status);
  1997. EXPECT_EQ("Hello World!", res->body);
  1998. }
  1999. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2000. Server svr;
  2001. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2002. // Port number that overflows int — should not crash
  2003. res.set_redirect("http://localhost:99999999999999999999/target");
  2004. });
  2005. auto port = svr.bind_to_any_port(HOST);
  2006. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2007. auto se = detail::scope_exit([&] {
  2008. svr.stop();
  2009. thread.join();
  2010. ASSERT_FALSE(svr.is_running());
  2011. });
  2012. svr.wait_until_ready();
  2013. Client cli(HOST, port);
  2014. cli.set_follow_location(true);
  2015. auto res = cli.Get("/redir");
  2016. // Should fail gracefully, not crash (no valid response due to bad port)
  2017. EXPECT_FALSE(res);
  2018. }
  2019. TEST(RedirectFromPageWithContent, Redirect) {
  2020. Server svr;
  2021. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2022. res.set_content("___", "text/plain");
  2023. res.set_redirect("/2");
  2024. });
  2025. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2026. res.set_content("Hello World!", "text/plain");
  2027. });
  2028. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2029. auto se = detail::scope_exit([&] {
  2030. svr.stop();
  2031. th.join();
  2032. ASSERT_FALSE(svr.is_running());
  2033. });
  2034. svr.wait_until_ready();
  2035. {
  2036. Client cli("localhost", PORT);
  2037. cli.set_follow_location(true);
  2038. std::string body;
  2039. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2040. body.append(data, data_length);
  2041. return true;
  2042. });
  2043. ASSERT_TRUE(res);
  2044. EXPECT_EQ(StatusCode::OK_200, res->status);
  2045. EXPECT_EQ("Hello World!", body);
  2046. }
  2047. {
  2048. Client cli("localhost", PORT);
  2049. std::string body;
  2050. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2051. body.append(data, data_length);
  2052. return true;
  2053. });
  2054. ASSERT_TRUE(res);
  2055. EXPECT_EQ(StatusCode::Found_302, res->status);
  2056. EXPECT_EQ("___", body);
  2057. }
  2058. }
  2059. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2060. Server svr;
  2061. auto port_str = std::to_string(PORT);
  2062. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2063. auto expected_host = "[::1]:" + port_str;
  2064. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2065. res.set_content("___", "text/plain");
  2066. // res.set_redirect("/2");
  2067. res.set_redirect(redirect_url);
  2068. });
  2069. svr.Get("/2", [&](const Request &req, Response &res) {
  2070. auto host_header = req.headers.find("Host");
  2071. ASSERT_TRUE(host_header != req.headers.end());
  2072. EXPECT_EQ(expected_host, host_header->second);
  2073. res.set_content("Hello World!", "text/plain");
  2074. });
  2075. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2076. auto se = detail::scope_exit([&] {
  2077. svr.stop();
  2078. th.join();
  2079. ASSERT_FALSE(svr.is_running());
  2080. });
  2081. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2082. // actually starts anything, so the condition !svr.is_running() will
  2083. // always remain true, and the loop never stops.
  2084. // This basically counts how many milliseconds have passed since the
  2085. // call to svr.listen(), and if after 5 seconds nothing started yet
  2086. // aborts the test.
  2087. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2088. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2089. ASSERT_LT(milliseconds, 5000U);
  2090. }
  2091. {
  2092. Client cli("::1", PORT);
  2093. cli.set_follow_location(true);
  2094. std::string body;
  2095. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2096. body.append(data, data_length);
  2097. return true;
  2098. });
  2099. ASSERT_TRUE(res);
  2100. EXPECT_EQ(StatusCode::OK_200, res->status);
  2101. EXPECT_EQ("Hello World!", body);
  2102. }
  2103. {
  2104. Client cli("::1", PORT);
  2105. std::string body;
  2106. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2107. body.append(data, data_length);
  2108. return true;
  2109. });
  2110. ASSERT_TRUE(res);
  2111. EXPECT_EQ(StatusCode::Found_302, res->status);
  2112. EXPECT_EQ("___", body);
  2113. }
  2114. }
  2115. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2116. Server svr;
  2117. svr.Get("/foo", [](const Request &req, Response &res) {
  2118. auto a = req.params.find("a");
  2119. if (a != req.params.end()) {
  2120. res.set_content((*a).second, "text/plain");
  2121. res.status = StatusCode::OK_200;
  2122. } else {
  2123. res.status = StatusCode::BadRequest_400;
  2124. }
  2125. });
  2126. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2127. auto se = detail::scope_exit([&] {
  2128. svr.stop();
  2129. thread.join();
  2130. ASSERT_FALSE(svr.is_running());
  2131. });
  2132. svr.wait_until_ready();
  2133. {
  2134. Client cli(HOST, PORT);
  2135. cli.set_path_encode(false);
  2136. auto res = cli.Get("/foo?a=explicitly+encoded");
  2137. ASSERT_TRUE(res);
  2138. EXPECT_EQ(StatusCode::OK_200, res->status);
  2139. // This expects it back with a space, as the `+` won't have been
  2140. // url-encoded, and server-side the params get decoded turning `+`
  2141. // into spaces.
  2142. EXPECT_EQ("explicitly encoded", res->body);
  2143. }
  2144. }
  2145. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2146. Server svr;
  2147. svr.Get("/", [](const Request &req, Response &) {
  2148. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2149. });
  2150. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2151. auto se = detail::scope_exit([&] {
  2152. svr.stop();
  2153. thread.join();
  2154. ASSERT_FALSE(svr.is_running());
  2155. });
  2156. svr.wait_until_ready();
  2157. {
  2158. Client cli(HOST, PORT);
  2159. cli.set_path_encode(false);
  2160. auto res = cli.Get("/?something=%0A");
  2161. ASSERT_TRUE(res);
  2162. EXPECT_EQ(StatusCode::OK_200, res->status);
  2163. }
  2164. }
  2165. TEST(BindServerTest, BindDualStack) {
  2166. Server svr;
  2167. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2168. res.set_content("Hello World!", "text/plain");
  2169. });
  2170. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2171. auto se = detail::scope_exit([&] {
  2172. svr.stop();
  2173. thread.join();
  2174. ASSERT_FALSE(svr.is_running());
  2175. });
  2176. svr.wait_until_ready();
  2177. {
  2178. Client cli("127.0.0.1", PORT);
  2179. auto res = cli.Get("/1");
  2180. ASSERT_TRUE(res);
  2181. EXPECT_EQ(StatusCode::OK_200, res->status);
  2182. EXPECT_EQ("Hello World!", res->body);
  2183. }
  2184. {
  2185. Client cli("::1", PORT);
  2186. auto res = cli.Get("/1");
  2187. ASSERT_TRUE(res);
  2188. EXPECT_EQ(StatusCode::OK_200, res->status);
  2189. EXPECT_EQ("Hello World!", res->body);
  2190. }
  2191. }
  2192. TEST(BindServerTest, BindAndListenSeparately) {
  2193. Server svr;
  2194. int port = svr.bind_to_any_port("0.0.0.0");
  2195. ASSERT_TRUE(svr.is_valid());
  2196. ASSERT_TRUE(port > 0);
  2197. svr.stop();
  2198. }
  2199. #ifdef CPPHTTPLIB_SSL_ENABLED
  2200. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2201. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2202. CLIENT_CA_CERT_DIR);
  2203. int port = svr.bind_to_any_port("0.0.0.0");
  2204. ASSERT_TRUE(svr.is_valid());
  2205. ASSERT_TRUE(port > 0);
  2206. svr.stop();
  2207. }
  2208. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2209. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2210. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2211. int port = svr.bind_to_any_port("0.0.0.0");
  2212. ASSERT_TRUE(svr.is_valid());
  2213. ASSERT_TRUE(port > 0);
  2214. svr.stop();
  2215. }
  2216. TEST(BindServerTest, UpdateCertsPem) {
  2217. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2218. int port = svr.bind_to_any_port("0.0.0.0");
  2219. ASSERT_TRUE(svr.is_valid());
  2220. ASSERT_TRUE(port > 0);
  2221. // Read PEM files
  2222. std::string cert_pem, key_pem, ca_pem;
  2223. read_file(SERVER_CERT_FILE, cert_pem);
  2224. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2225. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2226. // Update server certificates using PEM API
  2227. ASSERT_TRUE(
  2228. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2229. ASSERT_TRUE(svr.is_valid());
  2230. svr.stop();
  2231. }
  2232. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2233. // Start server with client CA (enables client auth)
  2234. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2235. ASSERT_TRUE(svr.is_valid());
  2236. bool handler_called = false;
  2237. svr.Get("/test", [&](const Request &req, Response &res) {
  2238. handler_called = true;
  2239. // Verify client certificate is present
  2240. auto cert = req.peer_cert();
  2241. EXPECT_TRUE(static_cast<bool>(cert));
  2242. res.set_content("ok", "text/plain");
  2243. });
  2244. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2245. auto se = detail::scope_exit([&] {
  2246. svr.stop();
  2247. t.join();
  2248. ASSERT_FALSE(svr.is_running());
  2249. });
  2250. svr.wait_until_ready();
  2251. // Read PEM files
  2252. std::string cert_pem, key_pem, ca_pem;
  2253. read_file(SERVER_CERT_FILE, cert_pem);
  2254. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2255. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2256. // Update server certificates and client CA using PEM API while server running
  2257. ASSERT_TRUE(
  2258. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2259. // Connect with client certificate
  2260. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2261. cli.enable_server_certificate_verification(false);
  2262. cli.set_connection_timeout(30);
  2263. auto res = cli.Get("/test");
  2264. ASSERT_TRUE(res);
  2265. ASSERT_EQ(StatusCode::OK_200, res->status);
  2266. ASSERT_TRUE(handler_called);
  2267. EXPECT_EQ("ok", res->body);
  2268. }
  2269. #endif
  2270. TEST(ErrorHandlerTest, ContentLength) {
  2271. Server svr;
  2272. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2273. res.status = StatusCode::OK_200;
  2274. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2275. "text/html"); // <= Content-Length still 13
  2276. });
  2277. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2278. res.set_content("Hello World!\n", "text/plain");
  2279. res.status = 524;
  2280. });
  2281. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2282. auto se = detail::scope_exit([&] {
  2283. svr.stop();
  2284. thread.join();
  2285. ASSERT_FALSE(svr.is_running());
  2286. });
  2287. svr.wait_until_ready();
  2288. {
  2289. Client cli(HOST, PORT);
  2290. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2291. ASSERT_TRUE(res);
  2292. EXPECT_EQ(StatusCode::OK_200, res->status);
  2293. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2294. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2295. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2296. }
  2297. }
  2298. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2299. TEST(ExceptionTest, WithoutExceptionHandler) {
  2300. Server svr;
  2301. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2302. throw std::runtime_error("exception...");
  2303. });
  2304. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2305. throw std::runtime_error("exception\r\n...");
  2306. });
  2307. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2308. auto se = detail::scope_exit([&] {
  2309. svr.stop();
  2310. listen_thread.join();
  2311. ASSERT_FALSE(svr.is_running());
  2312. });
  2313. svr.wait_until_ready();
  2314. Client cli("localhost", PORT);
  2315. {
  2316. auto res = cli.Get("/exception");
  2317. ASSERT_TRUE(res);
  2318. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2319. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2320. }
  2321. {
  2322. auto res = cli.Get("/unknown");
  2323. ASSERT_TRUE(res);
  2324. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2325. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2326. }
  2327. }
  2328. TEST(ExceptionTest, WithExceptionHandler) {
  2329. Server svr;
  2330. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2331. std::exception_ptr ep) {
  2332. EXPECT_FALSE(ep == nullptr);
  2333. try {
  2334. std::rethrow_exception(ep);
  2335. } catch (std::exception &e) {
  2336. EXPECT_EQ("abc", std::string(e.what()));
  2337. } catch (...) {}
  2338. res.status = StatusCode::InternalServerError_500;
  2339. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2340. "text/html"); // <= Content-Length still 13 at this point
  2341. });
  2342. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2343. res.set_content("Hello World!\n", "text/plain");
  2344. throw std::runtime_error("abc");
  2345. });
  2346. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2347. auto se = detail::scope_exit([&] {
  2348. svr.stop();
  2349. thread.join();
  2350. ASSERT_FALSE(svr.is_running());
  2351. });
  2352. svr.wait_until_ready();
  2353. for (size_t i = 0; i < 10; i++) {
  2354. Client cli(HOST, PORT);
  2355. for (size_t j = 0; j < 100; j++) {
  2356. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2357. ASSERT_TRUE(res);
  2358. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2359. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2360. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2361. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2362. }
  2363. cli.set_keep_alive(true);
  2364. for (size_t j = 0; j < 100; j++) {
  2365. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2366. ASSERT_TRUE(res);
  2367. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2368. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2369. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2370. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2371. }
  2372. }
  2373. }
  2374. TEST(ExceptionTest, AndErrorHandler) {
  2375. Server svr;
  2376. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2377. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2378. });
  2379. svr.set_exception_handler(
  2380. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2381. EXPECT_FALSE(ep == nullptr);
  2382. try {
  2383. std::rethrow_exception(ep);
  2384. } catch (std::exception &e) {
  2385. res.set_content(e.what(), "text/html");
  2386. } catch (...) {}
  2387. res.status = StatusCode::InternalServerError_500;
  2388. });
  2389. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2390. throw std::runtime_error("EXCEPTION");
  2391. });
  2392. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2393. res.set_content("ERROR", "text/html");
  2394. res.status = StatusCode::InternalServerError_500;
  2395. });
  2396. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2397. auto se = detail::scope_exit([&] {
  2398. svr.stop();
  2399. thread.join();
  2400. ASSERT_FALSE(svr.is_running());
  2401. });
  2402. svr.wait_until_ready();
  2403. Client cli(HOST, PORT);
  2404. {
  2405. auto res = cli.Get("/exception");
  2406. ASSERT_TRUE(res);
  2407. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2408. EXPECT_EQ("EXCEPTION", res->body);
  2409. }
  2410. {
  2411. auto res = cli.Get("/error");
  2412. ASSERT_TRUE(res);
  2413. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2414. EXPECT_EQ("ERROR", res->body);
  2415. }
  2416. {
  2417. auto res = cli.Get("/invalid");
  2418. ASSERT_TRUE(res);
  2419. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2420. EXPECT_EQ("NOT_FOUND", res->body);
  2421. }
  2422. }
  2423. #endif
  2424. TEST(NoContentTest, ContentLength) {
  2425. Server svr;
  2426. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2427. res.status = StatusCode::NoContent_204;
  2428. });
  2429. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2430. auto se = detail::scope_exit([&] {
  2431. svr.stop();
  2432. thread.join();
  2433. ASSERT_FALSE(svr.is_running());
  2434. });
  2435. svr.wait_until_ready();
  2436. {
  2437. Client cli(HOST, PORT);
  2438. auto res = cli.Get("/hi");
  2439. ASSERT_TRUE(res);
  2440. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2441. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2442. }
  2443. }
  2444. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2445. #ifdef CPPHTTPLIB_SSL_ENABLED
  2446. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2447. ASSERT_TRUE(svr.is_valid());
  2448. #else
  2449. Server svr;
  2450. #endif
  2451. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2452. if (req.path == "/routing_handler") {
  2453. res.set_header("PRE_ROUTING", "on");
  2454. res.set_content("Routing Handler", "text/plain");
  2455. return httplib::Server::HandlerResponse::Handled;
  2456. }
  2457. return httplib::Server::HandlerResponse::Unhandled;
  2458. });
  2459. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2460. res.set_content("Error", "text/html");
  2461. });
  2462. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2463. if (req.path == "/routing_handler") {
  2464. res.set_header("POST_ROUTING", "on");
  2465. }
  2466. });
  2467. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2468. res.set_content("Hello World!\n", "text/plain");
  2469. });
  2470. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2471. auto se = detail::scope_exit([&] {
  2472. svr.stop();
  2473. thread.join();
  2474. ASSERT_FALSE(svr.is_running());
  2475. });
  2476. svr.wait_until_ready();
  2477. {
  2478. #ifdef CPPHTTPLIB_SSL_ENABLED
  2479. SSLClient cli(HOST, PORT);
  2480. cli.enable_server_certificate_verification(false);
  2481. #else
  2482. Client cli(HOST, PORT);
  2483. #endif
  2484. auto res = cli.Get("/routing_handler");
  2485. ASSERT_TRUE(res);
  2486. EXPECT_EQ(StatusCode::OK_200, res->status);
  2487. EXPECT_EQ("Routing Handler", res->body);
  2488. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2489. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2490. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2491. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2492. }
  2493. {
  2494. #ifdef CPPHTTPLIB_SSL_ENABLED
  2495. SSLClient cli(HOST, PORT);
  2496. cli.enable_server_certificate_verification(false);
  2497. #else
  2498. Client cli(HOST, PORT);
  2499. #endif
  2500. auto res = cli.Get("/hi");
  2501. ASSERT_TRUE(res);
  2502. EXPECT_EQ(StatusCode::OK_200, res->status);
  2503. EXPECT_EQ("Hello World!\n", res->body);
  2504. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2505. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2506. }
  2507. {
  2508. #ifdef CPPHTTPLIB_SSL_ENABLED
  2509. SSLClient cli(HOST, PORT);
  2510. cli.enable_server_certificate_verification(false);
  2511. #else
  2512. Client cli(HOST, PORT);
  2513. #endif
  2514. auto res = cli.Get("/aaa");
  2515. ASSERT_TRUE(res);
  2516. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2517. EXPECT_EQ("Error", res->body);
  2518. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2519. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2520. }
  2521. }
  2522. TEST(RequestHandlerTest, PreRequestHandler) {
  2523. auto route_path = "/user/:user";
  2524. Server svr;
  2525. svr.Get("/hi", [](const Request &, Response &res) {
  2526. res.set_content("hi", "text/plain");
  2527. });
  2528. svr.Get(route_path, [](const Request &req, Response &res) {
  2529. res.set_content(req.path_params.at("user"), "text/plain");
  2530. });
  2531. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2532. if (req.matched_route == route_path) {
  2533. auto user = req.path_params.at("user");
  2534. if (user != "john") {
  2535. res.status = StatusCode::Forbidden_403;
  2536. res.set_content("error", "text/html");
  2537. return Server::HandlerResponse::Handled;
  2538. }
  2539. }
  2540. return Server::HandlerResponse::Unhandled;
  2541. });
  2542. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2543. auto se = detail::scope_exit([&] {
  2544. svr.stop();
  2545. thread.join();
  2546. ASSERT_FALSE(svr.is_running());
  2547. });
  2548. svr.wait_until_ready();
  2549. Client cli(HOST, PORT);
  2550. {
  2551. auto res = cli.Get("/hi");
  2552. ASSERT_TRUE(res);
  2553. EXPECT_EQ(StatusCode::OK_200, res->status);
  2554. EXPECT_EQ("hi", res->body);
  2555. }
  2556. {
  2557. auto res = cli.Get("/user/john");
  2558. ASSERT_TRUE(res);
  2559. EXPECT_EQ(StatusCode::OK_200, res->status);
  2560. EXPECT_EQ("john", res->body);
  2561. }
  2562. {
  2563. auto res = cli.Get("/user/invalid-user");
  2564. ASSERT_TRUE(res);
  2565. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2566. EXPECT_EQ("error", res->body);
  2567. }
  2568. }
  2569. TEST(AnyTest, BasicOperations) {
  2570. // Default construction
  2571. httplib::any a;
  2572. EXPECT_FALSE(a.has_value());
  2573. // Value construction and any_cast (pointer form, noexcept)
  2574. httplib::any b(42);
  2575. EXPECT_TRUE(b.has_value());
  2576. auto *p = httplib::any_cast<int>(&b);
  2577. ASSERT_NE(nullptr, p);
  2578. EXPECT_EQ(42, *p);
  2579. // Type mismatch → nullptr
  2580. auto *q = httplib::any_cast<std::string>(&b);
  2581. EXPECT_EQ(nullptr, q);
  2582. // any_cast (value form) succeeds
  2583. EXPECT_EQ(42, httplib::any_cast<int>(b));
  2584. // any_cast (value form) throws on type mismatch
  2585. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2586. EXPECT_THROW(httplib::any_cast<std::string>(b), httplib::bad_any_cast);
  2587. #endif
  2588. // Copy
  2589. httplib::any c = b;
  2590. EXPECT_EQ(42, httplib::any_cast<int>(c));
  2591. // Move
  2592. httplib::any d = std::move(c);
  2593. EXPECT_EQ(42, httplib::any_cast<int>(d));
  2594. // Assignment with different type
  2595. b = std::string("hello");
  2596. EXPECT_EQ("hello", httplib::any_cast<std::string>(b));
  2597. // Reset
  2598. b.reset();
  2599. EXPECT_FALSE(b.has_value());
  2600. }
  2601. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2602. struct AuthCtx {
  2603. std::string user_id;
  2604. };
  2605. Server svr;
  2606. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2607. res.user_data["auth"] = AuthCtx{"alice"};
  2608. return Server::HandlerResponse::Unhandled;
  2609. });
  2610. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2611. auto *ctx = httplib::any_cast<AuthCtx>(&res.user_data["auth"]);
  2612. ASSERT_NE(nullptr, ctx);
  2613. res.set_content("Hello " + ctx->user_id, "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("/me");
  2624. ASSERT_TRUE(res);
  2625. EXPECT_EQ(StatusCode::OK_200, res->status);
  2626. EXPECT_EQ("Hello alice", res->body);
  2627. }
  2628. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2629. struct RoleCtx {
  2630. std::string role;
  2631. };
  2632. Server svr;
  2633. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2634. res.user_data["role"] = RoleCtx{"admin"};
  2635. return Server::HandlerResponse::Unhandled;
  2636. });
  2637. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2638. auto *ctx = httplib::any_cast<RoleCtx>(&res.user_data["role"]);
  2639. ASSERT_NE(nullptr, ctx);
  2640. res.set_content(ctx->role, "text/plain");
  2641. });
  2642. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2643. auto se = detail::scope_exit([&] {
  2644. svr.stop();
  2645. thread.join();
  2646. ASSERT_FALSE(svr.is_running());
  2647. });
  2648. svr.wait_until_ready();
  2649. Client cli(HOST, PORT);
  2650. auto res = cli.Get("/role");
  2651. ASSERT_TRUE(res);
  2652. EXPECT_EQ(StatusCode::OK_200, res->status);
  2653. EXPECT_EQ("admin", res->body);
  2654. }
  2655. TEST(InvalidFormatTest, StatusCode) {
  2656. Server svr;
  2657. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2658. res.set_content("Hello World!\n", "text/plain");
  2659. res.status = 9999; // Status should be a three-digit code...
  2660. });
  2661. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2662. auto se = detail::scope_exit([&] {
  2663. svr.stop();
  2664. thread.join();
  2665. ASSERT_FALSE(svr.is_running());
  2666. });
  2667. svr.wait_until_ready();
  2668. {
  2669. Client cli(HOST, PORT);
  2670. auto res = cli.Get("/hi");
  2671. ASSERT_FALSE(res);
  2672. }
  2673. }
  2674. TEST(URLFragmentTest, WithFragment) {
  2675. Server svr;
  2676. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2677. EXPECT_TRUE(req.target == "/hi");
  2678. });
  2679. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2680. auto se = detail::scope_exit([&] {
  2681. svr.stop();
  2682. thread.join();
  2683. ASSERT_FALSE(svr.is_running());
  2684. });
  2685. svr.wait_until_ready();
  2686. {
  2687. Client cli(HOST, PORT);
  2688. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2689. EXPECT_TRUE(res);
  2690. EXPECT_EQ(StatusCode::OK_200, res->status);
  2691. res = cli.Get("/hi%23key1=val1=key2=val2");
  2692. EXPECT_TRUE(res);
  2693. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2694. }
  2695. }
  2696. TEST(HeaderWriter, SetHeaderWriter) {
  2697. Server svr;
  2698. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2699. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2700. return detail::write_headers(strm, hdrs);
  2701. });
  2702. svr.Get("/hi", [](const Request &req, Response &res) {
  2703. auto it = req.headers.find("CustomClientHeader");
  2704. EXPECT_TRUE(it != req.headers.end());
  2705. EXPECT_EQ(it->second, "CustomClientValue");
  2706. res.set_content("Hello World!\n", "text/plain");
  2707. });
  2708. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2709. auto se = detail::scope_exit([&] {
  2710. svr.stop();
  2711. thread.join();
  2712. ASSERT_FALSE(svr.is_running());
  2713. });
  2714. svr.wait_until_ready();
  2715. {
  2716. Client cli(HOST, PORT);
  2717. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2718. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2719. return detail::write_headers(strm, hdrs);
  2720. });
  2721. auto res = cli.Get("/hi");
  2722. EXPECT_TRUE(res);
  2723. EXPECT_EQ(StatusCode::OK_200, res->status);
  2724. auto it = res->headers.find("CustomServerHeader");
  2725. EXPECT_TRUE(it != res->headers.end());
  2726. EXPECT_EQ(it->second, "CustomServerValue");
  2727. }
  2728. }
  2729. class ServerTest : public ::testing::Test {
  2730. protected:
  2731. ServerTest()
  2732. : cli_(HOST, PORT)
  2733. #ifdef CPPHTTPLIB_SSL_ENABLED
  2734. ,
  2735. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2736. #endif
  2737. {
  2738. #ifdef CPPHTTPLIB_SSL_ENABLED
  2739. cli_.enable_server_certificate_verification(false);
  2740. #endif
  2741. // Allow LARGE_DATA (100MB) responses
  2742. cli_.set_payload_max_length(200 * 1024 * 1024);
  2743. }
  2744. virtual void SetUp() {
  2745. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2746. svr_.set_payload_max_length(200 * 1024 * 1024);
  2747. svr_.set_mount_point("/", "./www");
  2748. svr_.set_mount_point("/mount", "./www2");
  2749. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2750. svr_.Get("/hi",
  2751. [&](const Request & /*req*/, Response &res) {
  2752. res.set_content("Hello World!", "text/plain");
  2753. })
  2754. .Get("/file_content",
  2755. [&](const Request & /*req*/, Response &res) {
  2756. res.set_file_content("./www/dir/test.html");
  2757. })
  2758. .Get("/file_content_with_content_type",
  2759. [&](const Request & /*req*/, Response &res) {
  2760. res.set_file_content("./www/file", "text/plain");
  2761. })
  2762. .Get("/invalid_file_content",
  2763. [&](const Request & /*req*/, Response &res) {
  2764. res.set_file_content("./www/dir/invalid_file_path");
  2765. })
  2766. .Get("/http_response_splitting",
  2767. [&](const Request & /*req*/, Response &res) {
  2768. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2769. EXPECT_EQ(0U, res.headers.size());
  2770. EXPECT_FALSE(res.has_header("a"));
  2771. res.set_header("a", "1\nSet-Cookie: a=1");
  2772. EXPECT_EQ(0U, res.headers.size());
  2773. EXPECT_FALSE(res.has_header("a"));
  2774. res.set_header("a", "1\rSet-Cookie: a=1");
  2775. EXPECT_EQ(0U, res.headers.size());
  2776. EXPECT_FALSE(res.has_header("a"));
  2777. res.set_header("a\r\nb", "0");
  2778. EXPECT_EQ(0U, res.headers.size());
  2779. EXPECT_FALSE(res.has_header("a"));
  2780. res.set_header("a\rb", "0");
  2781. EXPECT_EQ(0U, res.headers.size());
  2782. EXPECT_FALSE(res.has_header("a"));
  2783. res.set_header("a\nb", "0");
  2784. EXPECT_EQ(0U, res.headers.size());
  2785. EXPECT_FALSE(res.has_header("a"));
  2786. res.set_redirect("1\r\nSet-Cookie: a=1");
  2787. EXPECT_EQ(0U, res.headers.size());
  2788. EXPECT_FALSE(res.has_header("Location"));
  2789. })
  2790. .Get("/slow",
  2791. [&](const Request & /*req*/, Response &res) {
  2792. std::this_thread::sleep_for(std::chrono::seconds(2));
  2793. res.set_content("slow", "text/plain");
  2794. })
  2795. #if 0
  2796. .Post("/slowpost",
  2797. [&](const Request & /*req*/, Response &res) {
  2798. std::this_thread::sleep_for(std::chrono::seconds(2));
  2799. res.set_content("slow", "text/plain");
  2800. })
  2801. #endif
  2802. .Get("/remote_addr",
  2803. [&](const Request &req, Response &res) {
  2804. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2805. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2806. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2807. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2808. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2809. #endif
  2810. res.set_content(req.remote_addr, "text/plain");
  2811. })
  2812. .Get("/local_addr",
  2813. [&](const Request &req, Response &res) {
  2814. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2815. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2816. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2817. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2818. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2819. #endif
  2820. auto local_addr = req.local_addr;
  2821. auto local_port = std::to_string(req.local_port);
  2822. res.set_content(local_addr.append(":").append(local_port),
  2823. "text/plain");
  2824. })
  2825. .Get("/endwith%",
  2826. [&](const Request & /*req*/, Response &res) {
  2827. res.set_content("Hello World!", "text/plain");
  2828. })
  2829. .Get("/a\\+\\+b",
  2830. [&](const Request &req, Response &res) {
  2831. ASSERT_TRUE(req.has_param("a +b"));
  2832. auto val = req.get_param_value("a +b");
  2833. res.set_content(val, "text/plain");
  2834. })
  2835. .Get("/", [&](const Request & /*req*/,
  2836. Response &res) { res.set_redirect("/hi"); })
  2837. .Post("/1",
  2838. [](const Request & /*req*/, Response &res) {
  2839. res.set_redirect("/2", StatusCode::SeeOther_303);
  2840. })
  2841. .Get("/2",
  2842. [](const Request & /*req*/, Response &res) {
  2843. res.set_content("redirected.", "text/plain");
  2844. res.status = StatusCode::OK_200;
  2845. })
  2846. .Post("/person",
  2847. [&](const Request &req, Response &res) {
  2848. if (req.has_param("name") && req.has_param("note")) {
  2849. persons_[req.get_param_value("name")] =
  2850. req.get_param_value("note");
  2851. } else {
  2852. res.status = StatusCode::BadRequest_400;
  2853. }
  2854. })
  2855. .Put("/person",
  2856. [&](const Request &req, Response &res) {
  2857. if (req.has_param("name") && req.has_param("note")) {
  2858. persons_[req.get_param_value("name")] =
  2859. req.get_param_value("note");
  2860. } else {
  2861. res.status = StatusCode::BadRequest_400;
  2862. }
  2863. })
  2864. .Get("/person/(.*)",
  2865. [&](const Request &req, Response &res) {
  2866. string name = req.matches[1];
  2867. if (persons_.find(name) != persons_.end()) {
  2868. auto note = persons_[name];
  2869. res.set_content(note, "text/plain");
  2870. } else {
  2871. res.status = StatusCode::NotFound_404;
  2872. }
  2873. })
  2874. .Delete("/person",
  2875. [&](const Request &req, Response &res) {
  2876. if (req.has_param("name")) {
  2877. string name = req.get_param_value("name");
  2878. if (persons_.find(name) != persons_.end()) {
  2879. persons_.erase(name);
  2880. res.set_content("DELETED", "text/plain");
  2881. } else {
  2882. res.status = StatusCode::NotFound_404;
  2883. }
  2884. } else {
  2885. res.status = StatusCode::BadRequest_400;
  2886. }
  2887. })
  2888. .Post("/x-www-form-urlencoded-json",
  2889. [&](const Request &req, Response &res) {
  2890. auto json = req.get_param_value("json");
  2891. ASSERT_EQ(JSON_DATA, json);
  2892. res.set_content(json, "appliation/json");
  2893. res.status = StatusCode::OK_200;
  2894. })
  2895. .Get("/streamed-chunked",
  2896. [&](const Request & /*req*/, Response &res) {
  2897. res.set_chunked_content_provider(
  2898. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2899. sink.os << "123";
  2900. sink.os << "456";
  2901. sink.os << "789";
  2902. sink.done();
  2903. return true;
  2904. });
  2905. })
  2906. .Get("/streamed-chunked-with-prohibited-trailer",
  2907. [&](const Request & /*req*/, Response &res) {
  2908. auto i = new int(0);
  2909. // Declare both a prohibited trailer (Content-Length) and an
  2910. // allowed one
  2911. res.set_header("Trailer", "Content-Length, X-Allowed");
  2912. res.set_chunked_content_provider(
  2913. "text/plain",
  2914. [i](size_t /*offset*/, DataSink &sink) {
  2915. switch (*i) {
  2916. case 0: sink.os << "123"; break;
  2917. case 1: sink.os << "456"; break;
  2918. case 2: sink.os << "789"; break;
  2919. case 3: {
  2920. sink.done_with_trailer(
  2921. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2922. } break;
  2923. }
  2924. (*i)++;
  2925. return true;
  2926. },
  2927. [i](bool success) {
  2928. EXPECT_TRUE(success);
  2929. delete i;
  2930. });
  2931. })
  2932. .Get("/streamed-chunked2",
  2933. [&](const Request & /*req*/, Response &res) {
  2934. auto i = new int(0);
  2935. res.set_chunked_content_provider(
  2936. "text/plain",
  2937. [i](size_t /*offset*/, DataSink &sink) {
  2938. switch (*i) {
  2939. case 0: sink.os << "123"; break;
  2940. case 1: sink.os << "456"; break;
  2941. case 2: sink.os << "789"; break;
  2942. case 3: sink.done(); break;
  2943. }
  2944. (*i)++;
  2945. return true;
  2946. },
  2947. [i](bool success) {
  2948. EXPECT_TRUE(success);
  2949. delete i;
  2950. });
  2951. })
  2952. .Get("/streamed-chunked-with-trailer",
  2953. [&](const Request & /*req*/, Response &res) {
  2954. auto i = new int(0);
  2955. res.set_header("Trailer", "Dummy1, Dummy2");
  2956. res.set_chunked_content_provider(
  2957. "text/plain",
  2958. [i](size_t /*offset*/, DataSink &sink) {
  2959. switch (*i) {
  2960. case 0: sink.os << "123"; break;
  2961. case 1: sink.os << "456"; break;
  2962. case 2: sink.os << "789"; break;
  2963. case 3: {
  2964. sink.done_with_trailer(
  2965. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2966. } break;
  2967. }
  2968. (*i)++;
  2969. return true;
  2970. },
  2971. [i](bool success) {
  2972. EXPECT_TRUE(success);
  2973. delete i;
  2974. });
  2975. })
  2976. .Get("/streamed",
  2977. [&](const Request & /*req*/, Response &res) {
  2978. res.set_content_provider(
  2979. 6, "text/plain",
  2980. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2981. sink.os << (offset < 3 ? "a" : "b");
  2982. return true;
  2983. });
  2984. })
  2985. .Get("/streamed-with-range",
  2986. [&](const Request &req, Response &res) {
  2987. auto data = new std::string("abcdefg");
  2988. res.set_content_provider(
  2989. data->size(), "text/plain",
  2990. [data](size_t offset, size_t length, DataSink &sink) {
  2991. size_t DATA_CHUNK_SIZE = 4;
  2992. const auto &d = *data;
  2993. auto out_len =
  2994. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2995. auto ret =
  2996. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2997. EXPECT_TRUE(ret);
  2998. return true;
  2999. },
  3000. [data, &req](bool success) {
  3001. EXPECT_EQ(success, !req.has_param("error"));
  3002. delete data;
  3003. });
  3004. })
  3005. .Get("/streamed-cancel",
  3006. [&](const Request & /*req*/, Response &res) {
  3007. res.set_content_provider(
  3008. size_t(-1), "text/plain",
  3009. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3010. sink.os << "data_chunk";
  3011. return true;
  3012. });
  3013. })
  3014. .Get("/regex-with-delimiter",
  3015. [&](const Request &req, Response & /*res*/) {
  3016. ASSERT_TRUE(req.has_param("key"));
  3017. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3018. })
  3019. .Get("/with-range",
  3020. [&](const Request & /*req*/, Response &res) {
  3021. res.set_content("abcdefg", "text/plain");
  3022. })
  3023. .Get("/test-start-time",
  3024. [&](const Request &req, Response & /*res*/) {
  3025. EXPECT_NE(req.start_time_,
  3026. std::chrono::steady_clock::time_point::min());
  3027. })
  3028. .Get("/with-range-customized-response",
  3029. [&](const Request & /*req*/, Response &res) {
  3030. res.status = StatusCode::BadRequest_400;
  3031. res.set_content(JSON_DATA, "application/json");
  3032. })
  3033. .Post("/chunked",
  3034. [&](const Request &req, Response & /*res*/) {
  3035. EXPECT_EQ(req.body, "dechunked post body");
  3036. })
  3037. .Post("/large-chunked",
  3038. [&](const Request &req, Response & /*res*/) {
  3039. std::string expected(6 * 30 * 1024u, 'a');
  3040. EXPECT_EQ(req.body, expected);
  3041. })
  3042. .Post("/multipart",
  3043. [&](const Request &req, Response & /*res*/) {
  3044. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3045. req.form.get_field_count("text2") +
  3046. req.form.get_field_count("file3") +
  3047. req.form.get_field_count("file4"));
  3048. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3049. req.form.get_file_count("file2"));
  3050. ASSERT_TRUE(!req.form.has_file("???"));
  3051. ASSERT_TRUE(!req.form.has_field("???"));
  3052. ASSERT_TRUE(req.body.empty());
  3053. {
  3054. const auto &text = req.form.get_field("text1");
  3055. EXPECT_EQ("text default", text);
  3056. }
  3057. {
  3058. const auto &text = req.form.get_field("text2");
  3059. EXPECT_EQ("aωb", text);
  3060. }
  3061. {
  3062. const auto &file = req.form.get_file("file1");
  3063. EXPECT_EQ("hello.txt", file.filename);
  3064. EXPECT_EQ("text/plain", file.content_type);
  3065. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3066. }
  3067. {
  3068. const auto &file = req.form.get_file("file2");
  3069. EXPECT_EQ("world.json", file.filename);
  3070. EXPECT_EQ("application/json", file.content_type);
  3071. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3072. }
  3073. {
  3074. const auto &text = req.form.get_field("file3");
  3075. EXPECT_EQ(0u, text.size());
  3076. }
  3077. {
  3078. const auto &text = req.form.get_field("file4");
  3079. EXPECT_EQ(0u, text.size());
  3080. }
  3081. })
  3082. .Post("/multipart/multi_file_values",
  3083. [&](const Request &req, Response & /*res*/) {
  3084. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3085. req.form.get_field_count("multi_text1"));
  3086. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3087. ASSERT_TRUE(!req.form.has_file("???"));
  3088. ASSERT_TRUE(!req.form.has_field("???"));
  3089. ASSERT_TRUE(req.body.empty());
  3090. {
  3091. const auto &text = req.form.get_field("text");
  3092. EXPECT_EQ("default text", text);
  3093. }
  3094. {
  3095. const auto &text1_values = req.form.get_fields("multi_text1");
  3096. EXPECT_EQ(2u, text1_values.size());
  3097. EXPECT_EQ("aaaaa", text1_values[0]);
  3098. EXPECT_EQ("bbbbb", text1_values[1]);
  3099. }
  3100. {
  3101. const auto &file1_values = req.form.get_files("multi_file1");
  3102. EXPECT_EQ(2u, file1_values.size());
  3103. auto file1 = file1_values[0];
  3104. EXPECT_EQ(file1.filename, "hello.txt");
  3105. EXPECT_EQ(file1.content_type, "text/plain");
  3106. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3107. auto file2 = file1_values[1];
  3108. EXPECT_EQ(file2.filename, "world.json");
  3109. EXPECT_EQ(file2.content_type, "application/json");
  3110. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3111. }
  3112. })
  3113. .Post("/empty",
  3114. [&](const Request &req, Response &res) {
  3115. EXPECT_EQ(req.body, "");
  3116. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3117. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3118. res.set_content("empty", "text/plain");
  3119. })
  3120. .Post("/empty-no-content-type",
  3121. [&](const Request &req, Response &res) {
  3122. EXPECT_EQ(req.body, "");
  3123. EXPECT_FALSE(req.has_header("Content-Type"));
  3124. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3125. res.set_content("empty-no-content-type", "text/plain");
  3126. })
  3127. .Post("/path-only",
  3128. [&](const Request &req, Response &res) {
  3129. EXPECT_EQ(req.body, "");
  3130. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3131. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3132. res.set_content("path-only", "text/plain");
  3133. })
  3134. .Post("/path-headers-only",
  3135. [&](const Request &req, Response &res) {
  3136. EXPECT_EQ(req.body, "");
  3137. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3138. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3139. EXPECT_EQ("world", req.get_header_value("hello"));
  3140. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3141. res.set_content("path-headers-only", "text/plain");
  3142. })
  3143. .Post("/post-large",
  3144. [&](const Request &req, Response &res) {
  3145. EXPECT_EQ(req.body, LARGE_DATA);
  3146. res.set_content(req.body, "text/plain");
  3147. })
  3148. .Post("/post-loopback",
  3149. [&](const Request &, Response &res,
  3150. ContentReader const &content_reader) {
  3151. std::string body;
  3152. content_reader([&](const char *data, size_t data_length) {
  3153. body.append(data, data_length);
  3154. return true;
  3155. });
  3156. res.set_content(body, "text/plain");
  3157. })
  3158. .Put("/put-loopback",
  3159. [&](const Request &, Response &res,
  3160. ContentReader const &content_reader) {
  3161. std::string body;
  3162. content_reader([&](const char *data, size_t data_length) {
  3163. body.append(data, data_length);
  3164. return true;
  3165. });
  3166. res.set_content(body, "text/plain");
  3167. })
  3168. .Patch("/patch-loopback",
  3169. [&](const Request &, Response &res,
  3170. ContentReader const &content_reader) {
  3171. std::string body;
  3172. content_reader([&](const char *data, size_t data_length) {
  3173. body.append(data, data_length);
  3174. return true;
  3175. });
  3176. res.set_content(body, "text/plain");
  3177. })
  3178. .Put("/empty-no-content-type",
  3179. [&](const Request &req, Response &res) {
  3180. EXPECT_EQ(req.body, "");
  3181. EXPECT_FALSE(req.has_header("Content-Type"));
  3182. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3183. res.set_content("empty-no-content-type", "text/plain");
  3184. })
  3185. .Put("/put",
  3186. [&](const Request &req, Response &res) {
  3187. EXPECT_EQ(req.body, "PUT");
  3188. res.set_content(req.body, "text/plain");
  3189. })
  3190. .Put("/put-large",
  3191. [&](const Request &req, Response &res) {
  3192. EXPECT_EQ(req.body, LARGE_DATA);
  3193. res.set_content(req.body, "text/plain");
  3194. })
  3195. .Patch("/patch",
  3196. [&](const Request &req, Response &res) {
  3197. EXPECT_EQ(req.body, "PATCH");
  3198. res.set_content(req.body, "text/plain");
  3199. })
  3200. .Delete("/delete",
  3201. [&](const Request & /*req*/, Response &res) {
  3202. res.set_content("DELETE", "text/plain");
  3203. })
  3204. .Delete("/delete-body",
  3205. [&](const Request &req, Response &res) {
  3206. EXPECT_EQ(req.body, "content");
  3207. res.set_content(req.body, "text/plain");
  3208. })
  3209. .Options(R"(\*)",
  3210. [&](const Request & /*req*/, Response &res) {
  3211. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3212. })
  3213. .Get("/request-target",
  3214. [&](const Request &req, Response & /*res*/) {
  3215. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3216. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3217. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3218. })
  3219. .Get("/long-query-value",
  3220. [&](const Request &req, Response & /*res*/) {
  3221. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3222. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3223. })
  3224. .Get("/too-long-query-value",
  3225. [&](const Request &req, Response & /*res*/) {
  3226. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3227. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3228. })
  3229. .Get("/array-param",
  3230. [&](const Request &req, Response & /*res*/) {
  3231. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3232. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3233. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3234. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3235. })
  3236. .Post("/validate-no-multiple-headers",
  3237. [&](const Request &req, Response & /*res*/) {
  3238. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3239. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3240. })
  3241. .Post("/content_receiver",
  3242. [&](const Request &req, Response &res,
  3243. const ContentReader &content_reader) {
  3244. if (req.is_multipart_form_data()) {
  3245. std::vector<FormData> items;
  3246. content_reader(
  3247. [&](const FormData &file) {
  3248. items.push_back(file);
  3249. return true;
  3250. },
  3251. [&](const char *data, size_t data_length) {
  3252. items.back().content.append(data, data_length);
  3253. return true;
  3254. });
  3255. EXPECT_EQ(5u, items.size());
  3256. {
  3257. const auto &file = get_file_value(items, "text1");
  3258. EXPECT_TRUE(file.filename.empty());
  3259. EXPECT_EQ("text default", file.content);
  3260. }
  3261. {
  3262. const auto &file = get_file_value(items, "text2");
  3263. EXPECT_TRUE(file.filename.empty());
  3264. EXPECT_EQ("aωb", file.content);
  3265. }
  3266. {
  3267. const auto &file = get_file_value(items, "file1");
  3268. EXPECT_EQ("hello.txt", file.filename);
  3269. EXPECT_EQ("text/plain", file.content_type);
  3270. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3271. }
  3272. {
  3273. const auto &file = get_file_value(items, "file2");
  3274. EXPECT_EQ("world.json", file.filename);
  3275. EXPECT_EQ("application/json", file.content_type);
  3276. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3277. }
  3278. {
  3279. const auto &file = get_file_value(items, "file3");
  3280. EXPECT_TRUE(file.filename.empty());
  3281. EXPECT_EQ("application/octet-stream", file.content_type);
  3282. EXPECT_EQ(0u, file.content.size());
  3283. }
  3284. } else {
  3285. std::string body;
  3286. content_reader([&](const char *data, size_t data_length) {
  3287. EXPECT_EQ(7U, data_length);
  3288. body.append(data, data_length);
  3289. return true;
  3290. });
  3291. EXPECT_EQ(body, "content");
  3292. res.set_content(body, "text/plain");
  3293. }
  3294. })
  3295. .Put("/content_receiver",
  3296. [&](const Request & /*req*/, Response &res,
  3297. const ContentReader &content_reader) {
  3298. std::string body;
  3299. content_reader([&](const char *data, size_t data_length) {
  3300. body.append(data, data_length);
  3301. return true;
  3302. });
  3303. EXPECT_EQ(body, "content");
  3304. res.set_content(body, "text/plain");
  3305. })
  3306. .Patch("/content_receiver",
  3307. [&](const Request & /*req*/, Response &res,
  3308. const ContentReader &content_reader) {
  3309. std::string body;
  3310. content_reader([&](const char *data, size_t data_length) {
  3311. body.append(data, data_length);
  3312. return true;
  3313. });
  3314. EXPECT_EQ(body, "content");
  3315. res.set_content(body, "text/plain");
  3316. })
  3317. .Post("/query-string-and-body",
  3318. [&](const Request &req, Response & /*res*/) {
  3319. ASSERT_TRUE(req.has_param("key"));
  3320. EXPECT_EQ(req.get_param_value("key"), "value");
  3321. EXPECT_EQ(req.body, "content");
  3322. })
  3323. .Get("/last-request",
  3324. [&](const Request &req, Response & /*res*/) {
  3325. EXPECT_EQ("close", req.get_header_value("Connection"));
  3326. })
  3327. .Get(R"(/redirect/(\d+))",
  3328. [&](const Request &req, Response &res) {
  3329. auto num = std::stoi(req.matches[1]) + 1;
  3330. std::string url = "/redirect/" + std::to_string(num);
  3331. res.set_redirect(url);
  3332. })
  3333. .Post("/binary",
  3334. [&](const Request &req, Response &res) {
  3335. EXPECT_EQ(4U, req.body.size());
  3336. EXPECT_EQ("application/octet-stream",
  3337. req.get_header_value("Content-Type"));
  3338. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3339. res.set_content(req.body, "application/octet-stream");
  3340. })
  3341. .Put("/binary",
  3342. [&](const Request &req, Response &res) {
  3343. EXPECT_EQ(4U, req.body.size());
  3344. EXPECT_EQ("application/octet-stream",
  3345. req.get_header_value("Content-Type"));
  3346. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3347. res.set_content(req.body, "application/octet-stream");
  3348. })
  3349. .Patch("/binary",
  3350. [&](const Request &req, Response &res) {
  3351. EXPECT_EQ(4U, req.body.size());
  3352. EXPECT_EQ("application/octet-stream",
  3353. req.get_header_value("Content-Type"));
  3354. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3355. res.set_content(req.body, "application/octet-stream");
  3356. })
  3357. .Delete("/binary",
  3358. [&](const Request &req, Response &res) {
  3359. EXPECT_EQ(4U, req.body.size());
  3360. EXPECT_EQ("application/octet-stream",
  3361. req.get_header_value("Content-Type"));
  3362. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3363. res.set_content(req.body, "application/octet-stream");
  3364. })
  3365. .Get("/issue1772",
  3366. [&](const Request & /*req*/, Response &res) {
  3367. res.status = 401;
  3368. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3369. })
  3370. .Delete("/issue609",
  3371. [](const httplib::Request &, httplib::Response &res,
  3372. const httplib::ContentReader &) {
  3373. res.set_content("ok", "text/plain");
  3374. })
  3375. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3376. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3377. .Get("/compress",
  3378. [&](const Request & /*req*/, Response &res) {
  3379. res.set_content(
  3380. "12345678901234567890123456789012345678901234567890123456789"
  3381. "01234567890123456789012345678901234567890",
  3382. "text/plain");
  3383. })
  3384. .Get("/compress-with-charset",
  3385. [&](const Request & /*req*/, Response &res) {
  3386. res.set_content(
  3387. "12345678901234567890123456789012345678901234567890123456789"
  3388. "01234567890123456789012345678901234567890",
  3389. "application/json; charset=utf-8");
  3390. })
  3391. .Get("/nocompress",
  3392. [&](const Request & /*req*/, Response &res) {
  3393. res.set_content(
  3394. "12345678901234567890123456789012345678901234567890123456789"
  3395. "01234567890123456789012345678901234567890",
  3396. "application/octet-stream");
  3397. })
  3398. .Post("/compress-multipart",
  3399. [&](const Request &req, Response & /*res*/) {
  3400. EXPECT_EQ(2u, req.form.fields.size());
  3401. ASSERT_TRUE(!req.form.has_field("???"));
  3402. {
  3403. const auto &text = req.form.get_field("key1");
  3404. EXPECT_EQ("test", text);
  3405. }
  3406. {
  3407. const auto &text = req.form.get_field("key2");
  3408. EXPECT_EQ("--abcdefg123", text);
  3409. }
  3410. })
  3411. #endif
  3412. ;
  3413. persons_["john"] = "programmer";
  3414. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3415. svr_.wait_until_ready();
  3416. }
  3417. virtual void TearDown() {
  3418. svr_.stop();
  3419. if (!request_threads_.empty()) {
  3420. std::this_thread::sleep_for(std::chrono::seconds(1));
  3421. for (auto &t : request_threads_) {
  3422. t.join();
  3423. }
  3424. }
  3425. t_.join();
  3426. }
  3427. map<string, string> persons_;
  3428. #ifdef CPPHTTPLIB_SSL_ENABLED
  3429. SSLClient cli_;
  3430. SSLServer svr_;
  3431. #else
  3432. Client cli_;
  3433. Server svr_;
  3434. #endif
  3435. thread t_;
  3436. std::vector<thread> request_threads_;
  3437. };
  3438. TEST_F(ServerTest, GetMethod200) {
  3439. auto res = cli_.Get("/hi");
  3440. ASSERT_TRUE(res);
  3441. EXPECT_EQ("HTTP/1.1", res->version);
  3442. EXPECT_EQ(StatusCode::OK_200, res->status);
  3443. EXPECT_EQ("OK", res->reason);
  3444. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3445. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3446. EXPECT_EQ("Hello World!", res->body);
  3447. }
  3448. TEST_F(ServerTest, GetEmptyFile) {
  3449. auto res = cli_.Get("/empty_file");
  3450. ASSERT_TRUE(res);
  3451. EXPECT_EQ(StatusCode::OK_200, res->status);
  3452. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3453. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3454. EXPECT_EQ("", res->body);
  3455. }
  3456. TEST_F(ServerTest, GetFileContent) {
  3457. auto res = cli_.Get("/file_content");
  3458. ASSERT_TRUE(res);
  3459. EXPECT_EQ(StatusCode::OK_200, res->status);
  3460. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3461. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3462. EXPECT_EQ("test.html", res->body);
  3463. }
  3464. TEST_F(ServerTest, GetFileContentWithRange) {
  3465. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3466. ASSERT_TRUE(res);
  3467. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3468. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3469. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3470. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3471. EXPECT_EQ("est", res->body);
  3472. }
  3473. TEST_F(ServerTest, GetFileContentWithContentType) {
  3474. auto res = cli_.Get("/file_content_with_content_type");
  3475. ASSERT_TRUE(res);
  3476. EXPECT_EQ(StatusCode::OK_200, res->status);
  3477. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3478. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3479. EXPECT_EQ("file\n", res->body);
  3480. }
  3481. TEST_F(ServerTest, GetInvalidFileContent) {
  3482. auto res = cli_.Get("/invalid_file_content");
  3483. ASSERT_TRUE(res);
  3484. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3485. }
  3486. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3487. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3488. ASSERT_TRUE(res);
  3489. EXPECT_EQ("HTTP/1.1", res->version);
  3490. EXPECT_EQ(StatusCode::OK_200, res->status);
  3491. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3492. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3493. EXPECT_EQ("Hello World!", res->body);
  3494. }
  3495. TEST_F(ServerTest, GetMethod302) {
  3496. auto res = cli_.Get("/");
  3497. ASSERT_TRUE(res);
  3498. EXPECT_EQ(StatusCode::Found_302, res->status);
  3499. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3500. }
  3501. TEST_F(ServerTest, GetMethod302Redirect) {
  3502. cli_.set_follow_location(true);
  3503. auto res = cli_.Get("/");
  3504. ASSERT_TRUE(res);
  3505. EXPECT_EQ(StatusCode::OK_200, res->status);
  3506. EXPECT_EQ("Hello World!", res->body);
  3507. EXPECT_EQ("/hi", res->location);
  3508. }
  3509. TEST_F(ServerTest, GetMethod404) {
  3510. auto res = cli_.Get("/invalid");
  3511. ASSERT_TRUE(res);
  3512. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3513. }
  3514. TEST_F(ServerTest, HeadMethod200) {
  3515. auto res = cli_.Head("/hi");
  3516. ASSERT_TRUE(res);
  3517. EXPECT_EQ(StatusCode::OK_200, res->status);
  3518. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3519. EXPECT_TRUE(res->body.empty());
  3520. }
  3521. TEST_F(ServerTest, HeadMethod200Static) {
  3522. auto res = cli_.Head("/mount/dir/index.html");
  3523. ASSERT_TRUE(res);
  3524. EXPECT_EQ(StatusCode::OK_200, res->status);
  3525. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3526. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3527. EXPECT_TRUE(res->body.empty());
  3528. }
  3529. TEST_F(ServerTest, HeadMethod404) {
  3530. auto res = cli_.Head("/invalid");
  3531. ASSERT_TRUE(res);
  3532. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3533. EXPECT_TRUE(res->body.empty());
  3534. }
  3535. TEST_F(ServerTest, GetMethodPersonJohn) {
  3536. auto res = cli_.Get("/person/john");
  3537. ASSERT_TRUE(res);
  3538. EXPECT_EQ(StatusCode::OK_200, res->status);
  3539. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3540. EXPECT_EQ("programmer", res->body);
  3541. }
  3542. TEST_F(ServerTest, PostMethod1) {
  3543. auto res = cli_.Get("/person/john1");
  3544. ASSERT_TRUE(res);
  3545. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3546. res = cli_.Post("/person", "name=john1&note=coder",
  3547. "application/x-www-form-urlencoded");
  3548. ASSERT_TRUE(res);
  3549. ASSERT_EQ(StatusCode::OK_200, res->status);
  3550. res = cli_.Get("/person/john1");
  3551. ASSERT_TRUE(res);
  3552. ASSERT_EQ(StatusCode::OK_200, res->status);
  3553. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3554. ASSERT_EQ("coder", res->body);
  3555. }
  3556. TEST_F(ServerTest, PostMethod2) {
  3557. auto res = cli_.Get("/person/john2");
  3558. ASSERT_TRUE(res);
  3559. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3560. Params params;
  3561. params.emplace("name", "john2");
  3562. params.emplace("note", "coder");
  3563. res = cli_.Post("/person", params);
  3564. ASSERT_TRUE(res);
  3565. ASSERT_EQ(StatusCode::OK_200, res->status);
  3566. res = cli_.Get("/person/john2");
  3567. ASSERT_TRUE(res);
  3568. ASSERT_EQ(StatusCode::OK_200, res->status);
  3569. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3570. ASSERT_EQ("coder", res->body);
  3571. }
  3572. TEST_F(ServerTest, PutMethod3) {
  3573. auto res = cli_.Get("/person/john3");
  3574. ASSERT_TRUE(res);
  3575. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3576. Params params;
  3577. params.emplace("name", "john3");
  3578. params.emplace("note", "coder");
  3579. res = cli_.Put("/person", params);
  3580. ASSERT_TRUE(res);
  3581. ASSERT_EQ(StatusCode::OK_200, res->status);
  3582. res = cli_.Get("/person/john3");
  3583. ASSERT_TRUE(res);
  3584. ASSERT_EQ(StatusCode::OK_200, res->status);
  3585. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3586. ASSERT_EQ("coder", res->body);
  3587. }
  3588. TEST_F(ServerTest, DeleteMethod1) {
  3589. auto res = cli_.Get("/person/john4");
  3590. ASSERT_TRUE(res);
  3591. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3592. Params params;
  3593. params.emplace("name", "john4");
  3594. params.emplace("note", "coder");
  3595. res = cli_.Post("/person", params);
  3596. ASSERT_TRUE(res);
  3597. ASSERT_EQ(StatusCode::OK_200, res->status);
  3598. res = cli_.Get("/person/john4");
  3599. ASSERT_TRUE(res);
  3600. ASSERT_EQ(StatusCode::OK_200, res->status);
  3601. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3602. ASSERT_EQ("coder", res->body);
  3603. Params delete_params;
  3604. delete_params.emplace("name", "john4");
  3605. res = cli_.Delete("/person", 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/john4");
  3610. ASSERT_TRUE(res);
  3611. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3612. }
  3613. TEST_F(ServerTest, DeleteMethod2) {
  3614. auto res = cli_.Get("/person/john5");
  3615. ASSERT_TRUE(res);
  3616. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3617. Params params;
  3618. params.emplace("name", "john5");
  3619. params.emplace("note", "developer");
  3620. res = cli_.Post("/person", params);
  3621. ASSERT_TRUE(res);
  3622. ASSERT_EQ(StatusCode::OK_200, res->status);
  3623. res = cli_.Get("/person/john5");
  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("developer", res->body);
  3628. Params delete_params;
  3629. delete_params.emplace("name", "john5");
  3630. Headers headers;
  3631. headers.emplace("Custom-Header", "test-value");
  3632. res = cli_.Delete("/person", headers, delete_params);
  3633. ASSERT_TRUE(res);
  3634. ASSERT_EQ(StatusCode::OK_200, res->status);
  3635. ASSERT_EQ("DELETED", res->body);
  3636. res = cli_.Get("/person/john5");
  3637. ASSERT_TRUE(res);
  3638. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3639. }
  3640. TEST_F(ServerTest, DeleteMethod3) {
  3641. auto res = cli_.Get("/person/john6");
  3642. ASSERT_TRUE(res);
  3643. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3644. Params params;
  3645. params.emplace("name", "john6");
  3646. params.emplace("note", "tester");
  3647. res = cli_.Post("/person", params);
  3648. ASSERT_TRUE(res);
  3649. ASSERT_EQ(StatusCode::OK_200, res->status);
  3650. res = cli_.Get("/person/john6");
  3651. ASSERT_TRUE(res);
  3652. ASSERT_EQ(StatusCode::OK_200, res->status);
  3653. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3654. ASSERT_EQ("tester", res->body);
  3655. Params delete_params;
  3656. delete_params.emplace("name", "john6");
  3657. Headers headers;
  3658. headers.emplace("Custom-Header", "test-value");
  3659. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3660. ASSERT_TRUE(res);
  3661. ASSERT_EQ(StatusCode::OK_200, res->status);
  3662. ASSERT_EQ("DELETED", res->body);
  3663. res = cli_.Get("/person/john6");
  3664. ASSERT_TRUE(res);
  3665. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3666. }
  3667. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3668. Params params;
  3669. params.emplace("json", JSON_DATA);
  3670. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3671. ASSERT_TRUE(res);
  3672. ASSERT_EQ(StatusCode::OK_200, res->status);
  3673. ASSERT_EQ(JSON_DATA, res->body);
  3674. }
  3675. TEST_F(ServerTest, PostEmptyContent) {
  3676. auto res = cli_.Post("/empty", "", "text/plain");
  3677. ASSERT_TRUE(res);
  3678. ASSERT_EQ(StatusCode::OK_200, res->status);
  3679. ASSERT_EQ("empty", res->body);
  3680. }
  3681. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3682. auto res = cli_.Post("/empty-no-content-type");
  3683. ASSERT_TRUE(res);
  3684. ASSERT_EQ(StatusCode::OK_200, res->status);
  3685. ASSERT_EQ("empty-no-content-type", res->body);
  3686. }
  3687. TEST_F(ServerTest, PostPathOnly) {
  3688. auto res = cli_.Post("/path-only");
  3689. ASSERT_TRUE(res);
  3690. ASSERT_EQ(StatusCode::OK_200, res->status);
  3691. ASSERT_EQ("path-only", res->body);
  3692. }
  3693. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3694. auto res = cli_.Post("/path-headers-only",
  3695. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3696. ASSERT_TRUE(res);
  3697. ASSERT_EQ(StatusCode::OK_200, res->status);
  3698. ASSERT_EQ("path-headers-only", res->body);
  3699. }
  3700. TEST_F(ServerTest, PostLarge) {
  3701. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3702. ASSERT_TRUE(res);
  3703. ASSERT_EQ(StatusCode::OK_200, res->status);
  3704. EXPECT_EQ(LARGE_DATA, res->body);
  3705. }
  3706. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3707. auto res = cli_.Put("/empty-no-content-type");
  3708. ASSERT_TRUE(res);
  3709. ASSERT_EQ(StatusCode::OK_200, res->status);
  3710. ASSERT_EQ("empty-no-content-type", res->body);
  3711. }
  3712. TEST_F(ServerTest, GetMethodDir) {
  3713. auto res = cli_.Get("/dir/");
  3714. ASSERT_TRUE(res);
  3715. EXPECT_EQ(StatusCode::OK_200, res->status);
  3716. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3717. auto body = R"(<html>
  3718. <head>
  3719. </head>
  3720. <body>
  3721. <a href="/dir/test.html">Test</a>
  3722. <a href="/hi">hi</a>
  3723. </body>
  3724. </html>
  3725. )";
  3726. EXPECT_EQ(body, res->body);
  3727. }
  3728. TEST_F(ServerTest, GetMethodDirTest) {
  3729. auto res = cli_.Get("/dir/test.html");
  3730. ASSERT_TRUE(res);
  3731. EXPECT_EQ(StatusCode::OK_200, res->status);
  3732. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3733. EXPECT_EQ("test.html", res->body);
  3734. }
  3735. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3736. auto res = cli_.Get("/dir/../dir/test.html");
  3737. ASSERT_TRUE(res);
  3738. EXPECT_EQ(StatusCode::OK_200, res->status);
  3739. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3740. EXPECT_EQ("test.html", res->body);
  3741. }
  3742. TEST_F(ServerTest, GetMethodInvalidPath) {
  3743. auto res = cli_.Get("/dir/../test.html");
  3744. ASSERT_TRUE(res);
  3745. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3746. }
  3747. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3748. auto res = cli_.Get("/../www/dir/test.html");
  3749. ASSERT_TRUE(res);
  3750. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3751. }
  3752. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3753. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3754. ASSERT_TRUE(res);
  3755. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3756. }
  3757. TEST_F(ServerTest, GetMethodDirMountTest) {
  3758. auto res = cli_.Get("/mount/dir/test.html");
  3759. ASSERT_TRUE(res);
  3760. EXPECT_EQ(StatusCode::OK_200, res->status);
  3761. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3762. EXPECT_EQ("test.html", res->body);
  3763. }
  3764. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3765. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3766. ASSERT_TRUE(res);
  3767. EXPECT_EQ(StatusCode::OK_200, res->status);
  3768. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3769. EXPECT_EQ("test.html", res->body);
  3770. }
  3771. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3772. auto res = cli_.Get("/mount/dir/../test.html");
  3773. ASSERT_TRUE(res);
  3774. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3775. }
  3776. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3777. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3778. ASSERT_TRUE(res);
  3779. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3780. }
  3781. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3782. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3783. ASSERT_TRUE(res);
  3784. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3785. }
  3786. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3787. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3788. ASSERT_TRUE(res);
  3789. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3790. }
  3791. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3792. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3793. ASSERT_TRUE(res);
  3794. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3795. }
  3796. TEST_F(ServerTest, PostMethod303) {
  3797. auto res = cli_.Post("/1", "body", "text/plain");
  3798. ASSERT_TRUE(res);
  3799. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3800. EXPECT_EQ("/2", res->get_header_value("Location"));
  3801. }
  3802. TEST_F(ServerTest, PostMethod303Redirect) {
  3803. cli_.set_follow_location(true);
  3804. auto res = cli_.Post("/1", "body", "text/plain");
  3805. ASSERT_TRUE(res);
  3806. EXPECT_EQ(StatusCode::OK_200, res->status);
  3807. EXPECT_EQ("redirected.", res->body);
  3808. EXPECT_EQ("/2", res->location);
  3809. }
  3810. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3811. auto res = cli_.Get("/dir/test.abcde");
  3812. ASSERT_TRUE(res);
  3813. EXPECT_EQ(StatusCode::OK_200, res->status);
  3814. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3815. EXPECT_EQ("abcde", res->body);
  3816. }
  3817. TEST_F(ServerTest, StaticFileRange) {
  3818. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3819. ASSERT_TRUE(res);
  3820. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3821. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3822. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3823. EXPECT_EQ(true, res->has_header("Content-Range"));
  3824. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3825. EXPECT_EQ(std::string("cd"), res->body);
  3826. }
  3827. TEST_F(ServerTest, StaticFileRanges) {
  3828. auto res =
  3829. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3830. ASSERT_TRUE(res);
  3831. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3832. EXPECT_TRUE(
  3833. res->get_header_value("Content-Type")
  3834. .find(
  3835. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3836. 0);
  3837. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3838. }
  3839. TEST_F(ServerTest, StaticFileRangeHead) {
  3840. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3841. ASSERT_TRUE(res);
  3842. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3843. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3844. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3845. EXPECT_EQ(true, res->has_header("Content-Range"));
  3846. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3847. }
  3848. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3849. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3850. ASSERT_TRUE(res);
  3851. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3852. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3853. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3854. EXPECT_EQ(true, res->has_header("Content-Range"));
  3855. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3856. res->get_header_value("Content-Range"));
  3857. EXPECT_EQ("LAST\n", res->body);
  3858. }
  3859. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3860. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3861. ASSERT_TRUE(res);
  3862. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3863. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3864. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3865. EXPECT_EQ(true, res->has_header("Content-Range"));
  3866. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3867. }
  3868. TEST_F(ServerTest, StaticFileBigFile) {
  3869. auto res = cli_.Get("/dir/1MB.txt");
  3870. ASSERT_TRUE(res);
  3871. EXPECT_EQ(StatusCode::OK_200, res->status);
  3872. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3873. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3874. }
  3875. TEST_F(ServerTest, InvalidBaseDirMount) {
  3876. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3877. }
  3878. TEST_F(ServerTest, Binary) {
  3879. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3880. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3881. "application/octet-stream");
  3882. ASSERT_TRUE(res);
  3883. ASSERT_EQ(StatusCode::OK_200, res->status);
  3884. ASSERT_EQ(4U, res->body.size());
  3885. res = cli_.Put("/binary", binary.data(), binary.size(),
  3886. "application/octet-stream");
  3887. ASSERT_TRUE(res);
  3888. ASSERT_EQ(StatusCode::OK_200, res->status);
  3889. ASSERT_EQ(4U, res->body.size());
  3890. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3891. "application/octet-stream");
  3892. ASSERT_TRUE(res);
  3893. ASSERT_EQ(StatusCode::OK_200, res->status);
  3894. ASSERT_EQ(4U, res->body.size());
  3895. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3896. "application/octet-stream");
  3897. ASSERT_TRUE(res);
  3898. ASSERT_EQ(StatusCode::OK_200, res->status);
  3899. ASSERT_EQ(4U, res->body.size());
  3900. }
  3901. TEST_F(ServerTest, BinaryString) {
  3902. auto binary = std::string("\x00\x01\x02\x03", 4);
  3903. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3904. ASSERT_TRUE(res);
  3905. ASSERT_EQ(StatusCode::OK_200, res->status);
  3906. ASSERT_EQ(4U, res->body.size());
  3907. res = cli_.Put("/binary", binary, "application/octet-stream");
  3908. ASSERT_TRUE(res);
  3909. ASSERT_EQ(StatusCode::OK_200, res->status);
  3910. ASSERT_EQ(4U, res->body.size());
  3911. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3912. ASSERT_TRUE(res);
  3913. ASSERT_EQ(StatusCode::OK_200, res->status);
  3914. ASSERT_EQ(4U, res->body.size());
  3915. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3916. ASSERT_TRUE(res);
  3917. ASSERT_EQ(StatusCode::OK_200, res->status);
  3918. ASSERT_EQ(4U, res->body.size());
  3919. }
  3920. TEST_F(ServerTest, EmptyRequest) {
  3921. auto res = cli_.Get("");
  3922. ASSERT_TRUE(!res);
  3923. EXPECT_EQ(Error::Connection, res.error());
  3924. }
  3925. TEST_F(ServerTest, LongRequest) {
  3926. std::string request;
  3927. for (size_t i = 0; i < 545; i++) {
  3928. request += "/TooLongRequest";
  3929. }
  3930. request += "OK";
  3931. auto res = cli_.Get(request.c_str());
  3932. ASSERT_TRUE(res);
  3933. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3934. }
  3935. TEST_F(ServerTest, TooLongRequest) {
  3936. std::string request;
  3937. for (size_t i = 0; i < 546; i++) {
  3938. request += "/TooLongRequest";
  3939. }
  3940. request += "_NG";
  3941. auto start = std::chrono::high_resolution_clock::now();
  3942. cli_.set_keep_alive(true);
  3943. auto res = cli_.Get(request.c_str());
  3944. auto end = std::chrono::high_resolution_clock::now();
  3945. auto elapsed =
  3946. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3947. .count();
  3948. ASSERT_TRUE(res);
  3949. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3950. EXPECT_LE(elapsed, 1000);
  3951. EXPECT_EQ("close", res->get_header_value("Connection"));
  3952. EXPECT_FALSE(cli_.is_socket_open());
  3953. }
  3954. TEST_F(ServerTest, AlmostTooLongRequest) {
  3955. // test for #2046 - URI length check shouldn't include other content on req
  3956. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3957. // leading /, space, HTTP/1.1)
  3958. std::string request =
  3959. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3960. auto res = cli_.Get(request.c_str());
  3961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3962. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3963. }
  3964. TEST_F(ServerTest, LongHeader) {
  3965. Request req;
  3966. req.method = "GET";
  3967. req.path = "/hi";
  3968. std::string host_and_port;
  3969. host_and_port += HOST;
  3970. host_and_port += ":";
  3971. host_and_port += std::to_string(PORT);
  3972. req.headers.emplace("Host", host_and_port.c_str());
  3973. req.headers.emplace("Accept", "*/*");
  3974. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3975. req.headers.emplace(
  3976. "Header-Name",
  3977. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3978. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3979. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3980. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3981. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3982. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3983. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3984. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3985. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3986. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3987. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3988. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3989. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3990. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3991. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3992. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3993. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3994. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3995. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3996. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3997. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3998. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3999. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4000. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4001. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4002. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4003. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4004. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4005. "@@@@@@@@@@@@@@@@");
  4006. auto res = std::make_shared<Response>();
  4007. auto error = Error::Success;
  4008. auto ret = cli_.send(req, *res, error);
  4009. ASSERT_TRUE(ret);
  4010. EXPECT_EQ(StatusCode::OK_200, res->status);
  4011. }
  4012. TEST_F(ServerTest, LongQueryValue) {
  4013. auto start = std::chrono::high_resolution_clock::now();
  4014. cli_.set_keep_alive(true);
  4015. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4016. auto end = std::chrono::high_resolution_clock::now();
  4017. auto elapsed =
  4018. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4019. .count();
  4020. ASSERT_TRUE(res);
  4021. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4022. EXPECT_LE(elapsed, 1000);
  4023. EXPECT_EQ("close", res->get_header_value("Connection"));
  4024. EXPECT_FALSE(cli_.is_socket_open());
  4025. }
  4026. TEST_F(ServerTest, TooLongQueryValue) {
  4027. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4028. ASSERT_FALSE(res);
  4029. EXPECT_EQ(Error::Read, res.error());
  4030. }
  4031. TEST_F(ServerTest, TooLongHeader) {
  4032. Request req;
  4033. req.method = "GET";
  4034. req.path = "/hi";
  4035. std::string host_and_port;
  4036. host_and_port += HOST;
  4037. host_and_port += ":";
  4038. host_and_port += std::to_string(PORT);
  4039. req.headers.emplace("Host", host_and_port.c_str());
  4040. req.headers.emplace("Accept", "*/*");
  4041. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4042. req.headers.emplace(
  4043. "Header-Name",
  4044. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4045. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4046. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4047. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4048. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4049. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4050. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4051. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4052. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4053. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4054. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4055. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4056. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4057. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4058. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4059. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4060. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4061. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4062. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4063. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4064. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4065. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4066. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4067. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4068. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4069. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4070. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4071. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4072. "@@@@@@@@@@@@@@@@@");
  4073. auto res = std::make_shared<Response>();
  4074. auto error = Error::Success;
  4075. auto ret = cli_.send(req, *res, error);
  4076. ASSERT_TRUE(ret);
  4077. EXPECT_EQ(StatusCode::OK_200, res->status);
  4078. }
  4079. TEST_F(ServerTest, HeaderCountAtLimit) {
  4080. // Test with headers just under the 100 limit
  4081. httplib::Headers headers;
  4082. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4083. // This should keep us just under the 100 header limit
  4084. for (int i = 0; i < 95; i++) {
  4085. std::string name = "X-Test-Header-" + std::to_string(i);
  4086. std::string value = "value" + std::to_string(i);
  4087. headers.emplace(name, value);
  4088. }
  4089. // This should work fine as we're under the limit
  4090. auto res = cli_.Get("/hi", headers);
  4091. EXPECT_TRUE(res);
  4092. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4093. }
  4094. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4095. // Test with many headers to exceed the 100 limit
  4096. httplib::Headers headers;
  4097. // Add 150 headers to definitely exceed the 100 limit
  4098. for (int i = 0; i < 150; i++) {
  4099. std::string name = "X-Test-Header-" + std::to_string(i);
  4100. std::string value = "value" + std::to_string(i);
  4101. headers.emplace(name, value);
  4102. }
  4103. // This should fail due to exceeding header count limit
  4104. cli_.set_keep_alive(true);
  4105. auto res = cli_.Get("/hi", headers);
  4106. // The server should respond with 400 Bad Request
  4107. ASSERT_TRUE(res);
  4108. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4109. EXPECT_EQ("close", res->get_header_value("Connection"));
  4110. EXPECT_FALSE(cli_.is_socket_open());
  4111. }
  4112. TEST_F(ServerTest, PercentEncoding) {
  4113. auto res = cli_.Get("/e%6edwith%");
  4114. ASSERT_TRUE(res);
  4115. EXPECT_EQ(StatusCode::OK_200, res->status);
  4116. }
  4117. TEST_F(ServerTest, PercentEncodingUnicode) {
  4118. auto res = cli_.Get("/e%u006edwith%");
  4119. ASSERT_TRUE(res);
  4120. EXPECT_EQ(StatusCode::OK_200, res->status);
  4121. }
  4122. TEST_F(ServerTest, InvalidPercentEncoding) {
  4123. auto res = cli_.Get("/%endwith%");
  4124. ASSERT_TRUE(res);
  4125. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4126. }
  4127. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4128. auto res = cli_.Get("/%uendwith%");
  4129. ASSERT_TRUE(res);
  4130. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4131. }
  4132. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4133. auto res = cli_.Get("/hello?aaa=bbb%");
  4134. ASSERT_TRUE(res);
  4135. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4136. }
  4137. TEST_F(ServerTest, PlusSignEncoding) {
  4138. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4139. ASSERT_TRUE(res);
  4140. EXPECT_EQ(StatusCode::OK_200, res->status);
  4141. EXPECT_EQ("a +b", res->body);
  4142. }
  4143. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4144. // This test simulates a potential DoS attack using many headers
  4145. // to verify our security fix prevents memory exhaustion
  4146. httplib::Headers attack_headers;
  4147. // Attempt to add many headers like an attacker would (200 headers to far
  4148. // exceed limit)
  4149. for (int i = 0; i < 200; i++) {
  4150. std::string name = "X-Attack-Header-" + std::to_string(i);
  4151. std::string value = "attack_payload_" + std::to_string(i);
  4152. attack_headers.emplace(name, value);
  4153. }
  4154. // Try to POST with excessive headers
  4155. cli_.set_keep_alive(true);
  4156. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4157. // Should either fail or return 400 Bad Request due to security limit
  4158. if (res) {
  4159. // If we get a response, it should be 400 Bad Request
  4160. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4161. EXPECT_EQ("close", res->get_header_value("Connection"));
  4162. }
  4163. EXPECT_FALSE(cli_.is_socket_open());
  4164. }
  4165. TEST_F(ServerTest, MultipartFormData) {
  4166. UploadFormDataItems items = {
  4167. {"text1", "text default", "", ""},
  4168. {"text2", "aωb", "", ""},
  4169. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4170. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4171. {"file3", "", "", "application/octet-stream"},
  4172. {"file4", "", "", " application/json tmp-string "}};
  4173. auto res = cli_.Post("/multipart", items);
  4174. ASSERT_TRUE(res);
  4175. EXPECT_EQ(StatusCode::OK_200, res->status);
  4176. }
  4177. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4178. UploadFormDataItems items = {
  4179. {"text", "default text", "", ""},
  4180. {"multi_text1", "aaaaa", "", ""},
  4181. {"multi_text1", "bbbbb", "", ""},
  4182. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4183. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4184. "application/json"},
  4185. };
  4186. auto res = cli_.Post("/multipart/multi_file_values", items);
  4187. ASSERT_TRUE(res);
  4188. EXPECT_EQ(StatusCode::OK_200, res->status);
  4189. }
  4190. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4191. auto res = cli_.Get("/hi");
  4192. ASSERT_TRUE(res);
  4193. EXPECT_EQ(StatusCode::OK_200, res->status);
  4194. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4195. EXPECT_EQ("Hello World!", res->body);
  4196. }
  4197. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4198. Request req;
  4199. req.method = "POST";
  4200. req.path = "/chunked";
  4201. std::string host_and_port;
  4202. host_and_port += HOST;
  4203. host_and_port += ":";
  4204. host_and_port += std::to_string(PORT);
  4205. req.headers.emplace("Host", host_and_port.c_str());
  4206. req.headers.emplace("Accept", "*/*");
  4207. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4208. req.headers.emplace("Content-Type", "text/plain");
  4209. req.headers.emplace("Content-Length", "0");
  4210. req.headers.emplace(
  4211. "Transfer-Encoding",
  4212. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4213. // Client does not chunk, so make a chunked body manually.
  4214. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4215. auto res = std::make_shared<Response>();
  4216. auto error = Error::Success;
  4217. auto ret = cli_.send(req, *res, error);
  4218. ASSERT_TRUE(ret);
  4219. EXPECT_EQ(StatusCode::OK_200, res->status);
  4220. }
  4221. TEST_F(ServerTest, GetStreamed2) {
  4222. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4223. ASSERT_TRUE(res);
  4224. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4225. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4226. EXPECT_EQ(true, res->has_header("Content-Range"));
  4227. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4228. EXPECT_EQ(std::string("ab"), res->body);
  4229. }
  4230. TEST_F(ServerTest, GetStreamed) {
  4231. auto res = cli_.Get("/streamed");
  4232. ASSERT_TRUE(res);
  4233. EXPECT_EQ(StatusCode::OK_200, res->status);
  4234. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4235. EXPECT_EQ(std::string("aaabbb"), res->body);
  4236. }
  4237. TEST_F(ServerTest, GetStreamedWithRange1) {
  4238. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4239. ASSERT_TRUE(res);
  4240. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4241. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4242. EXPECT_EQ(true, res->has_header("Content-Range"));
  4243. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4244. EXPECT_EQ(std::string("def"), res->body);
  4245. }
  4246. TEST_F(ServerTest, GetStreamedWithRange2) {
  4247. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4248. ASSERT_TRUE(res);
  4249. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4250. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4251. EXPECT_EQ(true, res->has_header("Content-Range"));
  4252. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4253. EXPECT_EQ(std::string("bcdefg"), res->body);
  4254. }
  4255. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4256. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4257. ASSERT_TRUE(res);
  4258. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4259. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4260. EXPECT_EQ(true, res->has_header("Content-Range"));
  4261. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4262. EXPECT_EQ(std::string("efg"), res->body);
  4263. }
  4264. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4265. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4266. ASSERT_TRUE(res);
  4267. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4268. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4269. EXPECT_EQ(false, res->has_header("Content-Range"));
  4270. EXPECT_EQ(0U, res->body.size());
  4271. }
  4272. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4273. auto res = cli_.Get("/streamed-with-range",
  4274. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4275. "92233720368547758079223372036854775807"}});
  4276. ASSERT_TRUE(res);
  4277. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4278. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4279. EXPECT_EQ(false, res->has_header("Content-Range"));
  4280. EXPECT_EQ(0U, res->body.size());
  4281. }
  4282. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4283. auto res = cli_.Get(
  4284. "/with-range",
  4285. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4286. {"Accept-Encoding", ""}});
  4287. ASSERT_TRUE(res);
  4288. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4289. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4290. EXPECT_EQ(true, res->has_header("Content-Range"));
  4291. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4292. EXPECT_EQ(std::string("abcdefg"), res->body);
  4293. }
  4294. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4295. auto res = cli_.Get("/with-range", {
  4296. {"Range", "bytes=0-"},
  4297. {"Accept-Encoding", ""},
  4298. });
  4299. ASSERT_TRUE(res);
  4300. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4301. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4302. EXPECT_EQ(true, res->has_header("Content-Range"));
  4303. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4304. EXPECT_EQ(std::string("abcdefg"), res->body);
  4305. }
  4306. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4307. auto res =
  4308. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4309. ASSERT_TRUE(res);
  4310. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4311. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4312. EXPECT_EQ(false, res->has_header("Content-Range"));
  4313. EXPECT_EQ(267U, res->body.size());
  4314. // Check that both range contents are present
  4315. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4316. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4317. // Check that Content-Range headers are present for both ranges
  4318. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4319. std::string::npos);
  4320. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4321. std::string::npos);
  4322. }
  4323. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4324. Ranges ranges;
  4325. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4326. ranges.emplace_back(0, -1);
  4327. }
  4328. auto res =
  4329. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4330. ASSERT_TRUE(res);
  4331. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4332. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4333. EXPECT_EQ(false, res->has_header("Content-Range"));
  4334. EXPECT_EQ(0U, res->body.size());
  4335. }
  4336. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4337. auto res =
  4338. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4339. ASSERT_TRUE(res);
  4340. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4341. EXPECT_EQ(5U, res->body.size());
  4342. // Check that overlapping ranges are coalesced into a single range
  4343. EXPECT_EQ("bcdef", res->body);
  4344. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4345. // Should be single range, not multipart
  4346. EXPECT_TRUE(res->has_header("Content-Range"));
  4347. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4348. }
  4349. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4350. auto res =
  4351. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4352. ASSERT_TRUE(res);
  4353. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4354. EXPECT_EQ(268U, res->body.size());
  4355. // Check that both range contents are present
  4356. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4357. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4358. // Check that Content-Range headers are present for both ranges
  4359. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4360. std::string::npos);
  4361. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4362. std::string::npos);
  4363. }
  4364. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4365. auto res =
  4366. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4367. ASSERT_TRUE(res);
  4368. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4369. EXPECT_EQ(269U, res->body.size());
  4370. // Check that both duplicate range contents are present
  4371. size_t first_abc = res->body.find("abc\r\n");
  4372. EXPECT_TRUE(first_abc != std::string::npos);
  4373. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4374. EXPECT_TRUE(second_abc != std::string::npos);
  4375. // Check that Content-Range headers are present for both ranges
  4376. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4377. EXPECT_TRUE(first_range != std::string::npos);
  4378. size_t second_range =
  4379. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4380. EXPECT_TRUE(second_range != std::string::npos);
  4381. }
  4382. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4383. auto res = cli_.Get("/streamed-with-range?error",
  4384. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4385. ASSERT_TRUE(res);
  4386. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4387. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4388. EXPECT_EQ(false, res->has_header("Content-Range"));
  4389. EXPECT_EQ(0U, res->body.size());
  4390. }
  4391. TEST_F(ServerTest, GetStreamedEndless) {
  4392. uint64_t offset = 0;
  4393. auto res = cli_.Get("/streamed-cancel",
  4394. [&](const char * /*data*/, uint64_t data_length) {
  4395. if (offset < 100) {
  4396. offset += data_length;
  4397. return true;
  4398. }
  4399. return false;
  4400. });
  4401. ASSERT_TRUE(!res);
  4402. EXPECT_EQ(Error::Canceled, res.error());
  4403. }
  4404. TEST_F(ServerTest, ClientStop) {
  4405. std::atomic_size_t count{4};
  4406. std::vector<std::thread> threads;
  4407. for (auto i = count.load(); i != 0; --i) {
  4408. threads.emplace_back([&]() {
  4409. auto res = cli_.Get("/streamed-cancel",
  4410. [&](const char *, uint64_t) { return true; });
  4411. --count;
  4412. ASSERT_TRUE(!res);
  4413. EXPECT_TRUE(res.error() == Error::Canceled ||
  4414. res.error() == Error::Read || res.error() == Error::Write);
  4415. });
  4416. }
  4417. std::this_thread::sleep_for(std::chrono::seconds(2));
  4418. while (count != 0) {
  4419. cli_.stop();
  4420. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4421. }
  4422. for (auto &t : threads) {
  4423. t.join();
  4424. }
  4425. }
  4426. TEST_F(ServerTest, GetWithRange1) {
  4427. auto res = cli_.Get("/with-range", {
  4428. make_range_header({{3, 5}}),
  4429. {"Accept-Encoding", ""},
  4430. });
  4431. ASSERT_TRUE(res);
  4432. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4433. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4434. EXPECT_EQ(true, res->has_header("Content-Range"));
  4435. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4436. EXPECT_EQ(std::string("def"), res->body);
  4437. }
  4438. TEST_F(ServerTest, GetWithRange2) {
  4439. auto res = cli_.Get("/with-range", {
  4440. make_range_header({{1, -1}}),
  4441. {"Accept-Encoding", ""},
  4442. });
  4443. ASSERT_TRUE(res);
  4444. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4445. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4446. EXPECT_EQ(true, res->has_header("Content-Range"));
  4447. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4448. EXPECT_EQ(std::string("bcdefg"), res->body);
  4449. }
  4450. TEST_F(ServerTest, GetWithRange3) {
  4451. auto res = cli_.Get("/with-range", {
  4452. make_range_header({{0, 0}}),
  4453. {"Accept-Encoding", ""},
  4454. });
  4455. ASSERT_TRUE(res);
  4456. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4457. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4458. EXPECT_EQ(true, res->has_header("Content-Range"));
  4459. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4460. EXPECT_EQ(std::string("a"), res->body);
  4461. }
  4462. TEST_F(ServerTest, GetWithRange4) {
  4463. auto res = cli_.Get("/with-range", {
  4464. make_range_header({{-1, 2}}),
  4465. {"Accept-Encoding", ""},
  4466. });
  4467. ASSERT_TRUE(res);
  4468. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4469. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4470. EXPECT_EQ(true, res->has_header("Content-Range"));
  4471. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4472. EXPECT_EQ(std::string("fg"), res->body);
  4473. }
  4474. TEST_F(ServerTest, GetWithRange5) {
  4475. auto res = cli_.Get("/with-range", {
  4476. make_range_header({{0, 5}}),
  4477. {"Accept-Encoding", ""},
  4478. });
  4479. ASSERT_TRUE(res);
  4480. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4481. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4482. EXPECT_EQ(true, res->has_header("Content-Range"));
  4483. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4484. EXPECT_EQ(std::string("abcdef"), res->body);
  4485. }
  4486. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4487. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4488. ASSERT_TRUE(res);
  4489. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4490. }
  4491. TEST_F(ServerTest, GetWithRangeMultipart) {
  4492. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4493. ASSERT_TRUE(res);
  4494. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4495. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4496. EXPECT_EQ(false, res->has_header("Content-Range"));
  4497. EXPECT_EQ(267U, res->body.size());
  4498. }
  4499. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4500. auto res =
  4501. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4502. ASSERT_TRUE(res);
  4503. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4504. }
  4505. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4506. auto res = cli_.Get("/with-range-customized-response",
  4507. {{make_range_header({{1, 2}})}});
  4508. ASSERT_TRUE(res);
  4509. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4510. EXPECT_EQ(true, res->has_header("Content-Length"));
  4511. EXPECT_EQ(false, res->has_header("Content-Range"));
  4512. EXPECT_EQ(JSON_DATA, res->body);
  4513. }
  4514. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4515. auto res = cli_.Get("/with-range-customized-response",
  4516. {{make_range_header({{1, 2}, {4, 5}})}});
  4517. ASSERT_TRUE(res);
  4518. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4519. EXPECT_EQ(true, res->has_header("Content-Length"));
  4520. EXPECT_EQ(false, res->has_header("Content-Range"));
  4521. EXPECT_EQ(JSON_DATA, res->body);
  4522. }
  4523. TEST_F(ServerTest, Issue1772) {
  4524. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4525. ASSERT_TRUE(res);
  4526. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4527. }
  4528. TEST_F(ServerTest, Issue609) {
  4529. auto res = cli_.Delete("/issue609");
  4530. ASSERT_TRUE(res);
  4531. EXPECT_EQ(StatusCode::OK_200, res->status);
  4532. EXPECT_EQ(std::string("ok"), res->body);
  4533. }
  4534. TEST_F(ServerTest, GetStreamedChunked) {
  4535. auto res = cli_.Get("/streamed-chunked");
  4536. ASSERT_TRUE(res);
  4537. EXPECT_EQ(StatusCode::OK_200, res->status);
  4538. EXPECT_EQ(std::string("123456789"), res->body);
  4539. }
  4540. TEST_F(ServerTest, GetStreamedChunked2) {
  4541. auto res = cli_.Get("/streamed-chunked2");
  4542. ASSERT_TRUE(res);
  4543. EXPECT_EQ(StatusCode::OK_200, res->status);
  4544. EXPECT_EQ(std::string("123456789"), res->body);
  4545. }
  4546. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4547. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4548. ASSERT_TRUE(res);
  4549. EXPECT_EQ(StatusCode::OK_200, res->status);
  4550. EXPECT_EQ(std::string("123456789"), res->body);
  4551. EXPECT_TRUE(res->has_header("Trailer"));
  4552. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4553. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4554. // Trailers are now stored separately from headers (security fix)
  4555. EXPECT_EQ(2U, res->trailers.size());
  4556. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4557. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4558. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4559. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4560. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4561. // Verify trailers are NOT in headers (security verification)
  4562. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4563. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4564. }
  4565. TEST_F(ServerTest, LargeChunkedPost) {
  4566. Request req;
  4567. req.method = "POST";
  4568. req.path = "/large-chunked";
  4569. std::string host_and_port;
  4570. host_and_port += HOST;
  4571. host_and_port += ":";
  4572. host_and_port += std::to_string(PORT);
  4573. req.headers.emplace("Host", host_and_port.c_str());
  4574. req.headers.emplace("Accept", "*/*");
  4575. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4576. req.headers.emplace("Content-Type", "text/plain");
  4577. req.headers.emplace("Content-Length", "0");
  4578. req.headers.emplace("Transfer-Encoding", "chunked");
  4579. std::string long_string(30 * 1024u, 'a');
  4580. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4581. // Attempt to make a large enough post to exceed OS buffers, to test that
  4582. // the server handles short reads if the full chunk data isn't available.
  4583. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4584. auto res = std::make_shared<Response>();
  4585. auto error = Error::Success;
  4586. auto ret = cli_.send(req, *res, error);
  4587. ASSERT_TRUE(ret);
  4588. EXPECT_EQ(StatusCode::OK_200, res->status);
  4589. }
  4590. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4591. auto res = cli_.Get("/remote_addr");
  4592. ASSERT_TRUE(res);
  4593. EXPECT_EQ(StatusCode::OK_200, res->status);
  4594. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4595. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4596. }
  4597. TEST_F(ServerTest, GetMethodLocalAddr) {
  4598. auto res = cli_.Get("/local_addr");
  4599. ASSERT_TRUE(res);
  4600. EXPECT_EQ(StatusCode::OK_200, res->status);
  4601. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4602. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4603. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4604. }
  4605. TEST_F(ServerTest, HTTPResponseSplitting) {
  4606. auto res = cli_.Get("/http_response_splitting");
  4607. ASSERT_TRUE(res);
  4608. EXPECT_EQ(StatusCode::OK_200, res->status);
  4609. }
  4610. TEST_F(ServerTest, SlowRequest) {
  4611. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4612. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4613. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4614. }
  4615. #if 0
  4616. TEST_F(ServerTest, SlowPost) {
  4617. char buffer[64 * 1024];
  4618. memset(buffer, 0x42, sizeof(buffer));
  4619. auto res = cli_.Post(
  4620. "/slowpost", 64 * 1024 * 1024,
  4621. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4622. auto ret = sink.write(buffer, sizeof(buffer));
  4623. EXPECT_TRUE(ret);
  4624. return true;
  4625. },
  4626. "text/plain");
  4627. ASSERT_TRUE(res);
  4628. EXPECT_EQ(StatusCode::OK_200, res->status);
  4629. }
  4630. TEST_F(ServerTest, SlowPostFail) {
  4631. char buffer[64 * 1024];
  4632. memset(buffer, 0x42, sizeof(buffer));
  4633. cli_.set_write_timeout(std::chrono::seconds(0));
  4634. auto res = cli_.Post(
  4635. "/slowpost", 64 * 1024 * 1024,
  4636. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4637. sink.write(buffer, sizeof(buffer));
  4638. return true;
  4639. },
  4640. "text/plain");
  4641. ASSERT_TRUE(!res);
  4642. EXPECT_EQ(Error::Write, res.error());
  4643. }
  4644. #endif
  4645. TEST_F(ServerTest, Put) {
  4646. auto res = cli_.Put("/put", "PUT", "text/plain");
  4647. ASSERT_TRUE(res);
  4648. EXPECT_EQ(StatusCode::OK_200, res->status);
  4649. EXPECT_EQ("PUT", res->body);
  4650. }
  4651. TEST_F(ServerTest, PutWithContentProvider) {
  4652. auto res = cli_.Put(
  4653. "/put", 3,
  4654. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4655. sink.os << "PUT";
  4656. return true;
  4657. },
  4658. "text/plain");
  4659. ASSERT_TRUE(res);
  4660. EXPECT_EQ(StatusCode::OK_200, res->status);
  4661. EXPECT_EQ("PUT", res->body);
  4662. }
  4663. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4664. auto res = cli_.Post(
  4665. "/post", 42,
  4666. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4667. return false;
  4668. },
  4669. "text/plain");
  4670. ASSERT_TRUE(!res);
  4671. EXPECT_EQ(Error::Canceled, res.error());
  4672. }
  4673. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4674. auto res = cli_.Put(
  4675. "/put",
  4676. [](size_t /*offset*/, DataSink &sink) {
  4677. sink.os << "PUT";
  4678. sink.done();
  4679. return true;
  4680. },
  4681. "text/plain");
  4682. ASSERT_TRUE(res);
  4683. EXPECT_EQ(StatusCode::OK_200, res->status);
  4684. EXPECT_EQ("PUT", res->body);
  4685. }
  4686. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4687. auto res = cli_.Post(
  4688. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4689. "text/plain");
  4690. ASSERT_TRUE(!res);
  4691. EXPECT_EQ(Error::Canceled, res.error());
  4692. }
  4693. TEST_F(ServerTest, PostLoopBack) {
  4694. std::string body;
  4695. auto res = cli_.Post(
  4696. "/post-loopback", 9,
  4697. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4698. EXPECT_EQ(9u, length);
  4699. sink.write("123", 3);
  4700. sink.write("456", 3);
  4701. sink.write("789", 3);
  4702. return true;
  4703. },
  4704. "text/plain",
  4705. [&body](const char *data, size_t data_length) {
  4706. body.append(data, data_length);
  4707. return true;
  4708. });
  4709. ASSERT_TRUE(res);
  4710. EXPECT_EQ(StatusCode::OK_200, res->status);
  4711. EXPECT_EQ("123456789", body);
  4712. }
  4713. TEST_F(ServerTest, PutLoopBack) {
  4714. std::string body;
  4715. auto res = cli_.Put(
  4716. "/put-loopback", 9,
  4717. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4718. EXPECT_EQ(9u, length);
  4719. sink.write("123", 3);
  4720. sink.write("456", 3);
  4721. sink.write("789", 3);
  4722. return true;
  4723. },
  4724. "text/plain",
  4725. [&body](const char *data, size_t data_length) {
  4726. body.append(data, data_length);
  4727. return true;
  4728. });
  4729. ASSERT_TRUE(res);
  4730. EXPECT_EQ(StatusCode::OK_200, res->status);
  4731. EXPECT_EQ("123456789", body);
  4732. }
  4733. TEST_F(ServerTest, PatchLoopBack) {
  4734. std::string body;
  4735. auto res = cli_.Patch(
  4736. "/patch-loopback", 9,
  4737. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4738. EXPECT_EQ(9u, length);
  4739. sink.write("123", 3);
  4740. sink.write("456", 3);
  4741. sink.write("789", 3);
  4742. return true;
  4743. },
  4744. "text/plain",
  4745. [&body](const char *data, size_t data_length) {
  4746. body.append(data, data_length);
  4747. return true;
  4748. });
  4749. ASSERT_TRUE(res);
  4750. EXPECT_EQ(StatusCode::OK_200, res->status);
  4751. EXPECT_EQ("123456789", body);
  4752. }
  4753. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4754. std::string body;
  4755. auto res = cli_.Post(
  4756. "/post-loopback",
  4757. [](size_t /*offset*/, DataSink &sink) {
  4758. sink.write("123", 3);
  4759. sink.write("456", 3);
  4760. sink.write("789", 3);
  4761. sink.done();
  4762. return true;
  4763. },
  4764. "text/plain",
  4765. [&body](const char *data, size_t data_length) {
  4766. body.append(data, data_length);
  4767. return true;
  4768. });
  4769. ASSERT_TRUE(res);
  4770. EXPECT_EQ(StatusCode::OK_200, res->status);
  4771. EXPECT_EQ("123456789", body);
  4772. }
  4773. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4774. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4775. cli_.set_compress(true);
  4776. auto res = cli_.Put(
  4777. "/put", 3,
  4778. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4779. sink.os << "PUT";
  4780. return true;
  4781. },
  4782. "text/plain");
  4783. ASSERT_TRUE(res);
  4784. EXPECT_EQ(StatusCode::OK_200, res->status);
  4785. EXPECT_EQ("PUT", res->body);
  4786. }
  4787. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4788. cli_.set_compress(true);
  4789. auto res = cli_.Post(
  4790. "/post", 42,
  4791. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4792. return false;
  4793. },
  4794. "text/plain");
  4795. ASSERT_TRUE(!res);
  4796. EXPECT_EQ(Error::Canceled, res.error());
  4797. }
  4798. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4799. cli_.set_compress(true);
  4800. auto res = cli_.Put(
  4801. "/put",
  4802. [](size_t /*offset*/, DataSink &sink) {
  4803. sink.os << "PUT";
  4804. sink.done();
  4805. return true;
  4806. },
  4807. "text/plain");
  4808. ASSERT_TRUE(res);
  4809. EXPECT_EQ(StatusCode::OK_200, res->status);
  4810. EXPECT_EQ("PUT", res->body);
  4811. }
  4812. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4813. cli_.set_compress(true);
  4814. auto res = cli_.Post(
  4815. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4816. "text/plain");
  4817. ASSERT_TRUE(!res);
  4818. EXPECT_EQ(Error::Canceled, res.error());
  4819. }
  4820. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4821. cli_.set_compress(true);
  4822. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4823. ASSERT_TRUE(res);
  4824. EXPECT_EQ(StatusCode::OK_200, res->status);
  4825. EXPECT_EQ(LARGE_DATA, res->body);
  4826. }
  4827. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4828. #ifdef CPPHTTPLIB_SSL_ENABLED
  4829. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4830. Client cli(s.c_str());
  4831. cli.enable_server_certificate_verification(false);
  4832. #else
  4833. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4834. Client cli(s.c_str());
  4835. #endif
  4836. cli.set_compress(true);
  4837. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4838. ASSERT_TRUE(res);
  4839. EXPECT_EQ(StatusCode::OK_200, res->status);
  4840. EXPECT_EQ(LARGE_DATA, res->body);
  4841. // The compressed size should be less than a 10th of the original. May vary
  4842. // depending on the zlib library.
  4843. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4844. static_cast<uint64_t>(10 * 1024 * 1024));
  4845. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4846. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  4847. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  4848. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4849. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4850. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  4851. #endif
  4852. }
  4853. TEST_F(ServerTest, PutContentWithDeflate) {
  4854. cli_.set_compress(false);
  4855. Headers headers;
  4856. headers.emplace("Content-Encoding", "deflate");
  4857. // PUT in deflate format:
  4858. auto res = cli_.Put("/put", headers,
  4859. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4860. ASSERT_TRUE(res);
  4861. EXPECT_EQ(StatusCode::OK_200, res->status);
  4862. EXPECT_EQ("PUT", res->body);
  4863. }
  4864. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4865. Headers headers;
  4866. headers.emplace("Accept-Encoding", "gzip, deflate");
  4867. auto res = cli_.Get("/streamed-chunked", headers);
  4868. ASSERT_TRUE(res);
  4869. EXPECT_EQ(StatusCode::OK_200, res->status);
  4870. EXPECT_EQ(std::string("123456789"), res->body);
  4871. }
  4872. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4873. Headers headers;
  4874. headers.emplace("Accept-Encoding", "gzip, deflate");
  4875. auto res = cli_.Get("/streamed-chunked2", headers);
  4876. ASSERT_TRUE(res);
  4877. EXPECT_EQ(StatusCode::OK_200, res->status);
  4878. EXPECT_EQ(std::string("123456789"), res->body);
  4879. }
  4880. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4881. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4882. ASSERT_TRUE(res);
  4883. EXPECT_EQ(StatusCode::OK_200, res->status);
  4884. }
  4885. TEST(GzipDecompressor, ChunkedDecompression) {
  4886. std::string data;
  4887. for (size_t i = 0; i < 32 * 1024; ++i) {
  4888. data.push_back(static_cast<char>('a' + i % 26));
  4889. }
  4890. std::string compressed_data;
  4891. {
  4892. httplib::detail::gzip_compressor compressor;
  4893. bool result = compressor.compress(
  4894. data.data(), data.size(),
  4895. /*last=*/true,
  4896. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4897. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4898. compressed_data_size);
  4899. return true;
  4900. });
  4901. ASSERT_TRUE(result);
  4902. }
  4903. std::string decompressed_data;
  4904. {
  4905. httplib::detail::gzip_decompressor decompressor;
  4906. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4907. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4908. size_t chunk_size = 130;
  4909. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4910. chunk_begin += chunk_size) {
  4911. size_t current_chunk_size =
  4912. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4913. bool result = decompressor.decompress(
  4914. compressed_data.data() + chunk_begin, current_chunk_size,
  4915. [&](const char *decompressed_data_chunk,
  4916. size_t decompressed_data_chunk_size) {
  4917. decompressed_data.insert(decompressed_data.size(),
  4918. decompressed_data_chunk,
  4919. decompressed_data_chunk_size);
  4920. return true;
  4921. });
  4922. ASSERT_TRUE(result);
  4923. }
  4924. }
  4925. ASSERT_EQ(data, decompressed_data);
  4926. }
  4927. TEST(GzipDecompressor, DeflateDecompression) {
  4928. std::string original_text = "Raw deflate without gzip";
  4929. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4930. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4931. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4932. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4933. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4934. std::string decompressed_data;
  4935. {
  4936. httplib::detail::gzip_decompressor decompressor;
  4937. bool result = decompressor.decompress(
  4938. compressed_data.data(), compressed_data.size(),
  4939. [&](const char *decompressed_data_chunk,
  4940. size_t decompressed_data_chunk_size) {
  4941. decompressed_data.insert(decompressed_data.size(),
  4942. decompressed_data_chunk,
  4943. decompressed_data_chunk_size);
  4944. return true;
  4945. });
  4946. ASSERT_TRUE(result);
  4947. }
  4948. ASSERT_EQ(original_text, decompressed_data);
  4949. }
  4950. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4951. std::string original_text = "Raw deflate without gzip";
  4952. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4953. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4954. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4955. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4956. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4957. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4958. std::string decompressed_data;
  4959. {
  4960. httplib::detail::gzip_decompressor decompressor;
  4961. bool result = decompressor.decompress(
  4962. compressed_data.data(), compressed_data.size(),
  4963. [&](const char *decompressed_data_chunk,
  4964. size_t decompressed_data_chunk_size) {
  4965. decompressed_data.insert(decompressed_data.size(),
  4966. decompressed_data_chunk,
  4967. decompressed_data_chunk_size);
  4968. return true;
  4969. });
  4970. ASSERT_TRUE(result);
  4971. }
  4972. ASSERT_EQ(original_text, decompressed_data);
  4973. }
  4974. #ifdef _WIN32
  4975. TEST(GzipDecompressor, LargeRandomData) {
  4976. // prepare large random data that is difficult to be compressed and is
  4977. // expected to have large size even when compressed
  4978. std::random_device seed_gen;
  4979. std::mt19937 random(seed_gen());
  4980. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4981. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4982. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4983. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4984. // compress data over 4GiB
  4985. std::string compressed_data;
  4986. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4987. httplib::detail::gzip_compressor compressor;
  4988. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4989. data.size() * sizeof(std::uint32_t), true,
  4990. [&](const char *data, size_t size) {
  4991. compressed_data.insert(
  4992. compressed_data.size(), data, size);
  4993. return true;
  4994. });
  4995. ASSERT_TRUE(result);
  4996. // FIXME: compressed data size is expected to be greater than 4GiB,
  4997. // but there is no guarantee
  4998. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4999. // decompress data over 4GiB
  5000. std::string decompressed_data;
  5001. decompressed_data.reserve(data_size);
  5002. httplib::detail::gzip_decompressor decompressor;
  5003. result = decompressor.decompress(
  5004. compressed_data.data(), compressed_data.size(),
  5005. [&](const char *data, size_t size) {
  5006. decompressed_data.insert(decompressed_data.size(), data, size);
  5007. return true;
  5008. });
  5009. ASSERT_TRUE(result);
  5010. // compare
  5011. ASSERT_EQ(data_size, decompressed_data.size());
  5012. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  5013. 0);
  5014. }
  5015. #endif
  5016. #endif
  5017. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5018. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5019. Headers headers;
  5020. headers.emplace("Accept-Encoding", "br");
  5021. auto res = cli_.Get("/streamed-chunked", headers);
  5022. ASSERT_TRUE(res);
  5023. EXPECT_EQ(StatusCode::OK_200, res->status);
  5024. EXPECT_EQ(std::string("123456789"), res->body);
  5025. }
  5026. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5027. Headers headers;
  5028. headers.emplace("Accept-Encoding", "br");
  5029. auto res = cli_.Get("/streamed-chunked2", headers);
  5030. ASSERT_TRUE(res);
  5031. EXPECT_EQ(StatusCode::OK_200, res->status);
  5032. EXPECT_EQ(std::string("123456789"), res->body);
  5033. }
  5034. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5035. cli_.set_compress(true);
  5036. auto res = cli_.Put(
  5037. "/put", 3,
  5038. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5039. sink.os << "PUT";
  5040. return true;
  5041. },
  5042. "text/plain");
  5043. ASSERT_TRUE(res);
  5044. EXPECT_EQ(StatusCode::OK_200, res->status);
  5045. EXPECT_EQ("PUT", res->body);
  5046. }
  5047. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5048. cli_.set_compress(true);
  5049. auto res = cli_.Put(
  5050. "/put",
  5051. [](size_t /*offset*/, DataSink &sink) {
  5052. sink.os << "PUT";
  5053. sink.done();
  5054. return true;
  5055. },
  5056. "text/plain");
  5057. ASSERT_TRUE(res);
  5058. EXPECT_EQ(StatusCode::OK_200, res->status);
  5059. EXPECT_EQ("PUT", res->body);
  5060. }
  5061. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5062. cli_.set_compress(true);
  5063. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5064. ASSERT_TRUE(res);
  5065. EXPECT_EQ(StatusCode::OK_200, res->status);
  5066. EXPECT_EQ(LARGE_DATA, res->body);
  5067. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5068. }
  5069. #endif
  5070. TEST_F(ServerTest, Patch) {
  5071. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5072. ASSERT_TRUE(res);
  5073. EXPECT_EQ(StatusCode::OK_200, res->status);
  5074. EXPECT_EQ("PATCH", res->body);
  5075. }
  5076. TEST_F(ServerTest, Delete) {
  5077. auto res = cli_.Delete("/delete");
  5078. ASSERT_TRUE(res);
  5079. EXPECT_EQ(StatusCode::OK_200, res->status);
  5080. EXPECT_EQ("DELETE", res->body);
  5081. }
  5082. TEST_F(ServerTest, DeleteContentReceiver) {
  5083. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5084. ASSERT_TRUE(res);
  5085. EXPECT_EQ(StatusCode::OK_200, res->status);
  5086. EXPECT_EQ("content", res->body);
  5087. }
  5088. TEST_F(ServerTest, Options) {
  5089. auto res = cli_.Options("*");
  5090. ASSERT_TRUE(res);
  5091. EXPECT_EQ(StatusCode::OK_200, res->status);
  5092. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5093. EXPECT_TRUE(res->body.empty());
  5094. }
  5095. TEST_F(ServerTest, URL) {
  5096. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5097. ASSERT_TRUE(res);
  5098. EXPECT_EQ(StatusCode::OK_200, res->status);
  5099. }
  5100. TEST_F(ServerTest, ArrayParam) {
  5101. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5102. ASSERT_TRUE(res);
  5103. EXPECT_EQ(StatusCode::OK_200, res->status);
  5104. }
  5105. TEST_F(ServerTest, NoMultipleHeaders) {
  5106. Headers headers = {{"Content-Length", "5"}};
  5107. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5108. "text/plain");
  5109. ASSERT_TRUE(res);
  5110. EXPECT_EQ(StatusCode::OK_200, res->status);
  5111. }
  5112. TEST_F(ServerTest, PostContentReceiver) {
  5113. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5114. ASSERT_TRUE(res);
  5115. ASSERT_EQ(StatusCode::OK_200, res->status);
  5116. ASSERT_EQ("content", res->body);
  5117. }
  5118. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5119. UploadFormDataItems items = {
  5120. {"text1", "text default", "", ""},
  5121. {"text2", "aωb", "", ""},
  5122. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5123. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5124. {"file3", "", "", "application/octet-stream"},
  5125. };
  5126. auto res = cli_.Post("/content_receiver", items);
  5127. ASSERT_TRUE(res);
  5128. EXPECT_EQ(StatusCode::OK_200, res->status);
  5129. }
  5130. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5131. UploadFormDataItems items = {
  5132. {"text1", "text default", "", ""},
  5133. {"text2", "aωb", "", ""},
  5134. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5135. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5136. {"file3", "", "", "application/octet-stream"},
  5137. };
  5138. auto boundary = std::string("+++++");
  5139. std::string body;
  5140. for (const auto &item : items) {
  5141. body += "--" + boundary + "\r\n";
  5142. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5143. if (!item.filename.empty()) {
  5144. body += "; filename=\"" + item.filename + "\"";
  5145. }
  5146. body += "\r\n";
  5147. if (!item.content_type.empty()) {
  5148. body += "Content-Type: " + item.content_type + "\r\n";
  5149. }
  5150. body += "\r\n";
  5151. body += item.content + "\r\n";
  5152. }
  5153. body += "--" + boundary + "--\r\n";
  5154. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5155. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5156. ASSERT_TRUE(res);
  5157. EXPECT_EQ(StatusCode::OK_200, res->status);
  5158. }
  5159. TEST_F(ServerTest, PostContentReceiverGzip) {
  5160. cli_.set_compress(true);
  5161. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5162. ASSERT_TRUE(res);
  5163. ASSERT_EQ(StatusCode::OK_200, res->status);
  5164. ASSERT_EQ("content", res->body);
  5165. }
  5166. TEST_F(ServerTest, PutContentReceiver) {
  5167. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5168. ASSERT_TRUE(res);
  5169. ASSERT_EQ(StatusCode::OK_200, res->status);
  5170. ASSERT_EQ("content", res->body);
  5171. }
  5172. TEST_F(ServerTest, PatchContentReceiver) {
  5173. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5174. ASSERT_TRUE(res);
  5175. ASSERT_EQ(StatusCode::OK_200, res->status);
  5176. ASSERT_EQ("content", res->body);
  5177. }
  5178. template <typename ClientType>
  5179. void TestWithHeadersAndContentReceiver(
  5180. ClientType &cli,
  5181. std::function<Result(ClientType &, const std::string &, const Headers &,
  5182. const std::string &, const std::string &,
  5183. ContentReceiver, DownloadProgress)>
  5184. request_func) {
  5185. Headers headers;
  5186. headers.emplace("X-Custom-Header", "test-value");
  5187. std::string received_body;
  5188. auto res = request_func(
  5189. cli, "/content_receiver", headers, "content", "application/json",
  5190. [&](const char *data, size_t data_length) {
  5191. received_body.append(data, data_length);
  5192. return true;
  5193. },
  5194. nullptr);
  5195. ASSERT_TRUE(res);
  5196. EXPECT_EQ(StatusCode::OK_200, res->status);
  5197. EXPECT_EQ("content", received_body);
  5198. }
  5199. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5200. #ifdef CPPHTTPLIB_SSL_ENABLED
  5201. using ClientT = SSLClient;
  5202. #else
  5203. using ClientT = Client;
  5204. #endif
  5205. TestWithHeadersAndContentReceiver<ClientT>(
  5206. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5207. const std::string &body, const std::string &content_type,
  5208. ContentReceiver receiver, DownloadProgress progress) {
  5209. return cli.Post(path, headers, body, content_type, receiver, progress);
  5210. });
  5211. }
  5212. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5213. #ifdef CPPHTTPLIB_SSL_ENABLED
  5214. using ClientT = SSLClient;
  5215. #else
  5216. using ClientT = Client;
  5217. #endif
  5218. TestWithHeadersAndContentReceiver<ClientT>(
  5219. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5220. const std::string &body, const std::string &content_type,
  5221. ContentReceiver receiver, DownloadProgress progress) {
  5222. return cli.Put(path, headers, body, content_type, receiver, progress);
  5223. });
  5224. }
  5225. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5226. #ifdef CPPHTTPLIB_SSL_ENABLED
  5227. using ClientT = SSLClient;
  5228. #else
  5229. using ClientT = Client;
  5230. #endif
  5231. TestWithHeadersAndContentReceiver<ClientT>(
  5232. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5233. const std::string &body, const std::string &content_type,
  5234. ContentReceiver receiver, DownloadProgress progress) {
  5235. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5236. });
  5237. }
  5238. template <typename ClientType>
  5239. void TestWithHeadersAndContentReceiverWithProgress(
  5240. ClientType &cli,
  5241. std::function<Result(ClientType &, const std::string &, const Headers &,
  5242. const std::string &, const std::string &,
  5243. ContentReceiver, DownloadProgress)>
  5244. request_func) {
  5245. Headers headers;
  5246. headers.emplace("X-Test-Header", "progress-test");
  5247. std::string received_body;
  5248. auto progress_called = false;
  5249. auto res = request_func(
  5250. cli, "/content_receiver", headers, "content", "text/plain",
  5251. [&](const char *data, size_t data_length) {
  5252. received_body.append(data, data_length);
  5253. return true;
  5254. },
  5255. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5256. progress_called = true;
  5257. return true;
  5258. });
  5259. ASSERT_TRUE(res);
  5260. EXPECT_EQ(StatusCode::OK_200, res->status);
  5261. EXPECT_EQ("content", received_body);
  5262. EXPECT_TRUE(progress_called);
  5263. }
  5264. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5265. #ifdef CPPHTTPLIB_SSL_ENABLED
  5266. using ClientT = SSLClient;
  5267. #else
  5268. using ClientT = Client;
  5269. #endif
  5270. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5271. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5272. const std::string &body, const std::string &content_type,
  5273. ContentReceiver receiver, DownloadProgress progress) {
  5274. return cli.Post(path, headers, body, content_type, receiver, progress);
  5275. });
  5276. }
  5277. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5278. #ifdef CPPHTTPLIB_SSL_ENABLED
  5279. using ClientT = SSLClient;
  5280. #else
  5281. using ClientT = Client;
  5282. #endif
  5283. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5284. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5285. const std::string &body, const std::string &content_type,
  5286. ContentReceiver receiver, DownloadProgress progress) {
  5287. return cli.Put(path, headers, body, content_type, receiver, progress);
  5288. });
  5289. }
  5290. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5291. #ifdef CPPHTTPLIB_SSL_ENABLED
  5292. using ClientT = SSLClient;
  5293. #else
  5294. using ClientT = Client;
  5295. #endif
  5296. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5297. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5298. const std::string &body, const std::string &content_type,
  5299. ContentReceiver receiver, DownloadProgress progress) {
  5300. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5301. });
  5302. }
  5303. template <typename ClientType>
  5304. void TestWithHeadersAndContentReceiverError(
  5305. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5306. const Headers &, const std::string &,
  5307. const std::string &, ContentReceiver)>
  5308. request_func) {
  5309. Headers headers;
  5310. headers.emplace("X-Error-Test", "true");
  5311. std::string received_body;
  5312. auto receiver_failed = false;
  5313. auto res =
  5314. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5315. [&](const char *data, size_t data_length) {
  5316. received_body.append(data, data_length);
  5317. receiver_failed = true;
  5318. return false;
  5319. });
  5320. ASSERT_FALSE(res);
  5321. EXPECT_TRUE(receiver_failed);
  5322. }
  5323. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5324. #ifdef CPPHTTPLIB_SSL_ENABLED
  5325. using ClientT = SSLClient;
  5326. #else
  5327. using ClientT = Client;
  5328. #endif
  5329. TestWithHeadersAndContentReceiverError<ClientT>(
  5330. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5331. const std::string &body, const std::string &content_type,
  5332. ContentReceiver receiver) {
  5333. return cli.Post(path, headers, body, content_type, receiver);
  5334. });
  5335. }
  5336. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5337. #ifdef CPPHTTPLIB_SSL_ENABLED
  5338. using ClientT = SSLClient;
  5339. #else
  5340. using ClientT = Client;
  5341. #endif
  5342. TestWithHeadersAndContentReceiverError<ClientT>(
  5343. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5344. const std::string &body, const std::string &content_type,
  5345. ContentReceiver receiver) {
  5346. return cli.Put(path, headers, body, content_type, receiver);
  5347. });
  5348. }
  5349. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5350. #ifdef CPPHTTPLIB_SSL_ENABLED
  5351. using ClientT = SSLClient;
  5352. #else
  5353. using ClientT = Client;
  5354. #endif
  5355. TestWithHeadersAndContentReceiverError<ClientT>(
  5356. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5357. const std::string &body, const std::string &content_type,
  5358. ContentReceiver receiver) {
  5359. return cli.Patch(path, headers, body, content_type, receiver);
  5360. });
  5361. }
  5362. TEST_F(ServerTest, PostQueryStringAndBody) {
  5363. auto res =
  5364. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5365. ASSERT_TRUE(res);
  5366. ASSERT_EQ(StatusCode::OK_200, res->status);
  5367. }
  5368. TEST_F(ServerTest, HTTP2Magic) {
  5369. Request req;
  5370. req.method = "PRI";
  5371. req.path = "*";
  5372. req.body = "SM";
  5373. auto res = std::make_shared<Response>();
  5374. auto error = Error::Success;
  5375. auto ret = cli_.send(req, *res, error);
  5376. ASSERT_TRUE(ret);
  5377. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5378. }
  5379. TEST_F(ServerTest, KeepAlive) {
  5380. auto res = cli_.Get("/hi");
  5381. ASSERT_TRUE(res);
  5382. EXPECT_EQ(StatusCode::OK_200, res->status);
  5383. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5384. EXPECT_EQ("Hello World!", res->body);
  5385. res = cli_.Get("/hi");
  5386. ASSERT_TRUE(res);
  5387. EXPECT_EQ(StatusCode::OK_200, res->status);
  5388. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5389. EXPECT_EQ("Hello World!", res->body);
  5390. res = cli_.Get("/hi");
  5391. ASSERT_TRUE(res);
  5392. EXPECT_EQ(StatusCode::OK_200, res->status);
  5393. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5394. EXPECT_EQ("Hello World!", res->body);
  5395. res = cli_.Get("/not-exist");
  5396. ASSERT_TRUE(res);
  5397. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5398. res = cli_.Post("/empty", "", "text/plain");
  5399. ASSERT_TRUE(res);
  5400. EXPECT_EQ(StatusCode::OK_200, res->status);
  5401. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5402. EXPECT_EQ("empty", res->body);
  5403. EXPECT_EQ("close", res->get_header_value("Connection"));
  5404. res = cli_.Post(
  5405. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5406. "text/plain");
  5407. ASSERT_TRUE(res);
  5408. EXPECT_EQ(StatusCode::OK_200, res->status);
  5409. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5410. EXPECT_EQ("empty", res->body);
  5411. cli_.set_keep_alive(false);
  5412. res = cli_.Get("/last-request");
  5413. ASSERT_TRUE(res);
  5414. EXPECT_EQ(StatusCode::OK_200, res->status);
  5415. EXPECT_EQ("close", res->get_header_value("Connection"));
  5416. }
  5417. TEST_F(ServerTest, TooManyRedirect) {
  5418. cli_.set_follow_location(true);
  5419. auto res = cli_.Get("/redirect/0");
  5420. ASSERT_TRUE(!res);
  5421. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5422. }
  5423. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5424. Request req;
  5425. req.method = "FOOBAR";
  5426. req.path = "/hi";
  5427. cli_.set_keep_alive(true);
  5428. auto res = cli_.send(req);
  5429. ASSERT_TRUE(res);
  5430. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5431. EXPECT_EQ("close", res->get_header_value("Connection"));
  5432. EXPECT_FALSE(cli_.is_socket_open());
  5433. }
  5434. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5435. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5436. TEST_F(ServerTest, Gzip) {
  5437. Headers headers;
  5438. headers.emplace("Accept-Encoding", "gzip, deflate");
  5439. auto res = cli_.Get("/compress", headers);
  5440. ASSERT_TRUE(res);
  5441. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5442. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5443. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5444. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5445. "7890123456789012345678901234567890",
  5446. res->body);
  5447. EXPECT_EQ(StatusCode::OK_200, res->status);
  5448. }
  5449. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5450. Headers headers;
  5451. headers.emplace("Accept-Encoding", "gzip, deflate");
  5452. auto res = cli_.Get("/compress-with-charset", headers);
  5453. ASSERT_TRUE(res);
  5454. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5455. EXPECT_EQ("application/json; charset=utf-8",
  5456. res->get_header_value("Content-Type"));
  5457. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5458. "7890123456789012345678901234567890",
  5459. res->body);
  5460. EXPECT_EQ(StatusCode::OK_200, res->status);
  5461. }
  5462. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5463. Headers headers;
  5464. headers.emplace("Accept-Encoding", "");
  5465. auto res = cli_.Get("/compress", headers);
  5466. ASSERT_TRUE(res);
  5467. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5468. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5469. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5470. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5471. "7890123456789012345678901234567890",
  5472. res->body);
  5473. EXPECT_EQ(StatusCode::OK_200, res->status);
  5474. }
  5475. TEST_F(ServerTest, GzipWithContentReceiver) {
  5476. Headers headers;
  5477. headers.emplace("Accept-Encoding", "gzip, deflate");
  5478. std::string body;
  5479. auto res = cli_.Get("/compress", headers,
  5480. [&](const char *data, uint64_t data_length) {
  5481. EXPECT_EQ(100U, data_length);
  5482. body.append(data, data_length);
  5483. return true;
  5484. });
  5485. ASSERT_TRUE(res);
  5486. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5487. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5488. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5489. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5490. "7890123456789012345678901234567890",
  5491. body);
  5492. EXPECT_EQ(StatusCode::OK_200, res->status);
  5493. }
  5494. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5495. Headers headers;
  5496. headers.emplace("Accept-Encoding", "gzip, deflate");
  5497. cli_.set_decompress(false);
  5498. auto res = cli_.Get("/compress", headers);
  5499. ASSERT_TRUE(res);
  5500. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5501. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5502. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5503. EXPECT_EQ(33U, res->body.size());
  5504. EXPECT_EQ(StatusCode::OK_200, res->status);
  5505. }
  5506. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5507. Headers headers;
  5508. headers.emplace("Accept-Encoding", "");
  5509. std::string body;
  5510. auto res = cli_.Get("/compress", headers,
  5511. [&](const char *data, uint64_t data_length) {
  5512. EXPECT_EQ(100U, data_length);
  5513. body.append(data, data_length);
  5514. return true;
  5515. });
  5516. ASSERT_TRUE(res);
  5517. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5518. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5519. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5520. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5521. "7890123456789012345678901234567890",
  5522. body);
  5523. EXPECT_EQ(StatusCode::OK_200, res->status);
  5524. }
  5525. TEST_F(ServerTest, NoGzip) {
  5526. Headers headers;
  5527. headers.emplace("Accept-Encoding", "gzip, deflate");
  5528. auto res = cli_.Get("/nocompress", headers);
  5529. ASSERT_TRUE(res);
  5530. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5531. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5532. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5533. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5534. "7890123456789012345678901234567890",
  5535. res->body);
  5536. EXPECT_EQ(StatusCode::OK_200, res->status);
  5537. }
  5538. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5539. Headers headers;
  5540. headers.emplace("Accept-Encoding", "gzip, deflate");
  5541. std::string body;
  5542. auto res = cli_.Get("/nocompress", headers,
  5543. [&](const char *data, uint64_t data_length) {
  5544. EXPECT_EQ(100U, data_length);
  5545. body.append(data, data_length);
  5546. return true;
  5547. });
  5548. ASSERT_TRUE(res);
  5549. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5550. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5551. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5552. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5553. "7890123456789012345678901234567890",
  5554. body);
  5555. EXPECT_EQ(StatusCode::OK_200, res->status);
  5556. }
  5557. TEST_F(ServerTest, MultipartFormDataGzip) {
  5558. UploadFormDataItems items = {
  5559. {"key1", "test", "", ""},
  5560. {"key2", "--abcdefg123", "", ""},
  5561. };
  5562. cli_.set_compress(true);
  5563. auto res = cli_.Post("/compress-multipart", items);
  5564. ASSERT_TRUE(res);
  5565. EXPECT_EQ(StatusCode::OK_200, res->status);
  5566. }
  5567. #endif
  5568. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5569. TEST_F(ServerTest, Brotli) {
  5570. Headers headers;
  5571. headers.emplace("Accept-Encoding", "br");
  5572. auto res = cli_.Get("/compress", headers);
  5573. ASSERT_TRUE(res);
  5574. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5575. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5576. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5577. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5578. "7890123456789012345678901234567890",
  5579. res->body);
  5580. EXPECT_EQ(StatusCode::OK_200, res->status);
  5581. }
  5582. #endif
  5583. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5584. TEST_F(ServerTest, Zstd) {
  5585. Headers headers;
  5586. headers.emplace("Accept-Encoding", "zstd");
  5587. auto res = cli_.Get("/compress", headers);
  5588. ASSERT_TRUE(res);
  5589. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5590. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5591. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5592. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5593. "7890123456789012345678901234567890",
  5594. res->body);
  5595. EXPECT_EQ(StatusCode::OK_200, res->status);
  5596. }
  5597. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5598. Headers headers;
  5599. headers.emplace("Accept-Encoding", "");
  5600. auto res = cli_.Get("/compress", headers);
  5601. ASSERT_TRUE(res);
  5602. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5603. EXPECT_EQ("text/plain", 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, ZstdWithContentReceiver) {
  5611. Headers headers;
  5612. headers.emplace("Accept-Encoding", "zstd");
  5613. std::string body;
  5614. auto res = cli_.Get("/compress", 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("zstd", res->get_header_value("Content-Encoding"));
  5622. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5623. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5624. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5625. "7890123456789012345678901234567890",
  5626. body);
  5627. EXPECT_EQ(StatusCode::OK_200, res->status);
  5628. }
  5629. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5630. Headers headers;
  5631. headers.emplace("Accept-Encoding", "zstd");
  5632. cli_.set_decompress(false);
  5633. auto res = cli_.Get("/compress", headers);
  5634. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5635. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5636. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5637. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5638. ASSERT_TRUE(res);
  5639. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5640. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5641. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5642. EXPECT_EQ(StatusCode::OK_200, res->status);
  5643. ASSERT_EQ(26U, res->body.size());
  5644. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5645. 0);
  5646. }
  5647. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5648. Headers headers;
  5649. headers.emplace("Accept-Encoding", "");
  5650. std::string body;
  5651. auto res = cli_.Get("/compress", headers,
  5652. [&](const char *data, uint64_t data_length) {
  5653. EXPECT_EQ(100U, data_length);
  5654. body.append(data, data_length);
  5655. return true;
  5656. });
  5657. ASSERT_TRUE(res);
  5658. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5659. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5660. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5661. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5662. "7890123456789012345678901234567890",
  5663. body);
  5664. EXPECT_EQ(StatusCode::OK_200, res->status);
  5665. }
  5666. TEST_F(ServerTest, NoZstd) {
  5667. Headers headers;
  5668. headers.emplace("Accept-Encoding", "zstd");
  5669. auto res = cli_.Get("/nocompress", headers);
  5670. ASSERT_TRUE(res);
  5671. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5672. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5673. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5674. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5675. "7890123456789012345678901234567890",
  5676. res->body);
  5677. EXPECT_EQ(StatusCode::OK_200, res->status);
  5678. }
  5679. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5680. Headers headers;
  5681. headers.emplace("Accept-Encoding", "zstd");
  5682. std::string body;
  5683. auto res = cli_.Get("/nocompress", headers,
  5684. [&](const char *data, uint64_t data_length) {
  5685. EXPECT_EQ(100U, data_length);
  5686. body.append(data, data_length);
  5687. return true;
  5688. });
  5689. ASSERT_TRUE(res);
  5690. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5691. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5692. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5693. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5694. "7890123456789012345678901234567890",
  5695. body);
  5696. EXPECT_EQ(StatusCode::OK_200, res->status);
  5697. }
  5698. // TODO: How to enable zstd ??
  5699. TEST_F(ServerTest, MultipartFormDataZstd) {
  5700. UploadFormDataItems items = {
  5701. {"key1", "test", "", ""},
  5702. {"key2", "--abcdefg123", "", ""},
  5703. };
  5704. Headers headers;
  5705. headers.emplace("Accept-Encoding", "zstd");
  5706. cli_.set_compress(true);
  5707. auto res = cli_.Post("/compress-multipart", headers, items);
  5708. ASSERT_TRUE(res);
  5709. EXPECT_EQ(StatusCode::OK_200, res->status);
  5710. }
  5711. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5712. Headers headers;
  5713. headers.emplace("Accept-Encoding", "zstd");
  5714. cli_.set_compress(true);
  5715. auto res = cli_.Put(
  5716. "/put", headers, 3,
  5717. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5718. sink.os << "PUT";
  5719. return true;
  5720. },
  5721. "text/plain");
  5722. ASSERT_TRUE(res);
  5723. EXPECT_EQ(StatusCode::OK_200, res->status);
  5724. EXPECT_EQ("PUT", res->body);
  5725. }
  5726. // Pre-compression logging tests
  5727. TEST_F(ServerTest, PreCompressionLogging) {
  5728. // Test data for compression (matches the actual /compress endpoint content)
  5729. const std::string test_content =
  5730. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5731. "3456789012345678901234567890";
  5732. // Variables to capture logging data
  5733. std::string pre_compression_body;
  5734. std::string pre_compression_content_type;
  5735. std::string pre_compression_content_encoding;
  5736. std::string post_compression_body;
  5737. std::string post_compression_content_type;
  5738. std::string post_compression_content_encoding;
  5739. // Set up pre-compression logger
  5740. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5741. const Response &res) {
  5742. pre_compression_body = res.body;
  5743. pre_compression_content_type = res.get_header_value("Content-Type");
  5744. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5745. });
  5746. // Set up post-compression logger
  5747. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5748. post_compression_body = res.body;
  5749. post_compression_content_type = res.get_header_value("Content-Type");
  5750. post_compression_content_encoding =
  5751. res.get_header_value("Content-Encoding");
  5752. });
  5753. // Test with gzip compression
  5754. Headers headers;
  5755. headers.emplace("Accept-Encoding", "gzip");
  5756. auto res = cli_.Get("/compress", headers);
  5757. // Verify response was compressed
  5758. ASSERT_TRUE(res);
  5759. EXPECT_EQ(StatusCode::OK_200, res->status);
  5760. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5761. // Verify pre-compression logger captured uncompressed content
  5762. EXPECT_EQ(test_content, pre_compression_body);
  5763. EXPECT_EQ("text/plain", pre_compression_content_type);
  5764. EXPECT_TRUE(pre_compression_content_encoding
  5765. .empty()); // No encoding header before compression
  5766. // Verify post-compression logger captured compressed content
  5767. EXPECT_NE(test_content,
  5768. post_compression_body); // Should be different after compression
  5769. EXPECT_EQ("text/plain", post_compression_content_type);
  5770. EXPECT_EQ("gzip", post_compression_content_encoding);
  5771. // Verify compressed content is smaller
  5772. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5773. }
  5774. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5775. const std::string test_content =
  5776. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5777. "3456789012345678901234567890";
  5778. std::string pre_compression_body;
  5779. std::string post_compression_body;
  5780. svr_.set_pre_compression_logger(
  5781. [&](const Request & /*req*/, const Response &res) {
  5782. pre_compression_body = res.body;
  5783. });
  5784. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5785. post_compression_body = res.body;
  5786. });
  5787. Headers headers;
  5788. headers.emplace("Accept-Encoding", "br");
  5789. auto res = cli_.Get("/compress", headers);
  5790. ASSERT_TRUE(res);
  5791. EXPECT_EQ(StatusCode::OK_200, res->status);
  5792. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5793. // Verify pre-compression content is uncompressed
  5794. EXPECT_EQ(test_content, pre_compression_body);
  5795. // Verify post-compression content is compressed
  5796. EXPECT_NE(test_content, post_compression_body);
  5797. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5798. }
  5799. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5800. const std::string test_content =
  5801. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5802. "3456789012345678901234567890";
  5803. std::string pre_compression_body;
  5804. std::string post_compression_body;
  5805. svr_.set_pre_compression_logger(
  5806. [&](const Request & /*req*/, const Response &res) {
  5807. pre_compression_body = res.body;
  5808. });
  5809. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5810. post_compression_body = res.body;
  5811. });
  5812. // Request without compression (use /nocompress endpoint)
  5813. Headers headers;
  5814. auto res = cli_.Get("/nocompress", headers);
  5815. ASSERT_TRUE(res);
  5816. EXPECT_EQ(StatusCode::OK_200, res->status);
  5817. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5818. // Pre-compression logger should not be called when no compression is applied
  5819. EXPECT_TRUE(
  5820. pre_compression_body.empty()); // Pre-compression logger not called
  5821. EXPECT_EQ(
  5822. test_content,
  5823. post_compression_body); // Post-compression logger captures final content
  5824. }
  5825. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5826. const std::string test_content =
  5827. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5828. "3456789012345678901234567890";
  5829. std::string pre_compression_body;
  5830. bool pre_logger_called = false;
  5831. // Set only pre-compression logger
  5832. svr_.set_pre_compression_logger(
  5833. [&](const Request & /*req*/, const Response &res) {
  5834. pre_compression_body = res.body;
  5835. pre_logger_called = true;
  5836. });
  5837. Headers headers;
  5838. headers.emplace("Accept-Encoding", "gzip");
  5839. auto res = cli_.Get("/compress", headers);
  5840. ASSERT_TRUE(res);
  5841. EXPECT_EQ(StatusCode::OK_200, res->status);
  5842. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5843. // Verify pre-compression logger was called
  5844. EXPECT_TRUE(pre_logger_called);
  5845. EXPECT_EQ(test_content, pre_compression_body);
  5846. }
  5847. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5848. {
  5849. // Test with Expect: 100-continue header - success case
  5850. // Server returns 100 Continue, client sends body, server returns 200 OK
  5851. Request req;
  5852. req.method = "POST";
  5853. req.path = "/post-large";
  5854. req.set_header("Expect", "100-continue");
  5855. req.body = LARGE_DATA;
  5856. Response res;
  5857. auto error = Error::Success;
  5858. cli_.set_keep_alive(true);
  5859. auto ret = cli_.send(req, res, error);
  5860. EXPECT_TRUE(ret);
  5861. EXPECT_EQ(StatusCode::OK_200, res.status);
  5862. EXPECT_EQ(LARGE_DATA, res.body);
  5863. }
  5864. {
  5865. // Test with Expect: 100-continue header - error case
  5866. // Client should not send the body when server returns an error
  5867. Request req;
  5868. req.method = "POST";
  5869. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5870. req.set_header("Expect", "100-continue");
  5871. req.body = LARGE_DATA;
  5872. Response res;
  5873. auto error = Error::Success;
  5874. auto start = std::chrono::high_resolution_clock::now();
  5875. cli_.set_keep_alive(true);
  5876. auto ret = cli_.send(req, res, error);
  5877. auto end = std::chrono::high_resolution_clock::now();
  5878. auto elapsed =
  5879. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5880. .count();
  5881. // With Expect: 100-continue, request completes successfully but with error
  5882. EXPECT_TRUE(ret);
  5883. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5884. EXPECT_EQ("close", res.get_header_value("Connection"));
  5885. EXPECT_FALSE(cli_.is_socket_open());
  5886. EXPECT_LE(elapsed, 200);
  5887. }
  5888. {
  5889. // Send an extra GET request to ensure error recovery without hanging
  5890. Request req;
  5891. req.method = "GET";
  5892. req.path = "/hi";
  5893. auto start = std::chrono::high_resolution_clock::now();
  5894. auto res = cli_.send(req);
  5895. auto end = std::chrono::high_resolution_clock::now();
  5896. auto elapsed =
  5897. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5898. .count();
  5899. ASSERT_TRUE(res);
  5900. EXPECT_EQ(StatusCode::OK_200, res->status);
  5901. EXPECT_EQ("Hello World!", res->body);
  5902. EXPECT_LE(elapsed, 500);
  5903. }
  5904. }
  5905. TEST(ZstdDecompressor, ChunkedDecompression) {
  5906. std::string data;
  5907. for (size_t i = 0; i < 32 * 1024; ++i) {
  5908. data.push_back(static_cast<char>('a' + i % 26));
  5909. }
  5910. std::string compressed_data;
  5911. {
  5912. httplib::detail::zstd_compressor compressor;
  5913. bool result = compressor.compress(
  5914. data.data(), data.size(),
  5915. /*last=*/true,
  5916. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5917. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5918. compressed_data_size);
  5919. return true;
  5920. });
  5921. ASSERT_TRUE(result);
  5922. }
  5923. std::string decompressed_data;
  5924. {
  5925. httplib::detail::zstd_decompressor decompressor;
  5926. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5927. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5928. size_t chunk_size = 130;
  5929. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5930. chunk_begin += chunk_size) {
  5931. size_t current_chunk_size =
  5932. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5933. bool result = decompressor.decompress(
  5934. compressed_data.data() + chunk_begin, current_chunk_size,
  5935. [&](const char *decompressed_data_chunk,
  5936. size_t decompressed_data_chunk_size) {
  5937. decompressed_data.insert(decompressed_data.size(),
  5938. decompressed_data_chunk,
  5939. decompressed_data_chunk_size);
  5940. return true;
  5941. });
  5942. ASSERT_TRUE(result);
  5943. }
  5944. }
  5945. ASSERT_EQ(data, decompressed_data);
  5946. }
  5947. TEST(ZstdDecompressor, Decompress) {
  5948. std::string original_text = "Compressed with ZSTD";
  5949. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5950. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5951. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5952. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5953. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5954. std::string decompressed_data;
  5955. {
  5956. httplib::detail::zstd_decompressor decompressor;
  5957. bool result = decompressor.decompress(
  5958. compressed_data.data(), compressed_data.size(),
  5959. [&](const char *decompressed_data_chunk,
  5960. size_t decompressed_data_chunk_size) {
  5961. decompressed_data.insert(decompressed_data.size(),
  5962. decompressed_data_chunk,
  5963. decompressed_data_chunk_size);
  5964. return true;
  5965. });
  5966. ASSERT_TRUE(result);
  5967. }
  5968. ASSERT_EQ(original_text, decompressed_data);
  5969. }
  5970. #endif
  5971. // Sends a raw request to a server listening at HOST:PORT.
  5972. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5973. std::string *resp = nullptr) {
  5974. auto error = Error::Success;
  5975. auto client_sock = detail::create_client_socket(
  5976. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5977. /*connection_timeout_sec=*/5, 0,
  5978. /*read_timeout_sec=*/5, 0,
  5979. /*write_timeout_sec=*/5, 0, std::string(), error);
  5980. if (client_sock == INVALID_SOCKET) { return false; }
  5981. auto ret = detail::process_client_socket(
  5982. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5983. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5984. if (req.size() !=
  5985. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5986. return false;
  5987. }
  5988. char buf[512];
  5989. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5990. while (line_reader.getline()) {
  5991. if (resp) { *resp += line_reader.ptr(); }
  5992. }
  5993. return true;
  5994. });
  5995. detail::close_socket(client_sock);
  5996. return ret;
  5997. }
  5998. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5999. Server svr;
  6000. std::string header_value;
  6001. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6002. header_value = req.get_header_value("foo");
  6003. res.set_content("ok", "text/plain");
  6004. });
  6005. thread t = thread([&] { svr.listen(HOST, PORT); });
  6006. auto se = detail::scope_exit([&] {
  6007. svr.stop();
  6008. t.join();
  6009. ASSERT_FALSE(svr.is_running());
  6010. });
  6011. svr.wait_until_ready();
  6012. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  6013. // like characters are not treated the same - use vertical tab and escape.
  6014. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  6015. "foo: \t \v bar \x1B\t \r\n"
  6016. "Connection: close\r\n"
  6017. "\r\n";
  6018. std::string res;
  6019. ASSERT_TRUE(send_request(5, req, &res));
  6020. EXPECT_EQ(header_value, "");
  6021. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  6022. }
  6023. // Sends a raw request and verifies that there isn't a crash or exception.
  6024. static void test_raw_request(const std::string &req,
  6025. std::string *out = nullptr) {
  6026. Server svr;
  6027. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6028. res.set_content("ok", "text/plain");
  6029. });
  6030. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  6031. res.set_content("ok", "text/plain");
  6032. });
  6033. svr.Get("/header_field_value_check",
  6034. [&](const Request & /*req*/, Response &res) {
  6035. res.set_content("ok", "text/plain");
  6036. });
  6037. // Server read timeout must be longer than the client read timeout for the
  6038. // bug to reproduce, probably to force the server to process a request
  6039. // without a trailing blank line.
  6040. const time_t client_read_timeout_sec = 1;
  6041. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  6042. bool listen_thread_ok = false;
  6043. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  6044. auto se = detail::scope_exit([&] {
  6045. svr.stop();
  6046. t.join();
  6047. ASSERT_FALSE(svr.is_running());
  6048. EXPECT_TRUE(listen_thread_ok);
  6049. });
  6050. svr.wait_until_ready();
  6051. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  6052. }
  6053. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  6054. // A certain header line causes an exception if the header property is parsed
  6055. // naively with a single regex. This occurs with libc++ but not libstdc++.
  6056. test_raw_request(
  6057. "GET /hi HTTP/1.1\r\n"
  6058. " : "
  6059. " "
  6060. " ");
  6061. }
  6062. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6063. // A certain header line causes an exception if the header property *name* is
  6064. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6065. // greedy matcher and requires backtracking when there are a lot of ":"
  6066. // characters.
  6067. // This occurs with libc++ but not libstdc++.
  6068. test_raw_request(
  6069. "GET /hi HTTP/1.1\r\n"
  6070. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6071. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6072. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6073. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6074. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6075. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6076. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6077. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6078. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6079. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6080. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6081. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6082. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6083. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6084. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6085. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6086. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6087. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6088. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6089. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6090. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6091. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6092. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6093. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6094. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6095. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6096. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6097. "&&&%%%");
  6098. }
  6099. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6100. // Make sure this doesn't crash the server.
  6101. // In a previous version of the header line regex, the "\r" rendered the line
  6102. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6103. // a new position where the leading white space ended and the field value
  6104. // began.
  6105. // The crash occurs with libc++ but not libstdc++.
  6106. test_raw_request("GET /hi HTTP/1.1\r\n"
  6107. "a:" +
  6108. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6109. "\r\n"
  6110. "\r\n");
  6111. }
  6112. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6113. std::string out;
  6114. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6115. "Content-Type: text/plain\r\n"
  6116. "Transfer-Encoding: chunked\r\n"
  6117. "\r\n"
  6118. "nothex\r\n",
  6119. &out);
  6120. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6121. }
  6122. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6123. std::string out;
  6124. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6125. "Content-Type: text/plain\r\n"
  6126. "Transfer-Encoding: chunked\r\n"
  6127. "\r\n"
  6128. "3\r\n"
  6129. "xyz\r\n"
  6130. "NaN\r\n",
  6131. &out);
  6132. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6133. }
  6134. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6135. std::string out;
  6136. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6137. "Content-Type: text/plain\r\n"
  6138. "Transfer-Encoding: chunked\r\n"
  6139. "\r\n"
  6140. // Length is too large for 64 bits.
  6141. "1ffffffffffffffff\r\n"
  6142. "xyz\r\n",
  6143. &out);
  6144. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6145. }
  6146. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6147. test_raw_request("GET /hi HTTP/1.1\r\n"
  6148. "Content-Type: text/plain\r\n\r");
  6149. }
  6150. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6151. std::string out;
  6152. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6153. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6154. }
  6155. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6156. Server svr;
  6157. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6158. EXPECT_TRUE(!req.remote_addr.empty());
  6159. });
  6160. thread t = thread([&] { svr.listen(HOST, PORT); });
  6161. auto se = detail::scope_exit([&] {
  6162. svr.stop();
  6163. t.join();
  6164. ASSERT_FALSE(svr.is_running());
  6165. });
  6166. svr.wait_until_ready();
  6167. // Send an invalid request line to trigger Bad Request
  6168. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6169. std::string out;
  6170. ASSERT_TRUE(send_request(5, bad_req, &out));
  6171. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6172. }
  6173. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6174. std::string out;
  6175. std::string request(
  6176. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6177. test_raw_request(request, &out);
  6178. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6179. }
  6180. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6181. std::string out;
  6182. std::string request(
  6183. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6184. test_raw_request(request, &out);
  6185. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6186. }
  6187. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6188. std::string out;
  6189. std::string request(
  6190. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6191. test_raw_request(request, &out);
  6192. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6193. }
  6194. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6195. std::string out;
  6196. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6197. "Test: \r\n\r\n",
  6198. &out);
  6199. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6200. }
  6201. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6202. Server svr;
  6203. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6204. res.set_header("Cache-Control", "no-cache");
  6205. res.set_chunked_content_provider(
  6206. "text/event-stream", [](size_t offset, DataSink &sink) {
  6207. std::string s = "data:";
  6208. s += std::to_string(offset);
  6209. s += "\n\n";
  6210. auto ret = sink.write(s.data(), s.size());
  6211. EXPECT_TRUE(ret);
  6212. std::this_thread::sleep_for(std::chrono::seconds(1));
  6213. return true;
  6214. });
  6215. });
  6216. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6217. svr.wait_until_ready();
  6218. Client client(HOST, PORT);
  6219. const Headers headers = {{"Accept", "text/event-stream"}};
  6220. auto get_thread = std::thread([&client, &headers]() {
  6221. auto res = client.Get(
  6222. "/events", headers,
  6223. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6224. });
  6225. auto se = detail::scope_exit([&] {
  6226. svr.stop();
  6227. get_thread.join();
  6228. listen_thread.join();
  6229. ASSERT_FALSE(svr.is_running());
  6230. });
  6231. // Give GET time to get a few messages.
  6232. std::this_thread::sleep_for(std::chrono::seconds(2));
  6233. }
  6234. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6235. httplib::Server svr;
  6236. svr.Post("/hi",
  6237. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6238. res.status = StatusCode::OK_200;
  6239. });
  6240. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6241. svr.wait_until_ready();
  6242. Client cli(HOST, PORT);
  6243. auto res = cli.Post("/hi", "data", "text/plain");
  6244. ASSERT_TRUE(res);
  6245. EXPECT_EQ(StatusCode::OK_200, res->status);
  6246. svr.stop();
  6247. thread.join();
  6248. ASSERT_FALSE(svr.is_running());
  6249. res = cli.Post("/hi", "data", "text/plain");
  6250. ASSERT_FALSE(res);
  6251. }
  6252. TEST(ServerStopTest, ListenFailure) {
  6253. Server svr;
  6254. auto t = thread([&]() {
  6255. auto ret = svr.listen("????", PORT);
  6256. EXPECT_FALSE(ret);
  6257. });
  6258. svr.wait_until_ready();
  6259. svr.stop();
  6260. t.join();
  6261. }
  6262. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6263. TEST(ServerStopTest, Decommision) {
  6264. Server svr;
  6265. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6266. for (int i = 0; i < 4; i++) {
  6267. auto is_even = !(i % 2);
  6268. std::thread t{[&] {
  6269. try {
  6270. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6271. if (is_even) {
  6272. throw std::runtime_error("Some thing that happens to go wrong.");
  6273. }
  6274. svr.listen(HOST, PORT);
  6275. } catch (...) { svr.decommission(); }
  6276. }};
  6277. svr.wait_until_ready();
  6278. // Server is up
  6279. {
  6280. Client cli(HOST, PORT);
  6281. auto res = cli.Get("/hi");
  6282. if (is_even) {
  6283. EXPECT_FALSE(res);
  6284. } else {
  6285. EXPECT_TRUE(res);
  6286. EXPECT_EQ("hi...", res->body);
  6287. }
  6288. }
  6289. svr.stop();
  6290. t.join();
  6291. // Server is down...
  6292. {
  6293. Client cli(HOST, PORT);
  6294. auto res = cli.Get("/hi");
  6295. EXPECT_FALSE(res);
  6296. }
  6297. }
  6298. }
  6299. #endif
  6300. // Helper function for string body upload progress tests
  6301. template <typename SetupHandler, typename ClientCall>
  6302. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6303. ClientCall &&client_call,
  6304. const string &body) {
  6305. Server svr;
  6306. setup_handler(svr);
  6307. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6308. auto se = detail::scope_exit([&] {
  6309. svr.stop();
  6310. t.join();
  6311. });
  6312. svr.wait_until_ready();
  6313. Client cli(HOST, PORT);
  6314. vector<uint64_t> progress_values;
  6315. bool progress_called = false;
  6316. auto res =
  6317. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6318. progress_values.push_back(current);
  6319. progress_called = true;
  6320. return true;
  6321. });
  6322. ASSERT_TRUE(res);
  6323. EXPECT_EQ(200, res->status);
  6324. EXPECT_TRUE(progress_called);
  6325. }
  6326. TEST(UploadProgressTest, PostStringBodyBasic) {
  6327. TestStringBodyUploadProgress(
  6328. [](Server &svr) {
  6329. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6330. res.set_content("received", "text/plain");
  6331. });
  6332. },
  6333. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6334. return cli.Post("/test", body, "text/plain", progress_callback);
  6335. },
  6336. "test data for upload progress");
  6337. }
  6338. TEST(UploadProgressTest, PutStringBodyBasic) {
  6339. TestStringBodyUploadProgress(
  6340. [](Server &svr) {
  6341. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6342. res.set_content("put received", "text/plain");
  6343. });
  6344. },
  6345. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6346. return cli.Put("/test", body, "text/plain", progress_callback);
  6347. },
  6348. "put test data for upload progress");
  6349. }
  6350. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6351. TestStringBodyUploadProgress(
  6352. [](Server &svr) {
  6353. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6354. res.set_content("patch received", "text/plain");
  6355. });
  6356. },
  6357. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6358. return cli.Patch("/test", body, "text/plain", progress_callback);
  6359. },
  6360. "patch test data for upload progress");
  6361. }
  6362. // Helper function for content provider upload progress tests
  6363. template <typename SetupHandler, typename ClientCall>
  6364. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6365. ClientCall &&client_call) {
  6366. Server svr;
  6367. setup_handler(svr);
  6368. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6369. auto se = detail::scope_exit([&] {
  6370. svr.stop();
  6371. t.join();
  6372. });
  6373. svr.wait_until_ready();
  6374. Client cli(HOST, PORT);
  6375. vector<uint64_t> progress_values;
  6376. auto res =
  6377. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6378. progress_values.push_back(current);
  6379. return true;
  6380. });
  6381. ASSERT_TRUE(res);
  6382. EXPECT_EQ(200, res->status);
  6383. EXPECT_FALSE(progress_values.empty());
  6384. }
  6385. TEST(UploadProgressTest, PostContentProviderProgress) {
  6386. TestContentProviderUploadProgress(
  6387. [](Server &svr) {
  6388. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6389. res.set_content("provider received", "text/plain");
  6390. });
  6391. },
  6392. [](Client &cli, UploadProgress progress_callback) {
  6393. return cli.Post(
  6394. "/test", 10,
  6395. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6396. sink.os << "test data";
  6397. return true;
  6398. },
  6399. "text/plain", progress_callback);
  6400. });
  6401. }
  6402. // Helper function for multipart upload progress tests
  6403. template <typename SetupHandler, typename ClientCall>
  6404. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6405. ClientCall &&client_call,
  6406. const string &endpoint) {
  6407. Server svr;
  6408. setup_handler(svr);
  6409. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6410. auto se = detail::scope_exit([&] {
  6411. svr.stop();
  6412. t.join();
  6413. });
  6414. svr.wait_until_ready();
  6415. Client cli(HOST, PORT);
  6416. vector<uint64_t> progress_values;
  6417. UploadFormDataItems items = {
  6418. {"field1", "value1", "", ""},
  6419. {"field2", "longer value for progress tracking test", "", ""},
  6420. {"file1", "file content data for upload progress", "test.txt",
  6421. "text/plain"}};
  6422. auto res = client_call(cli, endpoint, items,
  6423. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6424. progress_values.push_back(current);
  6425. return true;
  6426. });
  6427. ASSERT_TRUE(res);
  6428. EXPECT_EQ(200, res->status);
  6429. EXPECT_FALSE(progress_values.empty());
  6430. }
  6431. TEST(UploadProgressTest, PostMultipartProgress) {
  6432. TestMultipartUploadProgress(
  6433. [](Server &svr) {
  6434. svr.Post("/multipart", [](const Request &req, Response &res) {
  6435. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6436. res.set_content("multipart received", "text/plain");
  6437. });
  6438. },
  6439. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6440. UploadProgress progress_callback) {
  6441. return cli.Post(endpoint, items, progress_callback);
  6442. },
  6443. "/multipart");
  6444. }
  6445. // Helper function for basic download progress tests
  6446. template <typename SetupHandler, typename ClientCall>
  6447. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6448. ClientCall &&client_call, const string &endpoint,
  6449. size_t expected_content_size) {
  6450. Server svr;
  6451. setup_handler(svr);
  6452. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6453. auto se = detail::scope_exit([&] {
  6454. svr.stop();
  6455. t.join();
  6456. });
  6457. svr.wait_until_ready();
  6458. Client cli(HOST, PORT);
  6459. vector<uint64_t> progress_values;
  6460. auto res = client_call(cli, endpoint,
  6461. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6462. progress_values.push_back(current);
  6463. return true;
  6464. });
  6465. ASSERT_TRUE(res);
  6466. EXPECT_EQ(200, res->status);
  6467. EXPECT_FALSE(progress_values.empty());
  6468. EXPECT_EQ(expected_content_size, res->body.size());
  6469. }
  6470. TEST(DownloadProgressTest, GetBasic) {
  6471. TestBasicDownloadProgress(
  6472. [](Server &svr) {
  6473. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6474. string content(1000, 'D');
  6475. res.set_content(content, "text/plain");
  6476. });
  6477. },
  6478. [](Client &cli, const string &endpoint,
  6479. DownloadProgress progress_callback) {
  6480. return cli.Get(endpoint, progress_callback);
  6481. },
  6482. "/download", 1000u);
  6483. }
  6484. // Helper function for content receiver download progress tests
  6485. template <typename SetupHandler, typename ClientCall>
  6486. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6487. ClientCall &&client_call,
  6488. const string &endpoint,
  6489. size_t expected_content_size) {
  6490. Server svr;
  6491. setup_handler(svr);
  6492. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6493. auto se = detail::scope_exit([&] {
  6494. svr.stop();
  6495. t.join();
  6496. });
  6497. svr.wait_until_ready();
  6498. Client cli(HOST, PORT);
  6499. vector<uint64_t> progress_values;
  6500. string received_body;
  6501. auto res = client_call(
  6502. cli, endpoint,
  6503. [&](const char *data, size_t data_length) -> bool {
  6504. received_body.append(data, data_length);
  6505. return true;
  6506. },
  6507. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6508. progress_values.push_back(current);
  6509. return true;
  6510. });
  6511. ASSERT_TRUE(res);
  6512. EXPECT_EQ(200, res->status);
  6513. EXPECT_FALSE(progress_values.empty());
  6514. EXPECT_EQ(expected_content_size, received_body.size());
  6515. EXPECT_TRUE(res->body.empty());
  6516. }
  6517. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6518. TestContentReceiverDownloadProgress(
  6519. [](Server &svr) {
  6520. svr.Get("/download-receiver",
  6521. [](const Request & /*req*/, Response &res) {
  6522. string content(2000, 'R');
  6523. res.set_content(content, "text/plain");
  6524. });
  6525. },
  6526. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6527. DownloadProgress progress_callback) {
  6528. return cli.Get(endpoint, content_receiver, progress_callback);
  6529. },
  6530. "/download-receiver", 2000u);
  6531. }
  6532. TEST(StreamingTest, NoContentLengthStreaming) {
  6533. Server svr;
  6534. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6535. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6536. if (offset < 6) {
  6537. sink.os << (offset < 3 ? "a" : "b");
  6538. } else {
  6539. sink.done();
  6540. }
  6541. return true;
  6542. });
  6543. });
  6544. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6545. auto listen_se = detail::scope_exit([&] {
  6546. svr.stop();
  6547. listen_thread.join();
  6548. ASSERT_FALSE(svr.is_running());
  6549. });
  6550. svr.wait_until_ready();
  6551. Client client(HOST, PORT);
  6552. auto get_thread = std::thread([&client]() {
  6553. std::string s;
  6554. auto res =
  6555. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6556. s += std::string(data, len);
  6557. return true;
  6558. });
  6559. ASSERT_TRUE(res);
  6560. EXPECT_EQ(StatusCode::OK_200, res->status);
  6561. EXPECT_EQ("aaabbb", s);
  6562. });
  6563. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6564. // Give GET time to get a few messages.
  6565. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6566. }
  6567. TEST(MountTest, Unmount) {
  6568. Server svr;
  6569. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6570. auto se = detail::scope_exit([&] {
  6571. svr.stop();
  6572. listen_thread.join();
  6573. ASSERT_FALSE(svr.is_running());
  6574. });
  6575. svr.wait_until_ready();
  6576. Client cli("localhost", PORT);
  6577. svr.set_mount_point("/mount2", "./www2");
  6578. auto res = cli.Get("/");
  6579. ASSERT_TRUE(res);
  6580. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6581. res = cli.Get("/mount2/dir/test.html");
  6582. ASSERT_TRUE(res);
  6583. EXPECT_EQ(StatusCode::OK_200, res->status);
  6584. svr.set_mount_point("/", "./www");
  6585. res = cli.Get("/dir/");
  6586. ASSERT_TRUE(res);
  6587. EXPECT_EQ(StatusCode::OK_200, res->status);
  6588. svr.remove_mount_point("/");
  6589. res = cli.Get("/dir/");
  6590. ASSERT_TRUE(res);
  6591. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6592. svr.remove_mount_point("/mount2");
  6593. res = cli.Get("/mount2/dir/test.html");
  6594. ASSERT_TRUE(res);
  6595. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6596. }
  6597. TEST(MountTest, Redicect) {
  6598. Server svr;
  6599. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6600. auto se = detail::scope_exit([&] {
  6601. svr.stop();
  6602. listen_thread.join();
  6603. ASSERT_FALSE(svr.is_running());
  6604. });
  6605. svr.set_mount_point("/", "./www");
  6606. svr.wait_until_ready();
  6607. Client cli("localhost", PORT);
  6608. auto res = cli.Get("/dir/");
  6609. ASSERT_TRUE(res);
  6610. EXPECT_EQ(StatusCode::OK_200, res->status);
  6611. res = cli.Get("/dir");
  6612. ASSERT_TRUE(res);
  6613. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6614. res = cli.Get("/file");
  6615. ASSERT_TRUE(res);
  6616. EXPECT_EQ(StatusCode::OK_200, res->status);
  6617. res = cli.Get("/file/");
  6618. ASSERT_TRUE(res);
  6619. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6620. cli.set_follow_location(true);
  6621. res = cli.Get("/dir");
  6622. ASSERT_TRUE(res);
  6623. EXPECT_EQ(StatusCode::OK_200, res->status);
  6624. }
  6625. TEST(MountTest, MultibytesPathName) {
  6626. Server svr;
  6627. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6628. auto se = detail::scope_exit([&] {
  6629. svr.stop();
  6630. listen_thread.join();
  6631. ASSERT_FALSE(svr.is_running());
  6632. });
  6633. svr.set_mount_point("/", "./www");
  6634. svr.wait_until_ready();
  6635. Client cli("localhost", PORT);
  6636. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6637. ASSERT_TRUE(res);
  6638. EXPECT_EQ(StatusCode::OK_200, res->status);
  6639. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6640. }
  6641. TEST(KeepAliveTest, ReadTimeout) {
  6642. Server svr;
  6643. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6644. std::this_thread::sleep_for(std::chrono::seconds(2));
  6645. res.set_content("a", "text/plain");
  6646. });
  6647. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6648. res.set_content("b", "text/plain");
  6649. });
  6650. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6651. auto se = detail::scope_exit([&] {
  6652. svr.stop();
  6653. listen_thread.join();
  6654. ASSERT_FALSE(svr.is_running());
  6655. });
  6656. svr.wait_until_ready();
  6657. Client cli("localhost", PORT);
  6658. cli.set_keep_alive(true);
  6659. cli.set_read_timeout(std::chrono::seconds(1));
  6660. auto resa = cli.Get("/a");
  6661. ASSERT_FALSE(resa);
  6662. EXPECT_EQ(Error::Read, resa.error());
  6663. auto resb = cli.Get("/b");
  6664. ASSERT_TRUE(resb);
  6665. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6666. EXPECT_EQ("b", resb->body);
  6667. }
  6668. TEST(KeepAliveTest, MaxCount) {
  6669. size_t keep_alive_max_count = 3;
  6670. Server svr;
  6671. svr.set_keep_alive_max_count(keep_alive_max_count);
  6672. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6673. res.set_content("Hello World!", "text/plain");
  6674. });
  6675. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6676. auto se = detail::scope_exit([&] {
  6677. svr.stop();
  6678. listen_thread.join();
  6679. ASSERT_FALSE(svr.is_running());
  6680. });
  6681. svr.wait_until_ready();
  6682. Client cli(HOST, PORT);
  6683. cli.set_keep_alive(true);
  6684. for (size_t i = 0; i < 5; i++) {
  6685. auto result = cli.Get("/hi");
  6686. ASSERT_TRUE(result);
  6687. EXPECT_EQ(StatusCode::OK_200, result->status);
  6688. if (i == keep_alive_max_count - 1) {
  6689. EXPECT_EQ("close", result->get_header_value("Connection"));
  6690. } else {
  6691. EXPECT_FALSE(result->has_header("Connection"));
  6692. }
  6693. }
  6694. }
  6695. TEST(KeepAliveTest, Issue1041) {
  6696. Server svr;
  6697. svr.set_keep_alive_timeout(3);
  6698. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6699. res.set_content("Hello World!", "text/plain");
  6700. });
  6701. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6702. auto se = detail::scope_exit([&] {
  6703. svr.stop();
  6704. listen_thread.join();
  6705. ASSERT_FALSE(svr.is_running());
  6706. });
  6707. svr.wait_until_ready();
  6708. Client cli(HOST, PORT);
  6709. cli.set_keep_alive(true);
  6710. auto result = cli.Get("/hi");
  6711. ASSERT_TRUE(result);
  6712. EXPECT_EQ(StatusCode::OK_200, result->status);
  6713. std::this_thread::sleep_for(std::chrono::seconds(5));
  6714. result = cli.Get("/hi");
  6715. ASSERT_TRUE(result);
  6716. EXPECT_EQ(StatusCode::OK_200, result->status);
  6717. }
  6718. TEST(KeepAliveTest, Issue1959) {
  6719. Server svr;
  6720. svr.set_keep_alive_timeout(5);
  6721. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6722. res.set_content("a", "text/plain");
  6723. });
  6724. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6725. auto se = detail::scope_exit([&] {
  6726. if (!svr.is_running()) return;
  6727. svr.stop();
  6728. listen_thread.join();
  6729. ASSERT_FALSE(svr.is_running());
  6730. });
  6731. svr.wait_until_ready();
  6732. Client cli("localhost", PORT);
  6733. cli.set_keep_alive(true);
  6734. using namespace std::chrono;
  6735. auto start = steady_clock::now();
  6736. cli.Get("/a");
  6737. svr.stop();
  6738. listen_thread.join();
  6739. auto end = steady_clock::now();
  6740. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6741. EXPECT_LT(elapsed, 5000);
  6742. }
  6743. #ifdef CPPHTTPLIB_SSL_ENABLED
  6744. TEST(KeepAliveTest, SSLClientReconnection) {
  6745. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6746. ASSERT_TRUE(svr.is_valid());
  6747. svr.set_keep_alive_timeout(1);
  6748. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6749. res.set_content("Hello World!", "text/plain");
  6750. });
  6751. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6752. auto se = detail::scope_exit([&] {
  6753. svr.stop();
  6754. listen_thread.join();
  6755. ASSERT_FALSE(svr.is_running());
  6756. });
  6757. svr.wait_until_ready();
  6758. SSLClient cli(HOST, PORT);
  6759. cli.enable_server_certificate_verification(false);
  6760. cli.set_keep_alive(true);
  6761. auto result = cli.Get("/hi");
  6762. ASSERT_TRUE(result);
  6763. EXPECT_EQ(StatusCode::OK_200, result->status);
  6764. result = cli.Get("/hi");
  6765. ASSERT_TRUE(result);
  6766. EXPECT_EQ(StatusCode::OK_200, result->status);
  6767. std::this_thread::sleep_for(std::chrono::seconds(2));
  6768. // Recoonect
  6769. result = cli.Get("/hi");
  6770. ASSERT_TRUE(result);
  6771. EXPECT_EQ(StatusCode::OK_200, result->status);
  6772. result = cli.Get("/hi");
  6773. ASSERT_TRUE(result);
  6774. EXPECT_EQ(StatusCode::OK_200, result->status);
  6775. }
  6776. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6777. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6778. ASSERT_TRUE(svr.is_valid());
  6779. svr.set_keep_alive_timeout(1);
  6780. std::string content = "reconnect";
  6781. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6782. res.set_content("Hello World!", "text/plain");
  6783. });
  6784. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6785. auto se = detail::scope_exit([&] {
  6786. svr.stop();
  6787. listen_thread.join();
  6788. ASSERT_FALSE(svr.is_running());
  6789. });
  6790. svr.wait_until_ready();
  6791. SSLClient cli(HOST, PORT);
  6792. cli.enable_server_certificate_verification(false);
  6793. cli.set_keep_alive(true);
  6794. auto result = cli.Post(
  6795. "/hi", content.size(),
  6796. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6797. sink.write(content.c_str(), content.size());
  6798. return true;
  6799. },
  6800. "text/plain");
  6801. ASSERT_TRUE(result);
  6802. EXPECT_EQ(200, result->status);
  6803. std::this_thread::sleep_for(std::chrono::seconds(2));
  6804. // Recoonect
  6805. result = cli.Post(
  6806. "/hi", content.size(),
  6807. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6808. sink.write(content.c_str(), content.size());
  6809. return true;
  6810. },
  6811. "text/plain");
  6812. ASSERT_TRUE(result);
  6813. EXPECT_EQ(200, result->status);
  6814. result = cli.Post(
  6815. "/hi", content.size(),
  6816. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6817. sink.write(content.c_str(), content.size());
  6818. return true;
  6819. },
  6820. "text/plain");
  6821. ASSERT_TRUE(result);
  6822. EXPECT_EQ(200, result->status);
  6823. }
  6824. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6825. using namespace httplib::tls;
  6826. {
  6827. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6828. ASSERT_TRUE(svr.is_valid());
  6829. svr.Get("/sni", [&](const Request &req, Response &res) {
  6830. std::string expected = req.sni();
  6831. EXPECT_EQ(expected, req.get_param_value("expected"));
  6832. res.set_content("ok", "text/plain");
  6833. });
  6834. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6835. auto se = detail::scope_exit([&] {
  6836. svr.stop();
  6837. listen_thread.join();
  6838. ASSERT_FALSE(svr.is_running());
  6839. });
  6840. svr.wait_until_ready();
  6841. {
  6842. SSLClient cli("localhost", PORT);
  6843. cli.enable_server_certificate_verification(false);
  6844. auto res = cli.Get("/sni?expected=localhost");
  6845. ASSERT_TRUE(res);
  6846. }
  6847. {
  6848. SSLClient cli("::1", PORT);
  6849. cli.enable_server_certificate_verification(false);
  6850. auto res = cli.Get("/sni?expected=");
  6851. // NOTE: This may fail if the server is listening on IPv4 only
  6852. // (e.g., when localhost resolves to 127.0.0.1 only)
  6853. if (res) {
  6854. EXPECT_EQ(StatusCode::OK_200, res->status);
  6855. } else {
  6856. EXPECT_EQ(Error::Connection, res.error());
  6857. }
  6858. }
  6859. }
  6860. }
  6861. #endif
  6862. TEST(ClientProblemDetectionTest, ContentProvider) {
  6863. Server svr;
  6864. size_t content_length = 1024 * 1024;
  6865. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6866. res.set_content_provider(
  6867. content_length, "text/plain",
  6868. [&](size_t offset, size_t length, DataSink &sink) {
  6869. auto out_len = std::min(length, static_cast<size_t>(1024));
  6870. std::string out(out_len, '@');
  6871. sink.write(out.data(), out_len);
  6872. return offset < 4096;
  6873. },
  6874. [](bool success) { ASSERT_FALSE(success); });
  6875. });
  6876. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6877. res.set_content_provider(
  6878. 0, "text/plain",
  6879. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6880. EXPECT_TRUE(false);
  6881. return true;
  6882. },
  6883. [](bool success) { ASSERT_FALSE(success); });
  6884. });
  6885. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6886. auto se = detail::scope_exit([&] {
  6887. svr.stop();
  6888. listen_thread.join();
  6889. ASSERT_FALSE(svr.is_running());
  6890. });
  6891. svr.wait_until_ready();
  6892. Client cli("localhost", PORT);
  6893. {
  6894. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6895. size_t /*data_length*/) { return false; });
  6896. ASSERT_FALSE(res);
  6897. }
  6898. {
  6899. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6900. size_t /*data_length*/) { return false; });
  6901. ASSERT_TRUE(res);
  6902. }
  6903. }
  6904. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6905. Server svr;
  6906. svr.set_error_handler([](Request const &, Response &res) -> void {
  6907. res.set_chunked_content_provider(
  6908. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6909. sink.os << "hello";
  6910. sink.os << "world";
  6911. sink.done();
  6912. return true;
  6913. });
  6914. });
  6915. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  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("/");
  6924. ASSERT_TRUE(res);
  6925. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6926. EXPECT_EQ("helloworld", res->body);
  6927. }
  6928. TEST(LongPollingTest, ClientCloseDetection) {
  6929. Server svr;
  6930. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6931. res.set_chunked_content_provider(
  6932. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6933. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6934. sink.os << "hello";
  6935. auto count = 10;
  6936. while (count > 0 && sink.is_writable()) {
  6937. this_thread::sleep_for(chrono::milliseconds(10));
  6938. count--;
  6939. }
  6940. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6941. return true;
  6942. });
  6943. });
  6944. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6945. auto se = detail::scope_exit([&] {
  6946. svr.stop();
  6947. listen_thread.join();
  6948. ASSERT_FALSE(svr.is_running());
  6949. });
  6950. svr.wait_until_ready();
  6951. Client cli("localhost", PORT);
  6952. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6953. EXPECT_EQ("hello", string(data, data_length));
  6954. return false; // close the socket immediately.
  6955. });
  6956. ASSERT_FALSE(res);
  6957. }
  6958. TEST(GetWithParametersTest, GetWithParameters) {
  6959. Server svr;
  6960. svr.Get("/", [&](const Request &req, Response &) {
  6961. EXPECT_EQ("world", req.get_param_value("hello"));
  6962. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6963. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6964. });
  6965. svr.Get("/params", [&](const Request &req, Response &) {
  6966. EXPECT_EQ("world", req.get_param_value("hello"));
  6967. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6968. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6969. });
  6970. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6971. EXPECT_EQ("resource-id", req.matches[1]);
  6972. EXPECT_EQ("foo", req.get_param_value("param1"));
  6973. EXPECT_EQ("bar", req.get_param_value("param2"));
  6974. });
  6975. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6976. EXPECT_EQ("user-id", req.path_params.at("id"));
  6977. EXPECT_EQ("foo", req.get_param_value("param1"));
  6978. EXPECT_EQ("bar", req.get_param_value("param2"));
  6979. });
  6980. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6981. auto se = detail::scope_exit([&] {
  6982. svr.stop();
  6983. listen_thread.join();
  6984. ASSERT_FALSE(svr.is_running());
  6985. });
  6986. svr.wait_until_ready();
  6987. {
  6988. Client cli(HOST, PORT);
  6989. Params params;
  6990. params.emplace("hello", "world");
  6991. params.emplace("hello2", "world2");
  6992. params.emplace("hello3", "world3");
  6993. auto res = cli.Get("/", params, Headers{});
  6994. ASSERT_TRUE(res);
  6995. EXPECT_EQ(StatusCode::OK_200, res->status);
  6996. }
  6997. {
  6998. Client cli(HOST, PORT);
  6999. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  7000. ASSERT_TRUE(res);
  7001. EXPECT_EQ(StatusCode::OK_200, res->status);
  7002. }
  7003. {
  7004. Client cli(HOST, PORT);
  7005. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  7006. ASSERT_TRUE(res);
  7007. EXPECT_EQ(StatusCode::OK_200, res->status);
  7008. }
  7009. {
  7010. Client cli(HOST, PORT);
  7011. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  7012. ASSERT_TRUE(res);
  7013. EXPECT_EQ(StatusCode::OK_200, res->status);
  7014. }
  7015. }
  7016. TEST(GetWithParametersTest, GetWithParameters2) {
  7017. Server svr;
  7018. svr.Get("/", [&](const Request &req, Response &res) {
  7019. auto text = req.get_param_value("hello");
  7020. res.set_content(text, "text/plain");
  7021. });
  7022. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7023. auto se = detail::scope_exit([&] {
  7024. svr.stop();
  7025. listen_thread.join();
  7026. ASSERT_FALSE(svr.is_running());
  7027. });
  7028. svr.wait_until_ready();
  7029. Client cli("localhost", PORT);
  7030. Params params;
  7031. params.emplace("hello", "world");
  7032. std::string body;
  7033. auto res = cli.Get("/", params, Headers{},
  7034. [&](const char *data, size_t data_length) {
  7035. body.append(data, data_length);
  7036. return true;
  7037. });
  7038. ASSERT_TRUE(res);
  7039. EXPECT_EQ(StatusCode::OK_200, res->status);
  7040. EXPECT_EQ("world", body);
  7041. }
  7042. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  7043. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7044. auto host = "httpcan.org";
  7045. auto path = std::string{"/range/32"};
  7046. #else
  7047. auto host = "nghttp2.org";
  7048. auto path = std::string{"/httpbin/range/32"};
  7049. #endif
  7050. #ifdef CPPHTTPLIB_SSL_ENABLED
  7051. SSLClient cli(host);
  7052. #else
  7053. Client cli(host);
  7054. #endif
  7055. cli.set_default_headers({make_range_header({{1, 10}})});
  7056. cli.set_connection_timeout(5);
  7057. {
  7058. auto res = cli.Get(path);
  7059. ASSERT_TRUE(res);
  7060. EXPECT_EQ("bcdefghijk", res->body);
  7061. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7062. }
  7063. {
  7064. auto res = cli.Get(path);
  7065. ASSERT_TRUE(res);
  7066. EXPECT_EQ("bcdefghijk", res->body);
  7067. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7068. }
  7069. }
  7070. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7071. Server svr;
  7072. svr.set_default_headers({{"Hello", "World"}});
  7073. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7074. res.set_content("ok", "text/plain");
  7075. });
  7076. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7077. auto se = detail::scope_exit([&] {
  7078. svr.stop();
  7079. listen_thread.join();
  7080. ASSERT_FALSE(svr.is_running());
  7081. });
  7082. svr.wait_until_ready();
  7083. Client cli("localhost", PORT);
  7084. auto res = cli.Get("/");
  7085. ASSERT_TRUE(res);
  7086. EXPECT_EQ(StatusCode::OK_200, res->status);
  7087. EXPECT_EQ("ok", res->body);
  7088. EXPECT_EQ("World", res->get_header_value("Hello"));
  7089. }
  7090. #ifdef CPPHTTPLIB_SSL_ENABLED
  7091. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7092. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7093. ASSERT_TRUE(svr.is_valid());
  7094. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7095. std::this_thread::sleep_for(std::chrono::seconds(2));
  7096. res.set_content("a", "text/plain");
  7097. });
  7098. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7099. res.set_content("b", "text/plain");
  7100. });
  7101. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7102. auto se = detail::scope_exit([&] {
  7103. svr.stop();
  7104. listen_thread.join();
  7105. ASSERT_FALSE(svr.is_running());
  7106. });
  7107. svr.wait_until_ready();
  7108. SSLClient cli("localhost", PORT);
  7109. cli.enable_server_certificate_verification(false);
  7110. cli.set_keep_alive(true);
  7111. cli.set_read_timeout(std::chrono::seconds(1));
  7112. auto resa = cli.Get("/a");
  7113. ASSERT_TRUE(!resa);
  7114. EXPECT_EQ(Error::Read, resa.error());
  7115. auto resb = cli.Get("/b");
  7116. ASSERT_TRUE(resb);
  7117. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7118. EXPECT_EQ("b", resb->body);
  7119. }
  7120. #endif
  7121. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7122. protected:
  7123. ServerTestWithAI_PASSIVE()
  7124. : cli_(HOST, PORT)
  7125. #ifdef CPPHTTPLIB_SSL_ENABLED
  7126. ,
  7127. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7128. #endif
  7129. {
  7130. #ifdef CPPHTTPLIB_SSL_ENABLED
  7131. cli_.enable_server_certificate_verification(false);
  7132. #endif
  7133. }
  7134. virtual void SetUp() {
  7135. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7136. res.set_content("Hello World!", "text/plain");
  7137. });
  7138. t_ = thread(
  7139. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7140. svr_.wait_until_ready();
  7141. }
  7142. virtual void TearDown() {
  7143. svr_.stop();
  7144. t_.join();
  7145. }
  7146. #ifdef CPPHTTPLIB_SSL_ENABLED
  7147. SSLClient cli_;
  7148. SSLServer svr_;
  7149. #else
  7150. Client cli_;
  7151. Server svr_;
  7152. #endif
  7153. thread t_;
  7154. };
  7155. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7156. auto res = cli_.Get("/hi");
  7157. ASSERT_TRUE(res);
  7158. EXPECT_EQ(StatusCode::OK_200, res->status);
  7159. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7160. EXPECT_EQ("Hello World!", res->body);
  7161. }
  7162. class ServerUpDownTest : public ::testing::Test {
  7163. protected:
  7164. ServerUpDownTest() : cli_(HOST, PORT) {}
  7165. virtual void SetUp() {
  7166. t_ = thread([&]() {
  7167. svr_.bind_to_any_port(HOST);
  7168. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7169. ASSERT_TRUE(svr_.listen_after_bind());
  7170. });
  7171. svr_.wait_until_ready();
  7172. }
  7173. virtual void TearDown() {
  7174. svr_.stop();
  7175. t_.join();
  7176. }
  7177. Client cli_;
  7178. Server svr_;
  7179. thread t_;
  7180. };
  7181. TEST_F(ServerUpDownTest, QuickStartStop) {
  7182. // Should not crash, especially when run with
  7183. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7184. }
  7185. class PayloadMaxLengthTest : public ::testing::Test {
  7186. protected:
  7187. PayloadMaxLengthTest()
  7188. : cli_(HOST, PORT)
  7189. #ifdef CPPHTTPLIB_SSL_ENABLED
  7190. ,
  7191. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7192. #endif
  7193. {
  7194. #ifdef CPPHTTPLIB_SSL_ENABLED
  7195. cli_.enable_server_certificate_verification(false);
  7196. #endif
  7197. }
  7198. virtual void SetUp() {
  7199. svr_.set_payload_max_length(8);
  7200. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7201. res.set_content("test", "text/plain");
  7202. });
  7203. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7204. svr_.wait_until_ready();
  7205. }
  7206. virtual void TearDown() {
  7207. svr_.stop();
  7208. t_.join();
  7209. }
  7210. #ifdef CPPHTTPLIB_SSL_ENABLED
  7211. SSLClient cli_;
  7212. SSLServer svr_;
  7213. #else
  7214. Client cli_;
  7215. Server svr_;
  7216. #endif
  7217. thread t_;
  7218. };
  7219. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7220. auto res = cli_.Post("/test", "123456789", "text/plain");
  7221. ASSERT_TRUE(res);
  7222. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7223. res = cli_.Post("/test", "12345678", "text/plain");
  7224. ASSERT_TRUE(res);
  7225. EXPECT_EQ(StatusCode::OK_200, res->status);
  7226. }
  7227. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7228. // Test chunked encoding with payload exceeding the 8-byte limit
  7229. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7230. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7231. ASSERT_TRUE(res);
  7232. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7233. }
  7234. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7235. // Test chunked encoding with payload within the 8-byte limit
  7236. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7237. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7238. ASSERT_TRUE(res);
  7239. EXPECT_EQ(StatusCode::OK_200, res->status);
  7240. }
  7241. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7242. // Test using send_request to send chunked data exceeding payload limit
  7243. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7244. "Host: " +
  7245. std::string(HOST) + ":" + std::to_string(PORT) +
  7246. "\r\n"
  7247. "Transfer-Encoding: chunked\r\n"
  7248. "Connection: close\r\n"
  7249. "\r\n"
  7250. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7251. "0123456789\r\n"
  7252. "0\r\n" // End chunk
  7253. "\r\n";
  7254. std::string response;
  7255. bool result = send_request(1, chunked_request, &response);
  7256. if (!result) {
  7257. // If send_request fails, it might be because the server closed the
  7258. // connection due to payload limit enforcement, which is acceptable
  7259. SUCCEED()
  7260. << "Server rejected oversized chunked request (connection closed)";
  7261. } else {
  7262. // If we got a response, check if it's an error response or connection was
  7263. // closed early Short response length indicates connection was closed due to
  7264. // payload limit
  7265. if (response.length() <= 10) {
  7266. SUCCEED() << "Server closed connection for oversized chunked request";
  7267. } else {
  7268. // Check for error status codes
  7269. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7270. response.find("Payload Too Large") != std::string::npos ||
  7271. response.find("400") != std::string::npos);
  7272. }
  7273. }
  7274. }
  7275. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7276. // Test request without Content-Length header exceeding payload limit
  7277. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7278. "Host: " +
  7279. std::string(HOST) + ":" +
  7280. std::to_string(PORT) +
  7281. "\r\n"
  7282. "Connection: close\r\n"
  7283. "\r\n";
  7284. // Add payload exceeding the 8-byte limit
  7285. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7286. request_without_content_length += large_payload;
  7287. std::string response;
  7288. bool result = send_request(1, request_without_content_length, &response);
  7289. if (!result) {
  7290. // If send_request fails, server likely closed connection due to payload
  7291. // limit
  7292. SUCCEED() << "Server rejected oversized request without Content-Length "
  7293. "(connection closed)";
  7294. } else {
  7295. // Check if server responded with error or closed connection early
  7296. if (response.length() <= 10) {
  7297. SUCCEED() << "Server closed connection for oversized request without "
  7298. "Content-Length";
  7299. } else {
  7300. // Check for error status codes
  7301. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7302. response.find("Payload Too Large") != std::string::npos ||
  7303. response.find("400") != std::string::npos);
  7304. }
  7305. }
  7306. }
  7307. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7308. // Test request without Content-Length header within payload limit
  7309. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7310. "Host: " +
  7311. std::string(HOST) + ":" +
  7312. std::to_string(PORT) +
  7313. "\r\n"
  7314. "Connection: close\r\n"
  7315. "\r\n";
  7316. // Add payload within the 8-byte limit
  7317. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7318. request_without_content_length += small_payload;
  7319. std::string response;
  7320. bool result = send_request(1, request_without_content_length, &response);
  7321. // For requests without Content-Length, the server may have different behavior
  7322. // The key is that it should not reject due to payload limit for small
  7323. // payloads
  7324. if (result) {
  7325. // Check for any HTTP response (success or error, but not connection closed)
  7326. if (response.length() > 10) {
  7327. SUCCEED()
  7328. << "Server processed request without Content-Length within limit";
  7329. } else {
  7330. // Short response might indicate connection closed, which is acceptable
  7331. SUCCEED() << "Server closed connection for request without "
  7332. "Content-Length (acceptable behavior)";
  7333. }
  7334. } else {
  7335. // Connection failure might be due to protocol requirements
  7336. SUCCEED() << "Connection issue with request without Content-Length "
  7337. "(environment-specific)";
  7338. }
  7339. }
  7340. class LargePayloadMaxLengthTest : public ::testing::Test {
  7341. protected:
  7342. LargePayloadMaxLengthTest()
  7343. : cli_(HOST, PORT)
  7344. #ifdef CPPHTTPLIB_SSL_ENABLED
  7345. ,
  7346. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7347. #endif
  7348. {
  7349. #ifdef CPPHTTPLIB_SSL_ENABLED
  7350. cli_.enable_server_certificate_verification(false);
  7351. #endif
  7352. }
  7353. virtual void SetUp() {
  7354. // Set 10MB payload limit
  7355. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7356. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7357. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7358. res.set_content("Large payload test", "text/plain");
  7359. });
  7360. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7361. svr_.wait_until_ready();
  7362. }
  7363. virtual void TearDown() {
  7364. svr_.stop();
  7365. t_.join();
  7366. }
  7367. #ifdef CPPHTTPLIB_SSL_ENABLED
  7368. SSLClient cli_;
  7369. SSLServer svr_;
  7370. #else
  7371. Client cli_;
  7372. Server svr_;
  7373. #endif
  7374. thread t_;
  7375. };
  7376. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7377. // Test chunked encoding with payload within 10MB limit
  7378. std::string medium_payload(5 * 1024 * 1024,
  7379. 'A'); // 5MB payload, within 10MB limit
  7380. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7381. ASSERT_TRUE(res);
  7382. EXPECT_EQ(StatusCode::OK_200, res->status);
  7383. }
  7384. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7385. // Test chunked encoding with payload exceeding 10MB limit
  7386. std::string large_payload(12 * 1024 * 1024,
  7387. 'B'); // 12MB payload, exceeds 10MB limit
  7388. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7389. // Server may either return 413 or close the connection
  7390. if (res) {
  7391. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7392. } else {
  7393. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7394. }
  7395. }
  7396. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7397. // Test request without Content-Length header within 10MB limit
  7398. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7399. "Host: " +
  7400. std::string(HOST) + ":" +
  7401. std::to_string(PORT) +
  7402. "\r\n"
  7403. "Connection: close\r\n"
  7404. "\r\n";
  7405. // Add 1MB payload (within 10MB limit)
  7406. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7407. request_without_content_length += medium_payload;
  7408. std::string response;
  7409. bool result = send_request(5, request_without_content_length, &response);
  7410. if (result) {
  7411. // Should get a proper HTTP response for payloads within limit
  7412. if (response.length() > 10) {
  7413. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7414. "10MB limit";
  7415. } else {
  7416. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7417. "Content-Length)";
  7418. }
  7419. } else {
  7420. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7421. }
  7422. }
  7423. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7424. // Test request without Content-Length header exceeding 10MB limit
  7425. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7426. "Host: " +
  7427. std::string(HOST) + ":" +
  7428. std::to_string(PORT) +
  7429. "\r\n"
  7430. "Connection: close\r\n"
  7431. "\r\n";
  7432. // Add 12MB payload (exceeds 10MB limit)
  7433. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7434. request_without_content_length += large_payload;
  7435. std::string response;
  7436. bool result = send_request(10, request_without_content_length, &response);
  7437. if (!result) {
  7438. // Server should close connection due to payload limit
  7439. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7440. "(connection closed)";
  7441. } else {
  7442. // Check for error response
  7443. if (response.length() <= 10) {
  7444. SUCCEED()
  7445. << "Server closed connection for 12MB request exceeding 10MB limit";
  7446. } else {
  7447. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7448. response.find("Payload Too Large") != std::string::npos ||
  7449. response.find("400") != std::string::npos);
  7450. }
  7451. }
  7452. }
  7453. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7454. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7455. // path.
  7456. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7457. Server svr;
  7458. const size_t LIMIT = 64 * 1024; // 64KB
  7459. svr.set_payload_max_length(LIMIT);
  7460. size_t total = 0;
  7461. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7462. const ContentReader &content_reader) {
  7463. content_reader([&](const char * /*data*/, size_t len) {
  7464. total += len;
  7465. return true;
  7466. });
  7467. res.status = 200;
  7468. res.set_content("stream_ok", "text/plain");
  7469. });
  7470. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7471. auto se = detail::scope_exit([&] {
  7472. svr.stop();
  7473. thread.join();
  7474. ASSERT_FALSE(svr.is_running());
  7475. });
  7476. svr.wait_until_ready();
  7477. // Prepare 256KB raw data and gzip-compress it
  7478. std::string raw(256 * 1024, 'A');
  7479. std::string gz;
  7480. {
  7481. z_stream zs{};
  7482. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7483. Z_DEFAULT_STRATEGY);
  7484. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7485. zs.avail_in = static_cast<uInt>(raw.size());
  7486. char outbuf[4096];
  7487. int ret;
  7488. do {
  7489. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7490. zs.avail_out = sizeof(outbuf);
  7491. ret = deflate(&zs, Z_FINISH);
  7492. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7493. } while (ret != Z_STREAM_END);
  7494. deflateEnd(&zs);
  7495. }
  7496. Client cli(HOST, PORT);
  7497. cli.set_connection_timeout(std::chrono::seconds(5));
  7498. Headers headers = {{"Content-Encoding", "gzip"}};
  7499. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7500. "application/octet-stream");
  7501. ASSERT_TRUE(res);
  7502. // Server must reject oversized decompressed payloads with 413.
  7503. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7504. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7505. EXPECT_LE(total, LIMIT);
  7506. }
  7507. #endif
  7508. // Regression test for DoS vulnerability: a malicious server sending a response
  7509. // without Content-Length header must not cause unbounded memory consumption on
  7510. // the client side. The client should stop reading after a reasonable limit,
  7511. // similar to the server-side set_payload_max_length protection.
  7512. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7513. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7514. #ifndef _WIN32
  7515. signal(SIGPIPE, SIG_IGN);
  7516. #endif
  7517. auto server_thread = std::thread([] {
  7518. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7519. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7520. default_socket_options(srv);
  7521. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7522. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7523. sockaddr_in addr{};
  7524. addr.sin_family = AF_INET;
  7525. addr.sin_port = htons(PORT + 2);
  7526. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7527. int opt = 1;
  7528. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7529. #ifdef _WIN32
  7530. reinterpret_cast<const char *>(&opt),
  7531. #else
  7532. &opt,
  7533. #endif
  7534. sizeof(opt));
  7535. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7536. ::listen(srv, 1);
  7537. sockaddr_in cli_addr{};
  7538. socklen_t cli_len = sizeof(cli_addr);
  7539. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7540. if (cli != INVALID_SOCKET) {
  7541. char buf[4096];
  7542. ::recv(cli, buf, sizeof(buf), 0);
  7543. // Malicious response: no Content-Length, no chunked encoding
  7544. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7545. "Connection: close\r\n"
  7546. "\r\n";
  7547. ::send(cli,
  7548. #ifdef _WIN32
  7549. static_cast<const char *>(response_header.c_str()),
  7550. static_cast<int>(response_header.size()),
  7551. #else
  7552. response_header.c_str(), response_header.size(),
  7553. #endif
  7554. 0);
  7555. // Send 10MB of data
  7556. std::string chunk(64 * 1024, 'A');
  7557. size_t total_sent = 0;
  7558. while (total_sent < MALICIOUS_DATA_SIZE) {
  7559. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7560. auto sent = ::send(cli,
  7561. #ifdef _WIN32
  7562. static_cast<const char *>(chunk.c_str()),
  7563. static_cast<int>(to_send),
  7564. #else
  7565. chunk.c_str(), to_send,
  7566. #endif
  7567. 0);
  7568. if (sent <= 0) break;
  7569. total_sent += static_cast<size_t>(sent);
  7570. }
  7571. detail::close_socket(cli);
  7572. }
  7573. detail::close_socket(srv);
  7574. });
  7575. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7576. size_t total_read = 0;
  7577. {
  7578. Client cli("127.0.0.1", PORT + 2);
  7579. cli.set_read_timeout(5, 0);
  7580. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7581. auto stream = cli.open_stream("GET", "/malicious");
  7582. ASSERT_TRUE(stream.is_valid());
  7583. char buffer[64 * 1024];
  7584. ssize_t n;
  7585. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7586. total_read += static_cast<size_t>(n);
  7587. }
  7588. } // StreamHandle and Client destroyed here, closing the socket
  7589. server_thread.join();
  7590. // With set_payload_max_length, the client must stop reading before consuming
  7591. // all 10MB. The read loop should be cut off at or near the configured limit.
  7592. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7593. << "Client read " << total_read << " bytes, exceeding the configured "
  7594. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7595. }
  7596. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7597. // the entire response body without truncation.
  7598. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7599. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7600. #ifndef _WIN32
  7601. signal(SIGPIPE, SIG_IGN);
  7602. #endif
  7603. auto server_thread = std::thread([] {
  7604. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7605. default_socket_options(srv);
  7606. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7607. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7608. sockaddr_in addr{};
  7609. addr.sin_family = AF_INET;
  7610. addr.sin_port = htons(PORT + 2);
  7611. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7612. int opt = 1;
  7613. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7614. #ifdef _WIN32
  7615. reinterpret_cast<const char *>(&opt),
  7616. #else
  7617. &opt,
  7618. #endif
  7619. sizeof(opt));
  7620. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7621. ::listen(srv, 1);
  7622. sockaddr_in cli_addr{};
  7623. socklen_t cli_len = sizeof(cli_addr);
  7624. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7625. if (cli != INVALID_SOCKET) {
  7626. char buf[4096];
  7627. ::recv(cli, buf, sizeof(buf), 0);
  7628. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7629. "Connection: close\r\n"
  7630. "\r\n";
  7631. ::send(cli,
  7632. #ifdef _WIN32
  7633. static_cast<const char *>(response_header.c_str()),
  7634. static_cast<int>(response_header.size()),
  7635. #else
  7636. response_header.c_str(), response_header.size(),
  7637. #endif
  7638. 0);
  7639. std::string chunk(64 * 1024, 'A');
  7640. size_t total_sent = 0;
  7641. while (total_sent < DATA_SIZE) {
  7642. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7643. auto sent = ::send(cli,
  7644. #ifdef _WIN32
  7645. static_cast<const char *>(chunk.c_str()),
  7646. static_cast<int>(to_send),
  7647. #else
  7648. chunk.c_str(), to_send,
  7649. #endif
  7650. 0);
  7651. if (sent <= 0) break;
  7652. total_sent += static_cast<size_t>(sent);
  7653. }
  7654. #ifdef _WIN32
  7655. ::shutdown(cli, SD_SEND);
  7656. #else
  7657. ::shutdown(cli, SHUT_WR);
  7658. #endif
  7659. // Drain until the client closes its end, ensuring all data is delivered
  7660. char drain[1024];
  7661. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7662. detail::close_socket(cli);
  7663. }
  7664. detail::close_socket(srv);
  7665. });
  7666. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7667. size_t total_read = 0;
  7668. {
  7669. Client cli("127.0.0.1", PORT + 2);
  7670. cli.set_read_timeout(5, 0);
  7671. cli.set_payload_max_length(0); // 0 means no limit
  7672. auto stream = cli.open_stream("GET", "/data");
  7673. ASSERT_TRUE(stream.is_valid());
  7674. char buffer[64 * 1024];
  7675. ssize_t n;
  7676. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7677. total_read += static_cast<size_t>(n);
  7678. }
  7679. }
  7680. server_thread.join();
  7681. EXPECT_EQ(total_read, DATA_SIZE)
  7682. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7683. << " bytes without truncation, but only read " << total_read << " bytes.";
  7684. }
  7685. // Verify that content_receiver bypasses the default payload_max_length,
  7686. // allowing streaming downloads larger than 100MB without requiring an explicit
  7687. // set_payload_max_length call.
  7688. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  7689. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7690. #ifndef _WIN32
  7691. signal(SIGPIPE, SIG_IGN);
  7692. #endif
  7693. auto server_thread = std::thread([] {
  7694. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7695. default_socket_options(srv);
  7696. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7697. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7698. sockaddr_in addr{};
  7699. addr.sin_family = AF_INET;
  7700. addr.sin_port = htons(PORT + 2);
  7701. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7702. int opt = 1;
  7703. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7704. #ifdef _WIN32
  7705. reinterpret_cast<const char *>(&opt),
  7706. #else
  7707. &opt,
  7708. #endif
  7709. sizeof(opt));
  7710. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7711. ::listen(srv, 1);
  7712. sockaddr_in cli_addr{};
  7713. socklen_t cli_len = sizeof(cli_addr);
  7714. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7715. if (cli != INVALID_SOCKET) {
  7716. char buf[4096];
  7717. ::recv(cli, buf, sizeof(buf), 0);
  7718. // Response with Content-Length larger than default 100MB limit
  7719. auto content_length = std::to_string(DATA_SIZE);
  7720. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7721. "Content-Length: " +
  7722. content_length +
  7723. "\r\n"
  7724. "Connection: close\r\n"
  7725. "\r\n";
  7726. ::send(cli,
  7727. #ifdef _WIN32
  7728. static_cast<const char *>(response_header.c_str()),
  7729. static_cast<int>(response_header.size()),
  7730. #else
  7731. response_header.c_str(), response_header.size(),
  7732. #endif
  7733. 0);
  7734. std::string chunk(64 * 1024, 'A');
  7735. size_t total_sent = 0;
  7736. while (total_sent < DATA_SIZE) {
  7737. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7738. auto sent = ::send(cli,
  7739. #ifdef _WIN32
  7740. static_cast<const char *>(chunk.c_str()),
  7741. static_cast<int>(to_send),
  7742. #else
  7743. chunk.c_str(), to_send,
  7744. #endif
  7745. 0);
  7746. if (sent <= 0) break;
  7747. total_sent += static_cast<size_t>(sent);
  7748. }
  7749. detail::close_socket(cli);
  7750. }
  7751. detail::close_socket(srv);
  7752. });
  7753. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7754. size_t total_received = 0;
  7755. {
  7756. Client cli("127.0.0.1", PORT + 2);
  7757. cli.set_read_timeout(10, 0);
  7758. // Do NOT call set_payload_max_length — use the default 100MB limit
  7759. auto res =
  7760. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7761. total_received += data_length;
  7762. return true;
  7763. });
  7764. ASSERT_TRUE(res);
  7765. EXPECT_EQ(StatusCode::OK_200, res->status);
  7766. }
  7767. server_thread.join();
  7768. EXPECT_EQ(total_received, DATA_SIZE)
  7769. << "With content_receiver, the client should read all " << DATA_SIZE
  7770. << " bytes despite the default 100MB payload_max_length, but only read "
  7771. << total_received << " bytes.";
  7772. }
  7773. // Verify that an explicit set_payload_max_length smaller than the response is
  7774. // enforced even when a content_receiver is used.
  7775. TEST(ClientVulnerabilityTest,
  7776. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  7777. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7778. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  7779. #ifndef _WIN32
  7780. signal(SIGPIPE, SIG_IGN);
  7781. #endif
  7782. auto server_thread = std::thread([] {
  7783. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7784. default_socket_options(srv);
  7785. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7786. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7787. sockaddr_in addr{};
  7788. addr.sin_family = AF_INET;
  7789. addr.sin_port = htons(PORT + 2);
  7790. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7791. int opt = 1;
  7792. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7793. #ifdef _WIN32
  7794. reinterpret_cast<const char *>(&opt),
  7795. #else
  7796. &opt,
  7797. #endif
  7798. sizeof(opt));
  7799. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7800. ::listen(srv, 1);
  7801. sockaddr_in cli_addr{};
  7802. socklen_t cli_len = sizeof(cli_addr);
  7803. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7804. if (cli != INVALID_SOCKET) {
  7805. char buf[4096];
  7806. ::recv(cli, buf, sizeof(buf), 0);
  7807. auto content_length = std::to_string(DATA_SIZE);
  7808. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7809. "Content-Length: " +
  7810. content_length +
  7811. "\r\n"
  7812. "Connection: close\r\n"
  7813. "\r\n";
  7814. ::send(cli,
  7815. #ifdef _WIN32
  7816. static_cast<const char *>(response_header.c_str()),
  7817. static_cast<int>(response_header.size()),
  7818. #else
  7819. response_header.c_str(), response_header.size(),
  7820. #endif
  7821. 0);
  7822. std::string chunk(64 * 1024, 'A');
  7823. size_t total_sent = 0;
  7824. while (total_sent < DATA_SIZE) {
  7825. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7826. auto sent = ::send(cli,
  7827. #ifdef _WIN32
  7828. static_cast<const char *>(chunk.c_str()),
  7829. static_cast<int>(to_send),
  7830. #else
  7831. chunk.c_str(), to_send,
  7832. #endif
  7833. 0);
  7834. if (sent <= 0) break;
  7835. total_sent += static_cast<size_t>(sent);
  7836. }
  7837. detail::close_socket(cli);
  7838. }
  7839. detail::close_socket(srv);
  7840. });
  7841. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7842. size_t total_received = 0;
  7843. {
  7844. Client cli("127.0.0.1", PORT + 2);
  7845. cli.set_read_timeout(10, 0);
  7846. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  7847. auto res =
  7848. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7849. total_received += data_length;
  7850. return true;
  7851. });
  7852. // Should fail because 200MB exceeds the explicit 150MB limit
  7853. EXPECT_FALSE(res);
  7854. }
  7855. server_thread.join();
  7856. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  7857. << "Client with content_receiver should respect the explicit "
  7858. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  7859. << total_received << " bytes.";
  7860. }
  7861. // Verify that an explicit set_payload_max_length larger than the response
  7862. // allows the content_receiver to read all data successfully.
  7863. TEST(ClientVulnerabilityTest,
  7864. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  7865. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7866. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  7867. #ifndef _WIN32
  7868. signal(SIGPIPE, SIG_IGN);
  7869. #endif
  7870. auto server_thread = std::thread([] {
  7871. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7872. default_socket_options(srv);
  7873. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7874. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7875. sockaddr_in addr{};
  7876. addr.sin_family = AF_INET;
  7877. addr.sin_port = htons(PORT + 2);
  7878. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7879. int opt = 1;
  7880. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7881. #ifdef _WIN32
  7882. reinterpret_cast<const char *>(&opt),
  7883. #else
  7884. &opt,
  7885. #endif
  7886. sizeof(opt));
  7887. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7888. ::listen(srv, 1);
  7889. sockaddr_in cli_addr{};
  7890. socklen_t cli_len = sizeof(cli_addr);
  7891. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7892. if (cli != INVALID_SOCKET) {
  7893. char buf[4096];
  7894. ::recv(cli, buf, sizeof(buf), 0);
  7895. auto content_length = std::to_string(DATA_SIZE);
  7896. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7897. "Content-Length: " +
  7898. content_length +
  7899. "\r\n"
  7900. "Connection: close\r\n"
  7901. "\r\n";
  7902. ::send(cli,
  7903. #ifdef _WIN32
  7904. static_cast<const char *>(response_header.c_str()),
  7905. static_cast<int>(response_header.size()),
  7906. #else
  7907. response_header.c_str(), response_header.size(),
  7908. #endif
  7909. 0);
  7910. std::string chunk(64 * 1024, 'A');
  7911. size_t total_sent = 0;
  7912. while (total_sent < DATA_SIZE) {
  7913. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7914. auto sent = ::send(cli,
  7915. #ifdef _WIN32
  7916. static_cast<const char *>(chunk.c_str()),
  7917. static_cast<int>(to_send),
  7918. #else
  7919. chunk.c_str(), to_send,
  7920. #endif
  7921. 0);
  7922. if (sent <= 0) break;
  7923. total_sent += static_cast<size_t>(sent);
  7924. }
  7925. #ifdef _WIN32
  7926. ::shutdown(cli, SD_SEND);
  7927. #else
  7928. ::shutdown(cli, SHUT_WR);
  7929. #endif
  7930. char drain[1024];
  7931. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7932. detail::close_socket(cli);
  7933. }
  7934. detail::close_socket(srv);
  7935. });
  7936. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7937. size_t total_received = 0;
  7938. {
  7939. Client cli("127.0.0.1", PORT + 2);
  7940. cli.set_read_timeout(10, 0);
  7941. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  7942. auto res =
  7943. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7944. total_received += data_length;
  7945. return true;
  7946. });
  7947. ASSERT_TRUE(res);
  7948. EXPECT_EQ(StatusCode::OK_200, res->status);
  7949. }
  7950. server_thread.join();
  7951. EXPECT_EQ(total_received, DATA_SIZE)
  7952. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  7953. << " bytes (larger than " << DATA_SIZE
  7954. << " bytes response), content_receiver should read all data, but only "
  7955. "read "
  7956. << total_received << " bytes.";
  7957. }
  7958. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  7959. // Regression test for "zip bomb" attack on the client side: a malicious server
  7960. // sends a small gzip-compressed response that decompresses to a huge payload.
  7961. // The client must enforce payload_max_length on the decompressed size.
  7962. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  7963. constexpr size_t DECOMPRESSED_SIZE =
  7964. 10 * 1024 * 1024; // 10MB after decompression
  7965. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7966. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  7967. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  7968. std::string compressed;
  7969. {
  7970. httplib::detail::gzip_compressor compressor;
  7971. bool ok =
  7972. compressor.compress(uncompressed.data(), uncompressed.size(),
  7973. /*last=*/true, [&](const char *buf, size_t len) {
  7974. compressed.append(buf, len);
  7975. return true;
  7976. });
  7977. ASSERT_TRUE(ok);
  7978. }
  7979. // Sanity: compressed data should be much smaller than the decompressed size
  7980. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  7981. #ifndef _WIN32
  7982. signal(SIGPIPE, SIG_IGN);
  7983. #endif
  7984. // Set up the listening socket in the main thread so the server is guaranteed
  7985. // to be ready before the client connects (eliminates race condition).
  7986. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7987. default_socket_options(srv);
  7988. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7989. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7990. sockaddr_in addr{};
  7991. addr.sin_family = AF_INET;
  7992. addr.sin_port = htons(PORT + 3);
  7993. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7994. int opt = 1;
  7995. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7996. #ifdef _WIN32
  7997. reinterpret_cast<const char *>(&opt),
  7998. #else
  7999. &opt,
  8000. #endif
  8001. sizeof(opt));
  8002. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  8003. ASSERT_EQ(0, ::listen(srv, 1));
  8004. auto server_thread = std::thread([&compressed, srv] {
  8005. sockaddr_in cli_addr{};
  8006. socklen_t cli_len = sizeof(cli_addr);
  8007. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8008. if (cli != INVALID_SOCKET) {
  8009. // Read the full HTTP request (until \r\n\r\n)
  8010. char buf[4096];
  8011. size_t total = 0;
  8012. while (total < sizeof(buf)) {
  8013. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  8014. if (n <= 0) break;
  8015. total += static_cast<size_t>(n);
  8016. // Check for end of headers
  8017. if (total >= 4) {
  8018. std::string req(buf, total);
  8019. if (req.find("\r\n\r\n") != std::string::npos) break;
  8020. }
  8021. }
  8022. // Malicious response: gzip-compressed body, no Content-Length
  8023. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8024. "Content-Encoding: gzip\r\n"
  8025. "Connection: close\r\n"
  8026. "\r\n";
  8027. ::send(cli,
  8028. #ifdef _WIN32
  8029. static_cast<const char *>(response_header.c_str()),
  8030. static_cast<int>(response_header.size()),
  8031. #else
  8032. response_header.c_str(), response_header.size(),
  8033. #endif
  8034. 0);
  8035. // Send the compressed payload (small on the wire, huge when decompressed)
  8036. size_t total_sent = 0;
  8037. while (total_sent < compressed.size()) {
  8038. auto to_send = std::min(compressed.size() - total_sent,
  8039. static_cast<size_t>(64 * 1024));
  8040. auto sent =
  8041. ::send(cli,
  8042. #ifdef _WIN32
  8043. static_cast<const char *>(compressed.c_str() + total_sent),
  8044. static_cast<int>(to_send),
  8045. #else
  8046. compressed.c_str() + total_sent, to_send,
  8047. #endif
  8048. 0);
  8049. if (sent <= 0) break;
  8050. total_sent += static_cast<size_t>(sent);
  8051. }
  8052. detail::close_socket(cli);
  8053. }
  8054. });
  8055. auto se = detail::scope_exit([&] {
  8056. detail::close_socket(srv);
  8057. server_thread.join();
  8058. });
  8059. size_t total_decompressed = 0;
  8060. {
  8061. Client cli("127.0.0.1", PORT + 3);
  8062. cli.set_read_timeout(5, 0);
  8063. cli.set_decompress(true);
  8064. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8065. auto stream = cli.open_stream("GET", "/zipbomb");
  8066. ASSERT_TRUE(stream.is_valid());
  8067. char buffer[64 * 1024];
  8068. ssize_t n;
  8069. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8070. total_decompressed += static_cast<size_t>(n);
  8071. }
  8072. }
  8073. // The decompressed size must be capped by payload_max_length. Without
  8074. // protection, the client would decompress the full 10MB from a tiny
  8075. // compressed payload, enabling a zip bomb DoS attack.
  8076. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8077. << "Client decompressed " << total_decompressed
  8078. << " bytes from a gzip response. The decompressed size should be "
  8079. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8080. }
  8081. #endif
  8082. TEST(HostAndPortPropertiesTest, NoSSL) {
  8083. httplib::Client cli("www.google.com", 1234);
  8084. ASSERT_EQ("www.google.com", cli.host());
  8085. ASSERT_EQ(1234, cli.port());
  8086. }
  8087. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8088. httplib::Client cli("www.google.com:1234");
  8089. ASSERT_EQ("www.google.com", cli.host());
  8090. ASSERT_EQ(1234, cli.port());
  8091. }
  8092. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8093. // Port number that overflows int — should not crash, client becomes invalid
  8094. httplib::Client cli("http://www.google.com:99999999999999999999");
  8095. ASSERT_FALSE(cli.is_valid());
  8096. }
  8097. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8098. // Port 99999 exceeds valid range (1-65535) — should not crash
  8099. httplib::Client cli("http://www.google.com:99999");
  8100. ASSERT_FALSE(cli.is_valid());
  8101. }
  8102. #ifdef CPPHTTPLIB_SSL_ENABLED
  8103. TEST(HostAndPortPropertiesTest, SSL) {
  8104. httplib::SSLClient cli("www.google.com");
  8105. ASSERT_EQ("www.google.com", cli.host());
  8106. ASSERT_EQ(443, cli.port());
  8107. }
  8108. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8109. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8110. std::string cert;
  8111. read_file(CA_CERT_FILE, cert);
  8112. httplib::SSLClient httplib_client("www.google.com");
  8113. // Load CA store first time
  8114. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8115. // Load CA store second time (update)
  8116. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8117. // Verify client is still valid and can make connections
  8118. httplib_client.enable_server_certificate_verification(true);
  8119. auto res = httplib_client.Get("/");
  8120. ASSERT_TRUE(res);
  8121. // Google may return 200 or 301 depending on various factors
  8122. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8123. res->status == StatusCode::MovedPermanently_301);
  8124. }
  8125. TEST(SSLClientTest, ServerNameIndication_Online) {
  8126. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  8127. auto host = "httpcan.org";
  8128. auto path = std::string{"/get"};
  8129. #else
  8130. auto host = "nghttp2.org";
  8131. auto path = std::string{"/httpbin/get"};
  8132. #endif
  8133. SSLClient cli(host, 443);
  8134. auto res = cli.Get(path);
  8135. ASSERT_TRUE(res);
  8136. ASSERT_EQ(StatusCode::OK_200, res->status);
  8137. }
  8138. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8139. // Use a site that will cause SSL verification failure due to self-signed cert
  8140. SSLClient cli("self-signed.badssl.com", 443);
  8141. cli.enable_server_certificate_verification(true);
  8142. auto res = cli.Get("/");
  8143. ASSERT_TRUE(!res);
  8144. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8145. // Verify backend error is captured for SSLServerVerification
  8146. // This occurs when certificate verification fails
  8147. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8148. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8149. EXPECT_NE(0UL, res.ssl_backend_error());
  8150. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8151. // For OpenSSL, ssl_error is 0 for verification errors
  8152. EXPECT_EQ(0, res.ssl_error());
  8153. #if !defined(_WIN32) || \
  8154. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8155. // On non-Windows or when Windows Schannel is disabled, the error comes
  8156. // from OpenSSL's verification
  8157. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8158. res.ssl_backend_error());
  8159. #endif
  8160. #endif
  8161. }
  8162. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8163. // Use a site where hostname doesn't match the certificate
  8164. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8165. SSLClient cli("wrong.host.badssl.com", 443);
  8166. cli.enable_server_certificate_verification(true);
  8167. cli.enable_server_hostname_verification(true);
  8168. auto res = cli.Get("/");
  8169. ASSERT_TRUE(!res);
  8170. // The error type depends on when hostname verification occurs:
  8171. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8172. // - Mbed TLS: SSLServerVerification (during handshake)
  8173. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8174. res.error() == Error::SSLServerVerification);
  8175. // Verify backend error is captured for hostname verification failure
  8176. EXPECT_NE(0UL, res.ssl_backend_error());
  8177. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8178. // For OpenSSL, ssl_error is 0 for verification errors
  8179. EXPECT_EQ(0, res.ssl_error());
  8180. #if !defined(_WIN32) || \
  8181. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8182. // On non-Windows or when Windows Schannel is disabled, the error comes
  8183. // from OpenSSL's hostname verification
  8184. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8185. res.ssl_backend_error());
  8186. #endif
  8187. #endif
  8188. }
  8189. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8190. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8191. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8192. SSLClient cli("www.google.com", 443);
  8193. cli.enable_server_certificate_verification(true);
  8194. auto res = cli.Get("/");
  8195. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8196. }
  8197. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8198. SSLClient cli("www.google.com", 443);
  8199. cli.enable_server_certificate_verification(true);
  8200. cli.enable_windows_certificate_verification(false);
  8201. auto res = cli.Get("/");
  8202. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8203. }
  8204. #endif
  8205. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8206. Client cli("https://google.com");
  8207. auto res = cli.Get("/");
  8208. ASSERT_TRUE(res);
  8209. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8210. }
  8211. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8212. SSLClient cli("google.com");
  8213. cli.set_ca_cert_path(CA_CERT_FILE);
  8214. auto res = cli.Get("/");
  8215. ASSERT_TRUE(res);
  8216. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8217. }
  8218. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8219. SSLClient cli("google.com");
  8220. cli.enable_server_certificate_verification(true);
  8221. cli.set_ca_cert_path("hello");
  8222. auto res = cli.Get("/");
  8223. ASSERT_TRUE(!res);
  8224. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8225. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8226. // should be set
  8227. EXPECT_EQ(0, res.ssl_error());
  8228. // Verify backend error is captured for SSLLoadingCerts
  8229. // This error occurs when loading CA certificates fails
  8230. EXPECT_NE(0UL, res.ssl_backend_error());
  8231. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8232. // OpenSSL specific error codes:
  8233. // > openssl errstr 0x80000002
  8234. // error:80000002:system library::No such file or directory
  8235. // > openssl errstr 0xA000126
  8236. // error:0A000126:SSL routines::unexpected eof while reading
  8237. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8238. res.ssl_backend_error() == 0xA000126);
  8239. #endif
  8240. }
  8241. TEST(SSLClientTest, ServerCertificateVerification4) {
  8242. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8243. ASSERT_TRUE(svr.is_valid());
  8244. svr.Get("/test", [&](const Request &, Response &res) {
  8245. res.set_content("test", "text/plain");
  8246. svr.stop();
  8247. ASSERT_TRUE(true);
  8248. });
  8249. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8250. auto se = detail::scope_exit([&] {
  8251. t.join();
  8252. ASSERT_FALSE(svr.is_running());
  8253. });
  8254. svr.wait_until_ready();
  8255. SSLClient cli("127.0.0.1", PORT);
  8256. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8257. cli.enable_server_certificate_verification(true);
  8258. cli.set_connection_timeout(30);
  8259. auto res = cli.Get("/test");
  8260. ASSERT_TRUE(res);
  8261. ASSERT_EQ(StatusCode::OK_200, res->status);
  8262. }
  8263. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8264. std::string cert;
  8265. read_file(CA_CERT_FILE, cert);
  8266. SSLClient cli("google.com");
  8267. cli.load_ca_cert_store(cert.data(), cert.size());
  8268. const auto res = cli.Get("/");
  8269. ASSERT_TRUE(res);
  8270. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8271. }
  8272. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8273. // clang-format off
  8274. static constexpr char cert[] =
  8275. "GlobalSign Root CA\n"
  8276. "==================\n"
  8277. "-----BEGIN CERTIFICATE-----\n"
  8278. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8279. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8280. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8281. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8282. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8283. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8284. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8285. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8286. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8287. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8288. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8289. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8290. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8291. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8292. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8293. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8294. "-----END CERTIFICATE-----\n";
  8295. // clang-format on
  8296. SSLClient cli("google.com");
  8297. cli.load_ca_cert_store(cert, sizeof(cert));
  8298. const auto res = cli.Get("/");
  8299. ASSERT_TRUE(res);
  8300. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8301. }
  8302. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8303. SSLClient cli("www.youtube.com");
  8304. cli.set_ca_cert_path(CA_CERT_FILE);
  8305. cli.enable_server_certificate_verification(true);
  8306. cli.set_follow_location(true);
  8307. auto res = cli.Get("/");
  8308. ASSERT_TRUE(res);
  8309. ASSERT_EQ(StatusCode::OK_200, res->status);
  8310. }
  8311. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8312. SSLClient cli("wWw.YouTube.Com");
  8313. cli.set_ca_cert_path(CA_CERT_FILE);
  8314. cli.enable_server_certificate_verification(true);
  8315. cli.enable_server_hostname_verification(true);
  8316. cli.set_follow_location(true);
  8317. auto res = cli.Get("/");
  8318. ASSERT_TRUE(res);
  8319. ASSERT_EQ(StatusCode::OK_200, res->status);
  8320. }
  8321. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8322. SSLClient cli("gOoGlE.COm");
  8323. cli.enable_server_certificate_verification(true);
  8324. cli.enable_server_hostname_verification(true);
  8325. cli.set_follow_location(true);
  8326. auto res = cli.Get("/");
  8327. ASSERT_TRUE(res);
  8328. ASSERT_EQ(StatusCode::OK_200, res->status);
  8329. }
  8330. TEST(SSLClientTest, Issue2004_Online) {
  8331. Client client("https://google.com");
  8332. client.set_follow_location(true);
  8333. auto res = client.Get("/");
  8334. ASSERT_TRUE(res);
  8335. ASSERT_EQ(StatusCode::OK_200, res->status);
  8336. auto body = res->body;
  8337. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8338. }
  8339. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8340. // Create SSLClient with invalid cert/key to make is_valid() return false
  8341. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8342. "nonexistent_key.pem");
  8343. // is_valid() should be false due to cert loading failure
  8344. ASSERT_FALSE(cli.is_valid());
  8345. auto res = cli.Get("/");
  8346. ASSERT_FALSE(res);
  8347. EXPECT_EQ(Error::SSLConnection, res.error());
  8348. }
  8349. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8350. // Test for Issue #2251: SSL error not properly reported when client cert
  8351. // and key paths are swapped or mismatched
  8352. // This simulates the scenario where user accidentally swaps the cert and key
  8353. // files
  8354. // Using client cert file as private key and vice versa (completely wrong)
  8355. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8356. // Should fail validation due to cert/key mismatch
  8357. ASSERT_FALSE(cli.is_valid());
  8358. // Attempt to make a request should fail with proper error
  8359. auto res = cli.Get("/");
  8360. ASSERT_FALSE(res);
  8361. EXPECT_EQ(Error::SSLConnection, res.error());
  8362. // SSL error should be recorded in the Result object (this is the key fix for
  8363. // Issue #2251)
  8364. auto backend_error = res.ssl_backend_error();
  8365. EXPECT_NE(0u, backend_error);
  8366. }
  8367. // Tests cert/key mismatch detection at the TLS context level
  8368. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8369. // Test that using mismatched cert/key causes connection failure.
  8370. // We verify this at the SSLClient level rather than through internal
  8371. // TLS API functions.
  8372. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8373. cli.enable_server_certificate_verification(false);
  8374. cli.set_connection_timeout(2);
  8375. // The mismatch should cause a connection or handshake error
  8376. auto res = cli.Get("/test");
  8377. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8378. // Either way, the request should fail
  8379. EXPECT_FALSE(res);
  8380. }
  8381. #endif
  8382. #if 0
  8383. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8384. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8385. ASSERT_TRUE(cli != nullptr);
  8386. cli->set_address_family(AF_INET6);
  8387. cli->set_interface("en0");
  8388. auto res = cli->Get("/get");
  8389. ASSERT_TRUE(res);
  8390. ASSERT_EQ(StatusCode::OK_200, res->status);
  8391. }
  8392. #endif
  8393. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8394. #ifdef CPPHTTPLIB_SSL_ENABLED
  8395. void ClientCertPresent(
  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. using namespace httplib::tls;
  8400. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8401. CLIENT_CA_CERT_DIR);
  8402. ASSERT_TRUE(svr.is_valid());
  8403. svr.Get("/test", [&](const Request &req, Response &res) {
  8404. res.set_content("test", "text/plain");
  8405. auto cert = req.peer_cert();
  8406. ASSERT_TRUE(static_cast<bool>(cert));
  8407. std::string common_name = cert.subject_cn();
  8408. EXPECT_EQ("Common Name", common_name);
  8409. });
  8410. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8411. auto se = detail::scope_exit([&] {
  8412. svr.stop();
  8413. t.join();
  8414. ASSERT_FALSE(svr.is_running());
  8415. });
  8416. svr.wait_until_ready();
  8417. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8418. client_encrypted_private_key_pass);
  8419. cli.enable_server_certificate_verification(false);
  8420. cli.set_connection_timeout(30);
  8421. auto res = cli.Get("/test");
  8422. ASSERT_TRUE(res);
  8423. ASSERT_EQ(StatusCode::OK_200, res->status);
  8424. }
  8425. TEST(SSLClientServerTest, ClientCertPresent) {
  8426. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8427. }
  8428. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8429. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8430. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8431. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8432. }
  8433. // PEM memory-based constructor tests (works with all TLS backends)
  8434. void PemMemoryClientCertPresent(
  8435. const std::string &client_cert_file,
  8436. const std::string &client_private_key_file,
  8437. const std::string &client_encrypted_private_key_pass = std::string()) {
  8438. // Read PEM files into memory
  8439. std::string server_cert_pem, server_key_pem;
  8440. std::string client_ca_pem;
  8441. std::string client_cert_pem, client_key_pem;
  8442. read_file(SERVER_CERT_FILE, server_cert_pem);
  8443. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8444. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8445. read_file(client_cert_file, client_cert_pem);
  8446. read_file(client_private_key_file, client_key_pem);
  8447. // Create server with PEM memory
  8448. SSLServer::PemMemory server_pem = {
  8449. server_cert_pem.c_str(),
  8450. server_cert_pem.size(),
  8451. server_key_pem.c_str(),
  8452. server_key_pem.size(),
  8453. client_ca_pem.c_str(),
  8454. client_ca_pem.size(),
  8455. nullptr // no password for server key
  8456. };
  8457. SSLServer svr(server_pem);
  8458. ASSERT_TRUE(svr.is_valid());
  8459. svr.Get("/test", [&](const Request &, Response &res) {
  8460. res.set_content("test", "text/plain");
  8461. });
  8462. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8463. auto se = detail::scope_exit([&] {
  8464. svr.stop();
  8465. t.join();
  8466. ASSERT_FALSE(svr.is_running());
  8467. });
  8468. svr.wait_until_ready();
  8469. // Create client with PEM memory
  8470. const char *password = client_encrypted_private_key_pass.empty()
  8471. ? nullptr
  8472. : client_encrypted_private_key_pass.c_str();
  8473. SSLClient::PemMemory client_pem = {
  8474. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8475. client_key_pem.size(), password};
  8476. SSLClient cli(HOST, PORT, client_pem);
  8477. cli.enable_server_certificate_verification(false);
  8478. cli.set_connection_timeout(30);
  8479. auto res = cli.Get("/test");
  8480. ASSERT_TRUE(res);
  8481. ASSERT_EQ(StatusCode::OK_200, res->status);
  8482. }
  8483. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8484. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8485. }
  8486. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8487. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8488. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8489. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8490. }
  8491. TEST(SSLClientServerTest, ClientCertMissing) {
  8492. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8493. CLIENT_CA_CERT_DIR);
  8494. ASSERT_TRUE(svr.is_valid());
  8495. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8496. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8497. auto se = detail::scope_exit([&] {
  8498. svr.stop();
  8499. t.join();
  8500. ASSERT_FALSE(svr.is_running());
  8501. });
  8502. svr.wait_until_ready();
  8503. SSLClient cli(HOST, PORT);
  8504. cli.set_connection_timeout(30);
  8505. auto res = cli.Get("/test");
  8506. ASSERT_TRUE(!res);
  8507. // When client cert is missing and server requires it, connection fails
  8508. // Error type depends on backend implementation
  8509. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8510. res.error() == Error::SSLConnection);
  8511. // Verify backend error is captured
  8512. // Note: This test may have different error codes depending on the exact
  8513. // verification failure
  8514. EXPECT_NE(0UL, res.ssl_backend_error());
  8515. }
  8516. TEST(SSLClientServerTest, TrustDirOptional) {
  8517. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, 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();
  8525. t.join();
  8526. ASSERT_FALSE(svr.is_running());
  8527. });
  8528. svr.wait_until_ready();
  8529. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8530. cli.enable_server_certificate_verification(false);
  8531. cli.set_connection_timeout(30);
  8532. auto res = cli.Get("/test");
  8533. ASSERT_TRUE(res);
  8534. ASSERT_EQ(StatusCode::OK_200, res->status);
  8535. }
  8536. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8537. class NoListenSSLServer : public SSLServer {
  8538. public:
  8539. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8540. const char *client_ca_cert_file_path,
  8541. const char *client_ca_cert_dir_path = nullptr)
  8542. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8543. client_ca_cert_dir_path),
  8544. stop_(false) {}
  8545. std::atomic_bool stop_;
  8546. private:
  8547. bool process_and_close_socket(socket_t /*sock*/) override {
  8548. // Don't create SSL context
  8549. while (!stop_.load()) {
  8550. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8551. }
  8552. return true;
  8553. }
  8554. };
  8555. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8556. CLIENT_CA_CERT_FILE);
  8557. ASSERT_TRUE(svr.is_valid());
  8558. svr.Get("/test", [&](const Request &, Response &res) {
  8559. res.set_content("test", "text/plain");
  8560. });
  8561. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8562. auto se = detail::scope_exit([&] {
  8563. svr.stop_ = true;
  8564. svr.stop();
  8565. t.join();
  8566. ASSERT_FALSE(svr.is_running());
  8567. });
  8568. svr.wait_until_ready();
  8569. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8570. cli.enable_server_certificate_verification(false);
  8571. cli.set_connection_timeout(1);
  8572. auto res = cli.Get("/test");
  8573. ASSERT_TRUE(!res);
  8574. EXPECT_EQ(Error::SSLConnection, res.error());
  8575. // Timeout results in WantRead error code (maps to backend-specific value)
  8576. EXPECT_NE(0, res.ssl_error());
  8577. }
  8578. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8579. // Test SSLServer with client certificate verification using the standard
  8580. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8581. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8582. CLIENT_CA_CERT_DIR);
  8583. ASSERT_TRUE(svr.is_valid());
  8584. svr.Get("/test", [&](const Request &req, Response &res) {
  8585. res.set_content("test", "text/plain");
  8586. auto cert = req.peer_cert();
  8587. ASSERT_TRUE(static_cast<bool>(cert));
  8588. auto common_name = cert.subject_cn();
  8589. EXPECT_EQ("Common Name", common_name);
  8590. });
  8591. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8592. auto se = detail::scope_exit([&] {
  8593. svr.stop();
  8594. t.join();
  8595. ASSERT_FALSE(svr.is_running());
  8596. });
  8597. svr.wait_until_ready();
  8598. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8599. cli.enable_server_certificate_verification(false);
  8600. cli.set_connection_timeout(30);
  8601. auto res = cli.Get("/test");
  8602. ASSERT_TRUE(res);
  8603. ASSERT_EQ(StatusCode::OK_200, res->status);
  8604. }
  8605. // Test verify_hostname for both OpenSSL and MbedTLS backends
  8606. // Verifies that wildcard matching and exact matching work consistently
  8607. TEST(SSLClientServerTest, TlsVerifyHostname) {
  8608. using namespace httplib::tls;
  8609. // We need a running server to test against
  8610. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8611. ASSERT_TRUE(svr.is_valid());
  8612. svr.Get("/test", [](const Request &, Response &res) {
  8613. res.set_content("ok", "text/plain");
  8614. });
  8615. thread t([&]() { svr.listen(HOST, PORT); });
  8616. auto se = detail::scope_exit([&] {
  8617. svr.stop();
  8618. t.join();
  8619. });
  8620. svr.wait_until_ready();
  8621. bool verify_callback_called = false;
  8622. bool verify_result_wrong = false;
  8623. SSLClient cli(HOST, PORT);
  8624. cli.enable_server_certificate_verification(true);
  8625. cli.set_ca_cert_path(CA_CERT_FILE);
  8626. cli.set_connection_timeout(5);
  8627. // Note: Test certificate has CN="Common Name", not "localhost"
  8628. bool verify_result_cn = false;
  8629. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8630. verify_callback_called = true;
  8631. if (!ctx.cert) return false;
  8632. // Test 1: "Common Name" should match (our test server cert CN)
  8633. verify_result_cn = ctx.check_hostname("Common Name");
  8634. // Test 2: wrong hostname should not match
  8635. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  8636. return true; // Accept for the purpose of this test
  8637. });
  8638. auto res = cli.Get("/test");
  8639. // The request may succeed or fail depending on cert configuration
  8640. // but the callback should have been called
  8641. ASSERT_TRUE(verify_callback_called)
  8642. << "Verify callback should have been called";
  8643. // CN="Common Name" should match our test certificate
  8644. EXPECT_TRUE(verify_result_cn)
  8645. << "verify_hostname should match 'Common Name' (certificate CN)";
  8646. // Wrong hostname should not match
  8647. EXPECT_FALSE(verify_result_wrong)
  8648. << "verify_hostname should not match 'wronghost.example.com'";
  8649. }
  8650. #endif
  8651. // mbedTLS-specific callback constructor test
  8652. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8653. #ifdef CPPHTTPLIB_SSL_ENABLED
  8654. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8655. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8656. ASSERT_TRUE(svr.is_valid());
  8657. // Set up a handler to verify client certificate is present
  8658. bool client_cert_verified = false;
  8659. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8660. // Verify that client certificate was provided
  8661. client_cert_verified = true;
  8662. res.set_content("success", "text/plain");
  8663. });
  8664. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8665. auto se = detail::scope_exit([&] {
  8666. svr.stop();
  8667. t.join();
  8668. ASSERT_FALSE(svr.is_running());
  8669. });
  8670. svr.wait_until_ready();
  8671. // Client with certificate
  8672. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8673. cli.enable_server_certificate_verification(false);
  8674. cli.set_connection_timeout(30);
  8675. auto res = cli.Get("/test");
  8676. ASSERT_TRUE(res);
  8677. ASSERT_EQ(StatusCode::OK_200, res->status);
  8678. ASSERT_TRUE(client_cert_verified);
  8679. EXPECT_EQ("success", res->body);
  8680. }
  8681. #endif
  8682. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  8683. // backends
  8684. #ifdef CPPHTTPLIB_SSL_ENABLED
  8685. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  8686. using namespace httplib::tls;
  8687. // Test that when client CA cert file is provided,
  8688. // the server properly requests and validates client certificates
  8689. // Create a server with client authentication
  8690. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8691. ASSERT_TRUE(svr.is_valid());
  8692. bool handler_called = false;
  8693. svr.Get("/test", [&](const Request &req, Response &res) {
  8694. handler_called = true;
  8695. // Verify that a client certificate was provided
  8696. auto cert = req.peer_cert();
  8697. ASSERT_TRUE(static_cast<bool>(cert));
  8698. // Get the issuer name
  8699. std::string issuer_str = cert.issuer_name();
  8700. ASSERT_FALSE(issuer_str.empty());
  8701. // The client certificate should be issued by our test CA
  8702. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  8703. res.set_content("authenticated", "text/plain");
  8704. });
  8705. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8706. auto se = detail::scope_exit([&] {
  8707. svr.stop();
  8708. t.join();
  8709. ASSERT_FALSE(svr.is_running());
  8710. });
  8711. svr.wait_until_ready();
  8712. // Connect with a client certificate issued by the CA
  8713. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8714. cli.enable_server_certificate_verification(false);
  8715. cli.set_connection_timeout(30);
  8716. auto res = cli.Get("/test");
  8717. ASSERT_TRUE(res);
  8718. ASSERT_EQ(StatusCode::OK_200, res->status);
  8719. ASSERT_TRUE(handler_called);
  8720. EXPECT_EQ("authenticated", res->body);
  8721. }
  8722. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  8723. using namespace httplib::tls;
  8724. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8725. ASSERT_TRUE(svr.is_valid());
  8726. svr.Get("/test", [](const Request &, Response &res) {
  8727. res.set_content("ok", "text/plain");
  8728. });
  8729. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8730. auto se = detail::scope_exit([&] {
  8731. svr.stop();
  8732. t.join();
  8733. });
  8734. svr.wait_until_ready();
  8735. SSLClient cli(HOST, PORT);
  8736. cli.enable_server_certificate_verification(false);
  8737. cli.set_connection_timeout(30);
  8738. bool cert_checked = false;
  8739. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8740. if (ctx.cert) {
  8741. auto sans = ctx.sans();
  8742. // Test certificate may or may not have SANs - just verify the API
  8743. // works If SANs exist, verify the types are valid
  8744. for (const auto &san : sans) {
  8745. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  8746. san.type == SanType::EMAIL || san.type == SanType::URI ||
  8747. san.type == SanType::OTHER);
  8748. EXPECT_FALSE(san.value.empty());
  8749. }
  8750. cert_checked = true;
  8751. }
  8752. return true;
  8753. });
  8754. auto res = cli.Get("/test");
  8755. ASSERT_TRUE(res);
  8756. EXPECT_TRUE(cert_checked);
  8757. }
  8758. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  8759. using namespace httplib::tls;
  8760. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8761. ASSERT_TRUE(svr.is_valid());
  8762. svr.Get("/test", [](const Request &, Response &res) {
  8763. res.set_content("ok", "text/plain");
  8764. });
  8765. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8766. auto se = detail::scope_exit([&] {
  8767. svr.stop();
  8768. t.join();
  8769. });
  8770. svr.wait_until_ready();
  8771. SSLClient cli(HOST, PORT);
  8772. cli.enable_server_certificate_verification(false);
  8773. cli.set_connection_timeout(30);
  8774. bool validity_checked = false;
  8775. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8776. if (ctx.cert) {
  8777. time_t not_before = 0, not_after = 0;
  8778. bool result = ctx.validity(not_before, not_after);
  8779. EXPECT_TRUE(result);
  8780. // Verify that not_before < now < not_after for a valid cert
  8781. time_t now = time(nullptr);
  8782. EXPECT_LT(not_before, now);
  8783. EXPECT_GT(not_after, now);
  8784. validity_checked = true;
  8785. }
  8786. return true;
  8787. });
  8788. auto res = cli.Get("/test");
  8789. ASSERT_TRUE(res);
  8790. EXPECT_TRUE(validity_checked);
  8791. }
  8792. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  8793. using namespace httplib::tls;
  8794. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8795. ASSERT_TRUE(svr.is_valid());
  8796. svr.Get("/test", [](const Request &, Response &res) {
  8797. res.set_content("ok", "text/plain");
  8798. });
  8799. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8800. auto se = detail::scope_exit([&] {
  8801. svr.stop();
  8802. t.join();
  8803. });
  8804. svr.wait_until_ready();
  8805. SSLClient cli(HOST, PORT);
  8806. cli.enable_server_certificate_verification(false);
  8807. cli.set_connection_timeout(30);
  8808. bool serial_checked = false;
  8809. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8810. if (ctx.cert) {
  8811. std::string serial = ctx.serial();
  8812. EXPECT_FALSE(serial.empty());
  8813. // Serial should be a hex string
  8814. for (char c : serial) {
  8815. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  8816. (c >= 'a' && c <= 'f'));
  8817. }
  8818. serial_checked = true;
  8819. }
  8820. return true;
  8821. });
  8822. auto res = cli.Get("/test");
  8823. ASSERT_TRUE(res);
  8824. EXPECT_TRUE(serial_checked);
  8825. }
  8826. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  8827. // Test 1: Valid CA file - no error should be recorded
  8828. {
  8829. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8830. CLIENT_CA_CERT_FILE);
  8831. ASSERT_TRUE(svr.is_valid());
  8832. // With valid setup, last_ssl_error should be 0
  8833. EXPECT_EQ(0, svr.ssl_last_error());
  8834. }
  8835. // Test 2: Invalid CA file content
  8836. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  8837. {
  8838. // Create a temporary file with completely invalid content
  8839. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  8840. {
  8841. std::ofstream ofs(temp_invalid_ca);
  8842. ofs << "This is not a certificate file at all\n";
  8843. ofs << "Just plain text content\n";
  8844. }
  8845. // Create server with invalid CA file
  8846. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  8847. // Clean up temporary file
  8848. std::remove(temp_invalid_ca);
  8849. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  8850. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  8851. // Note: SSL_CTX_load_verify_locations typically fails first,
  8852. // but our error handling code path is still exercised
  8853. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  8854. }
  8855. }
  8856. TEST(VerifyCallbackTest, VerifyContextFields) {
  8857. using namespace httplib::tls;
  8858. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8859. ASSERT_TRUE(svr.is_valid());
  8860. svr.Get("/test", [](const Request &, Response &res) {
  8861. res.set_content("ok", "text/plain");
  8862. });
  8863. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8864. auto se = detail::scope_exit([&] {
  8865. svr.stop();
  8866. t.join();
  8867. });
  8868. svr.wait_until_ready();
  8869. SSLClient cli(HOST, PORT);
  8870. cli.enable_server_certificate_verification(false);
  8871. cli.set_connection_timeout(30);
  8872. int callback_count = 0;
  8873. bool saw_leaf_cert = false;
  8874. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8875. if (ctx.cert) {
  8876. callback_count++;
  8877. // We should see at least one certificate (the leaf)
  8878. std::string cn = ctx.subject_cn();
  8879. if (!cn.empty()) { saw_leaf_cert = true; }
  8880. // Verify context fields are populated
  8881. EXPECT_NE(ctx.session, nullptr);
  8882. EXPECT_GE(ctx.depth, 0);
  8883. }
  8884. return true;
  8885. });
  8886. auto res = cli.Get("/test");
  8887. ASSERT_TRUE(res);
  8888. EXPECT_GT(callback_count, 0);
  8889. EXPECT_TRUE(saw_leaf_cert);
  8890. }
  8891. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  8892. using httplib::tls::TlsError;
  8893. // Test that verify_error_to_string returns empty for success
  8894. std::string success_str = TlsError::verify_error_to_string(0);
  8895. EXPECT_TRUE(success_str.empty());
  8896. // Test that verify_error_to_string returns non-empty for error codes
  8897. // Using a common error code (certificate expired)
  8898. std::string error_str =
  8899. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  8900. EXPECT_FALSE(error_str.empty());
  8901. }
  8902. TEST(SessionVerifierTest, CertificateAccepted) {
  8903. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8904. ASSERT_TRUE(svr.is_valid());
  8905. svr.Get("/test", [](const Request &, Response &res) {
  8906. res.set_content("ok", "text/plain");
  8907. });
  8908. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8909. auto se = detail::scope_exit([&] {
  8910. svr.stop();
  8911. t.join();
  8912. });
  8913. svr.wait_until_ready();
  8914. SSLClient cli(HOST, PORT);
  8915. cli.enable_server_certificate_verification(false);
  8916. cli.set_connection_timeout(30);
  8917. bool callback_called = false;
  8918. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8919. EXPECT_NE(session, nullptr);
  8920. callback_called = true;
  8921. return SSLVerifierResponse::CertificateAccepted;
  8922. });
  8923. auto res = cli.Get("/test");
  8924. ASSERT_TRUE(res);
  8925. EXPECT_EQ(200, res->status);
  8926. EXPECT_TRUE(callback_called);
  8927. }
  8928. TEST(SessionVerifierTest, CertificateRejected) {
  8929. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8930. ASSERT_TRUE(svr.is_valid());
  8931. svr.Get("/test", [](const Request &, Response &res) {
  8932. res.set_content("ok", "text/plain");
  8933. });
  8934. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8935. auto se = detail::scope_exit([&] {
  8936. svr.stop();
  8937. t.join();
  8938. });
  8939. svr.wait_until_ready();
  8940. SSLClient cli(HOST, PORT);
  8941. cli.enable_server_certificate_verification(false);
  8942. cli.set_connection_timeout(30);
  8943. bool callback_called = false;
  8944. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8945. EXPECT_NE(session, nullptr);
  8946. callback_called = true;
  8947. return SSLVerifierResponse::CertificateRejected;
  8948. });
  8949. auto res = cli.Get("/test");
  8950. EXPECT_FALSE(res);
  8951. EXPECT_TRUE(callback_called);
  8952. }
  8953. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  8954. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8955. ASSERT_TRUE(svr.is_valid());
  8956. svr.Get("/test", [](const Request &, Response &res) {
  8957. res.set_content("ok", "text/plain");
  8958. });
  8959. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8960. auto se = detail::scope_exit([&] {
  8961. svr.stop();
  8962. t.join();
  8963. });
  8964. svr.wait_until_ready();
  8965. // NoDecisionMade with verification disabled should succeed (no default check)
  8966. SSLClient cli(HOST, PORT);
  8967. cli.enable_server_certificate_verification(false);
  8968. cli.set_connection_timeout(30);
  8969. bool callback_called = false;
  8970. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8971. EXPECT_NE(session, nullptr);
  8972. callback_called = true;
  8973. return SSLVerifierResponse::NoDecisionMade;
  8974. });
  8975. auto res = cli.Get("/test");
  8976. ASSERT_TRUE(res);
  8977. EXPECT_EQ(200, res->status);
  8978. EXPECT_TRUE(callback_called);
  8979. }
  8980. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  8981. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8982. ASSERT_TRUE(svr.is_valid());
  8983. svr.Get("/test", [](const Request &, Response &res) {
  8984. res.set_content("ok", "text/plain");
  8985. });
  8986. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8987. auto se = detail::scope_exit([&] {
  8988. svr.stop();
  8989. t.join();
  8990. });
  8991. svr.wait_until_ready();
  8992. // NoDecisionMade with verification enabled should fail (self-signed cert).
  8993. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  8994. // so we only check that the request fails, not whether the callback was
  8995. // called.
  8996. SSLClient cli(HOST, PORT);
  8997. cli.enable_server_certificate_verification(true);
  8998. cli.set_connection_timeout(30);
  8999. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9000. EXPECT_NE(session, nullptr);
  9001. return SSLVerifierResponse::NoDecisionMade;
  9002. });
  9003. auto res = cli.Get("/test");
  9004. EXPECT_FALSE(res);
  9005. }
  9006. TEST(SSLClientServerTest, ClientCAListFromPem) {
  9007. // Test SSL server using PemMemory constructor with client CA certificates
  9008. // Read PEM files
  9009. std::string server_cert_pem, server_key_pem, client_ca_pem;
  9010. read_file(SERVER_CERT_FILE, server_cert_pem);
  9011. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9012. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9013. // Create SSLServer with PemMemory constructor including client CA
  9014. SSLServer::PemMemory server_pem = {
  9015. server_cert_pem.c_str(),
  9016. server_cert_pem.size(),
  9017. server_key_pem.c_str(),
  9018. server_key_pem.size(),
  9019. client_ca_pem.c_str(),
  9020. client_ca_pem.size(),
  9021. nullptr // no password for server key
  9022. };
  9023. SSLServer svr(server_pem);
  9024. ASSERT_TRUE(svr.is_valid());
  9025. // No SSL error should be recorded for valid setup
  9026. EXPECT_EQ(0, svr.ssl_last_error());
  9027. // Set up server endpoints
  9028. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  9029. res.set_content("ok", "text/plain");
  9030. });
  9031. // Start server in a thread
  9032. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  9033. svr.wait_until_ready();
  9034. // Connect with client certificate (using constructor with paths)
  9035. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9036. cli.enable_server_certificate_verification(false);
  9037. auto res = cli.Get("/test-pem-ca");
  9038. ASSERT_TRUE(res);
  9039. EXPECT_EQ(200, res->status);
  9040. EXPECT_EQ("ok", res->body);
  9041. svr.stop();
  9042. server_thread.join();
  9043. }
  9044. #endif
  9045. #ifdef _WIN32
  9046. TEST(CleanupTest, WSACleanup) {
  9047. int ret = WSACleanup();
  9048. ASSERT_EQ(0, ret);
  9049. }
  9050. #endif
  9051. #ifndef CPPHTTPLIB_SSL_ENABLED
  9052. TEST(NoSSLSupport, SimpleInterface) {
  9053. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  9054. }
  9055. #endif
  9056. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9057. TEST(InvalidScheme, SimpleInterface) {
  9058. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  9059. }
  9060. #endif
  9061. TEST(NoScheme, SimpleInterface) {
  9062. Client cli("yahoo.com:80");
  9063. ASSERT_TRUE(cli.is_valid());
  9064. }
  9065. TEST(SendAPI, SimpleInterface_Online) {
  9066. Client cli("http://yahoo.com");
  9067. Request req;
  9068. req.method = "GET";
  9069. req.path = "/";
  9070. auto res = cli.send(req);
  9071. ASSERT_TRUE(res);
  9072. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9073. }
  9074. TEST(SendAPI, WithParamsInRequest) {
  9075. Server svr;
  9076. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  9077. EXPECT_TRUE(req.has_param("test"));
  9078. EXPECT_EQ("test_value", req.get_param_value("test"));
  9079. });
  9080. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  9081. auto se = detail::scope_exit([&] {
  9082. svr.stop();
  9083. t.join();
  9084. ASSERT_FALSE(svr.is_running());
  9085. });
  9086. svr.wait_until_ready();
  9087. Client cli(HOST, PORT);
  9088. {
  9089. Request req;
  9090. req.method = "GET";
  9091. req.path = "/";
  9092. req.params.emplace("test", "test_value");
  9093. auto res = cli.send(req);
  9094. ASSERT_TRUE(res);
  9095. }
  9096. {
  9097. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  9098. ASSERT_TRUE(res);
  9099. }
  9100. }
  9101. TEST(ClientImplMethods, GetSocketTest) {
  9102. httplib::Server svr;
  9103. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9104. res.status = StatusCode::OK_200;
  9105. });
  9106. auto port = svr.bind_to_any_port("127.0.0.1");
  9107. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9108. auto se = detail::scope_exit([&] {
  9109. svr.stop();
  9110. thread.join();
  9111. ASSERT_FALSE(svr.is_running());
  9112. });
  9113. svr.wait_until_ready();
  9114. {
  9115. httplib::Client cli("127.0.0.1", port);
  9116. cli.set_keep_alive(true);
  9117. // Use the behavior of cpp-httplib of opening the connection
  9118. // only when the first request happens. If that changes,
  9119. // this test would be obsolete.
  9120. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9121. // This also implicitly tests the server. But other tests would fail much
  9122. // earlier than this one to be considered.
  9123. auto res = cli.Get("/");
  9124. ASSERT_TRUE(res);
  9125. EXPECT_EQ(StatusCode::OK_200, res->status);
  9126. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9127. }
  9128. }
  9129. #ifdef CPPHTTPLIB_SSL_ENABLED
  9130. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9131. Client cli("http://yahoo.com");
  9132. auto res = cli.Get("/");
  9133. ASSERT_TRUE(res);
  9134. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9135. cli.set_follow_location(true);
  9136. res = cli.Get("/");
  9137. ASSERT_TRUE(res);
  9138. EXPECT_EQ(StatusCode::OK_200, res->status);
  9139. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9140. }
  9141. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9142. Client cli("https://yahoo.com");
  9143. auto res = cli.Get("/");
  9144. ASSERT_TRUE(res);
  9145. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9146. cli.set_follow_location(true);
  9147. res = cli.Get("/");
  9148. ASSERT_TRUE(res);
  9149. EXPECT_EQ(StatusCode::OK_200, res->status);
  9150. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9151. }
  9152. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9153. Client cli("https://yahoo.com");
  9154. auto res = cli.Get("/");
  9155. ASSERT_TRUE(res);
  9156. ASSERT_FALSE(!res);
  9157. ASSERT_TRUE(res);
  9158. ASSERT_FALSE(res == nullptr);
  9159. ASSERT_TRUE(res != nullptr);
  9160. EXPECT_EQ(Error::Success, res.error());
  9161. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9162. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9163. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9164. cli.set_follow_location(true);
  9165. res = cli.Get("/");
  9166. ASSERT_TRUE(res);
  9167. EXPECT_EQ(Error::Success, res.error());
  9168. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9169. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9170. EXPECT_EQ(StatusCode::OK_200, res->status);
  9171. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9172. }
  9173. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9174. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9175. Client cli("https://cdnjs.cloudflare.com");
  9176. auto res =
  9177. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9178. ASSERT_TRUE(res);
  9179. EXPECT_EQ(StatusCode::OK_200, res->status);
  9180. EXPECT_EQ(287630U, res->body.size());
  9181. EXPECT_EQ("application/javascript; charset=utf-8",
  9182. res->get_header_value("Content-Type"));
  9183. }
  9184. #endif
  9185. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9186. #undef REDIR_HOST // Silence compiler warning
  9187. #define REDIR_HOST "https://httpbingo.org"
  9188. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9189. Client cli(REDIR_HOST);
  9190. cli.set_follow_location(true);
  9191. auto res =
  9192. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9193. ASSERT_TRUE(res);
  9194. EXPECT_EQ(StatusCode::OK_200, res->status);
  9195. }
  9196. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9197. Client cli(REDIR_HOST);
  9198. cli.set_follow_location(true);
  9199. Params params;
  9200. params.emplace("url", "http://example.com");
  9201. params.emplace("status_code", "302");
  9202. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9203. ASSERT_TRUE(res);
  9204. EXPECT_EQ(StatusCode::OK_200, res->status);
  9205. }
  9206. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9207. Client cli(REDIR_HOST);
  9208. cli.set_follow_location(true);
  9209. Params params;
  9210. params.emplace("url", "http://example.com");
  9211. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9212. ASSERT_TRUE(res);
  9213. EXPECT_EQ(StatusCode::OK_200, res->status);
  9214. }
  9215. TEST(HttpToHttpsRedirectTest, CertFile) {
  9216. auto ssl_port = PORT + 1;
  9217. Server svr;
  9218. ASSERT_TRUE(svr.is_valid());
  9219. svr.Get("/index", [&](const Request &, Response &res) {
  9220. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9221. "/index");
  9222. svr.stop();
  9223. });
  9224. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9225. ASSERT_TRUE(ssl_svr.is_valid());
  9226. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9227. res.set_content("test", "text/plain");
  9228. ssl_svr.stop();
  9229. });
  9230. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9231. thread t2 =
  9232. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9233. auto se = detail::scope_exit([&] {
  9234. t2.join();
  9235. t.join();
  9236. ASSERT_FALSE(svr.is_running());
  9237. });
  9238. svr.wait_until_ready();
  9239. ssl_svr.wait_until_ready();
  9240. Client cli("127.0.0.1", PORT);
  9241. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9242. cli.enable_server_certificate_verification(true);
  9243. cli.set_follow_location(true);
  9244. cli.set_connection_timeout(30);
  9245. auto res = cli.Get("/index");
  9246. ASSERT_TRUE(res);
  9247. ASSERT_EQ(StatusCode::OK_200, res->status);
  9248. }
  9249. TEST(SSLClientRedirectTest, CertFile) {
  9250. auto ssl_port = PORT + 1;
  9251. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9252. ASSERT_TRUE(ssl_svr1.is_valid());
  9253. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9254. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9255. "/index");
  9256. ssl_svr1.stop();
  9257. });
  9258. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9259. ASSERT_TRUE(ssl_svr2.is_valid());
  9260. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9261. res.set_content("test", "text/plain");
  9262. ssl_svr2.stop();
  9263. });
  9264. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9265. thread t2 =
  9266. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9267. auto se = detail::scope_exit([&] {
  9268. t2.join();
  9269. t.join();
  9270. ASSERT_FALSE(ssl_svr1.is_running());
  9271. });
  9272. ssl_svr1.wait_until_ready();
  9273. ssl_svr2.wait_until_ready();
  9274. SSLClient cli("127.0.0.1", PORT);
  9275. std::string cert;
  9276. read_file(SERVER_CERT2_FILE, cert);
  9277. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9278. cli.enable_server_certificate_verification(true);
  9279. cli.set_follow_location(true);
  9280. cli.set_connection_timeout(30);
  9281. auto res = cli.Get("/index");
  9282. ASSERT_TRUE(res);
  9283. ASSERT_EQ(StatusCode::OK_200, res->status);
  9284. }
  9285. #endif
  9286. #ifdef CPPHTTPLIB_SSL_ENABLED
  9287. // Test that set_ca_cert_store() skips system certs (consistent with
  9288. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9289. // should be trusted - system certs should NOT be loaded.
  9290. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9291. // Load a specific cert that is NOT a system CA cert
  9292. std::string cert;
  9293. read_file(SERVER_CERT2_FILE, cert);
  9294. SSLClient cli("google.com");
  9295. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9296. cli.enable_server_certificate_verification(true);
  9297. // This should FAIL because:
  9298. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9299. // 2. System certs should NOT be loaded when custom store is set
  9300. // If system certs WERE loaded, this would succeed
  9301. auto res = cli.Get("/");
  9302. ASSERT_FALSE(res);
  9303. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9304. }
  9305. TEST(MultipartFormDataTest, LargeData) {
  9306. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9307. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9308. const ContentReader &content_reader) {
  9309. if (req.is_multipart_form_data()) {
  9310. std::vector<FormData> items;
  9311. content_reader(
  9312. [&](const FormData &file) {
  9313. items.push_back(file);
  9314. return true;
  9315. },
  9316. [&](const char *data, size_t data_length) {
  9317. items.back().content.append(data, data_length);
  9318. return true;
  9319. });
  9320. EXPECT_TRUE(std::string(items[0].name) == "document");
  9321. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9322. EXPECT_TRUE(items[0].filename == "2MB_data");
  9323. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9324. EXPECT_TRUE(items[1].name == "hello");
  9325. EXPECT_TRUE(items[1].content == "world");
  9326. EXPECT_TRUE(items[1].filename == "");
  9327. EXPECT_TRUE(items[1].content_type == "");
  9328. } else {
  9329. std::string body;
  9330. content_reader([&](const char *data, size_t data_length) {
  9331. body.append(data, data_length);
  9332. return true;
  9333. });
  9334. }
  9335. });
  9336. auto port = svr.bind_to_any_port(HOST);
  9337. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9338. auto se = detail::scope_exit([&] {
  9339. svr.stop();
  9340. t.join();
  9341. ASSERT_FALSE(svr.is_running());
  9342. });
  9343. svr.wait_until_ready();
  9344. {
  9345. std::string data(1024 * 1024 * 2, '.');
  9346. std::stringstream buffer;
  9347. buffer << data;
  9348. SSLClient cli(HOST, port);
  9349. cli.enable_server_certificate_verification(false);
  9350. UploadFormDataItems items{
  9351. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9352. {"hello", "world", "", ""},
  9353. };
  9354. auto res = cli.Post("/post", items);
  9355. ASSERT_TRUE(res);
  9356. ASSERT_EQ(StatusCode::OK_200, res->status);
  9357. }
  9358. }
  9359. TEST(MultipartFormDataTest, DataProviderItems) {
  9360. std::random_device seed_gen;
  9361. std::mt19937 random(seed_gen());
  9362. std::string rand1;
  9363. rand1.resize(1000);
  9364. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9365. std::string rand2;
  9366. rand2.resize(3000);
  9367. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9368. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9369. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9370. const ContentReader &content_reader) {
  9371. ASSERT_FALSE(req.is_multipart_form_data());
  9372. std::string body;
  9373. content_reader([&](const char *data, size_t data_length) {
  9374. body.append(data, data_length);
  9375. return true;
  9376. });
  9377. EXPECT_EQ(body, "");
  9378. });
  9379. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9380. const ContentReader &content_reader) {
  9381. ASSERT_TRUE(req.is_multipart_form_data());
  9382. std::vector<FormData> items;
  9383. content_reader(
  9384. [&](const FormData &file) {
  9385. items.push_back(file);
  9386. return true;
  9387. },
  9388. [&](const char *data, size_t data_length) {
  9389. items.back().content.append(data, data_length);
  9390. return true;
  9391. });
  9392. ASSERT_TRUE(items.size() == 2);
  9393. EXPECT_EQ(std::string(items[0].name), "name1");
  9394. EXPECT_EQ(items[0].content, "Testing123");
  9395. EXPECT_EQ(items[0].filename, "filename1");
  9396. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9397. EXPECT_EQ(items[1].name, "name2");
  9398. EXPECT_EQ(items[1].content, "Testing456");
  9399. EXPECT_EQ(items[1].filename, "");
  9400. EXPECT_EQ(items[1].content_type, "");
  9401. });
  9402. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9403. const ContentReader &content_reader) {
  9404. ASSERT_TRUE(req.is_multipart_form_data());
  9405. std::vector<FormData> items;
  9406. content_reader(
  9407. [&](const FormData &file) {
  9408. items.push_back(file);
  9409. return true;
  9410. },
  9411. [&](const char *data, size_t data_length) {
  9412. items.back().content.append(data, data_length);
  9413. return true;
  9414. });
  9415. ASSERT_TRUE(items.size() == 2);
  9416. EXPECT_EQ(items[0].name, "name3");
  9417. EXPECT_EQ(items[0].content, rand1);
  9418. EXPECT_EQ(items[0].filename, "filename3");
  9419. EXPECT_EQ(items[0].content_type, "");
  9420. EXPECT_EQ(items[1].name, "name4");
  9421. EXPECT_EQ(items[1].content, rand2);
  9422. EXPECT_EQ(items[1].filename, "filename4");
  9423. EXPECT_EQ(items[1].content_type, "");
  9424. });
  9425. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9426. const ContentReader &content_reader) {
  9427. ASSERT_TRUE(req.is_multipart_form_data());
  9428. std::vector<FormData> items;
  9429. content_reader(
  9430. [&](const FormData &file) {
  9431. items.push_back(file);
  9432. return true;
  9433. },
  9434. [&](const char *data, size_t data_length) {
  9435. items.back().content.append(data, data_length);
  9436. return true;
  9437. });
  9438. ASSERT_TRUE(items.size() == 4);
  9439. EXPECT_EQ(std::string(items[0].name), "name1");
  9440. EXPECT_EQ(items[0].content, "Testing123");
  9441. EXPECT_EQ(items[0].filename, "filename1");
  9442. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9443. EXPECT_EQ(items[1].name, "name2");
  9444. EXPECT_EQ(items[1].content, "Testing456");
  9445. EXPECT_EQ(items[1].filename, "");
  9446. EXPECT_EQ(items[1].content_type, "");
  9447. EXPECT_EQ(items[2].name, "name3");
  9448. EXPECT_EQ(items[2].content, rand1);
  9449. EXPECT_EQ(items[2].filename, "filename3");
  9450. EXPECT_EQ(items[2].content_type, "");
  9451. EXPECT_EQ(items[3].name, "name4");
  9452. EXPECT_EQ(items[3].content, rand2);
  9453. EXPECT_EQ(items[3].filename, "filename4");
  9454. EXPECT_EQ(items[3].content_type, "");
  9455. });
  9456. auto port = svr.bind_to_any_port("localhost");
  9457. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9458. auto se = detail::scope_exit([&] {
  9459. svr.stop();
  9460. t.join();
  9461. ASSERT_FALSE(svr.is_running());
  9462. });
  9463. svr.wait_until_ready();
  9464. {
  9465. SSLClient cli("localhost", port);
  9466. cli.enable_server_certificate_verification(false);
  9467. UploadFormDataItems items{
  9468. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9469. {"name2", "Testing456", "", ""}, // not a file
  9470. };
  9471. {
  9472. auto res = cli.Post("/post-none", {}, {}, {});
  9473. ASSERT_TRUE(res);
  9474. ASSERT_EQ(StatusCode::OK_200, res->status);
  9475. }
  9476. FormDataProviderItems providers;
  9477. {
  9478. auto res =
  9479. cli.Post("/post-items", {}, items, providers); // empty providers
  9480. ASSERT_TRUE(res);
  9481. ASSERT_EQ(StatusCode::OK_200, res->status);
  9482. }
  9483. providers.push_back({"name3",
  9484. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9485. // test the offset is given correctly at each step
  9486. if (!offset)
  9487. sink.os.write(rand1.data(), 30);
  9488. else if (offset == 30)
  9489. sink.os.write(rand1.data() + 30, 300);
  9490. else if (offset == 330)
  9491. sink.os.write(rand1.data() + 330, 670);
  9492. else if (offset == rand1.size())
  9493. sink.done();
  9494. return true;
  9495. },
  9496. "filename3",
  9497. {}});
  9498. providers.push_back({"name4",
  9499. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9500. // test the offset is given correctly at each step
  9501. if (!offset)
  9502. sink.os.write(rand2.data(), 2000);
  9503. else if (offset == 2000)
  9504. sink.os.write(rand2.data() + 2000, 1);
  9505. else if (offset == 2001)
  9506. sink.os.write(rand2.data() + 2001, 999);
  9507. else if (offset == rand2.size())
  9508. sink.done();
  9509. return true;
  9510. },
  9511. "filename4",
  9512. {}});
  9513. {
  9514. auto res = cli.Post("/post-providers", {}, {}, providers);
  9515. ASSERT_TRUE(res);
  9516. ASSERT_EQ(StatusCode::OK_200, res->status);
  9517. }
  9518. {
  9519. auto res = cli.Post("/post-both", {}, items, providers);
  9520. ASSERT_TRUE(res);
  9521. ASSERT_EQ(StatusCode::OK_200, res->status);
  9522. }
  9523. }
  9524. }
  9525. TEST(MultipartFormDataTest, BadHeader) {
  9526. Server svr;
  9527. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9528. res.set_content("ok", "text/plain");
  9529. });
  9530. thread t = thread([&] { svr.listen(HOST, PORT); });
  9531. auto se = detail::scope_exit([&] {
  9532. svr.stop();
  9533. t.join();
  9534. ASSERT_FALSE(svr.is_running());
  9535. });
  9536. svr.wait_until_ready();
  9537. const std::string body =
  9538. "This is the preamble. It is to be ignored, though it\r\n"
  9539. "is a handy place for composition agents to include an\r\n"
  9540. "explanatory note to non-MIME conformant readers.\r\n"
  9541. "\r\n"
  9542. "\r\n"
  9543. "--simple boundary\r\n"
  9544. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9545. ": BAD...\r\n"
  9546. "\r\n"
  9547. "value1\r\n"
  9548. "--simple boundary\r\n"
  9549. "Content-Disposition: form-data; name=\"field2\"; "
  9550. "filename=\"example.txt\"\r\n"
  9551. "\r\n"
  9552. "value2\r\n"
  9553. "--simple boundary--\r\n"
  9554. "This is the epilogue. It is also to be ignored.\r\n";
  9555. std::string content_type =
  9556. R"(multipart/form-data; boundary="simple boundary")";
  9557. Client cli(HOST, PORT);
  9558. auto res = cli.Post("/post", body, content_type.c_str());
  9559. ASSERT_TRUE(res);
  9560. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9561. }
  9562. TEST(MultipartFormDataTest, WithPreamble) {
  9563. Server svr;
  9564. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9565. res.set_content("ok", "text/plain");
  9566. });
  9567. thread t = thread([&] { svr.listen(HOST, PORT); });
  9568. auto se = detail::scope_exit([&] {
  9569. svr.stop();
  9570. t.join();
  9571. ASSERT_FALSE(svr.is_running());
  9572. });
  9573. svr.wait_until_ready();
  9574. const std::string body =
  9575. "This is the preamble. It is to be ignored, though it\r\n"
  9576. "is a handy place for composition agents to include an\r\n"
  9577. "explanatory note to non-MIME conformant readers.\r\n"
  9578. "\r\n"
  9579. "\r\n"
  9580. "--simple boundary\r\n"
  9581. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9582. "\r\n"
  9583. "value1\r\n"
  9584. "--simple boundary\r\n"
  9585. "Content-Disposition: form-data; name=\"field2\"; "
  9586. "filename=\"example.txt\"\r\n"
  9587. "\r\n"
  9588. "value2\r\n"
  9589. "--simple boundary--\r\n"
  9590. "This is the epilogue. It is also to be ignored.\r\n";
  9591. std::string content_type =
  9592. R"(multipart/form-data; boundary="simple boundary")";
  9593. Client cli(HOST, PORT);
  9594. auto res = cli.Post("/post", body, content_type.c_str());
  9595. ASSERT_TRUE(res);
  9596. EXPECT_EQ(StatusCode::OK_200, res->status);
  9597. }
  9598. TEST(MultipartFormDataTest, PostCustomBoundary) {
  9599. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9600. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  9601. const ContentReader &content_reader) {
  9602. if (req.is_multipart_form_data()) {
  9603. std::vector<FormData> items;
  9604. content_reader(
  9605. [&](const FormData &file) {
  9606. items.push_back(file);
  9607. return true;
  9608. },
  9609. [&](const char *data, size_t data_length) {
  9610. items.back().content.append(data, data_length);
  9611. return true;
  9612. });
  9613. EXPECT_TRUE(std::string(items[0].name) == "document");
  9614. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9615. EXPECT_TRUE(items[0].filename == "2MB_data");
  9616. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9617. EXPECT_TRUE(items[1].name == "hello");
  9618. EXPECT_TRUE(items[1].content == "world");
  9619. EXPECT_TRUE(items[1].filename == "");
  9620. EXPECT_TRUE(items[1].content_type == "");
  9621. } else {
  9622. std::string body;
  9623. content_reader([&](const char *data, size_t data_length) {
  9624. body.append(data, data_length);
  9625. return true;
  9626. });
  9627. }
  9628. });
  9629. auto port = svr.bind_to_any_port("localhost");
  9630. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9631. auto se = detail::scope_exit([&] {
  9632. svr.stop();
  9633. t.join();
  9634. ASSERT_FALSE(svr.is_running());
  9635. });
  9636. svr.wait_until_ready();
  9637. {
  9638. std::string data(1024 * 1024 * 2, '.');
  9639. std::stringstream buffer;
  9640. buffer << data;
  9641. SSLClient cli("localhost", port);
  9642. cli.enable_server_certificate_verification(false);
  9643. UploadFormDataItems items{
  9644. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9645. {"hello", "world", "", ""},
  9646. };
  9647. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9648. ASSERT_TRUE(res);
  9649. ASSERT_EQ(StatusCode::OK_200, res->status);
  9650. }
  9651. }
  9652. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9653. std::string data(1024 * 1024 * 2, '&');
  9654. std::stringstream buffer;
  9655. buffer << data;
  9656. Client cli("https://localhost:8080");
  9657. UploadFormDataItems items{
  9658. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9659. {"hello", "world", "", ""},
  9660. };
  9661. for (const char &c : " \t\r\n") {
  9662. auto res =
  9663. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9664. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9665. ASSERT_FALSE(res);
  9666. }
  9667. }
  9668. TEST(MultipartFormDataTest, PutFormData) {
  9669. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9670. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9671. const ContentReader &content_reader) {
  9672. if (req.is_multipart_form_data()) {
  9673. std::vector<FormData> items;
  9674. content_reader(
  9675. [&](const FormData &file) {
  9676. items.push_back(file);
  9677. return true;
  9678. },
  9679. [&](const char *data, size_t data_length) {
  9680. items.back().content.append(data, data_length);
  9681. return true;
  9682. });
  9683. EXPECT_TRUE(std::string(items[0].name) == "document");
  9684. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9685. EXPECT_TRUE(items[0].filename == "2MB_data");
  9686. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9687. EXPECT_TRUE(items[1].name == "hello");
  9688. EXPECT_TRUE(items[1].content == "world");
  9689. EXPECT_TRUE(items[1].filename == "");
  9690. EXPECT_TRUE(items[1].content_type == "");
  9691. } else {
  9692. std::string body;
  9693. content_reader([&](const char *data, size_t data_length) {
  9694. body.append(data, data_length);
  9695. return true;
  9696. });
  9697. }
  9698. });
  9699. auto port = svr.bind_to_any_port("localhost");
  9700. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9701. auto se = detail::scope_exit([&] {
  9702. svr.stop();
  9703. t.join();
  9704. ASSERT_FALSE(svr.is_running());
  9705. });
  9706. svr.wait_until_ready();
  9707. {
  9708. std::string data(1024 * 1024 * 2, '&');
  9709. std::stringstream buffer;
  9710. buffer << data;
  9711. SSLClient cli("localhost", port);
  9712. cli.enable_server_certificate_verification(false);
  9713. UploadFormDataItems items{
  9714. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9715. {"hello", "world", "", ""},
  9716. };
  9717. auto res = cli.Put("/put", items);
  9718. ASSERT_TRUE(res);
  9719. ASSERT_EQ(StatusCode::OK_200, res->status);
  9720. }
  9721. }
  9722. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  9723. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9724. svr.Put("/put_customboundary",
  9725. [&](const Request &req, const Response & /*res*/,
  9726. const ContentReader &content_reader) {
  9727. if (req.is_multipart_form_data()) {
  9728. std::vector<FormData> items;
  9729. content_reader(
  9730. [&](const FormData &file) {
  9731. items.push_back(file);
  9732. return true;
  9733. },
  9734. [&](const char *data, size_t data_length) {
  9735. items.back().content.append(data, data_length);
  9736. return true;
  9737. });
  9738. EXPECT_TRUE(std::string(items[0].name) == "document");
  9739. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9740. EXPECT_TRUE(items[0].filename == "2MB_data");
  9741. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9742. EXPECT_TRUE(items[1].name == "hello");
  9743. EXPECT_TRUE(items[1].content == "world");
  9744. EXPECT_TRUE(items[1].filename == "");
  9745. EXPECT_TRUE(items[1].content_type == "");
  9746. } else {
  9747. std::string body;
  9748. content_reader([&](const char *data, size_t data_length) {
  9749. body.append(data, data_length);
  9750. return true;
  9751. });
  9752. }
  9753. });
  9754. auto port = svr.bind_to_any_port("localhost");
  9755. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9756. auto se = detail::scope_exit([&] {
  9757. svr.stop();
  9758. t.join();
  9759. ASSERT_FALSE(svr.is_running());
  9760. });
  9761. svr.wait_until_ready();
  9762. {
  9763. std::string data(1024 * 1024 * 2, '&');
  9764. std::stringstream buffer;
  9765. buffer << data;
  9766. SSLClient cli("localhost", port);
  9767. cli.enable_server_certificate_verification(false);
  9768. UploadFormDataItems items{
  9769. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9770. {"hello", "world", "", ""},
  9771. };
  9772. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  9773. ASSERT_TRUE(res);
  9774. ASSERT_EQ(StatusCode::OK_200, res->status);
  9775. }
  9776. }
  9777. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  9778. std::string data(1024 * 1024 * 2, '&');
  9779. std::stringstream buffer;
  9780. buffer << data;
  9781. Client cli("https://localhost:8080");
  9782. cli.enable_server_certificate_verification(false);
  9783. UploadFormDataItems items{
  9784. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9785. {"hello", "world", "", ""},
  9786. };
  9787. for (const char &c : " \t\r\n") {
  9788. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  9789. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9790. ASSERT_FALSE(res);
  9791. }
  9792. }
  9793. TEST(MultipartFormDataTest, AlternateFilename) {
  9794. auto handled = false;
  9795. Server svr;
  9796. svr.Post("/test", [&](const Request &req, Response &res) {
  9797. ASSERT_EQ(2u, req.form.files.size());
  9798. ASSERT_EQ(1u, req.form.fields.size());
  9799. // Test files
  9800. const auto &file1 = req.form.get_file("file1");
  9801. ASSERT_EQ("file1", file1.name);
  9802. ASSERT_EQ("A.txt", file1.filename);
  9803. ASSERT_EQ("text/plain", file1.content_type);
  9804. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  9805. const auto &file2 = req.form.get_file("file2");
  9806. ASSERT_EQ("file2", file2.name);
  9807. ASSERT_EQ("a.html", file2.filename);
  9808. ASSERT_EQ("text/html", file2.content_type);
  9809. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  9810. file2.content);
  9811. // Test text field
  9812. const auto &text = req.form.get_field("text");
  9813. ASSERT_EQ("text default", text);
  9814. res.set_content("ok", "text/plain");
  9815. handled = true;
  9816. });
  9817. thread t = thread([&] { svr.listen(HOST, PORT); });
  9818. auto se = detail::scope_exit([&] {
  9819. svr.stop();
  9820. t.join();
  9821. ASSERT_FALSE(svr.is_running());
  9822. ASSERT_TRUE(handled);
  9823. });
  9824. svr.wait_until_ready();
  9825. auto req = "POST /test HTTP/1.1\r\n"
  9826. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9827. "Content-Length: 399\r\n"
  9828. "\r\n"
  9829. "----------\r\n"
  9830. "Content-Disposition: form-data; name=\"text\"\r\n"
  9831. "\r\n"
  9832. "text default\r\n"
  9833. "----------\r\n"
  9834. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  9835. "filename=\"a.txt\"; name=\"file1\"\r\n"
  9836. "Content-Type: text/plain\r\n"
  9837. "\r\n"
  9838. "Content of a.txt.\r\n"
  9839. "\r\n"
  9840. "----------\r\n"
  9841. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  9842. "\"a.html\"\r\n"
  9843. "Content-Type: text/html\r\n"
  9844. "\r\n"
  9845. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  9846. "\r\n"
  9847. "------------\r\n";
  9848. ASSERT_TRUE(send_request(1, req));
  9849. }
  9850. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  9851. auto handled = false;
  9852. Server svr;
  9853. svr.Post("/test", [&](const Request &req, Response &res) {
  9854. // Case-insensitive "utf-8''" prefix with a long value
  9855. const auto &file = req.form.get_file("file1");
  9856. ASSERT_EQ("file1", file.name);
  9857. // 8000 chars exercises both the Content-Disposition parser and the
  9858. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  9859. // Prior to the fix, std::regex_match on this header would cause O(N)
  9860. // stack recursion in libstdc++, leading to SIGSEGV.
  9861. std::string expected_filename(8000, 'A');
  9862. ASSERT_EQ(expected_filename, file.filename);
  9863. res.set_content("ok", "text/plain");
  9864. handled = true;
  9865. });
  9866. thread t = thread([&] { svr.listen(HOST, PORT); });
  9867. auto se = detail::scope_exit([&] {
  9868. svr.stop();
  9869. t.join();
  9870. ASSERT_FALSE(svr.is_running());
  9871. ASSERT_TRUE(handled);
  9872. });
  9873. svr.wait_until_ready();
  9874. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  9875. // Regression test for GHSA-qq6v-r583-3h69
  9876. std::string long_filename(8000, 'A');
  9877. std::string body = "----------\r\n"
  9878. "Content-Disposition: form-data; name=\"file1\"; "
  9879. "filename*=\"Utf-8''" +
  9880. long_filename +
  9881. "\"\r\n"
  9882. "\r\n"
  9883. "hello\r\n"
  9884. "------------\r\n";
  9885. auto req = "POST /test HTTP/1.1\r\n"
  9886. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9887. "Content-Length: " +
  9888. std::to_string(body.size()) + "\r\n\r\n" + body;
  9889. ASSERT_TRUE(send_request(1, req));
  9890. }
  9891. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  9892. auto handled = false;
  9893. Server svr;
  9894. svr.Post("/test", [&](const Request &req, Response &) {
  9895. ASSERT_EQ(2u, req.form.fields.size());
  9896. const auto &text1 = req.form.get_field("text1");
  9897. ASSERT_EQ("text1", text1);
  9898. const auto &text2 = req.form.get_field("text2");
  9899. ASSERT_EQ("text2", text2);
  9900. handled = true;
  9901. });
  9902. thread t = thread([&] { svr.listen(HOST, PORT); });
  9903. auto se = detail::scope_exit([&] {
  9904. svr.stop();
  9905. t.join();
  9906. ASSERT_FALSE(svr.is_running());
  9907. ASSERT_TRUE(handled);
  9908. });
  9909. svr.wait_until_ready();
  9910. auto req = "POST /test HTTP/1.1\r\n"
  9911. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9912. "Content-Length: 146\r\n"
  9913. "\r\n----------\r\n"
  9914. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9915. "\r\n"
  9916. "text1"
  9917. "\r\n----------\r\n"
  9918. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9919. "\r\n"
  9920. "text2"
  9921. "\r\n------------";
  9922. std::string response;
  9923. ASSERT_TRUE(send_request(1, req, &response));
  9924. ASSERT_EQ("200", response.substr(9, 3));
  9925. }
  9926. TEST(MultipartFormDataTest, ContentLength) {
  9927. auto handled = false;
  9928. Server svr;
  9929. svr.Post("/test", [&](const Request &req, Response &) {
  9930. ASSERT_EQ(2u, req.form.fields.size());
  9931. const auto &text1 = req.form.get_field("text1");
  9932. ASSERT_EQ("text1", text1);
  9933. const auto &text2 = req.form.get_field("text2");
  9934. ASSERT_EQ("text2", text2);
  9935. handled = true;
  9936. });
  9937. thread t = thread([&] { svr.listen(HOST, PORT); });
  9938. auto se = detail::scope_exit([&] {
  9939. svr.stop();
  9940. t.join();
  9941. ASSERT_FALSE(svr.is_running());
  9942. ASSERT_TRUE(handled);
  9943. });
  9944. svr.wait_until_ready();
  9945. auto req = "POST /test HTTP/1.1\r\n"
  9946. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9947. "Content-Length: 167\r\n"
  9948. "\r\n----------\r\n"
  9949. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9950. "Content-Length: 5\r\n"
  9951. "\r\n"
  9952. "text1"
  9953. "\r\n----------\r\n"
  9954. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9955. "\r\n"
  9956. "text2"
  9957. "\r\n------------\r\n";
  9958. std::string response;
  9959. ASSERT_TRUE(send_request(1, req, &response));
  9960. ASSERT_EQ("200", response.substr(9, 3));
  9961. }
  9962. TEST(MultipartFormDataTest, AccessPartHeaders) {
  9963. auto handled = false;
  9964. Server svr;
  9965. svr.Post("/test", [&](const Request &req, Response &) {
  9966. ASSERT_EQ(2u, req.form.fields.size());
  9967. const auto &text1 = req.form.get_field("text1");
  9968. ASSERT_EQ("text1", text1);
  9969. // TODO: Add header access for text fields if needed
  9970. const auto &text2 = req.form.get_field("text2");
  9971. ASSERT_EQ("text2", text2);
  9972. // TODO: Header access for text fields needs to be implemented
  9973. // auto &headers = it->second.headers;
  9974. // ASSERT_EQ(3U, headers.size());
  9975. // auto custom_header = headers.find("x-whatever");
  9976. // ASSERT_TRUE(custom_header != headers.end());
  9977. // ASSERT_NE("customvalue", custom_header->second);
  9978. // ASSERT_EQ("CustomValue", custom_header->second);
  9979. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  9980. handled = true;
  9981. });
  9982. thread t = thread([&] { svr.listen(HOST, PORT); });
  9983. auto se = detail::scope_exit([&] {
  9984. svr.stop();
  9985. t.join();
  9986. ASSERT_FALSE(svr.is_running());
  9987. ASSERT_TRUE(handled);
  9988. });
  9989. svr.wait_until_ready();
  9990. auto req = "POST /test HTTP/1.1\r\n"
  9991. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9992. "Content-Length: 232\r\n"
  9993. "\r\n----------\r\n"
  9994. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9995. "Content-Length: 5\r\n"
  9996. "X-Test: 1\r\n"
  9997. "\r\n"
  9998. "text1"
  9999. "\r\n----------\r\n"
  10000. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10001. "Content-Type: text/plain\r\n"
  10002. "X-Whatever: CustomValue\r\n"
  10003. "\r\n"
  10004. "text2"
  10005. "\r\n------------\r\n"
  10006. "That should be disregarded. Not even read";
  10007. std::string response;
  10008. ASSERT_TRUE(send_request(1, req, &response));
  10009. ASSERT_EQ("200", response.substr(9, 3));
  10010. }
  10011. TEST(MultipartFormDataTest, LargeHeader) {
  10012. auto handled = false;
  10013. Server svr;
  10014. svr.Post("/test", [&](const Request &req, Response &) {
  10015. ASSERT_EQ(1u, req.form.fields.size());
  10016. const auto &text = req.form.get_field("name1");
  10017. ASSERT_EQ("text1", text);
  10018. handled = true;
  10019. });
  10020. thread t = thread([&] { svr.listen(HOST, PORT); });
  10021. auto se = detail::scope_exit([&] {
  10022. svr.stop();
  10023. t.join();
  10024. ASSERT_FALSE(svr.is_running());
  10025. ASSERT_TRUE(handled);
  10026. });
  10027. svr.wait_until_ready();
  10028. auto boundary = std::string("cpp-httplib-multipart-data");
  10029. std::string content = "--" + boundary +
  10030. "\r\n"
  10031. "Content-Disposition: form-data; name=\"name1\"\r\n"
  10032. "\r\n"
  10033. "text1\r\n"
  10034. "--" +
  10035. boundary + "--\r\n";
  10036. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  10037. "Content-Type: multipart/form-data;boundary=" +
  10038. boundary +
  10039. "\r\n"
  10040. "Content-Length: " +
  10041. std::to_string(content.size()) +
  10042. "\r\n"
  10043. "Dummy-Header: ";
  10044. std::string header_suffix = "\r\n"
  10045. "\r\n";
  10046. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  10047. size_t header_dummy_size =
  10048. read_buff_size -
  10049. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  10050. auto header_dummy = std::string(header_dummy_size, '@');
  10051. auto req = header_prefix + header_dummy + header_suffix + content;
  10052. std::string response;
  10053. ASSERT_TRUE(send_request(1, req, &response));
  10054. ASSERT_EQ("200", response.substr(9, 3));
  10055. }
  10056. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  10057. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  10058. // (not chunked Transfer-Encoding) after the streaming refactor.
  10059. auto handled = false;
  10060. Server svr;
  10061. svr.Post("/upload", [&](const Request &req, Response &res) {
  10062. auto cl_it = req.headers.find("Content-Length");
  10063. EXPECT_TRUE(cl_it != req.headers.end());
  10064. auto te_it = req.headers.find("Transfer-Encoding");
  10065. EXPECT_TRUE(te_it == req.headers.end());
  10066. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  10067. res.set_content("ok", "text/plain");
  10068. handled = true;
  10069. });
  10070. auto port = svr.bind_to_any_port(HOST);
  10071. auto t = thread([&] { svr.listen_after_bind(); });
  10072. auto se = detail::scope_exit([&] {
  10073. svr.stop();
  10074. t.join();
  10075. ASSERT_FALSE(svr.is_running());
  10076. ASSERT_TRUE(handled);
  10077. });
  10078. svr.wait_until_ready();
  10079. UploadFormDataItems items = {
  10080. {"field1", "hello", "", "text/plain"},
  10081. {"file1", "world", "test.txt", "application/octet-stream"},
  10082. };
  10083. Client cli(HOST, port);
  10084. auto res = cli.Post("/upload", {}, items);
  10085. ASSERT_TRUE(res);
  10086. EXPECT_EQ(StatusCode::OK_200, res->status);
  10087. }
  10088. TEST(MultipartFormDataTest, MakeFileProvider) {
  10089. // Verify make_file_provider sends a file's contents correctly.
  10090. const std::string file_content(4096, 'Z');
  10091. const std::string tmp_path = "/tmp/httplib_test_make_file_provider.bin";
  10092. {
  10093. std::ofstream ofs(tmp_path, std::ios::binary);
  10094. ofs.write(file_content.data(),
  10095. static_cast<std::streamsize>(file_content.size()));
  10096. }
  10097. auto handled = false;
  10098. Server svr;
  10099. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  10100. const ContentReader &content_reader) {
  10101. ASSERT_TRUE(req.is_multipart_form_data());
  10102. std::vector<FormData> items;
  10103. content_reader(
  10104. [&](const FormData &file) {
  10105. items.push_back(file);
  10106. return true;
  10107. },
  10108. [&](const char *data, size_t data_length) {
  10109. items.back().content.append(data, data_length);
  10110. return true;
  10111. });
  10112. ASSERT_EQ(1u, items.size());
  10113. EXPECT_EQ("myfile", items[0].name);
  10114. EXPECT_EQ("data.bin", items[0].filename);
  10115. EXPECT_EQ("application/octet-stream", items[0].content_type);
  10116. EXPECT_EQ(file_content, items[0].content);
  10117. handled = true;
  10118. });
  10119. auto port = svr.bind_to_any_port(HOST);
  10120. auto t = thread([&] { svr.listen_after_bind(); });
  10121. auto se = detail::scope_exit([&] {
  10122. svr.stop();
  10123. t.join();
  10124. ASSERT_FALSE(svr.is_running());
  10125. ASSERT_TRUE(handled);
  10126. std::remove(tmp_path.c_str());
  10127. });
  10128. svr.wait_until_ready();
  10129. FormDataProviderItems providers;
  10130. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  10131. "application/octet-stream"));
  10132. Client cli(HOST, port);
  10133. auto res = cli.Post("/upload", {}, {}, providers);
  10134. ASSERT_TRUE(res);
  10135. EXPECT_EQ(StatusCode::OK_200, res->status);
  10136. }
  10137. TEST(MakeFileBodyTest, Basic) {
  10138. const std::string file_content(4096, 'Z');
  10139. const std::string tmp_path = "/tmp/httplib_test_make_file_body.bin";
  10140. {
  10141. std::ofstream ofs(tmp_path, std::ios::binary);
  10142. ofs.write(file_content.data(),
  10143. static_cast<std::streamsize>(file_content.size()));
  10144. }
  10145. auto handled = false;
  10146. Server svr;
  10147. svr.Post("/upload", [&](const Request &req, Response &res) {
  10148. EXPECT_EQ(file_content, req.body);
  10149. handled = true;
  10150. res.status = StatusCode::OK_200;
  10151. });
  10152. auto port = svr.bind_to_any_port(HOST);
  10153. auto t = thread([&] { svr.listen_after_bind(); });
  10154. auto se = detail::scope_exit([&] {
  10155. svr.stop();
  10156. t.join();
  10157. ASSERT_FALSE(svr.is_running());
  10158. ASSERT_TRUE(handled);
  10159. std::remove(tmp_path.c_str());
  10160. });
  10161. svr.wait_until_ready();
  10162. auto fb = make_file_body(tmp_path);
  10163. ASSERT_GT(fb.first, 0u);
  10164. Client cli(HOST, port);
  10165. auto res =
  10166. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  10167. ASSERT_TRUE(res);
  10168. EXPECT_EQ(StatusCode::OK_200, res->status);
  10169. }
  10170. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  10171. static constexpr unsigned int number_of_tasks{1000000};
  10172. std::atomic_uint count{0};
  10173. std::unique_ptr<TaskQueue> task_queue{
  10174. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  10175. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10176. auto queued = task_queue->enqueue(
  10177. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  10178. EXPECT_TRUE(queued);
  10179. }
  10180. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10181. task_queue->shutdown();
  10182. #else
  10183. EXPECT_NO_THROW(task_queue->shutdown());
  10184. #endif
  10185. EXPECT_EQ(number_of_tasks, count.load());
  10186. }
  10187. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  10188. static constexpr unsigned int number_of_tasks{1000000};
  10189. static constexpr unsigned int qlimit{2};
  10190. unsigned int queued_count{0};
  10191. std::atomic_uint count{0};
  10192. std::unique_ptr<TaskQueue> task_queue{
  10193. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  10194. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10195. if (task_queue->enqueue(
  10196. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  10197. queued_count++;
  10198. }
  10199. }
  10200. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10201. task_queue->shutdown();
  10202. #else
  10203. EXPECT_NO_THROW(task_queue->shutdown());
  10204. #endif
  10205. EXPECT_EQ(queued_count, count.load());
  10206. EXPECT_TRUE(queued_count <= number_of_tasks);
  10207. EXPECT_TRUE(queued_count >= qlimit);
  10208. }
  10209. TEST(TaskQueueTest, MaxQueuedRequests) {
  10210. static constexpr unsigned int qlimit{3};
  10211. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  10212. std::condition_variable sem_cv;
  10213. std::mutex sem_mtx;
  10214. int credits = 0;
  10215. bool queued;
  10216. /* Fill up the queue with tasks that will block until we give them credits to
  10217. * complete. */
  10218. for (unsigned int n = 0; n <= qlimit;) {
  10219. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  10220. std::unique_lock<std::mutex> lock(sem_mtx);
  10221. while (credits <= 0) {
  10222. sem_cv.wait(lock);
  10223. }
  10224. /* Consume the credit and signal the test code if they are all gone. */
  10225. if (--credits == 0) { sem_cv.notify_one(); }
  10226. });
  10227. if (n < qlimit) {
  10228. /* The first qlimit enqueues must succeed. */
  10229. EXPECT_TRUE(queued);
  10230. } else {
  10231. /* The last one will succeed only when the worker thread
  10232. * starts and dequeues the first blocking task. Although
  10233. * not necessary for the correctness of this test, we sleep for
  10234. * a short while to avoid busy waiting. */
  10235. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10236. }
  10237. if (queued) { n++; }
  10238. }
  10239. /* Further enqueues must fail since the queue is full. */
  10240. for (auto i = 0; i < 4; i++) {
  10241. queued = task_queue->enqueue([] {});
  10242. EXPECT_FALSE(queued);
  10243. }
  10244. /* Give the credits to allow the previous tasks to complete. */
  10245. {
  10246. std::unique_lock<std::mutex> lock(sem_mtx);
  10247. credits += qlimit + 1;
  10248. }
  10249. sem_cv.notify_all();
  10250. /* Wait for all the credits to be consumed. */
  10251. {
  10252. std::unique_lock<std::mutex> lock(sem_mtx);
  10253. while (credits > 0) {
  10254. sem_cv.wait(lock);
  10255. }
  10256. }
  10257. /* Check that we are able again to enqueue at least qlimit tasks. */
  10258. for (unsigned int i = 0; i < qlimit; i++) {
  10259. queued = task_queue->enqueue([] {});
  10260. EXPECT_TRUE(queued);
  10261. }
  10262. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10263. task_queue->shutdown();
  10264. #else
  10265. EXPECT_NO_THROW(task_queue->shutdown());
  10266. #endif
  10267. }
  10268. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  10269. Server svr;
  10270. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10271. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  10272. });
  10273. svr.Get("/hello", [](const Request &req, Response &res) {
  10274. res.set_content(req.get_param_value("key"), "text/plain");
  10275. });
  10276. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10277. auto se = detail::scope_exit([&] {
  10278. svr.stop();
  10279. thread.join();
  10280. ASSERT_FALSE(svr.is_running());
  10281. });
  10282. svr.wait_until_ready();
  10283. {
  10284. Client cli(HOST, PORT);
  10285. cli.set_follow_location(true);
  10286. auto res = cli.Get("/");
  10287. ASSERT_TRUE(res);
  10288. EXPECT_EQ(StatusCode::OK_200, res->status);
  10289. EXPECT_EQ("val&key2=val2", res->body);
  10290. }
  10291. }
  10292. #endif
  10293. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  10294. Server svr;
  10295. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10296. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  10297. });
  10298. svr.Get("/hello", [](const Request &req, Response &res) {
  10299. res.set_content(req.get_param_value("key"), "text/plain");
  10300. });
  10301. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10302. auto se = detail::scope_exit([&] {
  10303. svr.stop();
  10304. thread.join();
  10305. ASSERT_FALSE(svr.is_running());
  10306. });
  10307. svr.wait_until_ready();
  10308. {
  10309. Client cli(HOST, PORT);
  10310. cli.set_follow_location(true);
  10311. auto res = cli.Get("/");
  10312. ASSERT_TRUE(res);
  10313. EXPECT_EQ(StatusCode::OK_200, res->status);
  10314. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  10315. }
  10316. }
  10317. #ifdef CPPHTTPLIB_SSL_ENABLED
  10318. TEST(RedirectTest, Issue2185_Online) {
  10319. SSLClient client("github.com");
  10320. client.set_follow_location(true);
  10321. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  10322. "Coollab-Windows.zip");
  10323. ASSERT_TRUE(res);
  10324. EXPECT_EQ(StatusCode::OK_200, res->status);
  10325. EXPECT_EQ(9920427U, res->body.size());
  10326. }
  10327. #endif
  10328. TEST(VulnerabilityTest, CRLFInjection) {
  10329. Server svr;
  10330. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  10331. res.set_content("Hello 1", "text/plain");
  10332. });
  10333. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  10334. res.set_content("Hello 2", "text/plain");
  10335. });
  10336. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  10337. res.set_content("Hello 3", "text/plain");
  10338. });
  10339. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  10340. res.set_content("Hello 4", "text/plain");
  10341. });
  10342. svr.set_logger([](const Request &req, const Response & /*res*/) {
  10343. for (const auto &x : req.headers) {
  10344. auto key = x.first;
  10345. EXPECT_STRNE("evil", key.c_str());
  10346. }
  10347. });
  10348. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10349. auto se = detail::scope_exit([&] {
  10350. svr.stop();
  10351. thread.join();
  10352. ASSERT_FALSE(svr.is_running());
  10353. });
  10354. svr.wait_until_ready();
  10355. {
  10356. Client cli(HOST, PORT);
  10357. cli.Post("/test1", "A=B",
  10358. "application/x-www-form-urlencoded\r\nevil: hello1");
  10359. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  10360. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  10361. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  10362. }
  10363. }
  10364. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  10365. auto server_thread = std::thread([] {
  10366. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10367. default_socket_options(srv);
  10368. sockaddr_in addr{};
  10369. addr.sin_family = AF_INET;
  10370. addr.sin_port = htons(PORT + 1);
  10371. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10372. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10373. ::listen(srv, 1);
  10374. sockaddr_in cli_addr{};
  10375. socklen_t cli_len = sizeof(cli_addr);
  10376. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10377. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  10378. std::string buf_all;
  10379. char buf[2048];
  10380. ssize_t n;
  10381. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  10382. buf_all.append(buf, static_cast<size_t>(n));
  10383. size_t pos;
  10384. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  10385. auto request_block = buf_all.substr(0, pos + 4); // include separator
  10386. auto e = request_block.find("\r\n");
  10387. if (e != std::string::npos) {
  10388. auto request_line = request_block.substr(0, e);
  10389. std::string msg =
  10390. "CRLF injection detected in request line: '" + request_line + "'";
  10391. EXPECT_FALSE(true) << msg;
  10392. }
  10393. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  10394. ::send(cli,
  10395. #ifdef _WIN32
  10396. static_cast<const char *>(resp.c_str()),
  10397. static_cast<int>(resp.size()),
  10398. #else
  10399. resp.c_str(), resp.size(),
  10400. #endif
  10401. 0);
  10402. buf_all.erase(0, pos + 4);
  10403. }
  10404. }
  10405. detail::close_socket(cli);
  10406. detail::close_socket(srv);
  10407. });
  10408. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10409. auto cli = Client("127.0.0.1", PORT + 1);
  10410. auto headers = Headers{
  10411. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  10412. {"Connection", "keep-alive"}};
  10413. auto res = cli.Get("/hi", headers);
  10414. EXPECT_FALSE(res);
  10415. EXPECT_EQ(Error::InvalidHeaders, res.error());
  10416. server_thread.join();
  10417. }
  10418. TEST(PathParamsTest, StaticMatch) {
  10419. const auto pattern = "/users/all";
  10420. detail::PathParamsMatcher matcher(pattern);
  10421. Request request;
  10422. request.path = "/users/all";
  10423. ASSERT_TRUE(matcher.match(request));
  10424. std::unordered_map<std::string, std::string> expected_params = {};
  10425. EXPECT_EQ(request.path_params, expected_params);
  10426. }
  10427. TEST(PathParamsTest, StaticMismatch) {
  10428. const auto pattern = "/users/all";
  10429. detail::PathParamsMatcher matcher(pattern);
  10430. Request request;
  10431. request.path = "/users/1";
  10432. ASSERT_FALSE(matcher.match(request));
  10433. }
  10434. TEST(PathParamsTest, SingleParamInTheMiddle) {
  10435. const auto pattern = "/users/:id/subscriptions";
  10436. detail::PathParamsMatcher matcher(pattern);
  10437. Request request;
  10438. request.path = "/users/42/subscriptions";
  10439. ASSERT_TRUE(matcher.match(request));
  10440. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10441. EXPECT_EQ(request.path_params, expected_params);
  10442. }
  10443. TEST(PathParamsTest, SingleParamInTheEnd) {
  10444. const auto pattern = "/users/:id";
  10445. detail::PathParamsMatcher matcher(pattern);
  10446. Request request;
  10447. request.path = "/users/24";
  10448. ASSERT_TRUE(matcher.match(request));
  10449. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  10450. EXPECT_EQ(request.path_params, expected_params);
  10451. }
  10452. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  10453. const auto pattern = "/users/:id/";
  10454. detail::PathParamsMatcher matcher(pattern);
  10455. Request request;
  10456. request.path = "/users/42/";
  10457. ASSERT_TRUE(matcher.match(request));
  10458. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10459. EXPECT_EQ(request.path_params, expected_params);
  10460. }
  10461. TEST(PathParamsTest, EmptyParam) {
  10462. const auto pattern = "/users/:id/";
  10463. detail::PathParamsMatcher matcher(pattern);
  10464. Request request;
  10465. request.path = "/users//";
  10466. ASSERT_TRUE(matcher.match(request));
  10467. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10468. EXPECT_EQ(request.path_params, expected_params);
  10469. }
  10470. TEST(PathParamsTest, FragmentMismatch) {
  10471. const auto pattern = "/users/:id/";
  10472. detail::PathParamsMatcher matcher(pattern);
  10473. Request request;
  10474. request.path = "/admins/24/";
  10475. ASSERT_FALSE(matcher.match(request));
  10476. }
  10477. TEST(PathParamsTest, ExtraFragments) {
  10478. const auto pattern = "/users/:id";
  10479. detail::PathParamsMatcher matcher(pattern);
  10480. Request request;
  10481. request.path = "/users/42/subscriptions";
  10482. ASSERT_FALSE(matcher.match(request));
  10483. }
  10484. TEST(PathParamsTest, MissingTrailingParam) {
  10485. const auto pattern = "/users/:id";
  10486. detail::PathParamsMatcher matcher(pattern);
  10487. Request request;
  10488. request.path = "/users";
  10489. ASSERT_FALSE(matcher.match(request));
  10490. }
  10491. TEST(PathParamsTest, MissingParamInTheMiddle) {
  10492. const auto pattern = "/users/:id/subscriptions";
  10493. detail::PathParamsMatcher matcher(pattern);
  10494. Request request;
  10495. request.path = "/users/subscriptions";
  10496. ASSERT_FALSE(matcher.match(request));
  10497. }
  10498. TEST(PathParamsTest, MultipleParams) {
  10499. const auto pattern = "/users/:userid/subscriptions/:subid";
  10500. detail::PathParamsMatcher matcher(pattern);
  10501. Request request;
  10502. request.path = "/users/42/subscriptions/2";
  10503. ASSERT_TRUE(matcher.match(request));
  10504. std::unordered_map<std::string, std::string> expected_params = {
  10505. {"userid", "42"}, {"subid", "2"}};
  10506. EXPECT_EQ(request.path_params, expected_params);
  10507. }
  10508. TEST(PathParamsTest, SequenceOfParams) {
  10509. const auto pattern = "/values/:x/:y/:z";
  10510. detail::PathParamsMatcher matcher(pattern);
  10511. Request request;
  10512. request.path = "/values/1/2/3";
  10513. ASSERT_TRUE(matcher.match(request));
  10514. std::unordered_map<std::string, std::string> expected_params = {
  10515. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  10516. EXPECT_EQ(request.path_params, expected_params);
  10517. }
  10518. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  10519. const auto pattern = "/prefix:suffix";
  10520. detail::PathParamsMatcher matcher(pattern);
  10521. Request request;
  10522. request.path = "/prefix:suffix";
  10523. ASSERT_TRUE(matcher.match(request));
  10524. const std::unordered_map<std::string, std::string> expected_params = {};
  10525. EXPECT_EQ(request.path_params, expected_params);
  10526. }
  10527. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  10528. // If ipv6 regex working, regex match codepath is taken.
  10529. // else port will default to 80 in Client impl
  10530. int clientImplMagicPort = 80;
  10531. int port = 4321;
  10532. // above ports must be different to avoid false negative
  10533. EXPECT_NE(clientImplMagicPort, port);
  10534. std::string ipV6TestURL = "http://[ff06::c3]";
  10535. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  10536. CLIENT_PRIVATE_KEY_FILE);
  10537. EXPECT_EQ(cli.port(), port);
  10538. }
  10539. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  10540. auto file_path = "./www/dir/index.html";
  10541. auto dir_path = "./www/dir";
  10542. detail::FileStat stat_file(file_path);
  10543. EXPECT_TRUE(stat_file.is_file());
  10544. EXPECT_FALSE(stat_file.is_dir());
  10545. detail::FileStat stat_dir(dir_path);
  10546. EXPECT_FALSE(stat_dir.is_file());
  10547. EXPECT_TRUE(stat_dir.is_dir());
  10548. }
  10549. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  10550. // IPv4 with default HTTP port (80)
  10551. EXPECT_EQ("example.com",
  10552. detail::make_host_and_port_string("example.com", 80, false));
  10553. // IPv4 with default HTTPS port (443)
  10554. EXPECT_EQ("example.com",
  10555. detail::make_host_and_port_string("example.com", 443, true));
  10556. // IPv4 with non-default HTTP port
  10557. EXPECT_EQ("example.com:8080",
  10558. detail::make_host_and_port_string("example.com", 8080, false));
  10559. // IPv4 with non-default HTTPS port
  10560. EXPECT_EQ("example.com:8443",
  10561. detail::make_host_and_port_string("example.com", 8443, true));
  10562. // IPv6 with default HTTP port (80)
  10563. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  10564. // IPv6 with default HTTPS port (443)
  10565. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  10566. // IPv6 with non-default HTTP port
  10567. EXPECT_EQ("[::1]:8080",
  10568. detail::make_host_and_port_string("::1", 8080, false));
  10569. // IPv6 with non-default HTTPS port
  10570. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  10571. // IPv6 full address with default port
  10572. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  10573. detail::make_host_and_port_string(
  10574. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  10575. // IPv6 full address with non-default port
  10576. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  10577. detail::make_host_and_port_string(
  10578. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  10579. // IPv6 localhost with non-default port
  10580. EXPECT_EQ("[::1]:3000",
  10581. detail::make_host_and_port_string("::1", 3000, false));
  10582. // IPv6 with zone ID (link-local address) with default port
  10583. EXPECT_EQ("[fe80::1%eth0]",
  10584. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  10585. // IPv6 with zone ID (link-local address) with non-default port
  10586. EXPECT_EQ("[fe80::1%eth0]:8080",
  10587. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  10588. // Edge case: Port 443 with is_ssl=false (should add port)
  10589. EXPECT_EQ("example.com:443",
  10590. detail::make_host_and_port_string("example.com", 443, false));
  10591. // Edge case: Port 80 with is_ssl=true (should add port)
  10592. EXPECT_EQ("example.com:80",
  10593. detail::make_host_and_port_string("example.com", 80, true));
  10594. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  10595. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  10596. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  10597. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  10598. // Security fix: Already bracketed IPv6 should not get double brackets
  10599. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  10600. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  10601. EXPECT_EQ("[::1]:8080",
  10602. detail::make_host_and_port_string("[::1]", 8080, false));
  10603. EXPECT_EQ("[2001:db8::1]:8080",
  10604. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  10605. EXPECT_EQ("[fe80::1%eth0]",
  10606. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  10607. EXPECT_EQ("[fe80::1%eth0]:8080",
  10608. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  10609. // Edge case: Empty host (should return as-is)
  10610. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  10611. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  10612. // This is a known limitation but shouldn't crash
  10613. EXPECT_EQ("[host:name]",
  10614. detail::make_host_and_port_string("host:name", 80, false));
  10615. // Port number edge cases (no validation, but should not crash)
  10616. EXPECT_EQ("example.com:0",
  10617. detail::make_host_and_port_string("example.com", 0, false));
  10618. EXPECT_EQ("example.com:-1",
  10619. detail::make_host_and_port_string("example.com", -1, false));
  10620. EXPECT_EQ("example.com:65535",
  10621. detail::make_host_and_port_string("example.com", 65535, false));
  10622. EXPECT_EQ("example.com:65536",
  10623. detail::make_host_and_port_string("example.com", 65536, false));
  10624. }
  10625. #ifdef CPPHTTPLIB_SSL_ENABLED
  10626. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  10627. httplib::SSLClient cli("roblox.com", 443);
  10628. cli.set_follow_location(true);
  10629. auto res = cli.Get("/");
  10630. ASSERT_TRUE(res);
  10631. EXPECT_EQ(StatusCode::OK_200, res->status);
  10632. }
  10633. #endif
  10634. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  10635. Server svr;
  10636. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10637. EXPECT_EQ(res.status, 400);
  10638. });
  10639. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10640. auto se = detail::scope_exit([&] {
  10641. svr.stop();
  10642. thread.join();
  10643. ASSERT_FALSE(svr.is_running());
  10644. });
  10645. svr.wait_until_ready();
  10646. Client cli(HOST, PORT);
  10647. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  10648. }
  10649. TEST(InvalidHeaderCharsTest, is_field_name) {
  10650. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  10651. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  10652. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  10653. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  10654. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  10655. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  10656. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  10657. EXPECT_FALSE(detail::fields::is_field_name(""));
  10658. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  10659. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  10660. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  10661. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  10662. }
  10663. TEST(InvalidHeaderCharsTest, is_field_value) {
  10664. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  10665. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  10666. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  10667. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  10668. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  10669. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  10670. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  10671. EXPECT_TRUE(detail::fields::is_field_value(""));
  10672. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  10673. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  10674. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  10675. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  10676. EXPECT_TRUE(detail::fields::is_field_value("0"));
  10677. }
  10678. TEST(InvalidHeaderCharsTest, OnServer) {
  10679. Server svr;
  10680. svr.Get("/test_name", [&](const Request &req, Response &res) {
  10681. std::string header = "Not Set";
  10682. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10683. res.set_header(header, "value");
  10684. res.set_content("Page Content Page Content", "text/plain");
  10685. });
  10686. svr.Get("/test_value", [&](const Request &req, Response &res) {
  10687. std::string header = "Not Set";
  10688. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10689. res.set_header("X-Test", header);
  10690. res.set_content("Page Content Page Content", "text/plain");
  10691. });
  10692. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10693. auto se = detail::scope_exit([&] {
  10694. svr.stop();
  10695. thread.join();
  10696. ASSERT_FALSE(svr.is_running());
  10697. });
  10698. svr.wait_until_ready();
  10699. Client cli(HOST, PORT);
  10700. {
  10701. auto res = cli.Get(
  10702. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10703. ASSERT_TRUE(res);
  10704. EXPECT_EQ("Page Content Page Content", res->body);
  10705. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10706. }
  10707. {
  10708. auto res = cli.Get(
  10709. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10710. ASSERT_TRUE(res);
  10711. EXPECT_EQ("Page Content Page Content", res->body);
  10712. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10713. }
  10714. }
  10715. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  10716. auto handled = false;
  10717. Server svr;
  10718. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10719. thread t = thread([&] { svr.listen(HOST, PORT); });
  10720. auto se = detail::scope_exit([&] {
  10721. svr.stop();
  10722. t.join();
  10723. ASSERT_FALSE(svr.is_running());
  10724. ASSERT_FALSE(handled);
  10725. });
  10726. svr.wait_until_ready();
  10727. auto req = "POST /test HTTP/1.1\r\n"
  10728. "Content-Length: x\r\n"
  10729. "\r\n";
  10730. std::string response;
  10731. ASSERT_TRUE(send_request(1, req, &response));
  10732. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10733. response.substr(0, response.find("\r\n")));
  10734. }
  10735. #ifndef _WIN32
  10736. TEST(Expect100ContinueTest, ServerClosesConnection) {
  10737. static constexpr char reject[] = "Unauthorized";
  10738. static constexpr char accept[] = "Upload accepted";
  10739. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  10740. Server svr;
  10741. svr.set_expect_100_continue_handler(
  10742. [](const Request & /*req*/, Response &res) {
  10743. res.status = StatusCode::Unauthorized_401;
  10744. res.set_content(reject, "text/plain");
  10745. return res.status;
  10746. });
  10747. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  10748. res.set_content(accept, "text/plain");
  10749. });
  10750. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10751. auto se = detail::scope_exit([&] {
  10752. svr.stop();
  10753. thread.join();
  10754. ASSERT_FALSE(svr.is_running());
  10755. });
  10756. svr.wait_until_ready();
  10757. {
  10758. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  10759. curl_easy_init(), &curl_easy_cleanup};
  10760. ASSERT_NE(curl, nullptr);
  10761. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  10762. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  10763. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  10764. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  10765. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  10766. &curl_slist_free_all};
  10767. ASSERT_NE(list, nullptr);
  10768. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  10769. struct read_data {
  10770. size_t read_size;
  10771. size_t total_size;
  10772. } data = {0, total_size};
  10773. using read_callback_t =
  10774. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10775. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  10776. void *userdata) -> size_t {
  10777. read_data *data = (read_data *)userdata;
  10778. if (!userdata || data->read_size >= data->total_size) { return 0; }
  10779. std::fill_n(ptr, size * nmemb, 'A');
  10780. data->read_size += size * nmemb;
  10781. return size * nmemb;
  10782. };
  10783. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  10784. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  10785. std::vector<char> buffer;
  10786. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  10787. using write_callback_t =
  10788. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10789. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  10790. void *userdata) -> size_t {
  10791. std::vector<char> *buffer = (std::vector<char> *)userdata;
  10792. buffer->reserve(buffer->size() + size * nmemb + 1);
  10793. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  10794. return size * nmemb;
  10795. };
  10796. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  10797. {
  10798. const auto res = curl_easy_perform(curl.get());
  10799. ASSERT_EQ(res, CURLE_OK);
  10800. }
  10801. {
  10802. auto response_code = long{};
  10803. const auto res =
  10804. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  10805. ASSERT_EQ(res, CURLE_OK);
  10806. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  10807. }
  10808. {
  10809. auto dl = curl_off_t{};
  10810. const auto res =
  10811. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  10812. ASSERT_EQ(res, CURLE_OK);
  10813. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  10814. }
  10815. {
  10816. buffer.push_back('\0');
  10817. ASSERT_STRCASEEQ(buffer.data(), reject);
  10818. }
  10819. }
  10820. }
  10821. #endif
  10822. template <typename S, typename C>
  10823. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  10824. svr.Get("/stream", [&](const Request &, Response &res) {
  10825. auto data = new std::string("01234567890123456789");
  10826. res.set_content_provider(
  10827. data->size(), "text/plain",
  10828. [&, data](size_t offset, size_t length, DataSink &sink) {
  10829. const size_t DATA_CHUNK_SIZE = 4;
  10830. const auto &d = *data;
  10831. std::this_thread::sleep_for(std::chrono::seconds(1));
  10832. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  10833. return true;
  10834. },
  10835. [data](bool success) {
  10836. EXPECT_FALSE(success);
  10837. delete data;
  10838. });
  10839. });
  10840. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  10841. auto i = new size_t(0);
  10842. res.set_content_provider(
  10843. "text/plain",
  10844. [i](size_t, DataSink &sink) {
  10845. if (*i < 5) {
  10846. std::this_thread::sleep_for(std::chrono::seconds(1));
  10847. sink.write("abcd", 4);
  10848. (*i)++;
  10849. } else {
  10850. sink.done();
  10851. }
  10852. return true;
  10853. },
  10854. [i](bool success) {
  10855. EXPECT_FALSE(success);
  10856. delete i;
  10857. });
  10858. });
  10859. svr.Get("/chunked", [&](const Request &, Response &res) {
  10860. auto i = new size_t(0);
  10861. res.set_chunked_content_provider(
  10862. "text/plain",
  10863. [i](size_t, DataSink &sink) {
  10864. if (*i < 5) {
  10865. std::this_thread::sleep_for(std::chrono::seconds(1));
  10866. sink.os << "abcd";
  10867. (*i)++;
  10868. } else {
  10869. sink.done();
  10870. }
  10871. return true;
  10872. },
  10873. [i](bool success) {
  10874. EXPECT_FALSE(success);
  10875. delete i;
  10876. });
  10877. });
  10878. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10879. auto se = detail::scope_exit([&] {
  10880. svr.stop();
  10881. listen_thread.join();
  10882. ASSERT_FALSE(svr.is_running());
  10883. });
  10884. svr.wait_until_ready();
  10885. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  10886. {
  10887. auto start = std::chrono::steady_clock::now();
  10888. auto res = cli.Get("/stream");
  10889. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10890. std::chrono::steady_clock::now() - start)
  10891. .count();
  10892. ASSERT_FALSE(res);
  10893. EXPECT_EQ(Error::Read, res.error());
  10894. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10895. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10896. }
  10897. {
  10898. auto start = std::chrono::steady_clock::now();
  10899. auto res = cli.Get("/stream_without_length");
  10900. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10901. std::chrono::steady_clock::now() - start)
  10902. .count();
  10903. ASSERT_FALSE(res);
  10904. EXPECT_EQ(Error::Read, res.error());
  10905. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10906. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10907. }
  10908. {
  10909. auto start = std::chrono::steady_clock::now();
  10910. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  10911. EXPECT_EQ("abcd", string(data, data_length));
  10912. return true;
  10913. });
  10914. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10915. std::chrono::steady_clock::now() - start)
  10916. .count();
  10917. ASSERT_FALSE(res);
  10918. EXPECT_EQ(Error::Read, res.error());
  10919. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10920. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10921. }
  10922. }
  10923. TEST(MaxTimeoutTest, ContentStream) {
  10924. time_t timeout = 2000;
  10925. time_t threshold = 200;
  10926. Server svr;
  10927. Client cli("localhost", PORT);
  10928. max_timeout_test(svr, cli, timeout, threshold);
  10929. }
  10930. #ifdef CPPHTTPLIB_SSL_ENABLED
  10931. TEST(MaxTimeoutTest, ContentStreamSSL) {
  10932. time_t timeout = 2000;
  10933. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  10934. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10935. SSLClient cli("localhost", PORT);
  10936. cli.enable_server_certificate_verification(false);
  10937. max_timeout_test(svr, cli, timeout, threshold);
  10938. }
  10939. #endif
  10940. class EventDispatcher {
  10941. public:
  10942. EventDispatcher() {}
  10943. bool wait_event(DataSink *sink) {
  10944. unique_lock<mutex> lk(m_);
  10945. int id = id_;
  10946. // Wait with timeout to prevent hanging if client disconnects
  10947. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  10948. [&] { return cid_ == id; })) {
  10949. return false; // Timeout occurred
  10950. }
  10951. sink->write(message_.data(), message_.size());
  10952. return true;
  10953. }
  10954. void send_event(const string &message) {
  10955. lock_guard<mutex> lk(m_);
  10956. cid_ = id_++;
  10957. message_ = message;
  10958. cv_.notify_all();
  10959. }
  10960. private:
  10961. mutex m_;
  10962. condition_variable cv_;
  10963. atomic_int id_{0};
  10964. atomic_int cid_{-1};
  10965. string message_;
  10966. };
  10967. TEST(ClientInThreadTest, Issue2068) {
  10968. EventDispatcher ed;
  10969. Server svr;
  10970. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  10971. res.set_chunked_content_provider("text/event-stream",
  10972. [&](size_t /*offset*/, DataSink &sink) {
  10973. return ed.wait_event(&sink);
  10974. });
  10975. });
  10976. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10977. svr.wait_until_ready();
  10978. thread event_thread([&] {
  10979. int id = 0;
  10980. while (svr.is_running()) {
  10981. this_thread::sleep_for(chrono::milliseconds(500));
  10982. std::stringstream ss;
  10983. ss << "data: " << id << "\n\n";
  10984. ed.send_event(ss.str());
  10985. id++;
  10986. }
  10987. });
  10988. auto se = detail::scope_exit([&] {
  10989. svr.stop();
  10990. listen_thread.join();
  10991. event_thread.join();
  10992. ASSERT_FALSE(svr.is_running());
  10993. });
  10994. {
  10995. auto client = detail::make_unique<Client>(HOST, PORT);
  10996. client->set_read_timeout(std::chrono::minutes(10));
  10997. std::atomic<bool> stop{false};
  10998. std::thread t([&] {
  10999. client->Get("/event1",
  11000. [&](const char *, size_t) -> bool { return !stop; });
  11001. });
  11002. std::this_thread::sleep_for(std::chrono::seconds(2));
  11003. stop = true;
  11004. client->stop();
  11005. t.join();
  11006. // Reset client after thread has finished
  11007. client.reset();
  11008. }
  11009. }
  11010. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  11011. auto handled = false;
  11012. Server svr;
  11013. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  11014. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11015. auto se = detail::scope_exit([&] {
  11016. svr.stop();
  11017. t.join();
  11018. ASSERT_FALSE(svr.is_running());
  11019. ASSERT_FALSE(handled);
  11020. });
  11021. svr.wait_until_ready();
  11022. // Two Content-Length headers with different values — must be rejected
  11023. auto req = "POST /test HTTP/1.1\r\n"
  11024. "Content-Length: 5\r\n"
  11025. "Content-Length: 10\r\n"
  11026. "\r\n"
  11027. "hello";
  11028. std::string response;
  11029. ASSERT_TRUE(send_request(1, req, &response));
  11030. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  11031. response.substr(0, response.find("\r\n")));
  11032. }
  11033. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  11034. auto handled = false;
  11035. Server svr;
  11036. svr.Post("/test", [&](const Request &, Response &res) {
  11037. handled = true;
  11038. res.set_content("ok", "text/plain");
  11039. });
  11040. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11041. auto se = detail::scope_exit([&] {
  11042. svr.stop();
  11043. t.join();
  11044. ASSERT_FALSE(svr.is_running());
  11045. ASSERT_TRUE(handled);
  11046. });
  11047. svr.wait_until_ready();
  11048. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  11049. auto req = "POST /test HTTP/1.1\r\n"
  11050. "Content-Length: 5\r\n"
  11051. "Content-Length: 5\r\n"
  11052. "\r\n"
  11053. "hello";
  11054. std::string response;
  11055. ASSERT_TRUE(send_request(1, req, &response));
  11056. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  11057. }
  11058. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  11059. Server svr;
  11060. svr.Get("/", [](const Request &req, Response &res) {
  11061. EXPECT_EQ(2U, req.trailers.size());
  11062. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  11063. // Denied
  11064. EXPECT_FALSE(req.has_trailer("Content-Length"));
  11065. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  11066. // Accepted
  11067. EXPECT_TRUE(req.has_trailer("X-Hello"));
  11068. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  11069. EXPECT_TRUE(req.has_trailer("X-World"));
  11070. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  11071. res.set_content("ok", "text/plain");
  11072. });
  11073. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11074. auto se = detail::scope_exit([&] {
  11075. svr.stop();
  11076. t.join();
  11077. ASSERT_FALSE(svr.is_running());
  11078. });
  11079. svr.wait_until_ready();
  11080. const std::string req = "GET / HTTP/1.1\r\n"
  11081. "Transfer-Encoding: chunked\r\n"
  11082. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  11083. "\r\n"
  11084. "0\r\n"
  11085. "Content-Length: 10\r\n"
  11086. "Host: internal.local\r\n"
  11087. "Content-Type: malicious/content\r\n"
  11088. "Cookie: any\r\n"
  11089. "Set-Cookie: any\r\n"
  11090. "X-Forwarded-For: attacker.com\r\n"
  11091. "X-Real-Ip: 1.1.1.1\r\n"
  11092. "X-Hello: hello\r\n"
  11093. "X-World: world\r\n"
  11094. "\r\n";
  11095. std::string res;
  11096. ASSERT_TRUE(send_request(1, req, &res));
  11097. }
  11098. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  11099. Server svr;
  11100. std::string observed_remote_addr;
  11101. std::string observed_xff;
  11102. svr.Get("/ip", [&](const Request &req, Response &res) {
  11103. observed_remote_addr = req.remote_addr;
  11104. observed_xff = req.get_header_value("X-Forwarded-For");
  11105. res.set_content("ok", "text/plain");
  11106. });
  11107. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11108. auto se = detail::scope_exit([&] {
  11109. svr.stop();
  11110. t.join();
  11111. ASSERT_FALSE(svr.is_running());
  11112. });
  11113. svr.wait_until_ready();
  11114. Client cli(HOST, PORT);
  11115. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  11116. ASSERT_TRUE(res);
  11117. EXPECT_EQ(StatusCode::OK_200, res->status);
  11118. EXPECT_EQ(observed_xff, "203.0.113.66");
  11119. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11120. observed_remote_addr == "127.0.0.1");
  11121. }
  11122. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  11123. Server svr;
  11124. svr.set_trusted_proxies({"203.0.113.66"});
  11125. std::string observed_remote_addr;
  11126. std::string observed_xff;
  11127. svr.Get("/ip", [&](const Request &req, Response &res) {
  11128. observed_remote_addr = req.remote_addr;
  11129. observed_xff = req.get_header_value("X-Forwarded-For");
  11130. res.set_content("ok", "text/plain");
  11131. });
  11132. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11133. auto se = detail::scope_exit([&] {
  11134. svr.stop();
  11135. t.join();
  11136. ASSERT_FALSE(svr.is_running());
  11137. });
  11138. svr.wait_until_ready();
  11139. Client cli(HOST, PORT);
  11140. auto res = cli.Get("/ip");
  11141. ASSERT_TRUE(res);
  11142. EXPECT_EQ(StatusCode::OK_200, res->status);
  11143. EXPECT_EQ(observed_xff, "");
  11144. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11145. observed_remote_addr == "127.0.0.1");
  11146. }
  11147. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  11148. Server svr;
  11149. svr.set_trusted_proxies({"203.0.113.66"});
  11150. std::string observed_remote_addr;
  11151. std::string observed_xff;
  11152. svr.Get("/ip", [&](const Request &req, Response &res) {
  11153. observed_remote_addr = req.remote_addr;
  11154. observed_xff = req.get_header_value("X-Forwarded-For");
  11155. res.set_content("ok", "text/plain");
  11156. });
  11157. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11158. auto se = detail::scope_exit([&] {
  11159. svr.stop();
  11160. t.join();
  11161. ASSERT_FALSE(svr.is_running());
  11162. });
  11163. svr.wait_until_ready();
  11164. Client cli(HOST, PORT);
  11165. auto res =
  11166. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  11167. ASSERT_TRUE(res);
  11168. EXPECT_EQ(StatusCode::OK_200, res->status);
  11169. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  11170. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11171. }
  11172. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  11173. Server svr;
  11174. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  11175. std::string observed_remote_addr;
  11176. std::string observed_xff;
  11177. svr.Get("/ip", [&](const Request &req, Response &res) {
  11178. observed_remote_addr = req.remote_addr;
  11179. observed_xff = req.get_header_value("X-Forwarded-For");
  11180. res.set_content("ok", "text/plain");
  11181. });
  11182. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11183. auto se = detail::scope_exit([&] {
  11184. svr.stop();
  11185. t.join();
  11186. ASSERT_FALSE(svr.is_running());
  11187. });
  11188. svr.wait_until_ready();
  11189. Client cli(HOST, PORT);
  11190. auto res = cli.Get(
  11191. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11192. ASSERT_TRUE(res);
  11193. EXPECT_EQ(StatusCode::OK_200, res->status);
  11194. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11195. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11196. }
  11197. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  11198. Server svr;
  11199. svr.set_trusted_proxies({"192.0.2.45"});
  11200. std::string observed_remote_addr;
  11201. std::string observed_xff;
  11202. svr.Get("/ip", [&](const Request &req, Response &res) {
  11203. observed_remote_addr = req.remote_addr;
  11204. observed_xff = req.get_header_value("X-Forwarded-For");
  11205. res.set_content("ok", "text/plain");
  11206. });
  11207. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11208. auto se = detail::scope_exit([&] {
  11209. svr.stop();
  11210. t.join();
  11211. ASSERT_FALSE(svr.is_running());
  11212. });
  11213. svr.wait_until_ready();
  11214. Client cli(HOST, PORT);
  11215. auto res =
  11216. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  11217. ASSERT_TRUE(res);
  11218. EXPECT_EQ(StatusCode::OK_200, res->status);
  11219. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  11220. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11221. }
  11222. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  11223. Server svr;
  11224. svr.set_trusted_proxies({"192.0.2.45"});
  11225. std::string observed_remote_addr;
  11226. std::string observed_xff;
  11227. svr.Get("/ip", [&](const Request &req, Response &res) {
  11228. observed_remote_addr = req.remote_addr;
  11229. observed_xff = req.get_header_value("X-Forwarded-For");
  11230. res.set_content("ok", "text/plain");
  11231. });
  11232. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11233. auto se = detail::scope_exit([&] {
  11234. svr.stop();
  11235. t.join();
  11236. ASSERT_FALSE(svr.is_running());
  11237. });
  11238. svr.wait_until_ready();
  11239. Client cli(HOST, PORT);
  11240. auto res = cli.Get(
  11241. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11242. ASSERT_TRUE(res);
  11243. EXPECT_EQ(StatusCode::OK_200, res->status);
  11244. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11245. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11246. }
  11247. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  11248. Server svr;
  11249. svr.set_trusted_proxies({"192.0.2.45"});
  11250. std::string observed_remote_addr;
  11251. std::string observed_xff;
  11252. svr.Get("/ip", [&](const Request &req, Response &res) {
  11253. observed_remote_addr = req.remote_addr;
  11254. observed_xff = req.get_header_value("X-Forwarded-For");
  11255. res.set_content("ok", "text/plain");
  11256. });
  11257. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11258. auto se = detail::scope_exit([&] {
  11259. svr.stop();
  11260. t.join();
  11261. ASSERT_FALSE(svr.is_running());
  11262. });
  11263. svr.wait_until_ready();
  11264. std::string raw_req =
  11265. "GET /ip HTTP/1.1\r\n"
  11266. "Host: localhost\r\n"
  11267. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  11268. "Connection: close\r\n"
  11269. "\r\n";
  11270. std::string out;
  11271. ASSERT_TRUE(send_request(5, raw_req, &out));
  11272. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11273. // Header parser trims surrounding whitespace of the header value
  11274. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  11275. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11276. }
  11277. #ifndef _WIN32
  11278. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  11279. Server svr;
  11280. svr.Post("/post", [&](const Request &req, Response &res) {
  11281. res.set_content(req.body, "text/plain");
  11282. });
  11283. svr.Put("/put", [&](const Request &req, Response &res) {
  11284. res.set_content(req.body, "text/plain");
  11285. });
  11286. svr.Patch("/patch", [&](const Request &req, Response &res) {
  11287. res.set_content(req.body, "text/plain");
  11288. });
  11289. svr.Delete("/delete", [&](const Request &req, Response &res) {
  11290. res.set_content(req.body, "text/plain");
  11291. });
  11292. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11293. auto se = detail::scope_exit([&] {
  11294. svr.stop();
  11295. t.join();
  11296. ASSERT_FALSE(svr.is_running());
  11297. });
  11298. svr.wait_until_ready();
  11299. std::string resp;
  11300. // POST without Content-Length
  11301. ASSERT_TRUE(send_request(5,
  11302. "POST /post HTTP/1.1\r\n"
  11303. "Host: localhost\r\n"
  11304. "Connection: close\r\n"
  11305. "\r\n",
  11306. &resp));
  11307. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11308. // PUT without Content-Length
  11309. resp.clear();
  11310. ASSERT_TRUE(send_request(5,
  11311. "PUT /put HTTP/1.1\r\n"
  11312. "Host: localhost\r\n"
  11313. "Connection: close\r\n"
  11314. "\r\n",
  11315. &resp));
  11316. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11317. // PATCH without Content-Length
  11318. resp.clear();
  11319. ASSERT_TRUE(send_request(5,
  11320. "PATCH /patch HTTP/1.1\r\n"
  11321. "Host: localhost\r\n"
  11322. "Connection: close\r\n"
  11323. "\r\n",
  11324. &resp));
  11325. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11326. // DELETE without Content-Length
  11327. resp.clear();
  11328. ASSERT_TRUE(send_request(5,
  11329. "DELETE /delete HTTP/1.1\r\n"
  11330. "Host: localhost\r\n"
  11331. "Connection: close\r\n"
  11332. "\r\n",
  11333. &resp));
  11334. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11335. }
  11336. #endif
  11337. //==============================================================================
  11338. // open_stream() Tests
  11339. //==============================================================================
  11340. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  11341. std::string result;
  11342. char buf[8192];
  11343. ssize_t n;
  11344. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11345. result.append(buf, static_cast<size_t>(n));
  11346. }
  11347. return result;
  11348. }
  11349. // Mock stream for unit tests
  11350. class MockStream : public Stream {
  11351. public:
  11352. std::string data;
  11353. size_t pos = 0;
  11354. ssize_t error_after = -1; // -1 = no error
  11355. explicit MockStream(const std::string &d, ssize_t err = -1)
  11356. : data(d), error_after(err) {}
  11357. bool is_readable() const override { return true; }
  11358. bool wait_readable() const override { return true; }
  11359. bool wait_writable() const override { return true; }
  11360. ssize_t read(char *ptr, size_t size) override {
  11361. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  11362. if (pos >= data.size()) return 0;
  11363. size_t limit =
  11364. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  11365. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  11366. std::memcpy(ptr, data.data() + pos, to_read);
  11367. pos += to_read;
  11368. return static_cast<ssize_t>(to_read);
  11369. }
  11370. ssize_t write(const char *, size_t) override { return -1; }
  11371. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  11372. ip = "127.0.0.1";
  11373. port = 0;
  11374. }
  11375. void get_local_ip_and_port(std::string &ip, int &port) const override {
  11376. ip = "127.0.0.1";
  11377. port = 0;
  11378. }
  11379. socket_t socket() const override { return INVALID_SOCKET; }
  11380. time_t duration() const override { return 0; }
  11381. };
  11382. TEST(StreamHandleTest, Basic) {
  11383. ClientImpl::StreamHandle handle;
  11384. EXPECT_FALSE(handle.is_valid());
  11385. handle.response = detail::make_unique<Response>();
  11386. handle.error = Error::Connection;
  11387. EXPECT_FALSE(handle.is_valid());
  11388. handle.error = Error::Success;
  11389. EXPECT_TRUE(handle.is_valid());
  11390. }
  11391. TEST(BodyReaderTest, Basic) {
  11392. MockStream stream("Hello, World!");
  11393. detail::BodyReader reader;
  11394. reader.stream = &stream;
  11395. reader.content_length = 13;
  11396. char buf[32];
  11397. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  11398. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  11399. EXPECT_TRUE(reader.eof);
  11400. }
  11401. TEST(BodyReaderTest, NoStream) {
  11402. detail::BodyReader reader;
  11403. char buf[32];
  11404. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11405. EXPECT_EQ(Error::Connection, reader.last_error);
  11406. }
  11407. TEST(BodyReaderTest, Error) {
  11408. MockStream stream("Hello, World!", 5);
  11409. detail::BodyReader reader;
  11410. reader.stream = &stream;
  11411. reader.content_length = 13;
  11412. char buf[32];
  11413. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  11414. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11415. EXPECT_EQ(Error::Read, reader.last_error);
  11416. }
  11417. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  11418. // Mock-based StreamHandle tests relying on private internals are removed.
  11419. class OpenStreamTest : public ::testing::Test {
  11420. protected:
  11421. void SetUp() override {
  11422. svr_.Get("/hello", [](const Request &, Response &res) {
  11423. res.set_content("Hello World!", "text/plain");
  11424. });
  11425. svr_.Get("/large", [](const Request &, Response &res) {
  11426. res.set_content(std::string(10000, 'X'), "text/plain");
  11427. });
  11428. svr_.Get("/chunked", [](const Request &, Response &res) {
  11429. res.set_chunked_content_provider("text/plain",
  11430. [](size_t offset, DataSink &sink) {
  11431. if (offset < 15) {
  11432. sink.write("chunk", 5);
  11433. return true;
  11434. }
  11435. sink.done();
  11436. return true;
  11437. });
  11438. });
  11439. svr_.Get("/compressible", [](const Request &, Response &res) {
  11440. res.set_chunked_content_provider("text/plain", [](size_t offset,
  11441. DataSink &sink) {
  11442. if (offset < 100 * 1024) {
  11443. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  11444. sink.write(chunk.data(), chunk.size());
  11445. return true;
  11446. }
  11447. sink.done();
  11448. return true;
  11449. });
  11450. });
  11451. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  11452. [](const Request & /*req*/, Response &res) {
  11453. auto i = new int(0);
  11454. res.set_header("Trailer", "Content-Length, X-Allowed");
  11455. res.set_chunked_content_provider(
  11456. "text/plain",
  11457. [i](size_t /*offset*/, DataSink &sink) {
  11458. switch (*i) {
  11459. case 0: sink.os << "123"; break;
  11460. case 1: sink.os << "456"; break;
  11461. case 2: sink.os << "789"; break;
  11462. case 3: {
  11463. sink.done_with_trailer(
  11464. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  11465. } break;
  11466. }
  11467. (*i)++;
  11468. return true;
  11469. },
  11470. [i](bool success) {
  11471. EXPECT_TRUE(success);
  11472. delete i;
  11473. });
  11474. });
  11475. // Echo headers endpoint for header-related tests
  11476. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  11477. std::string body;
  11478. for (const auto &h : req.headers) {
  11479. body.append(h.first);
  11480. body.push_back(':');
  11481. body.append(h.second);
  11482. body.push_back('\n');
  11483. }
  11484. res.set_content(body, "text/plain");
  11485. });
  11486. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  11487. std::string body;
  11488. for (const auto &h : req.headers) {
  11489. body.append(h.first);
  11490. body.push_back(':');
  11491. body.append(h.second);
  11492. body.push_back('\n');
  11493. }
  11494. res.set_content(body, "text/plain");
  11495. });
  11496. port_ = svr_.bind_to_any_port("127.0.0.1");
  11497. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11498. svr_.wait_until_ready();
  11499. }
  11500. void TearDown() override {
  11501. svr_.stop();
  11502. if (thread_.joinable()) thread_.join();
  11503. }
  11504. Server svr_;
  11505. std::thread thread_;
  11506. int port_ = 0;
  11507. };
  11508. TEST_F(OpenStreamTest, Basic) {
  11509. Client cli("127.0.0.1", port_);
  11510. auto handle = cli.open_stream("GET", "/hello");
  11511. EXPECT_TRUE(handle.is_valid());
  11512. EXPECT_EQ("Hello World!", read_all(handle));
  11513. }
  11514. TEST_F(OpenStreamTest, SmallBuffer) {
  11515. Client cli("127.0.0.1", port_);
  11516. auto handle = cli.open_stream("GET", "/hello");
  11517. std::string result;
  11518. char buf[4];
  11519. ssize_t n;
  11520. while ((n = handle.read(buf, sizeof(buf))) > 0)
  11521. result.append(buf, static_cast<size_t>(n));
  11522. EXPECT_EQ("Hello World!", result);
  11523. }
  11524. TEST_F(OpenStreamTest, DefaultHeaders) {
  11525. Client cli("127.0.0.1", port_);
  11526. // open_stream GET should include Host, User-Agent and Accept-Encoding
  11527. {
  11528. auto handle = cli.open_stream("GET", "/echo-headers");
  11529. ASSERT_TRUE(handle.is_valid());
  11530. auto body = read_all(handle);
  11531. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  11532. std::string::npos);
  11533. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  11534. std::string::npos);
  11535. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  11536. }
  11537. // open_stream POST with body and no explicit content_type should NOT add
  11538. // text/plain Content-Type (behavior differs from non-streaming path), but
  11539. // should include Content-Length
  11540. {
  11541. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  11542. ASSERT_TRUE(handle.is_valid());
  11543. auto body = read_all(handle);
  11544. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  11545. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  11546. }
  11547. // open_stream POST with explicit Content-Type should preserve it
  11548. {
  11549. auto handle = cli.open_stream("POST", "/echo-headers", {},
  11550. {{"Content-Type", "application/custom"}},
  11551. "{}", "application/custom");
  11552. ASSERT_TRUE(handle.is_valid());
  11553. auto body = read_all(handle);
  11554. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  11555. }
  11556. // User-specified User-Agent must not be overwritten for stream API
  11557. {
  11558. auto handle = cli.open_stream("GET", "/echo-headers", {},
  11559. {{"User-Agent", "MyAgent/1.2"}});
  11560. ASSERT_TRUE(handle.is_valid());
  11561. auto body = read_all(handle);
  11562. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  11563. }
  11564. }
  11565. TEST_F(OpenStreamTest, Large) {
  11566. Client cli("127.0.0.1", port_);
  11567. auto handle = cli.open_stream("GET", "/large");
  11568. EXPECT_EQ(10000u, read_all(handle).size());
  11569. }
  11570. TEST_F(OpenStreamTest, ConnectionError) {
  11571. Client cli("127.0.0.1", 9999);
  11572. auto handle = cli.open_stream("GET", "/hello");
  11573. EXPECT_FALSE(handle.is_valid());
  11574. }
  11575. TEST_F(OpenStreamTest, Chunked) {
  11576. Client cli("127.0.0.1", port_);
  11577. auto handle = cli.open_stream("GET", "/chunked");
  11578. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11579. "Transfer-Encoding") == "chunked");
  11580. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  11581. }
  11582. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  11583. Client cli("127.0.0.1", port_);
  11584. auto handle =
  11585. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  11586. ASSERT_TRUE(handle.is_valid());
  11587. // Consume body to allow trailers to be received/parsed
  11588. auto body = read_all(handle);
  11589. // Explicitly parse trailers (ensure trailers are available for assertion)
  11590. handle.parse_trailers_if_needed();
  11591. EXPECT_EQ(std::string("123456789"), body);
  11592. // The response should include a Trailer header declaring both names
  11593. ASSERT_TRUE(handle.response);
  11594. EXPECT_TRUE(handle.response->has_header("Trailer"));
  11595. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  11596. handle.response->get_header_value("Trailer"));
  11597. // Prohibited trailer must not be present
  11598. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  11599. // Allowed trailer should be present
  11600. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  11601. EXPECT_EQ(std::string("yes"),
  11602. handle.response->get_trailer_value("X-Allowed"));
  11603. // Verify trailers are NOT present as regular headers
  11604. EXPECT_EQ(std::string(""),
  11605. handle.response->get_header_value("Content-Length"));
  11606. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  11607. }
  11608. static std::thread serve_single_response(int port,
  11609. const std::string &response) {
  11610. return std::thread([port, response] {
  11611. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11612. default_socket_options(srv);
  11613. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11614. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11615. sockaddr_in addr{};
  11616. addr.sin_family = AF_INET;
  11617. addr.sin_port = htons(static_cast<uint16_t>(port));
  11618. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11619. int opt = 1;
  11620. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11621. #ifdef _WIN32
  11622. reinterpret_cast<const char *>(&opt),
  11623. #else
  11624. &opt,
  11625. #endif
  11626. sizeof(opt));
  11627. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11628. ::listen(srv, 1);
  11629. sockaddr_in cli_addr{};
  11630. socklen_t cli_len = sizeof(cli_addr);
  11631. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11632. if (cli != INVALID_SOCKET) {
  11633. char buf[4096];
  11634. ::recv(cli, buf, sizeof(buf), 0);
  11635. ::send(cli,
  11636. #ifdef _WIN32
  11637. static_cast<const char *>(response.c_str()),
  11638. static_cast<int>(response.size()),
  11639. #else
  11640. response.c_str(), response.size(),
  11641. #endif
  11642. 0);
  11643. detail::close_socket(cli);
  11644. }
  11645. detail::close_socket(srv);
  11646. });
  11647. }
  11648. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  11649. #ifndef _WIN32
  11650. signal(SIGPIPE, SIG_IGN);
  11651. #endif
  11652. auto server_thread =
  11653. serve_single_response(PORT + 2, "HTTP/1.1 200 OK\r\n"
  11654. "Content-Type: text/plain\r\n"
  11655. "Content-Length: not-a-number\r\n"
  11656. "Connection: close\r\n"
  11657. "\r\n"
  11658. "hello");
  11659. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11660. Client cli("127.0.0.1", PORT + 2);
  11661. auto handle = cli.open_stream("GET", "/");
  11662. EXPECT_FALSE(handle.is_valid());
  11663. server_thread.join();
  11664. }
  11665. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  11666. #ifndef _WIN32
  11667. signal(SIGPIPE, SIG_IGN);
  11668. #endif
  11669. auto server_thread = serve_single_response(
  11670. PORT + 4, "HTTP/1.1 200 OK\r\n"
  11671. "Content-Type: text/plain\r\n"
  11672. "Content-Length: 99999999999999999999999999\r\n"
  11673. "Connection: close\r\n"
  11674. "\r\n"
  11675. "hello");
  11676. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11677. // Before the fix, std::stoull would throw std::out_of_range here and
  11678. // crash the process. After the fix, strtoull silently clamps to
  11679. // ULLONG_MAX so the stream opens without crashing. The important thing
  11680. // is that the process does NOT terminate.
  11681. Client cli("127.0.0.1", PORT + 4);
  11682. auto handle = cli.open_stream("GET", "/");
  11683. EXPECT_TRUE(handle.is_valid());
  11684. server_thread.join();
  11685. }
  11686. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11687. TEST_F(OpenStreamTest, Gzip) {
  11688. Client cli("127.0.0.1", port_);
  11689. auto handle = cli.open_stream("GET", "/compressible", {},
  11690. {{"Accept-Encoding", "gzip"}});
  11691. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  11692. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11693. }
  11694. #endif
  11695. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11696. TEST_F(OpenStreamTest, Brotli) {
  11697. Client cli("127.0.0.1", port_);
  11698. auto handle =
  11699. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  11700. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  11701. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11702. }
  11703. #endif
  11704. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11705. TEST_F(OpenStreamTest, Zstd) {
  11706. Client cli("127.0.0.1", port_);
  11707. auto handle = cli.open_stream("GET", "/compressible", {},
  11708. {{"Accept-Encoding", "zstd"}});
  11709. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  11710. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11711. }
  11712. #endif
  11713. #ifdef CPPHTTPLIB_SSL_ENABLED
  11714. class SSLOpenStreamTest : public ::testing::Test {
  11715. protected:
  11716. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  11717. void SetUp() override {
  11718. svr_.Get("/hello", [](const Request &, Response &res) {
  11719. res.set_content("Hello SSL World!", "text/plain");
  11720. });
  11721. svr_.Get("/chunked", [](const Request &, Response &res) {
  11722. res.set_chunked_content_provider("text/plain",
  11723. [](size_t offset, DataSink &sink) {
  11724. if (offset < 15) {
  11725. sink.write("chunk", 5);
  11726. return true;
  11727. }
  11728. sink.done();
  11729. return true;
  11730. });
  11731. });
  11732. svr_.Post("/echo", [](const Request &req, Response &res) {
  11733. res.set_content(req.body, req.get_header_value("Content-Type"));
  11734. });
  11735. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  11736. std::string body = req.body;
  11737. res.set_chunked_content_provider(
  11738. "text/plain", [body](size_t offset, DataSink &sink) {
  11739. if (offset < body.size()) {
  11740. sink.write(body.data() + offset, body.size() - offset);
  11741. }
  11742. sink.done();
  11743. return true;
  11744. });
  11745. });
  11746. port_ = svr_.bind_to_any_port("127.0.0.1");
  11747. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11748. svr_.wait_until_ready();
  11749. }
  11750. void TearDown() override {
  11751. svr_.stop();
  11752. if (thread_.joinable()) thread_.join();
  11753. }
  11754. SSLServer svr_;
  11755. std::thread thread_;
  11756. int port_ = 0;
  11757. };
  11758. TEST_F(SSLOpenStreamTest, Basic) {
  11759. SSLClient cli("127.0.0.1", port_);
  11760. cli.enable_server_certificate_verification(false);
  11761. auto handle = cli.open_stream("GET", "/hello");
  11762. ASSERT_TRUE(handle.is_valid());
  11763. EXPECT_EQ("Hello SSL World!", read_all(handle));
  11764. }
  11765. TEST_F(SSLOpenStreamTest, Chunked) {
  11766. SSLClient cli("127.0.0.1", port_);
  11767. cli.enable_server_certificate_verification(false);
  11768. auto handle = cli.open_stream("GET", "/chunked");
  11769. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11770. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11771. "Transfer-Encoding") == "chunked");
  11772. auto body = read_all(handle);
  11773. EXPECT_EQ("chunkchunkchunk", body);
  11774. }
  11775. TEST_F(SSLOpenStreamTest, Post) {
  11776. SSLClient cli("127.0.0.1", port_);
  11777. cli.enable_server_certificate_verification(false);
  11778. auto handle =
  11779. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  11780. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11781. EXPECT_EQ(200, handle.response->status);
  11782. auto body = read_all(handle);
  11783. EXPECT_EQ("Hello SSL POST", body);
  11784. }
  11785. TEST_F(SSLOpenStreamTest, PostChunked) {
  11786. SSLClient cli("127.0.0.1", port_);
  11787. cli.enable_server_certificate_verification(false);
  11788. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  11789. "Chunked SSL Data", "text/plain");
  11790. ASSERT_TRUE(handle.is_valid());
  11791. EXPECT_EQ(200, handle.response->status);
  11792. auto body = read_all(handle);
  11793. EXPECT_EQ("Chunked SSL Data", body);
  11794. }
  11795. #endif // CPPHTTPLIB_SSL_ENABLED
  11796. //==============================================================================
  11797. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  11798. // results for various scenarios.
  11799. //==============================================================================
  11800. TEST(ParityTest, GetVsOpenStream) {
  11801. Server svr;
  11802. const std::string path = "/parity";
  11803. const std::string content = "Parity test content: hello world";
  11804. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11805. res.set_content(content, "text/plain");
  11806. });
  11807. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11808. auto se = detail::scope_exit([&] {
  11809. svr.stop();
  11810. t.join();
  11811. ASSERT_FALSE(svr.is_running());
  11812. });
  11813. svr.wait_until_ready();
  11814. Client cli(HOST, PORT);
  11815. // Non-stream path
  11816. auto r1 = cli.Get(path);
  11817. ASSERT_TRUE(r1);
  11818. EXPECT_EQ(StatusCode::OK_200, r1->status);
  11819. // Stream path
  11820. auto h = cli.open_stream("GET", path);
  11821. ASSERT_TRUE(h.is_valid());
  11822. EXPECT_EQ(r1->body, read_all(h));
  11823. }
  11824. // Helper to compress data with provided compressor type T
  11825. template <typename Compressor>
  11826. static std::string compress_payload_for_parity(const std::string &in) {
  11827. std::string out;
  11828. Compressor compressor;
  11829. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  11830. [&](const char *data, size_t n) {
  11831. out.append(data, n);
  11832. return true;
  11833. });
  11834. EXPECT_TRUE(ok);
  11835. return out;
  11836. }
  11837. // Helper function for compression parity tests
  11838. template <typename Compressor>
  11839. static void test_compression_parity(const std::string &original,
  11840. const std::string &path,
  11841. const std::string &encoding) {
  11842. const std::string compressed =
  11843. compress_payload_for_parity<Compressor>(original);
  11844. Server svr;
  11845. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11846. res.set_content(compressed, "application/octet-stream");
  11847. res.set_header("Content-Encoding", encoding);
  11848. });
  11849. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  11850. auto se = detail::scope_exit([&] {
  11851. svr.stop();
  11852. t.join();
  11853. ASSERT_FALSE(svr.is_running());
  11854. });
  11855. svr.wait_until_ready();
  11856. Client cli(HOST, PORT);
  11857. // Non-streaming
  11858. {
  11859. auto res = cli.Get(path);
  11860. ASSERT_TRUE(res);
  11861. EXPECT_EQ(StatusCode::OK_200, res->status);
  11862. EXPECT_EQ(original, res->body);
  11863. }
  11864. // Streaming
  11865. {
  11866. auto h = cli.open_stream("GET", path);
  11867. ASSERT_TRUE(h.is_valid());
  11868. EXPECT_EQ(original, read_all(h));
  11869. }
  11870. }
  11871. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11872. TEST(ParityTest, Gzip) {
  11873. test_compression_parity<detail::gzip_compressor>(
  11874. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  11875. }
  11876. #endif
  11877. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11878. TEST(ParityTest, Brotli) {
  11879. test_compression_parity<detail::brotli_compressor>(
  11880. "Hello, brotli parity test payload", "/parity-br", "br");
  11881. }
  11882. #endif
  11883. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11884. TEST(ParityTest, Zstd) {
  11885. test_compression_parity<detail::zstd_compressor>(
  11886. "Zstandard parity test payload", "/parity-zstd", "zstd");
  11887. }
  11888. #endif
  11889. //==============================================================================
  11890. // New Stream API Tests
  11891. //==============================================================================
  11892. inline std::string read_body(httplib::stream::Result &result) {
  11893. std::string body;
  11894. while (result.next()) {
  11895. body.append(result.data(), result.size());
  11896. }
  11897. return body;
  11898. }
  11899. TEST(ClientConnectionTest, Basic) {
  11900. httplib::ClientConnection conn;
  11901. EXPECT_FALSE(conn.is_open());
  11902. conn.sock = 1;
  11903. EXPECT_TRUE(conn.is_open());
  11904. httplib::ClientConnection conn2(std::move(conn));
  11905. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  11906. conn2.sock = INVALID_SOCKET;
  11907. }
  11908. // Unified test server for all stream::* tests
  11909. class StreamApiTest : public ::testing::Test {
  11910. protected:
  11911. void SetUp() override {
  11912. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11913. res.set_content("Hello World!", "text/plain");
  11914. });
  11915. svr_.Get("/echo-params",
  11916. [](const httplib::Request &req, httplib::Response &res) {
  11917. std::string r;
  11918. for (const auto &p : req.params) {
  11919. if (!r.empty()) r += "&";
  11920. r += p.first + "=" + p.second;
  11921. }
  11922. res.set_content(r, "text/plain");
  11923. });
  11924. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11925. res.set_content(req.body, req.get_header_value("Content-Type"));
  11926. });
  11927. svr_.Post("/echo-headers",
  11928. [](const httplib::Request &req, httplib::Response &res) {
  11929. std::string r;
  11930. for (const auto &h : req.headers)
  11931. r += h.first + ": " + h.second + "\n";
  11932. res.set_content(r, "text/plain");
  11933. });
  11934. svr_.Post("/echo-params",
  11935. [](const httplib::Request &req, httplib::Response &res) {
  11936. std::string r = "params:";
  11937. for (const auto &p : req.params)
  11938. r += p.first + "=" + p.second + ";";
  11939. res.set_content(r + " body:" + req.body, "text/plain");
  11940. });
  11941. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  11942. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  11943. });
  11944. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11945. res.set_content("PUT:" + req.body, "text/plain");
  11946. });
  11947. svr_.Patch("/echo",
  11948. [](const httplib::Request &req, httplib::Response &res) {
  11949. res.set_content("PATCH:" + req.body, "text/plain");
  11950. });
  11951. svr_.Delete(
  11952. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  11953. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  11954. "text/plain");
  11955. });
  11956. svr_.Get("/head-test",
  11957. [](const httplib::Request &, httplib::Response &res) {
  11958. res.set_content("body for HEAD", "text/plain");
  11959. });
  11960. svr_.Options("/options",
  11961. [](const httplib::Request &, httplib::Response &res) {
  11962. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  11963. });
  11964. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  11965. svr_.wait_until_ready();
  11966. }
  11967. void TearDown() override {
  11968. svr_.stop();
  11969. if (thread_.joinable()) thread_.join();
  11970. }
  11971. httplib::Server svr_;
  11972. std::thread thread_;
  11973. };
  11974. // stream::Get tests
  11975. TEST_F(StreamApiTest, GetBasic) {
  11976. httplib::Client cli(HOST, PORT);
  11977. auto result = httplib::stream::Get(cli, "/hello");
  11978. ASSERT_TRUE(result.is_valid());
  11979. EXPECT_EQ(200, result.status());
  11980. EXPECT_EQ("Hello World!", read_body(result));
  11981. }
  11982. TEST_F(StreamApiTest, GetWithParams) {
  11983. httplib::Client cli(HOST, PORT);
  11984. httplib::Params params{{"foo", "bar"}};
  11985. auto result = httplib::stream::Get(cli, "/echo-params", params);
  11986. ASSERT_TRUE(result.is_valid());
  11987. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  11988. }
  11989. TEST_F(StreamApiTest, GetConnectionError) {
  11990. httplib::Client cli(HOST, 9999);
  11991. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  11992. }
  11993. TEST_F(StreamApiTest, Get404) {
  11994. httplib::Client cli(HOST, PORT);
  11995. auto result = httplib::stream::Get(cli, "/nonexistent");
  11996. EXPECT_TRUE(result.is_valid());
  11997. EXPECT_EQ(404, result.status());
  11998. }
  11999. // stream::Post tests
  12000. TEST_F(StreamApiTest, PostBasic) {
  12001. httplib::Client cli(HOST, PORT);
  12002. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  12003. "application/json");
  12004. ASSERT_TRUE(result.is_valid());
  12005. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  12006. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  12007. }
  12008. TEST_F(StreamApiTest, PostWithHeaders) {
  12009. httplib::Client cli(HOST, PORT);
  12010. httplib::Headers headers{{"X-Custom", "value"}};
  12011. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  12012. "text/plain");
  12013. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  12014. }
  12015. TEST_F(StreamApiTest, PostWithParams) {
  12016. httplib::Client cli(HOST, PORT);
  12017. httplib::Params params{{"k", "v"}};
  12018. auto result =
  12019. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  12020. auto body = read_body(result);
  12021. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  12022. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  12023. }
  12024. TEST_F(StreamApiTest, PostLarge) {
  12025. httplib::Client cli(HOST, PORT);
  12026. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  12027. size_t total = 0;
  12028. while (result.next()) {
  12029. total += result.size();
  12030. }
  12031. EXPECT_EQ(100u * 1024u, total);
  12032. }
  12033. // stream::Put/Patch tests
  12034. TEST_F(StreamApiTest, PutAndPatch) {
  12035. httplib::Client cli(HOST, PORT);
  12036. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  12037. EXPECT_EQ("PUT:test", read_body(put));
  12038. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  12039. EXPECT_EQ("PATCH:test", read_body(patch));
  12040. }
  12041. // stream::Delete tests
  12042. TEST_F(StreamApiTest, Delete) {
  12043. httplib::Client cli(HOST, PORT);
  12044. auto del1 = httplib::stream::Delete(cli, "/resource");
  12045. EXPECT_EQ("Deleted", read_body(del1));
  12046. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  12047. EXPECT_EQ("Deleted:data", read_body(del2));
  12048. }
  12049. // stream::Head/Options tests
  12050. TEST_F(StreamApiTest, HeadAndOptions) {
  12051. httplib::Client cli(HOST, PORT);
  12052. auto head = httplib::stream::Head(cli, "/head-test");
  12053. EXPECT_TRUE(head.is_valid());
  12054. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  12055. auto opts = httplib::stream::Options(cli, "/options");
  12056. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  12057. }
  12058. // SSL stream::* tests
  12059. #ifdef CPPHTTPLIB_SSL_ENABLED
  12060. class SSLStreamApiTest : public ::testing::Test {
  12061. protected:
  12062. void SetUp() override {
  12063. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12064. res.set_content("Hello SSL!", "text/plain");
  12065. });
  12066. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12067. res.set_content(req.body, "text/plain");
  12068. });
  12069. port_ = svr_.bind_to_any_port("127.0.0.1");
  12070. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12071. svr_.wait_until_ready();
  12072. }
  12073. void TearDown() override {
  12074. svr_.stop();
  12075. if (thread_.joinable()) thread_.join();
  12076. }
  12077. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  12078. std::thread thread_;
  12079. int port_ = 0;
  12080. };
  12081. TEST_F(SSLStreamApiTest, GetAndPost) {
  12082. httplib::SSLClient cli("127.0.0.1", port_);
  12083. cli.enable_server_certificate_verification(false);
  12084. auto get = httplib::stream::Get(cli, "/hello");
  12085. EXPECT_EQ("Hello SSL!", read_body(get));
  12086. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  12087. EXPECT_EQ("test", read_body(post));
  12088. }
  12089. #endif
  12090. // Tests for Error::Timeout and Error::ConnectionClosed error types
  12091. // These errors are set in SocketStream/SSLSocketStream and propagated through
  12092. // BodyReader
  12093. TEST(ErrorHandlingTest, StreamReadTimeout) {
  12094. // Test that read timeout during streaming is detected
  12095. // Use a large content-length response where server delays mid-stream
  12096. Server svr;
  12097. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12098. // Send a large response with delay in the middle
  12099. res.set_content_provider(
  12100. 1000, // content_length
  12101. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  12102. if (offset < 100) {
  12103. // Send first 100 bytes immediately
  12104. std::string data(100, 'A');
  12105. sink.write(data.c_str(), data.size());
  12106. return true;
  12107. }
  12108. // Then delay longer than client timeout
  12109. std::this_thread::sleep_for(std::chrono::seconds(3));
  12110. std::string data(900, 'B');
  12111. sink.write(data.c_str(), data.size());
  12112. return true;
  12113. });
  12114. });
  12115. auto port = 8091;
  12116. std::thread t([&]() { svr.listen("localhost", port); });
  12117. svr.wait_until_ready();
  12118. Client cli("localhost", port);
  12119. cli.set_read_timeout(1, 0); // 1 second timeout
  12120. auto handle = cli.open_stream("GET", "/slow-stream");
  12121. ASSERT_TRUE(handle.is_valid());
  12122. char buf[256];
  12123. ssize_t total = 0;
  12124. ssize_t n;
  12125. bool got_error = false;
  12126. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12127. total += n;
  12128. }
  12129. if (n < 0) {
  12130. got_error = true;
  12131. // Should be timeout or read error
  12132. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12133. handle.get_read_error() == Error::Read)
  12134. << "Actual error: " << to_string(handle.get_read_error());
  12135. }
  12136. // Either we got an error, or we got less data than expected
  12137. EXPECT_TRUE(got_error || total < 1000)
  12138. << "Expected timeout but got all " << total << " bytes";
  12139. svr.stop();
  12140. t.join();
  12141. }
  12142. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  12143. // Test connection closed detection via BodyReader
  12144. Server svr;
  12145. std::atomic<bool> close_now{false};
  12146. svr.Get("/will-close", [&](const Request &, Response &res) {
  12147. res.set_content_provider(
  12148. 10000, // Large content_length that we won't fully send
  12149. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12150. if (offset < 100) {
  12151. std::string data(100, 'X');
  12152. sink.write(data.c_str(), data.size());
  12153. return true;
  12154. }
  12155. // Wait for signal then abort
  12156. while (!close_now) {
  12157. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12158. }
  12159. return false; // Abort - server will close connection
  12160. });
  12161. });
  12162. auto port = 8092;
  12163. std::thread t([&]() { svr.listen("localhost", port); });
  12164. svr.wait_until_ready();
  12165. Client cli("localhost", port);
  12166. auto handle = cli.open_stream("GET", "/will-close");
  12167. ASSERT_TRUE(handle.is_valid());
  12168. char buf[256];
  12169. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12170. EXPECT_GT(n, 0) << "First read should succeed";
  12171. // Signal server to close
  12172. close_now = true;
  12173. // Keep reading until error or EOF
  12174. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12175. // Keep reading
  12176. }
  12177. // Should get an error since content_length wasn't satisfied
  12178. if (n < 0) {
  12179. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12180. handle.get_read_error() == Error::Read)
  12181. << "Actual error: " << to_string(handle.get_read_error());
  12182. }
  12183. svr.stop();
  12184. t.join();
  12185. }
  12186. #ifdef CPPHTTPLIB_SSL_ENABLED
  12187. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  12188. // Test that read timeout during SSL streaming is detected
  12189. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12190. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12191. res.set_content_provider(
  12192. 1000, "text/plain",
  12193. [](size_t offset, size_t /*length*/, DataSink &sink) {
  12194. if (offset < 100) {
  12195. std::string data(100, 'A');
  12196. sink.write(data.c_str(), data.size());
  12197. return true;
  12198. }
  12199. std::this_thread::sleep_for(std::chrono::seconds(3));
  12200. std::string data(900, 'B');
  12201. sink.write(data.c_str(), data.size());
  12202. return true;
  12203. });
  12204. });
  12205. auto port = 8093;
  12206. std::thread t([&]() { svr.listen("localhost", port); });
  12207. svr.wait_until_ready();
  12208. SSLClient cli("localhost", port);
  12209. cli.enable_server_certificate_verification(false);
  12210. cli.set_read_timeout(1, 0); // 1 second timeout
  12211. auto handle = cli.open_stream("GET", "/slow-stream");
  12212. ASSERT_TRUE(handle.is_valid());
  12213. char buf[256];
  12214. ssize_t total = 0;
  12215. ssize_t n;
  12216. bool got_error = false;
  12217. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12218. total += n;
  12219. }
  12220. if (n < 0) {
  12221. got_error = true;
  12222. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12223. handle.get_read_error() == Error::Read)
  12224. << "Actual error: " << to_string(handle.get_read_error());
  12225. }
  12226. EXPECT_TRUE(got_error || total < 1000)
  12227. << "Expected timeout but got all " << total << " bytes";
  12228. svr.stop();
  12229. t.join();
  12230. }
  12231. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  12232. // Test SSL connection closed detection
  12233. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12234. std::atomic<bool> close_now{false};
  12235. svr.Get("/will-close", [&](const Request &, Response &res) {
  12236. res.set_content_provider(
  12237. 10000, "text/plain",
  12238. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12239. if (offset < 100) {
  12240. std::string data(100, 'X');
  12241. sink.write(data.c_str(), data.size());
  12242. return true;
  12243. }
  12244. while (!close_now) {
  12245. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12246. }
  12247. return false;
  12248. });
  12249. });
  12250. auto port = 8094;
  12251. std::thread t([&]() { svr.listen("localhost", port); });
  12252. svr.wait_until_ready();
  12253. SSLClient cli("localhost", port);
  12254. cli.enable_server_certificate_verification(false);
  12255. auto handle = cli.open_stream("GET", "/will-close");
  12256. ASSERT_TRUE(handle.is_valid());
  12257. char buf[256];
  12258. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12259. EXPECT_GT(n, 0);
  12260. // Signal server to close
  12261. close_now = true;
  12262. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12263. // Keep reading
  12264. }
  12265. if (n < 0) {
  12266. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12267. handle.get_read_error() == Error::Read)
  12268. << "Actual error: " << to_string(handle.get_read_error());
  12269. }
  12270. svr.stop();
  12271. t.join();
  12272. }
  12273. #endif
  12274. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  12275. using namespace httplib;
  12276. // Create a test file
  12277. const char *fname = "etag_testfile.txt";
  12278. const char *content = "etag-content";
  12279. {
  12280. std::ofstream ofs(fname);
  12281. ofs << content;
  12282. ASSERT_TRUE(ofs.good());
  12283. }
  12284. Server svr;
  12285. svr.set_mount_point("/static", ".");
  12286. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12287. svr.wait_until_ready();
  12288. Client cli(HOST, PORT);
  12289. // First request: should get 200 with ETag header
  12290. auto res1 = cli.Get("/static/etag_testfile.txt");
  12291. ASSERT_TRUE(res1);
  12292. ASSERT_EQ(200, res1->status);
  12293. ASSERT_TRUE(res1->has_header("ETag"));
  12294. std::string etag = res1->get_header_value("ETag");
  12295. EXPECT_FALSE(etag.empty());
  12296. // Verify ETag format: W/"hex-hex"
  12297. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  12298. EXPECT_EQ('W', etag[0]);
  12299. EXPECT_EQ('/', etag[1]);
  12300. EXPECT_EQ('"', etag[2]);
  12301. EXPECT_EQ('"', etag.back());
  12302. // Exact match: expect 304 Not Modified
  12303. Headers h2 = {{"If-None-Match", etag}};
  12304. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  12305. ASSERT_TRUE(res2);
  12306. EXPECT_EQ(304, res2->status);
  12307. // Wildcard match: expect 304 Not Modified
  12308. Headers h3 = {{"If-None-Match", "*"}};
  12309. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  12310. ASSERT_TRUE(res3);
  12311. EXPECT_EQ(304, res3->status);
  12312. // Non-matching ETag: expect 200
  12313. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  12314. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  12315. ASSERT_TRUE(res4);
  12316. EXPECT_EQ(200, res4->status);
  12317. // Multiple ETags with one matching: expect 304
  12318. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  12319. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  12320. ASSERT_TRUE(res5);
  12321. EXPECT_EQ(304, res5->status);
  12322. svr.stop();
  12323. t.join();
  12324. std::remove(fname);
  12325. }
  12326. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  12327. using namespace httplib;
  12328. Server svr;
  12329. svr.set_mount_point("/static", ".");
  12330. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12331. svr.wait_until_ready();
  12332. Client cli(HOST, PORT);
  12333. // Send If-None-Match: * to a non-existent file
  12334. Headers h = {{"If-None-Match", "*"}};
  12335. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  12336. ASSERT_TRUE(res);
  12337. EXPECT_EQ(404, res->status);
  12338. svr.stop();
  12339. t.join();
  12340. }
  12341. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  12342. using namespace httplib;
  12343. // Create a test file
  12344. const char *fname = "etag_boundary_testfile.txt";
  12345. const char *content = "boundary-test";
  12346. {
  12347. std::ofstream ofs(fname);
  12348. ofs << content;
  12349. ASSERT_TRUE(ofs.good());
  12350. }
  12351. Server svr;
  12352. svr.set_mount_point("/static", ".");
  12353. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12354. svr.wait_until_ready();
  12355. Client cli(HOST, PORT);
  12356. // Get the actual ETag
  12357. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  12358. ASSERT_TRUE(res1);
  12359. ASSERT_EQ(200, res1->status);
  12360. ASSERT_TRUE(res1->has_header("ETag"));
  12361. std::string etag = res1->get_header_value("ETag");
  12362. // Test 1: Very long ETag value (longer than actual ETag)
  12363. // Should NOT match and return 200 (not trigger out-of-bounds read)
  12364. Headers h1 = {{"If-None-Match", "W/"
  12365. "\"very-long-etag-value-that-is-much-longer-"
  12366. "than-the-actual-etag-value\""}};
  12367. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  12368. ASSERT_TRUE(res2);
  12369. EXPECT_EQ(200, res2->status); // Should not match
  12370. // Test 2: Long string followed by wildcard
  12371. // Should match on "*" and return 304 (without out-of-bounds read on the long
  12372. // string)
  12373. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  12374. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  12375. ASSERT_TRUE(res3);
  12376. EXPECT_EQ(304, res3->status); // Should match on "*"
  12377. // Test 3: Wildcard followed by long string
  12378. // Should match on "*" immediately and return 304
  12379. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  12380. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  12381. ASSERT_TRUE(res4);
  12382. EXPECT_EQ(304, res4->status); // Should match on "*"
  12383. // Test 4: Multiple long non-matching values
  12384. // Should NOT match and return 200 (test that all comparisons are safe)
  12385. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  12386. "W/\"second-long-non-matching-value\", "
  12387. "W/\"third-long-non-matching-value\""}};
  12388. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  12389. ASSERT_TRUE(res5);
  12390. EXPECT_EQ(200, res5->status); // Should not match
  12391. // Test 5: Single character that is not "*" (edge case)
  12392. Headers h5 = {{"If-None-Match", "X"}};
  12393. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  12394. ASSERT_TRUE(res6);
  12395. EXPECT_EQ(200, res6->status); // Should not match
  12396. svr.stop();
  12397. t.join();
  12398. std::remove(fname);
  12399. }
  12400. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  12401. using namespace httplib;
  12402. // Create a test file
  12403. const char *fname = "ims_testfile.txt";
  12404. const char *content = "if-modified-since-test";
  12405. {
  12406. std::ofstream ofs(fname);
  12407. ofs << content;
  12408. ASSERT_TRUE(ofs.good());
  12409. }
  12410. Server svr;
  12411. svr.set_mount_point("/static", ".");
  12412. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12413. svr.wait_until_ready();
  12414. Client cli(HOST, PORT);
  12415. // First request: should get 200 with Last-Modified header
  12416. auto res1 = cli.Get("/static/ims_testfile.txt");
  12417. ASSERT_TRUE(res1);
  12418. ASSERT_EQ(200, res1->status);
  12419. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12420. std::string last_modified = res1->get_header_value("Last-Modified");
  12421. EXPECT_FALSE(last_modified.empty());
  12422. // If-Modified-Since with same time: expect 304
  12423. Headers h2 = {{"If-Modified-Since", last_modified}};
  12424. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  12425. ASSERT_TRUE(res2);
  12426. EXPECT_EQ(304, res2->status);
  12427. // If-Modified-Since with future time: expect 304
  12428. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12429. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  12430. ASSERT_TRUE(res3);
  12431. EXPECT_EQ(304, res3->status);
  12432. // If-Modified-Since with past time: expect 200
  12433. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12434. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  12435. ASSERT_TRUE(res4);
  12436. EXPECT_EQ(200, res4->status);
  12437. // If-None-Match takes precedence over If-Modified-Since
  12438. // (send matching ETag with old If-Modified-Since -> should still be 304)
  12439. ASSERT_TRUE(res1->has_header("ETag"));
  12440. std::string etag = res1->get_header_value("ETag");
  12441. Headers h5 = {{"If-None-Match", etag},
  12442. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12443. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  12444. ASSERT_TRUE(res5);
  12445. EXPECT_EQ(304, res5->status);
  12446. svr.stop();
  12447. t.join();
  12448. std::remove(fname);
  12449. }
  12450. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  12451. using namespace httplib;
  12452. Server svr;
  12453. // Endpoint that returns compressible content
  12454. svr.Get("/compressible", [](const Request &, Response &res) {
  12455. // Return a large enough body to trigger compression
  12456. std::string body(1000, 'a');
  12457. res.set_content(body, "text/plain");
  12458. });
  12459. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12460. svr.wait_until_ready();
  12461. Client cli(HOST, PORT);
  12462. // Request with gzip support: should get Vary header when compressed
  12463. cli.set_compress(true);
  12464. auto res1 = cli.Get("/compressible");
  12465. ASSERT_TRUE(res1);
  12466. EXPECT_EQ(200, res1->status);
  12467. // If Content-Encoding is set, Vary should also be set
  12468. if (res1->has_header("Content-Encoding")) {
  12469. EXPECT_TRUE(res1->has_header("Vary"));
  12470. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  12471. }
  12472. // Request without Accept-Encoding header: should not have compression
  12473. Headers h_no_compress;
  12474. auto res2 = cli.Get("/compressible", h_no_compress);
  12475. ASSERT_TRUE(res2);
  12476. EXPECT_EQ(200, res2->status);
  12477. // Verify Vary header is present when compression is applied
  12478. // (the exact behavior depends on server configuration)
  12479. svr.stop();
  12480. t.join();
  12481. }
  12482. TEST(ETagTest, IfRangeWithETag) {
  12483. using namespace httplib;
  12484. // Create a test file with known content
  12485. const char *fname = "if_range_testfile.txt";
  12486. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  12487. {
  12488. std::ofstream ofs(fname);
  12489. ofs << content;
  12490. ASSERT_TRUE(ofs.good());
  12491. }
  12492. Server svr;
  12493. svr.set_mount_point("/static", ".");
  12494. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12495. svr.wait_until_ready();
  12496. Client cli(HOST, PORT);
  12497. // First request: get ETag
  12498. auto res1 = cli.Get("/static/if_range_testfile.txt");
  12499. ASSERT_TRUE(res1);
  12500. ASSERT_EQ(200, res1->status);
  12501. ASSERT_TRUE(res1->has_header("ETag"));
  12502. std::string etag = res1->get_header_value("ETag");
  12503. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  12504. // Since our server generates weak ETags (W/"..."), If-Range with our
  12505. // ETag should NOT result in partial content - it should return full content.
  12506. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  12507. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  12508. ASSERT_TRUE(res2);
  12509. // Weak ETag in If-Range -> full content (200), not partial (206)
  12510. EXPECT_EQ(200, res2->status);
  12511. EXPECT_EQ(content, res2->body);
  12512. EXPECT_FALSE(res2->has_header("Content-Range"));
  12513. // Range request with non-matching If-Range (ETag): should get 200 (full
  12514. // content)
  12515. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  12516. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  12517. ASSERT_TRUE(res3);
  12518. EXPECT_EQ(200, res3->status);
  12519. EXPECT_EQ(content, res3->body);
  12520. EXPECT_FALSE(res3->has_header("Content-Range"));
  12521. // Range request with strong ETag (hypothetical - our server doesn't generate
  12522. // strong ETags, but if client sends a strong ETag that doesn't match, it
  12523. // should return full content)
  12524. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  12525. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  12526. ASSERT_TRUE(res4);
  12527. EXPECT_EQ(200, res4->status);
  12528. EXPECT_EQ(content, res4->body);
  12529. EXPECT_FALSE(res4->has_header("Content-Range"));
  12530. svr.stop();
  12531. t.join();
  12532. std::remove(fname);
  12533. }
  12534. TEST(ETagTest, IfRangeWithDate) {
  12535. using namespace httplib;
  12536. // Create a test file
  12537. const char *fname = "if_range_date_testfile.txt";
  12538. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  12539. {
  12540. std::ofstream ofs(fname);
  12541. ofs << content;
  12542. ASSERT_TRUE(ofs.good());
  12543. }
  12544. Server svr;
  12545. svr.set_mount_point("/static", ".");
  12546. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12547. svr.wait_until_ready();
  12548. Client cli(HOST, PORT);
  12549. // First request: get Last-Modified
  12550. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  12551. ASSERT_TRUE(res1);
  12552. ASSERT_EQ(200, res1->status);
  12553. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12554. std::string last_modified = res1->get_header_value("Last-Modified");
  12555. // Range request with matching If-Range (date): should get 206
  12556. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  12557. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  12558. ASSERT_TRUE(res2);
  12559. EXPECT_EQ(206, res2->status);
  12560. EXPECT_EQ("FGHIJ", res2->body);
  12561. // Range request with old If-Range date: should get 200 (full content)
  12562. Headers h3 = {{"Range", "bytes=5-9"},
  12563. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12564. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  12565. ASSERT_TRUE(res3);
  12566. EXPECT_EQ(200, res3->status);
  12567. EXPECT_EQ(content, res3->body);
  12568. // Range request with future If-Range date: should get 206
  12569. Headers h4 = {{"Range", "bytes=0-4"},
  12570. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12571. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  12572. ASSERT_TRUE(res4);
  12573. EXPECT_EQ(206, res4->status);
  12574. EXPECT_EQ("ABCDE", res4->body);
  12575. svr.stop();
  12576. t.join();
  12577. std::remove(fname);
  12578. }
  12579. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  12580. using namespace httplib;
  12581. const char *fname = "etag_malformed.txt";
  12582. const char *content = "malformed-etag";
  12583. {
  12584. std::ofstream ofs(fname);
  12585. ofs << content;
  12586. ASSERT_TRUE(ofs.good());
  12587. }
  12588. Server svr;
  12589. svr.set_mount_point("/static", ".");
  12590. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12591. svr.wait_until_ready();
  12592. Client cli(HOST, PORT);
  12593. // baseline: should get 200 and an ETag
  12594. auto res1 = cli.Get("/static/etag_malformed.txt");
  12595. ASSERT_TRUE(res1);
  12596. ASSERT_EQ(200, res1->status);
  12597. ASSERT_TRUE(res1->has_header("ETag"));
  12598. // Malformed ETag value (missing quotes) should be treated as non-matching
  12599. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  12600. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  12601. ASSERT_TRUE(res_bad);
  12602. EXPECT_EQ(200, res_bad->status);
  12603. // Whitespace-only header value should be considered invalid / non-matching
  12604. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  12605. "Host: localhost\r\n"
  12606. "If-None-Match: \r\n"
  12607. "Connection: close\r\n"
  12608. "\r\n";
  12609. std::string out;
  12610. ASSERT_TRUE(send_request(5, raw_req, &out));
  12611. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12612. svr.stop();
  12613. t.join();
  12614. std::remove(fname);
  12615. }
  12616. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  12617. using namespace httplib;
  12618. const char *fname = "ims_invalid_format.txt";
  12619. const char *content = "ims-bad-format";
  12620. {
  12621. std::ofstream ofs(fname);
  12622. ofs << content;
  12623. ASSERT_TRUE(ofs.good());
  12624. }
  12625. Server svr;
  12626. svr.set_mount_point("/static", ".");
  12627. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12628. svr.wait_until_ready();
  12629. Client cli(HOST, PORT);
  12630. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  12631. ASSERT_TRUE(res1);
  12632. ASSERT_EQ(200, res1->status);
  12633. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12634. // If-Modified-Since with invalid format should not result in 304
  12635. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  12636. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  12637. ASSERT_TRUE(res_bad);
  12638. EXPECT_EQ(200, res_bad->status);
  12639. // If-Range with invalid date format should be treated as mismatch -> full
  12640. // content (200)
  12641. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  12642. {"If-Range", "invalid-date"}};
  12643. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  12644. ASSERT_TRUE(res_ifrange);
  12645. EXPECT_EQ(200, res_ifrange->status);
  12646. svr.stop();
  12647. t.join();
  12648. std::remove(fname);
  12649. }
  12650. TEST(ETagTest, IfRangeWithMalformedETag) {
  12651. using namespace httplib;
  12652. const char *fname = "ifrange_malformed.txt";
  12653. const std::string content = "0123456789";
  12654. {
  12655. std::ofstream ofs(fname);
  12656. ofs << content;
  12657. ASSERT_TRUE(ofs.good());
  12658. }
  12659. Server svr;
  12660. svr.set_mount_point("/static", ".");
  12661. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12662. svr.wait_until_ready();
  12663. Client cli(HOST, PORT);
  12664. // First request: get ETag
  12665. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  12666. ASSERT_TRUE(res1);
  12667. ASSERT_EQ(200, res1->status);
  12668. ASSERT_TRUE(res1->has_header("ETag"));
  12669. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  12670. // full content (200)
  12671. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  12672. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  12673. ASSERT_TRUE(res2);
  12674. EXPECT_EQ(200, res2->status);
  12675. EXPECT_EQ(content, res2->body);
  12676. svr.stop();
  12677. t.join();
  12678. std::remove(fname);
  12679. }
  12680. TEST(ETagTest, ExtremeLargeDateValues) {
  12681. using namespace httplib;
  12682. const char *fname = "ims_extreme_date.txt";
  12683. const char *content = "ims-extreme-date";
  12684. {
  12685. std::ofstream ofs(fname);
  12686. ofs << content;
  12687. ASSERT_TRUE(ofs.good());
  12688. }
  12689. Server svr;
  12690. svr.set_mount_point("/static", ".");
  12691. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12692. svr.wait_until_ready();
  12693. Client cli(HOST, PORT);
  12694. auto res1 = cli.Get(std::string("/static/") + fname);
  12695. ASSERT_TRUE(res1);
  12696. ASSERT_EQ(200, res1->status);
  12697. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12698. // Extremely large year that may overflow date parsing routines.
  12699. Headers h_large_date = {
  12700. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12701. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  12702. ASSERT_TRUE(res_bad);
  12703. // Expect server to treat this as invalid/mismatch and return full content
  12704. EXPECT_EQ(200, res_bad->status);
  12705. // If-Range with extremely large date should be treated as mismatch -> full
  12706. // content (200)
  12707. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  12708. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12709. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  12710. ASSERT_TRUE(res_ifrange);
  12711. EXPECT_EQ(200, res_ifrange->status);
  12712. svr.stop();
  12713. t.join();
  12714. std::remove(fname);
  12715. }
  12716. TEST(ETagTest, NegativeFileModificationTime) {
  12717. using namespace httplib;
  12718. const char *fname = "ims_negative_mtime.txt";
  12719. const std::string content = "negative-mtime";
  12720. {
  12721. std::ofstream ofs(fname);
  12722. ofs << content;
  12723. ASSERT_TRUE(ofs.good());
  12724. }
  12725. // Try to set file mtime to a negative value. This may fail on some
  12726. // platforms/filesystems; if it fails, the test will still verify server
  12727. // behaves safely by performing a regular conditional request.
  12728. #if defined(__APPLE__) || defined(__linux__)
  12729. bool set_negative = false;
  12730. do {
  12731. struct timeval times[2];
  12732. // access time: now
  12733. times[0].tv_sec = time(nullptr);
  12734. times[0].tv_usec = 0;
  12735. // modification time: negative (e.g., -1)
  12736. times[1].tv_sec = -1;
  12737. times[1].tv_usec = 0;
  12738. if (utimes(fname, times) == 0) { set_negative = true; }
  12739. } while (0);
  12740. #else
  12741. bool set_negative = false;
  12742. #endif
  12743. Server svr;
  12744. svr.set_mount_point("/static", ".");
  12745. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12746. svr.wait_until_ready();
  12747. Client cli(HOST, PORT);
  12748. auto res1 = cli.Get(std::string("/static/") + fname);
  12749. ASSERT_TRUE(res1);
  12750. ASSERT_EQ(200, res1->status);
  12751. bool has_last_modified = res1->has_header("Last-Modified");
  12752. std::string last_modified;
  12753. if (has_last_modified) {
  12754. last_modified = res1->get_header_value("Last-Modified");
  12755. }
  12756. if (set_negative) {
  12757. // If we successfully set a negative mtime, ensure server returns a
  12758. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  12759. // with an old date and ensure server handles it without crash.
  12760. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  12761. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  12762. ASSERT_TRUE(res2);
  12763. // Behavior may vary; at minimum ensure server responds (200 or 304).
  12764. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  12765. } else {
  12766. // Could not set negative mtime on this platform; fall back to verifying
  12767. // that normal invalid/malformed dates are treated safely (non-304).
  12768. Headers h_bad_date = {
  12769. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12770. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  12771. ASSERT_TRUE(res_bad);
  12772. EXPECT_EQ(200, res_bad->status);
  12773. }
  12774. svr.stop();
  12775. t.join();
  12776. std::remove(fname);
  12777. }
  12778. //==============================================================================
  12779. // SSE Parsing Tests
  12780. //==============================================================================
  12781. class SSEParsingTest : public ::testing::Test {
  12782. protected:
  12783. // Test helper that mimics SSE parsing behavior
  12784. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  12785. int &retry_ms) {
  12786. // Blank line signals end of event
  12787. if (line.empty() || line == "\r") { return true; }
  12788. // Lines starting with ':' are comments (ignored)
  12789. if (!line.empty() && line[0] == ':') { return false; }
  12790. // Find the colon separator
  12791. auto colon_pos = line.find(':');
  12792. if (colon_pos == std::string::npos) {
  12793. // Line with no colon is treated as field name with empty value
  12794. return false;
  12795. }
  12796. std::string field = line.substr(0, colon_pos);
  12797. std::string value;
  12798. // Value starts after colon, skip optional single space
  12799. if (colon_pos + 1 < line.size()) {
  12800. size_t value_start = colon_pos + 1;
  12801. if (line[value_start] == ' ') { value_start++; }
  12802. value = line.substr(value_start);
  12803. // Remove trailing \r if present
  12804. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  12805. }
  12806. // Handle known fields
  12807. if (field == "event") {
  12808. msg.event = value;
  12809. } else if (field == "data") {
  12810. // Multiple data lines are concatenated with newlines
  12811. if (!msg.data.empty()) { msg.data += "\n"; }
  12812. msg.data += value;
  12813. } else if (field == "id") {
  12814. // Empty id is valid (clears the last event ID)
  12815. msg.id = value;
  12816. } else if (field == "retry") {
  12817. // Parse retry interval in milliseconds
  12818. {
  12819. int v = 0;
  12820. auto res =
  12821. detail::from_chars(value.data(), value.data() + value.size(), v);
  12822. if (res.ec == std::errc{}) { retry_ms = v; }
  12823. }
  12824. }
  12825. // Unknown fields are ignored per SSE spec
  12826. return false;
  12827. }
  12828. };
  12829. // Test: Single-line data
  12830. TEST_F(SSEParsingTest, SingleLineData) {
  12831. sse::SSEMessage msg;
  12832. int retry_ms = 3000;
  12833. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  12834. EXPECT_EQ(msg.data, "hello");
  12835. EXPECT_EQ(msg.event, "message");
  12836. // Blank line ends event
  12837. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12838. }
  12839. // Test: Multi-line data
  12840. TEST_F(SSEParsingTest, MultiLineData) {
  12841. sse::SSEMessage msg;
  12842. int retry_ms = 3000;
  12843. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  12844. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  12845. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  12846. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  12847. }
  12848. // Test: Custom event types
  12849. TEST_F(SSEParsingTest, CustomEventType) {
  12850. sse::SSEMessage msg;
  12851. int retry_ms = 3000;
  12852. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  12853. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  12854. EXPECT_EQ(msg.event, "update");
  12855. EXPECT_EQ(msg.data, "payload");
  12856. }
  12857. // Test: Event ID handling
  12858. TEST_F(SSEParsingTest, EventIdHandling) {
  12859. sse::SSEMessage msg;
  12860. int retry_ms = 3000;
  12861. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  12862. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  12863. EXPECT_EQ(msg.id, "12345");
  12864. }
  12865. // Test: Empty event ID (clears last event ID)
  12866. TEST_F(SSEParsingTest, EmptyEventId) {
  12867. sse::SSEMessage msg;
  12868. msg.id = "previous";
  12869. int retry_ms = 3000;
  12870. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  12871. EXPECT_EQ(msg.id, "");
  12872. }
  12873. // Test: Retry field parsing
  12874. TEST_F(SSEParsingTest, RetryFieldParsing) {
  12875. sse::SSEMessage msg;
  12876. int retry_ms = 3000;
  12877. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  12878. EXPECT_EQ(retry_ms, 5000);
  12879. }
  12880. // Test: Invalid retry value
  12881. TEST_F(SSEParsingTest, InvalidRetryValue) {
  12882. sse::SSEMessage msg;
  12883. int retry_ms = 3000;
  12884. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  12885. EXPECT_EQ(retry_ms, 3000); // Unchanged
  12886. }
  12887. // Test: Comments (lines starting with :)
  12888. TEST_F(SSEParsingTest, CommentsIgnored) {
  12889. sse::SSEMessage msg;
  12890. int retry_ms = 3000;
  12891. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  12892. EXPECT_EQ(msg.data, "");
  12893. EXPECT_EQ(msg.event, "message");
  12894. }
  12895. // Test: Colon in value
  12896. TEST_F(SSEParsingTest, ColonInValue) {
  12897. sse::SSEMessage msg;
  12898. int retry_ms = 3000;
  12899. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  12900. EXPECT_EQ(msg.data, "hello:world:test");
  12901. }
  12902. // Test: Line with no colon (field name only)
  12903. TEST_F(SSEParsingTest, FieldNameOnly) {
  12904. sse::SSEMessage msg;
  12905. int retry_ms = 3000;
  12906. // According to SSE spec, this is treated as field name with empty value
  12907. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  12908. // Since we don't recognize "data" without colon, data should be empty
  12909. EXPECT_EQ(msg.data, "");
  12910. }
  12911. // Test: Trailing \r handling
  12912. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  12913. sse::SSEMessage msg;
  12914. int retry_ms = 3000;
  12915. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  12916. EXPECT_EQ(msg.data, "hello");
  12917. }
  12918. // Test: Unknown fields ignored
  12919. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  12920. sse::SSEMessage msg;
  12921. int retry_ms = 3000;
  12922. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  12923. EXPECT_EQ(msg.data, "");
  12924. EXPECT_EQ(msg.event, "message");
  12925. }
  12926. // Test: Space after colon is optional
  12927. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  12928. sse::SSEMessage msg1, msg2;
  12929. int retry_ms = 3000;
  12930. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  12931. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  12932. EXPECT_EQ(msg1.data, "hello");
  12933. EXPECT_EQ(msg2.data, "hello");
  12934. }
  12935. // Test: SSEMessage clear
  12936. TEST_F(SSEParsingTest, MessageClear) {
  12937. sse::SSEMessage msg;
  12938. msg.event = "custom";
  12939. msg.data = "some data";
  12940. msg.id = "123";
  12941. msg.clear();
  12942. EXPECT_EQ(msg.event, "message");
  12943. EXPECT_EQ(msg.data, "");
  12944. EXPECT_EQ(msg.id, "");
  12945. }
  12946. // Test: Complete event parsing
  12947. TEST_F(SSEParsingTest, CompleteEventParsing) {
  12948. sse::SSEMessage msg;
  12949. int retry_ms = 3000;
  12950. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  12951. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  12952. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  12953. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  12954. // Blank line ends event
  12955. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12956. EXPECT_EQ(msg.event, "notification");
  12957. EXPECT_EQ(msg.id, "evt-42");
  12958. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  12959. EXPECT_EQ(retry_ms, 1000);
  12960. }
  12961. //==============================================================================
  12962. // Integration Tests with Server
  12963. //==============================================================================
  12964. class SSEIntegrationTest : public ::testing::Test {
  12965. protected:
  12966. void SetUp() override {
  12967. stop_server_.store(false);
  12968. events_.clear();
  12969. server_ = httplib::detail::make_unique<Server>();
  12970. setup_server();
  12971. start_server();
  12972. }
  12973. void TearDown() override {
  12974. stop_server_.store(true);
  12975. event_cv_.notify_all();
  12976. server_->stop();
  12977. if (server_thread_.joinable()) { server_thread_.join(); }
  12978. }
  12979. void setup_server() {
  12980. // Simple SSE endpoint
  12981. server_->Get("/events", [this](const Request &req, Response &res) {
  12982. auto last_id = req.get_header_value("Last-Event-ID");
  12983. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  12984. res.set_chunked_content_provider(
  12985. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  12986. std::unique_lock<std::mutex> lock(event_mutex_);
  12987. if (event_cv_.wait_for(
  12988. lock, std::chrono::milliseconds(200), [this] {
  12989. return !events_.empty() || stop_server_.load();
  12990. })) {
  12991. if (stop_server_.load()) { return false; }
  12992. if (!events_.empty()) {
  12993. std::string event = events_.front();
  12994. events_.erase(events_.begin());
  12995. sink.write(event.data(), event.size());
  12996. return true;
  12997. }
  12998. }
  12999. return !stop_server_.load();
  13000. });
  13001. });
  13002. // Endpoint that returns error
  13003. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  13004. res.status = 500;
  13005. res.set_content("Internal Server Error", "text/plain");
  13006. });
  13007. // Endpoint for custom event types
  13008. server_->Get("/custom-events", [](const Request &, Response &res) {
  13009. res.set_chunked_content_provider(
  13010. "text/event-stream", [](size_t offset, DataSink &sink) {
  13011. if (offset == 0) {
  13012. std::string event = "event: update\ndata: updated\n\n"
  13013. "event: delete\ndata: deleted\n\n";
  13014. sink.write(event.data(), event.size());
  13015. }
  13016. return false; // End stream after sending
  13017. });
  13018. });
  13019. }
  13020. void start_server() {
  13021. port_ = server_->bind_to_any_port(HOST);
  13022. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13023. // Wait for server to start
  13024. while (!server_->is_running()) {
  13025. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13026. }
  13027. }
  13028. int get_port() const { return port_; }
  13029. void send_event(const std::string &event) {
  13030. std::lock_guard<std::mutex> lock(event_mutex_);
  13031. events_.push_back(event);
  13032. event_cv_.notify_all();
  13033. }
  13034. std::unique_ptr<Server> server_;
  13035. std::thread server_thread_;
  13036. std::mutex event_mutex_;
  13037. std::condition_variable event_cv_;
  13038. std::vector<std::string> events_;
  13039. std::atomic<bool> stop_server_{false};
  13040. std::string last_received_event_id_;
  13041. int port_ = 0;
  13042. };
  13043. // Test: Successful connection and on_open callback
  13044. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  13045. // Add a simple endpoint that sends one event and closes
  13046. server_->Get("/simple-event", [](const Request &, Response &res) {
  13047. res.set_chunked_content_provider(
  13048. "text/event-stream", [](size_t offset, DataSink &sink) {
  13049. if (offset == 0) {
  13050. std::string event = "data: hello\n\n";
  13051. sink.write(event.data(), event.size());
  13052. }
  13053. return false; // Close stream after sending
  13054. });
  13055. });
  13056. Client client("localhost", get_port());
  13057. sse::SSEClient sse(client, "/simple-event");
  13058. std::atomic<bool> open_called{false};
  13059. std::atomic<bool> message_received{false};
  13060. sse.on_open([&open_called]() { open_called.store(true); });
  13061. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  13062. if (msg.data == "hello") { message_received.store(true); }
  13063. });
  13064. sse.set_reconnect_interval(100);
  13065. sse.set_max_reconnect_attempts(1);
  13066. // Start async
  13067. sse.start_async();
  13068. // Wait for message to be processed
  13069. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13070. sse.stop();
  13071. EXPECT_TRUE(open_called.load());
  13072. EXPECT_TRUE(message_received.load());
  13073. }
  13074. // Test: on_message callback
  13075. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  13076. // Endpoint that sends multiple events then closes
  13077. server_->Get("/multi-event", [](const Request &, Response &res) {
  13078. res.set_chunked_content_provider(
  13079. "text/event-stream", [](size_t offset, DataSink &sink) {
  13080. if (offset == 0) {
  13081. std::string events = "data: message1\n\ndata: message2\n\n";
  13082. sink.write(events.data(), events.size());
  13083. }
  13084. return false;
  13085. });
  13086. });
  13087. Client client("localhost", get_port());
  13088. sse::SSEClient sse(client, "/multi-event");
  13089. std::vector<std::string> received_messages;
  13090. std::mutex messages_mutex;
  13091. sse.on_message([&](const sse::SSEMessage &msg) {
  13092. std::lock_guard<std::mutex> lock(messages_mutex);
  13093. received_messages.push_back(msg.data);
  13094. });
  13095. sse.set_reconnect_interval(100);
  13096. sse.set_max_reconnect_attempts(1);
  13097. sse.start_async();
  13098. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13099. sse.stop();
  13100. std::lock_guard<std::mutex> lock(messages_mutex);
  13101. EXPECT_GE(received_messages.size(), 2u);
  13102. if (received_messages.size() >= 2) {
  13103. EXPECT_EQ(received_messages[0], "message1");
  13104. EXPECT_EQ(received_messages[1], "message2");
  13105. }
  13106. }
  13107. // Test: on_event for specific types
  13108. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  13109. Client client("localhost", get_port());
  13110. sse::SSEClient sse(client, "/custom-events");
  13111. std::atomic<bool> update_received{false};
  13112. std::atomic<bool> delete_received{false};
  13113. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  13114. if (msg.data == "updated") { update_received.store(true); }
  13115. });
  13116. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  13117. if (msg.data == "deleted") { delete_received.store(true); }
  13118. });
  13119. sse.set_max_reconnect_attempts(1);
  13120. sse.start_async();
  13121. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  13122. sse.stop();
  13123. EXPECT_TRUE(update_received.load());
  13124. EXPECT_TRUE(delete_received.load());
  13125. }
  13126. // Test: on_error callback on connection failure
  13127. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  13128. // Connect to a non-existent port
  13129. Client client("localhost", 59999);
  13130. sse::SSEClient sse(client, "/events");
  13131. std::atomic<bool> error_called{false};
  13132. Error received_error = Error::Success;
  13133. sse.on_error([&](Error err) {
  13134. error_called.store(true);
  13135. received_error = err;
  13136. });
  13137. sse.set_reconnect_interval(50);
  13138. sse.set_max_reconnect_attempts(1);
  13139. sse.start_async();
  13140. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13141. sse.stop();
  13142. EXPECT_TRUE(error_called.load());
  13143. EXPECT_NE(received_error, Error::Success);
  13144. }
  13145. // Test: Last-Event-ID header sent on reconnect
  13146. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  13147. // Endpoint that sends event with ID
  13148. server_->Get("/event-with-id", [](const Request &, Response &res) {
  13149. res.set_chunked_content_provider(
  13150. "text/event-stream", [](size_t offset, DataSink &sink) {
  13151. if (offset == 0) {
  13152. std::string event = "id: evt-123\ndata: test\n\n";
  13153. sink.write(event.data(), event.size());
  13154. }
  13155. return false;
  13156. });
  13157. });
  13158. Client client("localhost", get_port());
  13159. sse::SSEClient sse(client, "/event-with-id");
  13160. std::atomic<bool> id_received{false};
  13161. sse.on_message([&](const sse::SSEMessage &msg) {
  13162. if (!msg.id.empty()) { id_received.store(true); }
  13163. });
  13164. sse.set_reconnect_interval(100);
  13165. sse.set_max_reconnect_attempts(1);
  13166. sse.start_async();
  13167. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13168. sse.stop();
  13169. EXPECT_TRUE(id_received.load());
  13170. EXPECT_EQ(sse.last_event_id(), "evt-123");
  13171. }
  13172. // Test: Manual stop
  13173. TEST_F(SSEIntegrationTest, ManualStop) {
  13174. // Endpoint that sends one event and stays open briefly
  13175. std::atomic<bool> handler_running{true};
  13176. server_->Get("/stay-open", [&handler_running](const Request &,
  13177. Response &res) {
  13178. res.set_chunked_content_provider(
  13179. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  13180. if (offset == 0) {
  13181. std::string event = "data: connected\n\n";
  13182. sink.write(event.data(), event.size());
  13183. }
  13184. // Keep connection open while handler_running is true
  13185. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  13186. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13187. }
  13188. return false;
  13189. });
  13190. });
  13191. Client client("localhost", get_port());
  13192. sse::SSEClient sse(client, "/stay-open");
  13193. std::atomic<bool> connected{false};
  13194. sse.on_open([&connected]() { connected.store(true); });
  13195. sse.set_reconnect_interval(100);
  13196. sse.set_max_reconnect_attempts(1);
  13197. sse.start_async();
  13198. // Wait for connection to establish
  13199. for (int i = 0; i < 20 && !connected.load(); ++i) {
  13200. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13201. }
  13202. EXPECT_TRUE(connected.load());
  13203. EXPECT_TRUE(sse.is_connected());
  13204. // Signal handler to stop
  13205. handler_running.store(false);
  13206. // Stop SSE client
  13207. sse.stop();
  13208. EXPECT_FALSE(sse.is_connected());
  13209. }
  13210. // Test: SSEClient with custom headers
  13211. TEST_F(SSEIntegrationTest, CustomHeaders) {
  13212. // Setup a server endpoint that checks for custom header
  13213. std::atomic<bool> header_received{false};
  13214. server_->Get("/header-check", [&](const Request &req, Response &res) {
  13215. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  13216. header_received.store(true);
  13217. }
  13218. res.set_chunked_content_provider("text/event-stream",
  13219. [](size_t, DataSink &) { return false; });
  13220. });
  13221. Client client("localhost", get_port());
  13222. Headers headers = {{"X-Custom-Header", "custom-value"}};
  13223. sse::SSEClient sse(client, "/header-check", headers);
  13224. sse.set_max_reconnect_attempts(1);
  13225. sse.start_async();
  13226. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13227. sse.stop();
  13228. EXPECT_TRUE(header_received.load());
  13229. }
  13230. // Test: Reconnect interval configuration
  13231. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  13232. Client client("localhost", get_port());
  13233. sse::SSEClient sse(client, "/events");
  13234. auto &result = sse.set_reconnect_interval(500);
  13235. // Builder pattern should return reference to self
  13236. EXPECT_EQ(&result, &sse);
  13237. }
  13238. // Test: Max reconnect attempts
  13239. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  13240. // Connect to non-existent port to force reconnects
  13241. Client client("localhost", 59998);
  13242. sse::SSEClient sse(client, "/events");
  13243. std::atomic<int> error_count{0};
  13244. sse.on_error([&](Error) { error_count.fetch_add(1); });
  13245. sse.set_reconnect_interval(50);
  13246. sse.set_max_reconnect_attempts(2);
  13247. auto start = std::chrono::steady_clock::now();
  13248. sse.start(); // Blocking call
  13249. auto end = std::chrono::steady_clock::now();
  13250. // Should have stopped after 2 failed attempts
  13251. EXPECT_GE(error_count.load(), 2);
  13252. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  13253. auto duration =
  13254. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  13255. #ifdef _WIN32
  13256. // Windows is much slower for socket connection failures
  13257. EXPECT_LT(duration.count(), 7000);
  13258. #else
  13259. EXPECT_LT(duration.count(), 1000);
  13260. #endif
  13261. }
  13262. // Test: Multi-line data in integration
  13263. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  13264. // Endpoint with multi-line data
  13265. server_->Get("/multiline-data", [](const Request &, Response &res) {
  13266. res.set_chunked_content_provider(
  13267. "text/event-stream", [](size_t offset, DataSink &sink) {
  13268. if (offset == 0) {
  13269. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  13270. sink.write(event.data(), event.size());
  13271. }
  13272. return false;
  13273. });
  13274. });
  13275. Client client("localhost", get_port());
  13276. sse::SSEClient sse(client, "/multiline-data");
  13277. std::string received_data;
  13278. std::mutex data_mutex;
  13279. sse.on_message([&](const sse::SSEMessage &msg) {
  13280. std::lock_guard<std::mutex> lock(data_mutex);
  13281. received_data = msg.data;
  13282. });
  13283. sse.set_reconnect_interval(100);
  13284. sse.set_max_reconnect_attempts(1);
  13285. sse.start_async();
  13286. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13287. sse.stop();
  13288. std::lock_guard<std::mutex> lock(data_mutex);
  13289. EXPECT_EQ(received_data, "line1\nline2\nline3");
  13290. }
  13291. // Test: Auto-reconnect after server disconnection
  13292. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  13293. std::atomic<int> connection_count{0};
  13294. std::atomic<int> message_count{0};
  13295. // Endpoint that sends one event and closes, forcing reconnect
  13296. server_->Get("/reconnect-test",
  13297. [&connection_count](const Request &, Response &res) {
  13298. connection_count.fetch_add(1);
  13299. res.set_chunked_content_provider(
  13300. "text/event-stream", [](size_t offset, DataSink &sink) {
  13301. if (offset == 0) {
  13302. std::string event = "data: hello\n\n";
  13303. sink.write(event.data(), event.size());
  13304. }
  13305. return false; // Close connection after sending
  13306. });
  13307. });
  13308. Client client("localhost", get_port());
  13309. sse::SSEClient sse(client, "/reconnect-test");
  13310. sse.on_message([&message_count](const sse::SSEMessage &) {
  13311. message_count.fetch_add(1);
  13312. });
  13313. sse.set_reconnect_interval(100);
  13314. sse.set_max_reconnect_attempts(3);
  13315. sse.start_async();
  13316. // Wait long enough for multiple reconnects
  13317. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13318. sse.stop();
  13319. // Should have connected multiple times (initial + reconnects)
  13320. EXPECT_GE(connection_count.load(), 2);
  13321. // Should have received messages from multiple connections
  13322. EXPECT_GE(message_count.load(), 2);
  13323. }
  13324. // Test: Last-Event-ID sent on reconnect
  13325. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  13326. std::atomic<int> connection_count{0};
  13327. std::vector<std::string> received_last_event_ids;
  13328. std::mutex id_mutex;
  13329. // Endpoint that checks Last-Event-ID header and sends event with ID
  13330. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  13331. int conn = connection_count.fetch_add(1);
  13332. // Capture the Last-Event-ID header from each connection
  13333. {
  13334. std::lock_guard<std::mutex> lock(id_mutex);
  13335. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  13336. }
  13337. res.set_chunked_content_provider(
  13338. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  13339. if (offset == 0) {
  13340. std::string event =
  13341. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  13342. sink.write(event.data(), event.size());
  13343. }
  13344. return false;
  13345. });
  13346. });
  13347. Client client("localhost", get_port());
  13348. sse::SSEClient sse(client, "/reconnect-with-id");
  13349. sse.set_reconnect_interval(100);
  13350. sse.set_max_reconnect_attempts(3);
  13351. sse.start_async();
  13352. // Wait for at least 2 connections
  13353. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13354. sse.stop();
  13355. // Verify behavior
  13356. std::lock_guard<std::mutex> lock(id_mutex);
  13357. EXPECT_GE(received_last_event_ids.size(), 2u);
  13358. // First connection should have no Last-Event-ID
  13359. if (!received_last_event_ids.empty()) {
  13360. EXPECT_EQ(received_last_event_ids[0], "");
  13361. }
  13362. // Second connection should have Last-Event-ID from first connection
  13363. if (received_last_event_ids.size() >= 2) {
  13364. EXPECT_EQ(received_last_event_ids[1], "event-0");
  13365. }
  13366. }
  13367. TEST(Issue2318Test, EmptyHostString) {
  13368. {
  13369. httplib::Client cli_empty("", PORT);
  13370. auto res = cli_empty.Get("/");
  13371. ASSERT_FALSE(res);
  13372. EXPECT_EQ(httplib::Error::Connection, res.error());
  13373. }
  13374. {
  13375. httplib::Client cli(" ", PORT);
  13376. auto res = cli.Get("/");
  13377. ASSERT_FALSE(res);
  13378. EXPECT_EQ(httplib::Error::Connection, res.error());
  13379. }
  13380. }
  13381. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13382. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  13383. Server svr;
  13384. // Set a small payload limit (1KB)
  13385. svr.set_payload_max_length(1024);
  13386. svr.Post("/test", [&](const Request &req, Response &res) {
  13387. res.set_content("Body size: " + std::to_string(req.body.size()),
  13388. "text/plain");
  13389. });
  13390. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13391. auto se = detail::scope_exit([&] {
  13392. svr.stop();
  13393. listen_thread.join();
  13394. });
  13395. svr.wait_until_ready();
  13396. // Create data that compresses well but exceeds limit when decompressed
  13397. // 8KB of repeated null bytes compresses to a very small size
  13398. std::string original_data(8 * 1024, '\0');
  13399. // Compress the data using gzip
  13400. std::string compressed_data;
  13401. detail::gzip_compressor compressor;
  13402. compressor.compress(original_data.data(), original_data.size(), true,
  13403. [&](const char *data, size_t size) {
  13404. compressed_data.append(data, size);
  13405. return true;
  13406. });
  13407. // Verify compression worked (compressed should be much smaller)
  13408. ASSERT_LT(compressed_data.size(), original_data.size());
  13409. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  13410. // Send compressed data with Content-Encoding: gzip
  13411. Client cli(HOST, PORT);
  13412. Headers headers = {{"Content-Encoding", "gzip"}};
  13413. auto res =
  13414. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  13415. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  13416. ASSERT_TRUE(res);
  13417. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13418. }
  13419. #endif
  13420. // ============================================================================
  13421. // OpenSSL-Specific Tests
  13422. // ============================================================================
  13423. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13424. X509 *readCertificate(const std::string &strFileName) {
  13425. std::ifstream inStream(strFileName);
  13426. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  13427. std::istreambuf_iterator<char>());
  13428. if (strCertPEM.empty()) return (nullptr);
  13429. BIO *pbCert = BIO_new(BIO_s_mem());
  13430. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  13431. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  13432. BIO_free(pbCert);
  13433. return (pCert);
  13434. }
  13435. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  13436. std::ifstream inStream(strFileName);
  13437. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  13438. std::istreambuf_iterator<char>());
  13439. if (strPrivateKeyPEM.empty()) return (nullptr);
  13440. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  13441. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  13442. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  13443. BIO_free(pbPrivKey);
  13444. return (pPrivateKey);
  13445. }
  13446. TEST(BindServerTest, UpdateCerts) {
  13447. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13448. int port = svr.bind_to_any_port("0.0.0.0");
  13449. ASSERT_TRUE(svr.is_valid());
  13450. ASSERT_TRUE(port > 0);
  13451. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13452. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13453. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13454. ASSERT_TRUE(cert != nullptr);
  13455. ASSERT_TRUE(ca_cert != nullptr);
  13456. ASSERT_TRUE(key != nullptr);
  13457. X509_STORE *cert_store = X509_STORE_new();
  13458. X509_STORE_add_cert(cert_store, ca_cert);
  13459. // svr.update_certs(cert, key, cert_store); // deprecated
  13460. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13461. CLIENT_CA_CERT_FILE);
  13462. ASSERT_TRUE(svr.is_valid());
  13463. svr.stop();
  13464. X509_STORE_free(cert_store);
  13465. X509_free(cert);
  13466. X509_free(ca_cert);
  13467. EVP_PKEY_free(key);
  13468. }
  13469. // Test that SSLServer(X509*, EVP_PKEY*, X509_STORE*) constructor sets
  13470. // client CA list correctly for TLS handshake
  13471. TEST(SSLClientServerTest, X509ConstructorSetsClientCAList) {
  13472. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13473. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13474. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13475. ASSERT_TRUE(cert != nullptr);
  13476. ASSERT_TRUE(ca_cert != nullptr);
  13477. ASSERT_TRUE(key != nullptr);
  13478. X509_STORE *cert_store = X509_STORE_new();
  13479. X509_STORE_add_cert(cert_store, ca_cert);
  13480. // Use X509-based constructor (deprecated but should still work correctly)
  13481. #pragma GCC diagnostic push
  13482. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  13483. SSLServer svr(cert, key, cert_store);
  13484. #pragma GCC diagnostic pop
  13485. ASSERT_TRUE(svr.is_valid());
  13486. // Verify that client CA list is set in SSL_CTX
  13487. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13488. ASSERT_TRUE(ssl_ctx != nullptr);
  13489. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13490. ASSERT_TRUE(ca_list != nullptr);
  13491. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13492. X509_free(cert);
  13493. X509_free(ca_cert);
  13494. EVP_PKEY_free(key);
  13495. }
  13496. // Test that update_certs() updates client CA list correctly
  13497. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  13498. // Start with file-based constructor
  13499. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13500. ASSERT_TRUE(svr.is_valid());
  13501. // Initially no client CA list should be set
  13502. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13503. ASSERT_TRUE(ssl_ctx != nullptr);
  13504. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  13505. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  13506. EXPECT_EQ(0, count_before);
  13507. // Now update with client CA (PEM string)
  13508. std::string cert_pem, key_pem, ca_pem;
  13509. read_file(SERVER_CERT_FILE, cert_pem);
  13510. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13511. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13512. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  13513. ASSERT_TRUE(svr.is_valid());
  13514. // Now client CA list should be set
  13515. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  13516. ASSERT_TRUE(ca_list_after != nullptr);
  13517. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  13518. }
  13519. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  13520. // Test that the file-path SSLServer constructor properly sets the client CA
  13521. // list that is sent to clients during the TLS handshake (CertificateRequest)
  13522. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13523. ASSERT_TRUE(svr.is_valid());
  13524. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13525. ASSERT_TRUE(ssl_ctx != nullptr);
  13526. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13527. ASSERT_TRUE(ca_list != nullptr);
  13528. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13529. }
  13530. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  13531. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  13532. // prepare large data
  13533. std::random_device seed_gen;
  13534. std::mt19937 random(seed_gen());
  13535. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  13536. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  13537. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  13538. // server
  13539. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13540. ASSERT_TRUE(svr.is_valid());
  13541. svr.Post("/binary", [&](const Request &req, Response &res) {
  13542. EXPECT_EQ(large_size_byte, req.body.size());
  13543. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  13544. res.set_content(req.body, "application/octet-stream");
  13545. });
  13546. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  13547. auto se = detail::scope_exit([&] {
  13548. svr.stop();
  13549. listen_thread.join();
  13550. ASSERT_FALSE(svr.is_running());
  13551. });
  13552. svr.wait_until_ready();
  13553. // client POST
  13554. SSLClient cli("localhost", PORT);
  13555. cli.enable_server_certificate_verification(false);
  13556. cli.set_read_timeout(std::chrono::seconds(100));
  13557. cli.set_write_timeout(std::chrono::seconds(100));
  13558. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  13559. large_size_byte, "application/octet-stream");
  13560. // compare
  13561. EXPECT_EQ(StatusCode::OK_200, res->status);
  13562. EXPECT_EQ(large_size_byte, res->body.size());
  13563. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  13564. }
  13565. #endif
  13566. // ============================================================================
  13567. // MbedTLS-Specific Tests
  13568. // ============================================================================
  13569. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  13570. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  13571. using namespace httplib::tls;
  13572. // Track if callback was invoked
  13573. bool callback_invoked = false;
  13574. // The callback receives void* ctx which is actually MbedTlsContext*
  13575. // We can access the mbedtls_ssl_config via the context
  13576. auto setup_callback = [&callback_invoked](void *ctx) {
  13577. callback_invoked = true;
  13578. // Cast to MbedTlsContext* to access the ssl config
  13579. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  13580. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  13581. // Use static variables to hold certificate data (simplified for test)
  13582. static mbedtls_x509_crt own_cert;
  13583. static mbedtls_pk_context own_key;
  13584. static mbedtls_x509_crt ca_chain;
  13585. static bool initialized = false;
  13586. if (!initialized) {
  13587. mbedtls_x509_crt_init(&own_cert);
  13588. mbedtls_pk_init(&own_key);
  13589. mbedtls_x509_crt_init(&ca_chain);
  13590. // Load server certificate
  13591. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  13592. return false;
  13593. }
  13594. // Load server private key
  13595. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  13596. #if MBEDTLS_VERSION_MAJOR >= 3
  13597. ,
  13598. mbedtls_ctr_drbg_random, nullptr
  13599. #endif
  13600. ) != 0) {
  13601. return false;
  13602. }
  13603. // Load CA chain for client verification
  13604. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  13605. return false;
  13606. }
  13607. initialized = true;
  13608. }
  13609. // Configure the SSL config
  13610. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  13611. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  13612. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  13613. // Set minimum TLS version using mbedTLS native API
  13614. #if MBEDTLS_VERSION_MAJOR >= 3
  13615. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  13616. #else
  13617. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  13618. MBEDTLS_SSL_MINOR_VERSION_3);
  13619. #endif
  13620. return true;
  13621. };
  13622. SSLServer svr(setup_callback);
  13623. ASSERT_TRUE(svr.is_valid());
  13624. ASSERT_TRUE(callback_invoked);
  13625. svr.Get("/test", [&](const Request &req, Response &res) {
  13626. res.set_content("test", "text/plain");
  13627. auto cert = req.peer_cert();
  13628. ASSERT_TRUE(static_cast<bool>(cert));
  13629. auto common_name = cert.subject_cn();
  13630. EXPECT_EQ("Common Name", common_name);
  13631. });
  13632. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13633. auto se = detail::scope_exit([&] {
  13634. svr.stop();
  13635. t.join();
  13636. ASSERT_FALSE(svr.is_running());
  13637. });
  13638. svr.wait_until_ready();
  13639. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13640. cli.enable_server_certificate_verification(false);
  13641. cli.set_connection_timeout(30);
  13642. auto res = cli.Get("/test");
  13643. ASSERT_TRUE(res);
  13644. ASSERT_EQ(StatusCode::OK_200, res->status);
  13645. }
  13646. #endif
  13647. // WebSocket Tests
  13648. TEST(WebSocketTest, RSVBitsMustBeZero) {
  13649. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  13650. // defining the meaning of these bits has been negotiated.
  13651. auto make_frame = [](uint8_t first_byte) {
  13652. std::string frame;
  13653. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  13654. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  13655. frame += "Hello";
  13656. return frame;
  13657. };
  13658. // RSV1 set (0x40)
  13659. {
  13660. detail::BufferStream strm;
  13661. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  13662. ws::Opcode opcode;
  13663. std::string payload;
  13664. bool fin;
  13665. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13666. false, 1024));
  13667. }
  13668. // RSV2 set (0x20)
  13669. {
  13670. detail::BufferStream strm;
  13671. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  13672. ws::Opcode opcode;
  13673. std::string payload;
  13674. bool fin;
  13675. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13676. false, 1024));
  13677. }
  13678. // RSV3 set (0x10)
  13679. {
  13680. detail::BufferStream strm;
  13681. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  13682. ws::Opcode opcode;
  13683. std::string payload;
  13684. bool fin;
  13685. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13686. false, 1024));
  13687. }
  13688. // No RSV bits set - should succeed
  13689. {
  13690. detail::BufferStream strm;
  13691. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  13692. ws::Opcode opcode;
  13693. std::string payload;
  13694. bool fin;
  13695. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13696. false, 1024));
  13697. EXPECT_EQ(ws::Opcode::Text, opcode);
  13698. EXPECT_EQ("Hello", payload);
  13699. EXPECT_TRUE(fin);
  13700. }
  13701. }
  13702. TEST(WebSocketTest, ControlFrameValidation) {
  13703. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  13704. // payload length <= 125.
  13705. // Ping with FIN=0 - must be rejected
  13706. {
  13707. detail::BufferStream strm;
  13708. std::string frame;
  13709. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  13710. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13711. strm.write(frame.data(), frame.size());
  13712. ws::Opcode opcode;
  13713. std::string payload;
  13714. bool fin;
  13715. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13716. false, 1024));
  13717. }
  13718. // Close with FIN=0 - must be rejected
  13719. {
  13720. detail::BufferStream strm;
  13721. std::string frame;
  13722. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  13723. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13724. strm.write(frame.data(), frame.size());
  13725. ws::Opcode opcode;
  13726. std::string payload;
  13727. bool fin;
  13728. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13729. false, 1024));
  13730. }
  13731. // Ping with payload_len=126 (extended length) - must be rejected
  13732. {
  13733. detail::BufferStream strm;
  13734. std::string frame;
  13735. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13736. frame += static_cast<char>(126); // payload_len=126 (>125)
  13737. frame += static_cast<char>(0x00); // extended length high byte
  13738. frame += static_cast<char>(126); // extended length low byte
  13739. frame += std::string(126, 'x');
  13740. strm.write(frame.data(), frame.size());
  13741. ws::Opcode opcode;
  13742. std::string payload;
  13743. bool fin;
  13744. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13745. false, 1024));
  13746. }
  13747. // Ping with FIN=1 and payload_len=125 - should succeed
  13748. {
  13749. detail::BufferStream strm;
  13750. std::string frame;
  13751. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13752. frame += static_cast<char>(125); // payload_len=125
  13753. frame += std::string(125, 'x');
  13754. strm.write(frame.data(), frame.size());
  13755. ws::Opcode opcode;
  13756. std::string payload;
  13757. bool fin;
  13758. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13759. false, 1024));
  13760. EXPECT_EQ(ws::Opcode::Ping, opcode);
  13761. EXPECT_EQ(125u, payload.size());
  13762. EXPECT_TRUE(fin);
  13763. }
  13764. }
  13765. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  13766. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  13767. // length MUST be 0.
  13768. // MSB set - must be rejected
  13769. {
  13770. detail::BufferStream strm;
  13771. std::string frame;
  13772. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13773. frame += static_cast<char>(127); // 64-bit extended length
  13774. frame += static_cast<char>(0x80); // MSB set (invalid)
  13775. frame += std::string(7, '\0'); // remaining 7 bytes of length
  13776. strm.write(frame.data(), frame.size());
  13777. ws::Opcode opcode;
  13778. std::string payload;
  13779. bool fin;
  13780. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13781. false, 1024));
  13782. }
  13783. // MSB clear - should pass length parsing (will be rejected by max_len,
  13784. // but that's a different check; use a small length to verify)
  13785. {
  13786. detail::BufferStream strm;
  13787. std::string frame;
  13788. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13789. frame += static_cast<char>(127); // 64-bit extended length
  13790. frame += std::string(7, '\0'); // high bytes = 0
  13791. frame += static_cast<char>(0x03); // length = 3
  13792. frame += "abc";
  13793. strm.write(frame.data(), frame.size());
  13794. ws::Opcode opcode;
  13795. std::string payload;
  13796. bool fin;
  13797. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13798. false, 1024));
  13799. EXPECT_EQ(ws::Opcode::Text, opcode);
  13800. EXPECT_EQ("abc", payload);
  13801. }
  13802. }
  13803. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  13804. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  13805. // Valid UTF-8
  13806. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  13807. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  13808. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  13809. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  13810. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  13811. // Invalid UTF-8
  13812. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  13813. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  13814. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  13815. EXPECT_FALSE(
  13816. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  13817. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  13818. }
  13819. TEST(WebSocketTest, ConnectAndDisconnect) {
  13820. Server svr;
  13821. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  13822. std::string msg;
  13823. while (ws.read(msg)) {}
  13824. });
  13825. auto port = svr.bind_to_any_port(HOST);
  13826. std::thread t([&]() { svr.listen_after_bind(); });
  13827. svr.wait_until_ready();
  13828. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  13829. ASSERT_TRUE(client.connect());
  13830. EXPECT_TRUE(client.is_open());
  13831. client.close();
  13832. EXPECT_FALSE(client.is_open());
  13833. svr.stop();
  13834. t.join();
  13835. }
  13836. TEST(WebSocketTest, ValidURL) {
  13837. ws::WebSocketClient ws1("ws://localhost:8080/path");
  13838. EXPECT_TRUE(ws1.is_valid());
  13839. ws::WebSocketClient ws2("ws://example.com/path");
  13840. EXPECT_TRUE(ws2.is_valid());
  13841. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  13842. EXPECT_TRUE(ws3.is_valid());
  13843. #ifdef CPPHTTPLIB_SSL_ENABLED
  13844. ws::WebSocketClient wss1("wss://example.com/path");
  13845. EXPECT_TRUE(wss1.is_valid());
  13846. ws::WebSocketClient wss2("wss://example.com:443/path");
  13847. EXPECT_TRUE(wss2.is_valid());
  13848. #endif
  13849. }
  13850. TEST(WebSocketTest, InvalidURL) {
  13851. // No scheme
  13852. ws::WebSocketClient ws1("localhost:8080/path");
  13853. EXPECT_FALSE(ws1.is_valid());
  13854. // No path
  13855. ws::WebSocketClient ws2("ws://localhost:8080");
  13856. EXPECT_FALSE(ws2.is_valid());
  13857. // Empty string
  13858. ws::WebSocketClient ws3("");
  13859. EXPECT_FALSE(ws3.is_valid());
  13860. // Missing host
  13861. ws::WebSocketClient ws4("ws://:8080/path");
  13862. EXPECT_FALSE(ws4.is_valid());
  13863. // Port number overflow — should not crash
  13864. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  13865. EXPECT_FALSE(ws5.is_valid());
  13866. // Port out of range
  13867. ws::WebSocketClient ws6("ws://localhost:99999/path");
  13868. EXPECT_FALSE(ws6.is_valid());
  13869. }
  13870. TEST(WebSocketTest, UnsupportedScheme) {
  13871. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13872. ws::WebSocketClient ws1("http://localhost:8080/path");
  13873. EXPECT_FALSE(ws1.is_valid());
  13874. ws::WebSocketClient ws2("https://localhost:8080/path");
  13875. EXPECT_FALSE(ws2.is_valid());
  13876. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  13877. EXPECT_FALSE(ws3.is_valid());
  13878. #else
  13879. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  13880. std::invalid_argument);
  13881. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  13882. std::invalid_argument);
  13883. #endif
  13884. }
  13885. TEST(WebSocketTest, ConnectWhenInvalid) {
  13886. ws::WebSocketClient ws("not a valid url");
  13887. EXPECT_FALSE(ws.is_valid());
  13888. EXPECT_FALSE(ws.connect());
  13889. }
  13890. TEST(WebSocketTest, DefaultPort) {
  13891. ws::WebSocketClient ws1("ws://example.com/path");
  13892. EXPECT_TRUE(ws1.is_valid());
  13893. // ws:// defaults to port 80 (verified by successful parse)
  13894. #ifdef CPPHTTPLIB_SSL_ENABLED
  13895. ws::WebSocketClient ws2("wss://example.com/path");
  13896. EXPECT_TRUE(ws2.is_valid());
  13897. // wss:// defaults to port 443 (verified by successful parse)
  13898. #endif
  13899. }
  13900. TEST(WebSocketTest, IPv6LiteralAddress) {
  13901. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  13902. EXPECT_TRUE(ws1.is_valid());
  13903. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  13904. EXPECT_TRUE(ws2.is_valid());
  13905. }
  13906. TEST(WebSocketTest, ComplexPath) {
  13907. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  13908. EXPECT_TRUE(ws1.is_valid());
  13909. ws::WebSocketClient ws2("ws://localhost:8080/");
  13910. EXPECT_TRUE(ws2.is_valid());
  13911. }
  13912. class WebSocketIntegrationTest : public ::testing::Test {
  13913. protected:
  13914. void SetUp() override {
  13915. server_ = httplib::detail::make_unique<Server>();
  13916. setup_server();
  13917. start_server();
  13918. }
  13919. void TearDown() override {
  13920. server_->stop();
  13921. if (server_thread_.joinable()) { server_thread_.join(); }
  13922. }
  13923. void setup_server() {
  13924. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  13925. std::string msg;
  13926. ws::ReadResult ret;
  13927. while ((ret = ws.read(msg))) {
  13928. if (ret == ws::Binary) {
  13929. ws.send(msg.data(), msg.size());
  13930. } else {
  13931. ws.send(msg);
  13932. }
  13933. }
  13934. });
  13935. server_->WebSocket("/ws-echo-string",
  13936. [](const Request &, ws::WebSocket &ws) {
  13937. std::string msg;
  13938. while (ws.read(msg)) {
  13939. ws.send("echo: " + msg);
  13940. }
  13941. });
  13942. server_->WebSocket(
  13943. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  13944. // Echo back request metadata
  13945. ws.send("path:" + req.path);
  13946. ws.send("header:" + req.get_header_value("X-Test-Header"));
  13947. std::string msg;
  13948. while (ws.read(msg)) {}
  13949. });
  13950. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  13951. std::string msg;
  13952. ws.read(msg); // wait for a message
  13953. ws.close();
  13954. });
  13955. server_->WebSocket("/ws-close-status",
  13956. [](const Request &, ws::WebSocket &ws) {
  13957. std::string msg;
  13958. ws.read(msg); // wait for a message
  13959. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  13960. });
  13961. server_->WebSocket(
  13962. "/ws-subprotocol",
  13963. [](const Request &, ws::WebSocket &ws) {
  13964. std::string msg;
  13965. while (ws.read(msg)) {
  13966. ws.send(msg);
  13967. }
  13968. },
  13969. [](const std::vector<std::string> &protocols) -> std::string {
  13970. for (const auto &p : protocols) {
  13971. if (p == "graphql-ws") { return p; }
  13972. }
  13973. return "";
  13974. });
  13975. }
  13976. void start_server() {
  13977. port_ = server_->bind_to_any_port(HOST);
  13978. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13979. server_->wait_until_ready();
  13980. }
  13981. std::unique_ptr<Server> server_;
  13982. std::thread server_thread_;
  13983. int port_ = 0;
  13984. };
  13985. TEST_F(WebSocketIntegrationTest, TextEcho) {
  13986. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13987. "/ws-echo");
  13988. ASSERT_TRUE(client.connect());
  13989. ASSERT_TRUE(client.is_open());
  13990. ASSERT_TRUE(client.send("Hello WebSocket"));
  13991. std::string msg;
  13992. EXPECT_EQ(ws::Text, client.read(msg));
  13993. EXPECT_EQ("Hello WebSocket", msg);
  13994. client.close();
  13995. }
  13996. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  13997. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13998. "/ws-echo");
  13999. ASSERT_TRUE(client.connect());
  14000. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  14001. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  14002. std::string msg;
  14003. EXPECT_EQ(ws::Binary, client.read(msg));
  14004. EXPECT_EQ(binary_data, msg);
  14005. client.close();
  14006. }
  14007. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  14008. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14009. "/ws-echo");
  14010. ASSERT_TRUE(client.connect());
  14011. for (int i = 0; i < 10; i++) {
  14012. auto text = "message " + std::to_string(i);
  14013. ASSERT_TRUE(client.send(text));
  14014. std::string msg;
  14015. ASSERT_TRUE(client.read(msg));
  14016. EXPECT_EQ(text, msg);
  14017. }
  14018. client.close();
  14019. }
  14020. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  14021. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14022. "/ws-close");
  14023. ASSERT_TRUE(client.connect());
  14024. // Send a message to trigger the server to close
  14025. ASSERT_TRUE(client.send("trigger close"));
  14026. // The server will close, so read should return false
  14027. std::string msg;
  14028. EXPECT_FALSE(client.read(msg));
  14029. EXPECT_FALSE(client.is_open());
  14030. }
  14031. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  14032. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14033. "/ws-echo");
  14034. ASSERT_TRUE(client.connect());
  14035. // 128KB message
  14036. std::string large_data(128 * 1024, 'X');
  14037. ASSERT_TRUE(client.send(large_data));
  14038. std::string msg;
  14039. ASSERT_TRUE(client.read(msg));
  14040. EXPECT_EQ(large_data, msg);
  14041. client.close();
  14042. }
  14043. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  14044. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14045. "/ws-echo");
  14046. ASSERT_TRUE(client.connect());
  14047. const int num_threads = 4;
  14048. std::vector<std::thread> threads;
  14049. std::atomic<int> send_count{0};
  14050. for (int t = 0; t < num_threads; t++) {
  14051. threads.emplace_back([&client, &send_count, t]() {
  14052. for (int i = 0; i < 5; i++) {
  14053. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  14054. if (client.send(text)) { send_count++; }
  14055. }
  14056. });
  14057. }
  14058. for (auto &th : threads) {
  14059. th.join();
  14060. }
  14061. int received = 0;
  14062. std::string msg;
  14063. while (received < send_count.load()) {
  14064. if (!client.read(msg)) { break; }
  14065. received++;
  14066. }
  14067. EXPECT_EQ(send_count.load(), received);
  14068. client.close();
  14069. }
  14070. TEST_F(WebSocketIntegrationTest, ReadString) {
  14071. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14072. "/ws-echo-string");
  14073. ASSERT_TRUE(client.connect());
  14074. ASSERT_TRUE(client.send("hello"));
  14075. std::string msg;
  14076. ASSERT_TRUE(client.read(msg));
  14077. EXPECT_EQ("echo: hello", msg);
  14078. ASSERT_TRUE(client.send("world"));
  14079. ASSERT_TRUE(client.read(msg));
  14080. EXPECT_EQ("echo: world", msg);
  14081. client.close();
  14082. }
  14083. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  14084. Headers headers = {{"X-Test-Header", "test-value"}};
  14085. ws::WebSocketClient client(
  14086. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  14087. ASSERT_TRUE(client.connect());
  14088. std::string msg;
  14089. ASSERT_TRUE(client.read(msg));
  14090. EXPECT_EQ("path:/ws-request-info", msg);
  14091. ASSERT_TRUE(client.read(msg));
  14092. EXPECT_EQ("header:test-value", msg);
  14093. client.close();
  14094. }
  14095. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  14096. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14097. "/ws-echo");
  14098. client.set_read_timeout(1, 0); // 1 second
  14099. ASSERT_TRUE(client.connect());
  14100. // Don't send anything — server echo handler waits for a message,
  14101. // so read() should time out and return false.
  14102. std::string msg;
  14103. EXPECT_FALSE(client.read(msg));
  14104. }
  14105. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  14106. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14107. "/ws-echo");
  14108. client.set_read_timeout(5, 0);
  14109. ASSERT_TRUE(client.connect());
  14110. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14111. // The server should reject it and close the connection.
  14112. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  14113. client.send(oversized);
  14114. // The server's read() should have failed due to payload limit,
  14115. // so our read() should return false (connection closed).
  14116. std::string msg;
  14117. EXPECT_FALSE(client.read(msg));
  14118. }
  14119. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  14120. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14121. "/ws-echo");
  14122. client.set_read_timeout(10, 0);
  14123. ASSERT_TRUE(client.connect());
  14124. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14125. // This should succeed.
  14126. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  14127. ASSERT_TRUE(client.send(at_limit));
  14128. std::string msg;
  14129. ASSERT_TRUE(client.read(msg));
  14130. EXPECT_EQ(at_limit.size(), msg.size());
  14131. client.close();
  14132. }
  14133. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  14134. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14135. "/nonexistent");
  14136. EXPECT_FALSE(client.connect());
  14137. EXPECT_FALSE(client.is_open());
  14138. }
  14139. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  14140. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14141. "/ws-echo");
  14142. ASSERT_TRUE(client.connect());
  14143. ASSERT_TRUE(client.send(""));
  14144. std::string msg;
  14145. EXPECT_EQ(ws::Text, client.read(msg));
  14146. EXPECT_EQ("", msg);
  14147. client.close();
  14148. }
  14149. TEST_F(WebSocketIntegrationTest, Reconnect) {
  14150. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14151. "/ws-echo");
  14152. // First connection
  14153. ASSERT_TRUE(client.connect());
  14154. ASSERT_TRUE(client.send("first"));
  14155. std::string msg;
  14156. ASSERT_TRUE(client.read(msg));
  14157. EXPECT_EQ("first", msg);
  14158. client.close();
  14159. EXPECT_FALSE(client.is_open());
  14160. // Reconnect using the same client object
  14161. ASSERT_TRUE(client.connect());
  14162. ASSERT_TRUE(client.is_open());
  14163. ASSERT_TRUE(client.send("second"));
  14164. ASSERT_TRUE(client.read(msg));
  14165. EXPECT_EQ("second", msg);
  14166. client.close();
  14167. }
  14168. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  14169. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14170. "/ws-close-status");
  14171. ASSERT_TRUE(client.connect());
  14172. // Trigger the server to close with GoingAway status
  14173. ASSERT_TRUE(client.send("trigger"));
  14174. // read() should return false after receiving the close frame
  14175. std::string msg;
  14176. EXPECT_FALSE(client.read(msg));
  14177. EXPECT_FALSE(client.is_open());
  14178. }
  14179. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  14180. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14181. "/ws-echo");
  14182. ASSERT_TRUE(client.connect());
  14183. client.close(ws::CloseStatus::GoingAway, "client leaving");
  14184. EXPECT_FALSE(client.is_open());
  14185. }
  14186. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  14187. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  14188. ws::WebSocketClient client(
  14189. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14190. ASSERT_TRUE(client.connect());
  14191. // Server should have selected graphql-ws
  14192. EXPECT_EQ("graphql-ws", client.subprotocol());
  14193. client.close();
  14194. }
  14195. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  14196. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  14197. ws::WebSocketClient client(
  14198. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14199. ASSERT_TRUE(client.connect());
  14200. // Server should not have selected any subprotocol
  14201. EXPECT_TRUE(client.subprotocol().empty());
  14202. client.close();
  14203. }
  14204. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  14205. // Connect without requesting any subprotocol
  14206. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14207. "/ws-subprotocol");
  14208. ASSERT_TRUE(client.connect());
  14209. EXPECT_TRUE(client.subprotocol().empty());
  14210. client.close();
  14211. }
  14212. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  14213. Server svr;
  14214. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  14215. if (!req.has_header("Authorization")) {
  14216. res.status = StatusCode::Unauthorized_401;
  14217. res.set_content("Unauthorized", "text/plain");
  14218. return Server::HandlerResponse::Handled;
  14219. }
  14220. return Server::HandlerResponse::Unhandled;
  14221. });
  14222. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14223. std::string msg;
  14224. while (ws.read(msg)) {
  14225. ws.send(msg);
  14226. }
  14227. });
  14228. auto port = svr.bind_to_any_port("localhost");
  14229. std::thread t([&]() { svr.listen_after_bind(); });
  14230. svr.wait_until_ready();
  14231. // Without Authorization header - should be rejected before upgrade
  14232. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  14233. EXPECT_FALSE(client1.connect());
  14234. // With Authorization header - should succeed
  14235. Headers headers = {{"Authorization", "Bearer token123"}};
  14236. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  14237. headers);
  14238. ASSERT_TRUE(client2.connect());
  14239. ASSERT_TRUE(client2.send("hello"));
  14240. std::string msg;
  14241. ASSERT_TRUE(client2.read(msg));
  14242. EXPECT_EQ("hello", msg);
  14243. client2.close();
  14244. svr.stop();
  14245. t.join();
  14246. }
  14247. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14248. class WebSocketSSLIntegrationTest : public ::testing::Test {
  14249. protected:
  14250. void SetUp() override {
  14251. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  14252. SERVER_PRIVATE_KEY_FILE);
  14253. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14254. std::string msg;
  14255. ws::ReadResult ret;
  14256. while ((ret = ws.read(msg))) {
  14257. if (ret == ws::Binary) {
  14258. ws.send(msg.data(), msg.size());
  14259. } else {
  14260. ws.send(msg);
  14261. }
  14262. }
  14263. });
  14264. port_ = server_->bind_to_any_port(HOST);
  14265. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14266. server_->wait_until_ready();
  14267. }
  14268. void TearDown() override {
  14269. server_->stop();
  14270. if (server_thread_.joinable()) { server_thread_.join(); }
  14271. }
  14272. std::unique_ptr<SSLServer> server_;
  14273. std::thread server_thread_;
  14274. int port_ = 0;
  14275. };
  14276. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  14277. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  14278. "/ws-echo");
  14279. client.enable_server_certificate_verification(false);
  14280. ASSERT_TRUE(client.connect());
  14281. ASSERT_TRUE(client.is_open());
  14282. ASSERT_TRUE(client.send("Hello WSS"));
  14283. std::string msg;
  14284. EXPECT_EQ(ws::Text, client.read(msg));
  14285. EXPECT_EQ("Hello WSS", msg);
  14286. client.close();
  14287. }
  14288. #endif
  14289. #if !defined(_WIN32)
  14290. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  14291. auto secret_dir = std::string("./symlink_test_secret");
  14292. auto served_dir = std::string("./symlink_test_served");
  14293. auto secret_file = secret_dir + "/secret.txt";
  14294. auto symlink_path = served_dir + "/escape";
  14295. // Setup: create directories and files
  14296. mkdir(secret_dir.c_str(), 0755);
  14297. mkdir(served_dir.c_str(), 0755);
  14298. {
  14299. std::ofstream ofs(secret_file);
  14300. ofs << "SECRET_DATA";
  14301. }
  14302. // Create symlink using absolute path so it resolves correctly
  14303. char abs_secret[PATH_MAX];
  14304. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  14305. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  14306. auto se = detail::scope_exit([&] {
  14307. unlink(symlink_path.c_str());
  14308. unlink(secret_file.c_str());
  14309. rmdir(served_dir.c_str());
  14310. rmdir(secret_dir.c_str());
  14311. });
  14312. Server svr;
  14313. svr.set_mount_point("/", served_dir);
  14314. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  14315. auto se2 = detail::scope_exit([&] {
  14316. svr.stop();
  14317. listen_thread.join();
  14318. });
  14319. svr.wait_until_ready();
  14320. Client cli("localhost", PORT);
  14321. // Symlink pointing outside base dir should be blocked
  14322. auto res = cli.Get("/escape/secret.txt");
  14323. ASSERT_TRUE(res);
  14324. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  14325. }
  14326. #endif